repo_name
stringlengths
7
71
file_path
stringlengths
5
118
context
list
import_statement
stringlengths
45
12.5k
token_num
int64
641
99.4k
cropped_code
stringlengths
44
17k
all_code
stringlengths
43
754k
next_line
stringlengths
2
330
gold_snippet_index
int64
0
68
created_at
stringlengths
25
25
level
stringclasses
9 values
alibaba-damo-academy/FunCodec
funcodec/models/encoder/sanm_encoder.py
[ { "identifier": "overlap_chunk", "path": "funcodec/modules/streaming_utils/chunk_utilis.py", "snippet": "class overlap_chunk():\n\t\"\"\"\n\tauthor: Speech Lab, Alibaba Group, China\n\tSan-m: Memory equipped self-attention for end-to-end speech recognition\n\thttps://arxiv.org/abs/2006.01713\n\n\t\"\"\"\n\tdef __init__(self,\n\t\tchunk_size: tuple = (16,),\n\t\tstride: tuple = (10,),\n\t\tpad_left: tuple = (0,),\n\t\tencoder_att_look_back_factor: tuple = (1,),\n shfit_fsmn: int = 0,\n decoder_att_look_back_factor: tuple = (1,),\n\t):\n\n\t\tpad_left = self.check_chunk_size_args(chunk_size, pad_left)\n\t\tencoder_att_look_back_factor = self.check_chunk_size_args(chunk_size, encoder_att_look_back_factor)\n\t\tdecoder_att_look_back_factor = self.check_chunk_size_args(chunk_size, decoder_att_look_back_factor)\n\t\tself.chunk_size, self.stride, self.pad_left, self.encoder_att_look_back_factor, self.decoder_att_look_back_factor \\\n\t\t\t= chunk_size, stride, pad_left, encoder_att_look_back_factor, decoder_att_look_back_factor\n\t\tself.shfit_fsmn = shfit_fsmn\n\t\tself.x_add_mask = None\n\t\tself.x_rm_mask = None\n\t\tself.x_len = None\n\t\tself.mask_shfit_chunk = None\n\t\tself.mask_chunk_predictor = None\n\t\tself.mask_att_chunk_encoder = None\n\t\tself.mask_shift_att_chunk_decoder = None\n\t\tself.chunk_outs = None\n\t\tself.chunk_size_cur, self.stride_cur, self.pad_left_cur, self.encoder_att_look_back_factor_cur, self.chunk_size_pad_shift_cur \\\n\t\t\t= None, None, None, None, None\n\n\tdef check_chunk_size_args(self, chunk_size, x):\n\t\tif len(x) < len(chunk_size):\n\t\t\tx = [x[0] for i in chunk_size]\n\t\treturn x\n\n\tdef get_chunk_size(self,\n\t\tind: int = 0\n\t):\n\t\t# with torch.no_grad:\n\t\tchunk_size, stride, pad_left, encoder_att_look_back_factor, decoder_att_look_back_factor = \\\n\t\t\tself.chunk_size[ind], self.stride[ind], self.pad_left[ind], self.encoder_att_look_back_factor[ind], self.decoder_att_look_back_factor[ind]\n\t\tself.chunk_size_cur, self.stride_cur, self.pad_left_cur, self.encoder_att_look_back_factor_cur, self.chunk_size_pad_shift_cur, self.decoder_att_look_back_factor_cur \\\n\t\t\t= chunk_size, stride, pad_left, encoder_att_look_back_factor, chunk_size + self.shfit_fsmn, decoder_att_look_back_factor\n\t\treturn self.chunk_size_cur, self.stride_cur, self.pad_left_cur, self.encoder_att_look_back_factor_cur, self.chunk_size_pad_shift_cur\n\n\tdef random_choice(self, training=True, decoding_ind=None):\n\t\tchunk_num = len(self.chunk_size)\n\t\tind = 0\n\t\tif training and chunk_num > 1:\n\t\t\tind = torch.randint(0, chunk_num-1, ()).cpu().item()\n\t\tif not training and decoding_ind is not None:\n\t\t\tind = int(decoding_ind)\n\n\t\treturn ind\n\n\n\n\n\tdef gen_chunk_mask(self, x_len, ind=0, num_units=1, num_units_predictor=1):\n\n\t\twith torch.no_grad():\n\t\t\tx_len = x_len.cpu().numpy()\n\t\t\tx_len_max = x_len.max()\n\n\t\t\tchunk_size, stride, pad_left, encoder_att_look_back_factor, chunk_size_pad_shift = self.get_chunk_size(ind)\n\t\t\tshfit_fsmn = self.shfit_fsmn\n\t\t\tpad_right = chunk_size - stride - pad_left\n\n\t\t\tchunk_num_batch = np.ceil(x_len/stride).astype(np.int32)\n\t\t\tx_len_chunk = (chunk_num_batch-1) * chunk_size_pad_shift + shfit_fsmn + pad_left + 0 + x_len - (chunk_num_batch-1) * stride\n\t\t\tx_len_chunk = x_len_chunk.astype(x_len.dtype)\n\t\t\tx_len_chunk_max = x_len_chunk.max()\n\n\t\t\tchunk_num = int(math.ceil(x_len_max/stride))\n\t\t\tdtype = np.int32\n\t\t\tmax_len_for_x_mask_tmp = max(chunk_size, x_len_max + pad_left)\n\t\t\tx_add_mask = np.zeros([0, max_len_for_x_mask_tmp], dtype=dtype)\n\t\t\tx_rm_mask = np.zeros([max_len_for_x_mask_tmp, 0], dtype=dtype)\n\t\t\tmask_shfit_chunk = np.zeros([0, num_units], dtype=dtype)\n\t\t\tmask_chunk_predictor = np.zeros([0, num_units_predictor], dtype=dtype)\n\t\t\tmask_shift_att_chunk_decoder = np.zeros([0, 1], dtype=dtype)\n\t\t\tmask_att_chunk_encoder = np.zeros([0, chunk_num*chunk_size_pad_shift], dtype=dtype)\n\t\t\tfor chunk_ids in range(chunk_num):\n\t\t\t\t# x_mask add\n\t\t\t\tfsmn_padding = np.zeros((shfit_fsmn, max_len_for_x_mask_tmp), dtype=dtype)\n\t\t\t\tx_mask_cur = np.diag(np.ones(chunk_size, dtype=np.float32))\n\t\t\t\tx_mask_pad_left = np.zeros((chunk_size, chunk_ids * stride), dtype=dtype)\n\t\t\t\tx_mask_pad_right = np.zeros((chunk_size, max_len_for_x_mask_tmp), dtype=dtype)\n\t\t\t\tx_cur_pad = np.concatenate([x_mask_pad_left, x_mask_cur, x_mask_pad_right], axis=1)\n\t\t\t\tx_cur_pad = x_cur_pad[:chunk_size, :max_len_for_x_mask_tmp]\n\t\t\t\tx_add_mask_fsmn = np.concatenate([fsmn_padding, x_cur_pad], axis=0)\n\t\t\t\tx_add_mask = np.concatenate([x_add_mask, x_add_mask_fsmn], axis=0)\n\n\t\t\t\t# x_mask rm\n\t\t\t\tfsmn_padding = np.zeros((max_len_for_x_mask_tmp, shfit_fsmn),dtype=dtype)\n\t\t\t\tpadding_mask_left = np.zeros((max_len_for_x_mask_tmp, pad_left),dtype=dtype)\n\t\t\t\tpadding_mask_right = np.zeros((max_len_for_x_mask_tmp, pad_right), dtype=dtype)\n\t\t\t\tx_mask_cur = np.diag(np.ones(stride, dtype=dtype))\n\t\t\t\tx_mask_cur_pad_top = np.zeros((chunk_ids*stride, stride), dtype=dtype)\n\t\t\t\tx_mask_cur_pad_bottom = np.zeros((max_len_for_x_mask_tmp, stride), dtype=dtype)\n\t\t\t\tx_rm_mask_cur = np.concatenate([x_mask_cur_pad_top, x_mask_cur, x_mask_cur_pad_bottom], axis=0)\n\t\t\t\tx_rm_mask_cur = x_rm_mask_cur[:max_len_for_x_mask_tmp, :stride]\n\t\t\t\tx_rm_mask_cur_fsmn = np.concatenate([fsmn_padding, padding_mask_left, x_rm_mask_cur, padding_mask_right], axis=1)\n\t\t\t\tx_rm_mask = np.concatenate([x_rm_mask, x_rm_mask_cur_fsmn], axis=1)\n\n\t\t\t\t# fsmn_padding_mask\n\t\t\t\tpad_shfit_mask = np.zeros([shfit_fsmn, num_units], dtype=dtype)\n\t\t\t\tones_1 = np.ones([chunk_size, num_units], dtype=dtype)\n\t\t\t\tmask_shfit_chunk_cur = np.concatenate([pad_shfit_mask, ones_1], axis=0)\n\t\t\t\tmask_shfit_chunk = np.concatenate([mask_shfit_chunk, mask_shfit_chunk_cur], axis=0)\n\n\t\t\t\t# predictor mask\n\t\t\t\tzeros_1 = np.zeros([shfit_fsmn + pad_left, num_units_predictor], dtype=dtype)\n\t\t\t\tones_2 = np.ones([stride, num_units_predictor], dtype=dtype)\n\t\t\t\tzeros_3 = np.zeros([chunk_size - stride - pad_left, num_units_predictor], dtype=dtype)\n\t\t\t\tones_zeros = np.concatenate([ones_2, zeros_3], axis=0)\n\t\t\t\tmask_chunk_predictor_cur = np.concatenate([zeros_1, ones_zeros], axis=0)\n\t\t\t\tmask_chunk_predictor = np.concatenate([mask_chunk_predictor, mask_chunk_predictor_cur], axis=0)\n\n\t\t\t\t# encoder att mask\n\t\t\t\tzeros_1_top = np.zeros([shfit_fsmn, chunk_num*chunk_size_pad_shift], dtype=dtype)\n\n\t\t\t\tzeros_2_num = max(chunk_ids - encoder_att_look_back_factor, 0)\n\t\t\t\tzeros_2 = np.zeros([chunk_size, zeros_2_num*chunk_size_pad_shift], dtype=dtype)\n\n\t\t\t\tencoder_att_look_back_num = max(chunk_ids - zeros_2_num, 0)\n\t\t\t\tzeros_2_left = np.zeros([chunk_size, shfit_fsmn], dtype=dtype)\n\t\t\t\tones_2_mid = np.ones([stride, stride], dtype=dtype)\n\t\t\t\tzeros_2_bottom = np.zeros([chunk_size-stride, stride], dtype=dtype)\n\t\t\t\tzeros_2_right = np.zeros([chunk_size, chunk_size-stride], dtype=dtype)\n\t\t\t\tones_2 = np.concatenate([ones_2_mid, zeros_2_bottom], axis=0)\n\t\t\t\tones_2 = np.concatenate([zeros_2_left, ones_2, zeros_2_right], axis=1)\n\t\t\t\tones_2 = np.tile(ones_2, [1, encoder_att_look_back_num])\n\n\t\t\t\tzeros_3_left = np.zeros([chunk_size, shfit_fsmn], dtype=dtype)\n\t\t\t\tones_3_right = np.ones([chunk_size, chunk_size], dtype=dtype)\n\t\t\t\tones_3 = np.concatenate([zeros_3_left, ones_3_right], axis=1)\n\n\t\t\t\tzeros_remain_num = max(chunk_num - 1 - chunk_ids, 0)\n\t\t\t\tzeros_remain = np.zeros([chunk_size, zeros_remain_num*chunk_size_pad_shift], dtype=dtype)\n\n\t\t\t\tones2_bottom = np.concatenate([zeros_2, ones_2, ones_3, zeros_remain], axis=1)\n\t\t\t\tmask_att_chunk_encoder_cur = np.concatenate([zeros_1_top, ones2_bottom], axis=0)\n\t\t\t\tmask_att_chunk_encoder = np.concatenate([mask_att_chunk_encoder, mask_att_chunk_encoder_cur], axis=0)\n\n\n\t\t\t\t# decoder fsmn_shift_att_mask\n\t\t\t\tzeros_1 = np.zeros([shfit_fsmn, 1])\n\t\t\t\tones_1 = np.ones([chunk_size, 1])\n\t\t\t\tmask_shift_att_chunk_decoder_cur = np.concatenate([zeros_1, ones_1], axis=0)\n\t\t\t\tmask_shift_att_chunk_decoder = np.concatenate(\n\t\t\t\t\t[mask_shift_att_chunk_decoder, mask_shift_att_chunk_decoder_cur], axis=0)\n\n\t\t\tself.x_add_mask = x_add_mask[:x_len_chunk_max, :x_len_max+pad_left]\n\t\t\tself.x_len_chunk = x_len_chunk\n\t\t\tself.x_rm_mask = x_rm_mask[:x_len_max, :x_len_chunk_max]\n\t\t\tself.x_len = x_len\n\t\t\tself.mask_shfit_chunk = mask_shfit_chunk[:x_len_chunk_max, :]\n\t\t\tself.mask_chunk_predictor = mask_chunk_predictor[:x_len_chunk_max, :]\n\t\t\tself.mask_att_chunk_encoder = mask_att_chunk_encoder[:x_len_chunk_max, :x_len_chunk_max]\n\t\t\tself.mask_shift_att_chunk_decoder = mask_shift_att_chunk_decoder[:x_len_chunk_max, :]\n\t\t\tself.chunk_outs = (self.x_add_mask,\n\t\t self.x_len_chunk,\n\t\t self.x_rm_mask,\n\t\t self.x_len,\n\t\t self.mask_shfit_chunk,\n\t\t self.mask_chunk_predictor,\n\t\t self.mask_att_chunk_encoder,\n\t\t self.mask_shift_att_chunk_decoder)\n\n\t\treturn self.chunk_outs\n\n\n\tdef split_chunk(self, x, x_len, chunk_outs):\n\t\t\"\"\"\n\t\t:param x: (b, t, d)\n\t\t:param x_length: (b)\n\t\t:param ind: int\n\t\t:return:\n\t\t\"\"\"\n\t\tx = x[:, :x_len.max(), :]\n\t\tb, t, d = x.size()\n\t\tx_len_mask = (~make_pad_mask(x_len, maxlen=t)).to(\n\t\t\tx.device)\n\t\tx *= x_len_mask[:, :, None]\n\n\t\tx_add_mask = self.get_x_add_mask(chunk_outs, x.device, dtype=x.dtype)\n\t\tx_len_chunk = self.get_x_len_chunk(chunk_outs, x_len.device, dtype=x_len.dtype)\n\t\tpad = (0, 0, self.pad_left_cur, 0)\n\t\tx = F.pad(x, pad, \"constant\", 0.0)\n\t\tb, t, d = x.size()\n\t\tx = torch.transpose(x, 1, 0)\n\t\tx = torch.reshape(x, [t, -1])\n\t\tx_chunk = torch.mm(x_add_mask, x)\n\t\tx_chunk = torch.reshape(x_chunk, [-1, b, d]).transpose(1, 0)\n\n\t\treturn x_chunk, x_len_chunk\n\n\tdef remove_chunk(self, x_chunk, x_len_chunk, chunk_outs):\n\t\tx_chunk = x_chunk[:, :x_len_chunk.max(), :]\n\t\tb, t, d = x_chunk.size()\n\t\tx_len_chunk_mask = (~make_pad_mask(x_len_chunk, maxlen=t)).to(\n\t\t\tx_chunk.device)\n\t\tx_chunk *= x_len_chunk_mask[:, :, None]\n\n\t\tx_rm_mask = self.get_x_rm_mask(chunk_outs, x_chunk.device, dtype=x_chunk.dtype)\n\t\tx_len = self.get_x_len(chunk_outs, x_len_chunk.device, dtype=x_len_chunk.dtype)\n\t\tx_chunk = torch.transpose(x_chunk, 1, 0)\n\t\tx_chunk = torch.reshape(x_chunk, [t, -1])\n\t\tx = torch.mm(x_rm_mask, x_chunk)\n\t\tx = torch.reshape(x, [-1, b, d]).transpose(1, 0)\n\n\t\treturn x, x_len\n\n\tdef get_x_add_mask(self, chunk_outs=None, device='cpu', idx=0, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x\n\n\tdef get_x_len_chunk(self, chunk_outs=None, device='cpu', idx=1, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x\n\n\n\tdef get_x_rm_mask(self, chunk_outs=None, device='cpu', idx=2, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x\n\n\tdef get_x_len(self, chunk_outs=None, device='cpu', idx=3, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x\n\n\n\tdef get_mask_shfit_chunk(self, chunk_outs=None, device='cpu', batch_size=1, num_units=1, idx=4, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = np.tile(x[None, :, :, ], [batch_size, 1, num_units])\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x\n\n\tdef get_mask_chunk_predictor(self, chunk_outs=None, device='cpu', batch_size=1, num_units=1, idx=5, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = np.tile(x[None, :, :, ], [batch_size, 1, num_units])\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x\n\n\tdef get_mask_att_chunk_encoder(self, chunk_outs=None, device='cpu', batch_size=1, idx=6, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = np.tile(x[None, :, :, ], [batch_size, 1, 1])\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x\n\n\tdef get_mask_shift_att_chunk_decoder(self, chunk_outs=None, device='cpu', batch_size=1, idx=7, dtype=torch.float32):\n\t\twith torch.no_grad():\n\t\t\tx = chunk_outs[idx] if chunk_outs is not None else self.chunk_outs[idx]\n\t\t\tx = np.tile(x[None, None, :, 0], [batch_size, 1, 1])\n\t\t\tx = torch.from_numpy(x).type(dtype).to(device)\n\t\treturn x" }, { "identifier": "make_pad_mask", "path": "funcodec/modules/nets_utils.py", "snippet": "def make_pad_mask(lengths, xs=None, length_dim=-1, maxlen=None):\n \"\"\"Make mask tensor containing indices of padded part.\n\n Args:\n lengths (LongTensor or List): Batch of lengths (B,).\n xs (Tensor, optional): The reference tensor.\n If set, masks will be the same shape as this tensor.\n length_dim (int, optional): Dimension indicator of the above tensor.\n See the example.\n\n Returns:\n Tensor: Mask tensor containing indices of padded part.\n dtype=torch.uint8 in PyTorch 1.2-\n dtype=torch.bool in PyTorch 1.2+ (including 1.2)\n\n Examples:\n With only lengths.\n\n >>> lengths = [5, 3, 2]\n >>> make_pad_mask(lengths)\n masks = [[0, 0, 0, 0 ,0],\n [0, 0, 0, 1, 1],\n [0, 0, 1, 1, 1]]\n\n With the reference tensor.\n\n >>> xs = torch.zeros((3, 2, 4))\n >>> make_pad_mask(lengths, xs)\n tensor([[[0, 0, 0, 0],\n [0, 0, 0, 0]],\n [[0, 0, 0, 1],\n [0, 0, 0, 1]],\n [[0, 0, 1, 1],\n [0, 0, 1, 1]]], dtype=torch.uint8)\n >>> xs = torch.zeros((3, 2, 6))\n >>> make_pad_mask(lengths, xs)\n tensor([[[0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1]],\n [[0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1]],\n [[0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8)\n\n With the reference tensor and dimension indicator.\n\n >>> xs = torch.zeros((3, 6, 6))\n >>> make_pad_mask(lengths, xs, 1)\n tensor([[[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1]],\n [[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1]],\n [[0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1]]], dtype=torch.uint8)\n >>> make_pad_mask(lengths, xs, 2)\n tensor([[[0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1]],\n [[0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1]],\n [[0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8)\n\n \"\"\"\n if length_dim == 0:\n raise ValueError(\"length_dim cannot be 0: {}\".format(length_dim))\n\n if not isinstance(lengths, list):\n lengths = lengths.tolist()\n bs = int(len(lengths))\n if maxlen is None:\n if xs is None:\n maxlen = int(max(lengths))\n else:\n maxlen = xs.size(length_dim)\n else:\n assert xs is None\n assert maxlen >= int(max(lengths))\n\n seq_range = torch.arange(0, maxlen, dtype=torch.int64)\n seq_range_expand = seq_range.unsqueeze(0).expand(bs, maxlen)\n seq_length_expand = seq_range_expand.new(lengths).unsqueeze(-1)\n mask = seq_range_expand >= seq_length_expand\n\n if xs is not None:\n assert xs.size(0) == bs, (xs.size(0), bs)\n\n if length_dim < 0:\n length_dim = xs.dim() + length_dim\n # ind = (:, None, ..., None, :, , None, ..., None)\n ind = tuple(\n slice(None) if i in (0, length_dim) else None for i in range(xs.dim())\n )\n mask = mask[ind].expand_as(xs).to(xs.device)\n return mask" }, { "identifier": "MultiHeadedAttention", "path": "funcodec/modules/attention.py", "snippet": "class MultiHeadedAttention(nn.Module):\n \"\"\"Multi-Head Attention layer.\n\n Args:\n n_head (int): The number of heads.\n n_feat (int): The number of features.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n\n def __init__(self, n_head, n_feat, dropout_rate):\n \"\"\"Construct an MultiHeadedAttention object.\"\"\"\n super(MultiHeadedAttention, self).__init__()\n assert n_feat % n_head == 0\n # We assume d_v always equals d_k\n self.d_k = n_feat // n_head\n self.h = n_head\n self.linear_q = nn.Linear(n_feat, n_feat)\n self.linear_k = nn.Linear(n_feat, n_feat)\n self.linear_v = nn.Linear(n_feat, n_feat)\n self.linear_out = nn.Linear(n_feat, n_feat)\n self.attn = None\n self.dropout = nn.Dropout(p=dropout_rate)\n\n def forward_qkv(self, query, key, value):\n \"\"\"Transform query, key and value.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n\n Returns:\n torch.Tensor: Transformed query tensor (#batch, n_head, time1, d_k).\n torch.Tensor: Transformed key tensor (#batch, n_head, time2, d_k).\n torch.Tensor: Transformed value tensor (#batch, n_head, time2, d_k).\n\n \"\"\"\n n_batch = query.size(0)\n q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)\n k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)\n v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)\n q = q.transpose(1, 2) # (batch, head, time1, d_k)\n k = k.transpose(1, 2) # (batch, head, time2, d_k)\n v = v.transpose(1, 2) # (batch, head, time2, d_k)\n\n return q, k, v\n\n def forward_attention(self, value, scores, mask):\n \"\"\"Compute attention context vector.\n\n Args:\n value (torch.Tensor): Transformed value (#batch, n_head, time2, d_k).\n scores (torch.Tensor): Attention score (#batch, n_head, time1, time2).\n mask (torch.Tensor): Mask (#batch, 1, time2) or (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Transformed value (#batch, time1, d_model)\n weighted by the attention score (#batch, time1, time2).\n\n \"\"\"\n n_batch = value.size(0)\n if mask is not None:\n mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2)\n min_value = float(\n numpy.finfo(torch.tensor(0, dtype=scores.dtype).numpy().dtype).min\n )\n scores = scores.masked_fill(mask, min_value)\n self.attn = torch.softmax(scores, dim=-1).masked_fill(\n mask, 0.0\n ) # (batch, head, time1, time2)\n else:\n self.attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)\n\n p_attn = self.dropout(self.attn)\n x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)\n x = (\n x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k)\n ) # (batch, time1, d_model)\n\n return self.linear_out(x) # (batch, time1, d_model)\n\n def forward(self, query, key, value, mask):\n \"\"\"Compute scaled dot product attention.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\n (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Output tensor (#batch, time1, d_model).\n\n \"\"\"\n q, k, v = self.forward_qkv(query, key, value)\n scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)\n return self.forward_attention(v, scores, mask)" }, { "identifier": "MultiHeadedAttentionSANM", "path": "funcodec/modules/attention.py", "snippet": "class MultiHeadedAttentionSANM(nn.Module):\n \"\"\"Multi-Head Attention layer.\n\n Args:\n n_head (int): The number of heads.\n n_feat (int): The number of features.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n\n def __init__(self, n_head, in_feat, n_feat, dropout_rate, kernel_size, sanm_shfit=0):\n \"\"\"Construct an MultiHeadedAttention object.\"\"\"\n super(MultiHeadedAttentionSANM, self).__init__()\n assert n_feat % n_head == 0\n # We assume d_v always equals d_k\n self.d_k = n_feat // n_head\n self.h = n_head\n # self.linear_q = nn.Linear(n_feat, n_feat)\n # self.linear_k = nn.Linear(n_feat, n_feat)\n # self.linear_v = nn.Linear(n_feat, n_feat)\n self.linear_out = nn.Linear(n_feat, n_feat)\n self.linear_q_k_v = nn.Linear(in_feat, n_feat * 3)\n self.attn = None\n self.dropout = nn.Dropout(p=dropout_rate)\n\n self.fsmn_block = nn.Conv1d(n_feat, n_feat, kernel_size, stride=1, padding=0, groups=n_feat, bias=False)\n # padding\n left_padding = (kernel_size - 1) // 2\n if sanm_shfit > 0:\n left_padding = left_padding + sanm_shfit\n right_padding = kernel_size - 1 - left_padding\n self.pad_fn = nn.ConstantPad1d((left_padding, right_padding), 0.0)\n\n def forward_fsmn(self, inputs, mask, mask_shfit_chunk=None):\n b, t, d = inputs.size()\n if mask is not None:\n mask = torch.reshape(mask, (b, -1, 1))\n if mask_shfit_chunk is not None:\n mask = mask * mask_shfit_chunk\n\n inputs = inputs * mask\n x = inputs.transpose(1, 2)\n x = self.pad_fn(x)\n x = self.fsmn_block(x)\n x = x.transpose(1, 2)\n x += inputs\n x = self.dropout(x)\n return x * mask\n\n def forward_qkv(self, x):\n \"\"\"Transform query, key and value.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n\n Returns:\n torch.Tensor: Transformed query tensor (#batch, n_head, time1, d_k).\n torch.Tensor: Transformed key tensor (#batch, n_head, time2, d_k).\n torch.Tensor: Transformed value tensor (#batch, n_head, time2, d_k).\n\n \"\"\"\n b, t, d = x.size()\n q_k_v = self.linear_q_k_v(x)\n q, k, v = torch.split(q_k_v, int(self.h * self.d_k), dim=-1)\n q_h = torch.reshape(q, (b, t, self.h, self.d_k)).transpose(1, 2) # (batch, head, time1, d_k)\n k_h = torch.reshape(k, (b, t, self.h, self.d_k)).transpose(1, 2) # (batch, head, time2, d_k)\n v_h = torch.reshape(v, (b, t, self.h, self.d_k)).transpose(1, 2) # (batch, head, time2, d_k)\n\n return q_h, k_h, v_h, v\n\n def forward_attention(self, value, scores, mask, mask_att_chunk_encoder=None):\n \"\"\"Compute attention context vector.\n\n Args:\n value (torch.Tensor): Transformed value (#batch, n_head, time2, d_k).\n scores (torch.Tensor): Attention score (#batch, n_head, time1, time2).\n mask (torch.Tensor): Mask (#batch, 1, time2) or (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Transformed value (#batch, time1, d_model)\n weighted by the attention score (#batch, time1, time2).\n\n \"\"\"\n n_batch = value.size(0)\n if mask is not None:\n if mask_att_chunk_encoder is not None:\n mask = mask * mask_att_chunk_encoder\n\n mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2)\n\n min_value = float(\n numpy.finfo(torch.tensor(0, dtype=scores.dtype).numpy().dtype).min\n )\n scores = scores.masked_fill(mask, min_value)\n self.attn = torch.softmax(scores, dim=-1).masked_fill(\n mask, 0.0\n ) # (batch, head, time1, time2)\n else:\n self.attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)\n\n p_attn = self.dropout(self.attn)\n x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)\n x = (\n x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k)\n ) # (batch, time1, d_model)\n\n return self.linear_out(x) # (batch, time1, d_model)\n\n def forward(self, x, mask, mask_shfit_chunk=None, mask_att_chunk_encoder=None):\n \"\"\"Compute scaled dot product attention.\n\n Args:\n query (torch.Tensor): Query tensor (#batch, time1, size).\n key (torch.Tensor): Key tensor (#batch, time2, size).\n value (torch.Tensor): Value tensor (#batch, time2, size).\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\n (#batch, time1, time2).\n\n Returns:\n torch.Tensor: Output tensor (#batch, time1, d_model).\n\n \"\"\"\n q_h, k_h, v_h, v = self.forward_qkv(x)\n fsmn_memory = self.forward_fsmn(v, mask, mask_shfit_chunk)\n q_h = q_h * self.d_k ** (-0.5)\n scores = torch.matmul(q_h, k_h.transpose(-2, -1))\n att_outs = self.forward_attention(v_h, scores, mask, mask_att_chunk_encoder)\n return att_outs + fsmn_memory" }, { "identifier": "SinusoidalPositionEncoder", "path": "funcodec/modules/embedding.py", "snippet": "class SinusoidalPositionEncoder(torch.nn.Module):\n '''\n\n '''\n def __int__(self, d_model=80, dropout_rate=0.1):\n pass\n\n def encode(self, positions: torch.Tensor = None, depth: int = None, dtype: torch.dtype = torch.float32):\n batch_size = positions.size(0)\n positions = positions.type(dtype)\n log_timescale_increment = torch.log(torch.tensor([10000], dtype=dtype)) / (depth / 2 - 1)\n inv_timescales = torch.exp(torch.arange(depth / 2).type(dtype) * (-log_timescale_increment))\n inv_timescales = torch.reshape(inv_timescales, [batch_size, -1])\n scaled_time = torch.reshape(positions, [1, -1, 1]) * torch.reshape(inv_timescales, [1, 1, -1])\n encoding = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=2)\n return encoding.type(dtype)\n\n def forward(self, x):\n batch_size, timesteps, input_dim = x.size()\n positions = torch.arange(1, timesteps+1)[None, :]\n position_encoding = self.encode(positions, input_dim, x.dtype).to(x.device)\n\n return x + position_encoding" }, { "identifier": "LayerNorm", "path": "funcodec/modules/layer_norm.py", "snippet": "class LayerNorm(torch.nn.LayerNorm):\n \"\"\"Layer normalization module.\n\n Args:\n nout (int): Output dim size.\n dim (int): Dimension to be normalized.\n\n \"\"\"\n\n def __init__(self, nout, dim=-1):\n \"\"\"Construct an LayerNorm object.\"\"\"\n super(LayerNorm, self).__init__(nout, eps=1e-12)\n self.dim = dim\n\n def forward(self, x):\n \"\"\"Apply layer normalization.\n\n Args:\n x (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Normalized tensor.\n\n \"\"\"\n if self.dim == -1:\n return super(LayerNorm, self).forward(x)\n return (\n super(LayerNorm, self)\n .forward(x.transpose(self.dim, -1))\n .transpose(self.dim, -1)\n )" }, { "identifier": "Conv1dLinear", "path": "funcodec/modules/multi_layer_conv.py", "snippet": "class Conv1dLinear(torch.nn.Module):\n \"\"\"Conv1D + Linear for Transformer block.\n\n A variant of MultiLayeredConv1d, which replaces second conv-layer to linear.\n\n \"\"\"\n\n def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):\n \"\"\"Initialize Conv1dLinear module.\n\n Args:\n in_chans (int): Number of input channels.\n hidden_chans (int): Number of hidden channels.\n kernel_size (int): Kernel size of conv1d.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n super(Conv1dLinear, self).__init__()\n self.w_1 = torch.nn.Conv1d(\n in_chans,\n hidden_chans,\n kernel_size,\n stride=1,\n padding=(kernel_size - 1) // 2,\n )\n self.w_2 = torch.nn.Linear(hidden_chans, in_chans)\n self.dropout = torch.nn.Dropout(dropout_rate)\n\n def forward(self, x):\n \"\"\"Calculate forward propagation.\n\n Args:\n x (torch.Tensor): Batch of input tensors (B, T, in_chans).\n\n Returns:\n torch.Tensor: Batch of output tensors (B, T, hidden_chans).\n\n \"\"\"\n x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)\n return self.w_2(self.dropout(x))" }, { "identifier": "MultiLayeredConv1d", "path": "funcodec/modules/multi_layer_conv.py", "snippet": "class MultiLayeredConv1d(torch.nn.Module):\n \"\"\"Multi-layered conv1d for Transformer block.\n\n This is a module of multi-leyered conv1d designed\n to replace positionwise feed-forward network\n in Transforner block, which is introduced in\n `FastSpeech: Fast, Robust and Controllable Text to Speech`_.\n\n .. _`FastSpeech: Fast, Robust and Controllable Text to Speech`:\n https://arxiv.org/pdf/1905.09263.pdf\n\n \"\"\"\n\n def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):\n \"\"\"Initialize MultiLayeredConv1d module.\n\n Args:\n in_chans (int): Number of input channels.\n hidden_chans (int): Number of hidden channels.\n kernel_size (int): Kernel size of conv1d.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n super(MultiLayeredConv1d, self).__init__()\n self.w_1 = torch.nn.Conv1d(\n in_chans,\n hidden_chans,\n kernel_size,\n stride=1,\n padding=(kernel_size - 1) // 2,\n )\n self.w_2 = torch.nn.Conv1d(\n hidden_chans,\n in_chans,\n kernel_size,\n stride=1,\n padding=(kernel_size - 1) // 2,\n )\n self.dropout = torch.nn.Dropout(dropout_rate)\n\n def forward(self, x):\n \"\"\"Calculate forward propagation.\n\n Args:\n x (torch.Tensor): Batch of input tensors (B, T, in_chans).\n\n Returns:\n torch.Tensor: Batch of output tensors (B, T, hidden_chans).\n\n \"\"\"\n x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)\n return self.w_2(self.dropout(x).transpose(-1, 1)).transpose(-1, 1)" }, { "identifier": "PositionwiseFeedForward", "path": "funcodec/modules/positionwise_feed_forward.py", "snippet": "class PositionwiseFeedForward(torch.nn.Module):\n \"\"\"Positionwise feed forward layer.\n\n Args:\n idim (int): Input dimenstion.\n hidden_units (int): The number of hidden units.\n dropout_rate (float): Dropout rate.\n\n \"\"\"\n\n def __init__(self, idim, hidden_units, dropout_rate, activation=torch.nn.ReLU()):\n \"\"\"Construct an PositionwiseFeedForward object.\"\"\"\n super(PositionwiseFeedForward, self).__init__()\n self.w_1 = torch.nn.Linear(idim, hidden_units)\n self.w_2 = torch.nn.Linear(hidden_units, idim)\n self.dropout = torch.nn.Dropout(dropout_rate)\n self.activation = activation\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n return self.w_2(self.dropout(self.activation(self.w_1(x))))" }, { "identifier": "repeat", "path": "funcodec/modules/repeat.py", "snippet": "def repeat(N, fn):\n \"\"\"Repeat module N times.\n\n Args:\n N (int): Number of repeat time.\n fn (Callable): Function to generate module.\n\n Returns:\n MultiSequential: Repeated model instance.\n\n \"\"\"\n return MultiSequential(*[fn(n) for n in range(N)])" }, { "identifier": "Conv2dSubsampling", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/4 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling object.\"\"\"\n super(Conv2dSubsampling, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 2),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 4.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 4.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-2:2]\n\n def __getitem__(self, key):\n \"\"\"Get item.\n\n When reset_parameters() is called, if use_scaled_pos_enc is used,\n return the positioning encoding.\n\n \"\"\"\n if key != -1:\n raise NotImplementedError(\"Support only `-1` (for `reset_parameters`).\")\n return self.out[key]" }, { "identifier": "Conv2dSubsampling2", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling2(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/2 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling2 object.\"\"\"\n super(Conv2dSubsampling2, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 1),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * (((idim - 1) // 2 - 2)), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 2.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 2.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-2:1]\n\n def __getitem__(self, key):\n \"\"\"Get item.\n\n When reset_parameters() is called, if use_scaled_pos_enc is used,\n return the positioning encoding.\n\n \"\"\"\n if key != -1:\n raise NotImplementedError(\"Support only `-1` (for `reset_parameters`).\")\n return self.out[key]" }, { "identifier": "Conv2dSubsampling6", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling6(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/6 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling6 object.\"\"\"\n super(Conv2dSubsampling6, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 5, 3),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * (((idim - 1) // 2 - 2) // 3), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 6.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 6.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-4:3]" }, { "identifier": "Conv2dSubsampling8", "path": "funcodec/modules/subsampling.py", "snippet": "class Conv2dSubsampling8(torch.nn.Module):\n \"\"\"Convolutional 2D subsampling (to 1/8 length).\n\n Args:\n idim (int): Input dimension.\n odim (int): Output dimension.\n dropout_rate (float): Dropout rate.\n pos_enc (torch.nn.Module): Custom position encoding layer.\n\n \"\"\"\n\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\n \"\"\"Construct an Conv2dSubsampling8 object.\"\"\"\n super(Conv2dSubsampling8, self).__init__()\n self.conv = torch.nn.Sequential(\n torch.nn.Conv2d(1, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 2),\n torch.nn.ReLU(),\n torch.nn.Conv2d(odim, odim, 3, 2),\n torch.nn.ReLU(),\n )\n self.out = torch.nn.Sequential(\n torch.nn.Linear(odim * ((((idim - 1) // 2 - 1) // 2 - 1) // 2), odim),\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\n )\n\n def forward(self, x, x_mask):\n \"\"\"Subsample x.\n\n Args:\n x (torch.Tensor): Input tensor (#batch, time, idim).\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\n\n Returns:\n torch.Tensor: Subsampled tensor (#batch, time', odim),\n where time' = time // 8.\n torch.Tensor: Subsampled mask (#batch, 1, time'),\n where time' = time // 8.\n\n \"\"\"\n x = x.unsqueeze(1) # (b, c, t, f)\n x = self.conv(x)\n b, c, t, f = x.size()\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\n if x_mask is None:\n return x, None\n return x, x_mask[:, :, :-2:2][:, :, :-2:2][:, :, :-2:2]" }, { "identifier": "TooShortUttError", "path": "funcodec/modules/subsampling.py", "snippet": "class TooShortUttError(Exception):\n \"\"\"Raised when the utt is too short for subsampling.\n\n Args:\n message (str): Message for error catch\n actual_size (int): the short size that cannot pass the subsampling\n limit (int): the limit size for subsampling\n\n \"\"\"\n\n def __init__(self, message, actual_size, limit):\n \"\"\"Construct a TooShortUttError for error handler.\"\"\"\n super().__init__(message)\n self.actual_size = actual_size\n self.limit = limit" }, { "identifier": "check_short_utt", "path": "funcodec/modules/subsampling.py", "snippet": "def check_short_utt(ins, size):\n \"\"\"Check if the utterance is too short for subsampling.\"\"\"\n if isinstance(ins, Conv2dSubsampling2) and size < 3:\n return True, 3\n if isinstance(ins, Conv2dSubsampling) and size < 7:\n return True, 7\n if isinstance(ins, Conv2dSubsampling6) and size < 11:\n return True, 11\n if isinstance(ins, Conv2dSubsampling8) and size < 15:\n return True, 15\n return False, -1" }, { "identifier": "AbsEncoder", "path": "funcodec/models/encoder/abs_encoder.py", "snippet": "class AbsEncoder(torch.nn.Module, ABC):\n @abstractmethod\n def output_size(self) -> int:\n raise NotImplementedError\n\n @abstractmethod\n def forward(\n self,\n xs_pad: torch.Tensor,\n ilens: torch.Tensor,\n prev_states: torch.Tensor = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:\n raise NotImplementedError" } ]
from typing import List from typing import Optional from typing import Sequence from typing import Tuple from typing import Union from funcodec.modules.streaming_utils.chunk_utilis import overlap_chunk from funcodec.modules.nets_utils import make_pad_mask from funcodec.modules.attention import MultiHeadedAttention, MultiHeadedAttentionSANM from funcodec.modules.embedding import SinusoidalPositionEncoder from funcodec.modules.layer_norm import LayerNorm from funcodec.modules.multi_layer_conv import Conv1dLinear from funcodec.modules.multi_layer_conv import MultiLayeredConv1d from funcodec.modules.positionwise_feed_forward import ( PositionwiseFeedForward, # noqa: H301 ) from funcodec.modules.repeat import repeat from funcodec.modules.subsampling import Conv2dSubsampling from funcodec.modules.subsampling import Conv2dSubsampling2 from funcodec.modules.subsampling import Conv2dSubsampling6 from funcodec.modules.subsampling import Conv2dSubsampling8 from funcodec.modules.subsampling import TooShortUttError from funcodec.modules.subsampling import check_short_utt from funcodec.models.encoder.abs_encoder import AbsEncoder import logging import torch import torch.nn as nn import numpy as np
14,431
if self.in_size == self.size: x = residual + stoch_layer_coeff * self.concat_linear(x_concat) else: x = stoch_layer_coeff * self.concat_linear(x_concat) else: if self.in_size == self.size: x = residual + stoch_layer_coeff * self.dropout( self.self_attn(x, mask, mask_shfit_chunk=mask_shfit_chunk, mask_att_chunk_encoder=mask_att_chunk_encoder) ) else: x = stoch_layer_coeff * self.dropout( self.self_attn(x, mask, mask_shfit_chunk=mask_shfit_chunk, mask_att_chunk_encoder=mask_att_chunk_encoder) ) if not self.normalize_before: x = self.norm1(x) residual = x if self.normalize_before: x = self.norm2(x) x = residual + stoch_layer_coeff * self.dropout(self.feed_forward(x)) if not self.normalize_before: x = self.norm2(x) return x, mask, cache, mask_shfit_chunk, mask_att_chunk_encoder class SANMEncoder(AbsEncoder): """ author: Speech Lab, Alibaba Group, China San-m: Memory equipped self-attention for end-to-end speech recognition https://arxiv.org/abs/2006.01713 """ def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, input_layer: Optional[str] = "conv2d", pos_enc_class=SinusoidalPositionEncoder, normalize_before: bool = True, concat_after: bool = False, positionwise_layer_type: str = "linear", positionwise_conv_kernel_size: int = 1, padding_idx: int = -1, interctc_layer_idx: List[int] = [], interctc_use_conditioning: bool = False, kernel_size : int = 11, sanm_shfit : int = 0, selfattention_layer_type: str = "sanm", tf2torch_tensor_name_prefix_torch: str = "encoder", tf2torch_tensor_name_prefix_tf: str = "seq2seq/encoder", ): super().__init__() self._output_size = output_size if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(input_size, output_size), torch.nn.LayerNorm(output_size), torch.nn.Dropout(dropout_rate), torch.nn.ReLU(), pos_enc_class(output_size, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling(input_size, output_size, dropout_rate) elif input_layer == "conv2d2": self.embed = Conv2dSubsampling2(input_size, output_size, dropout_rate) elif input_layer == "conv2d6": self.embed = Conv2dSubsampling6(input_size, output_size, dropout_rate) elif input_layer == "conv2d8": self.embed = Conv2dSubsampling8(input_size, output_size, dropout_rate) elif input_layer == "embed": self.embed = torch.nn.Sequential( torch.nn.Embedding(input_size, output_size, padding_idx=padding_idx), SinusoidalPositionEncoder(), ) elif input_layer is None: if input_size == output_size: self.embed = None else: self.embed = torch.nn.Linear(input_size, output_size) elif input_layer == "pe": self.embed = SinusoidalPositionEncoder() else: raise ValueError("unknown input_layer: " + input_layer) self.normalize_before = normalize_before if positionwise_layer_type == "linear": positionwise_layer = PositionwiseFeedForward positionwise_layer_args = ( output_size, linear_units, dropout_rate, ) elif positionwise_layer_type == "conv1d": positionwise_layer = MultiLayeredConv1d positionwise_layer_args = ( output_size, linear_units, positionwise_conv_kernel_size, dropout_rate, ) elif positionwise_layer_type == "conv1d-linear": positionwise_layer = Conv1dLinear positionwise_layer_args = ( output_size, linear_units, positionwise_conv_kernel_size, dropout_rate, ) else: raise NotImplementedError("Support only linear or conv1d.") if selfattention_layer_type == "selfattn":
class EncoderLayerSANM(nn.Module): def __init__( self, in_size, size, self_attn, feed_forward, dropout_rate, normalize_before=True, concat_after=False, stochastic_depth_rate=0.0, ): """Construct an EncoderLayer object.""" super(EncoderLayerSANM, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.norm1 = LayerNorm(in_size) self.norm2 = LayerNorm(size) self.dropout = nn.Dropout(dropout_rate) self.in_size = in_size self.size = size self.normalize_before = normalize_before self.concat_after = concat_after if self.concat_after: self.concat_linear = nn.Linear(size + size, size) self.stochastic_depth_rate = stochastic_depth_rate self.dropout_rate = dropout_rate def forward(self, x, mask, cache=None, mask_shfit_chunk=None, mask_att_chunk_encoder=None): """Compute encoded features. Args: x_input (torch.Tensor): Input tensor (#batch, time, size). mask (torch.Tensor): Mask tensor for the input (#batch, time). cache (torch.Tensor): Cache tensor of the input (#batch, time - 1, size). Returns: torch.Tensor: Output tensor (#batch, time, size). torch.Tensor: Mask tensor (#batch, time). """ skip_layer = False # with stochastic depth, residual connection `x + f(x)` becomes # `x <- x + 1 / (1 - p) * f(x)` at training time. stoch_layer_coeff = 1.0 if self.training and self.stochastic_depth_rate > 0: skip_layer = torch.rand(1).item() < self.stochastic_depth_rate stoch_layer_coeff = 1.0 / (1 - self.stochastic_depth_rate) if skip_layer: if cache is not None: x = torch.cat([cache, x], dim=1) return x, mask residual = x if self.normalize_before: x = self.norm1(x) if self.concat_after: x_concat = torch.cat((x, self.self_attn(x, mask, mask_shfit_chunk=mask_shfit_chunk, mask_att_chunk_encoder=mask_att_chunk_encoder)), dim=-1) if self.in_size == self.size: x = residual + stoch_layer_coeff * self.concat_linear(x_concat) else: x = stoch_layer_coeff * self.concat_linear(x_concat) else: if self.in_size == self.size: x = residual + stoch_layer_coeff * self.dropout( self.self_attn(x, mask, mask_shfit_chunk=mask_shfit_chunk, mask_att_chunk_encoder=mask_att_chunk_encoder) ) else: x = stoch_layer_coeff * self.dropout( self.self_attn(x, mask, mask_shfit_chunk=mask_shfit_chunk, mask_att_chunk_encoder=mask_att_chunk_encoder) ) if not self.normalize_before: x = self.norm1(x) residual = x if self.normalize_before: x = self.norm2(x) x = residual + stoch_layer_coeff * self.dropout(self.feed_forward(x)) if not self.normalize_before: x = self.norm2(x) return x, mask, cache, mask_shfit_chunk, mask_att_chunk_encoder class SANMEncoder(AbsEncoder): """ author: Speech Lab, Alibaba Group, China San-m: Memory equipped self-attention for end-to-end speech recognition https://arxiv.org/abs/2006.01713 """ def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, input_layer: Optional[str] = "conv2d", pos_enc_class=SinusoidalPositionEncoder, normalize_before: bool = True, concat_after: bool = False, positionwise_layer_type: str = "linear", positionwise_conv_kernel_size: int = 1, padding_idx: int = -1, interctc_layer_idx: List[int] = [], interctc_use_conditioning: bool = False, kernel_size : int = 11, sanm_shfit : int = 0, selfattention_layer_type: str = "sanm", tf2torch_tensor_name_prefix_torch: str = "encoder", tf2torch_tensor_name_prefix_tf: str = "seq2seq/encoder", ): super().__init__() self._output_size = output_size if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(input_size, output_size), torch.nn.LayerNorm(output_size), torch.nn.Dropout(dropout_rate), torch.nn.ReLU(), pos_enc_class(output_size, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling(input_size, output_size, dropout_rate) elif input_layer == "conv2d2": self.embed = Conv2dSubsampling2(input_size, output_size, dropout_rate) elif input_layer == "conv2d6": self.embed = Conv2dSubsampling6(input_size, output_size, dropout_rate) elif input_layer == "conv2d8": self.embed = Conv2dSubsampling8(input_size, output_size, dropout_rate) elif input_layer == "embed": self.embed = torch.nn.Sequential( torch.nn.Embedding(input_size, output_size, padding_idx=padding_idx), SinusoidalPositionEncoder(), ) elif input_layer is None: if input_size == output_size: self.embed = None else: self.embed = torch.nn.Linear(input_size, output_size) elif input_layer == "pe": self.embed = SinusoidalPositionEncoder() else: raise ValueError("unknown input_layer: " + input_layer) self.normalize_before = normalize_before if positionwise_layer_type == "linear": positionwise_layer = PositionwiseFeedForward positionwise_layer_args = ( output_size, linear_units, dropout_rate, ) elif positionwise_layer_type == "conv1d": positionwise_layer = MultiLayeredConv1d positionwise_layer_args = ( output_size, linear_units, positionwise_conv_kernel_size, dropout_rate, ) elif positionwise_layer_type == "conv1d-linear": positionwise_layer = Conv1dLinear positionwise_layer_args = ( output_size, linear_units, positionwise_conv_kernel_size, dropout_rate, ) else: raise NotImplementedError("Support only linear or conv1d.") if selfattention_layer_type == "selfattn":
encoder_selfattn_layer = MultiHeadedAttention
2
2023-10-07 02:00:40+00:00
24k
Beckschen/3D-TransUNet
nn_transunet/trainer/nnUNetTrainerV2.py
[ { "identifier": "get_moreDA_augmentation", "path": "nn_transunet/data/data_augmentation_moreDA.py", "snippet": "def get_moreDA_augmentation(dataloader_train, dataloader_val, patch_size, params=default_3D_augmentation_params,\n border_val_seg=-1,\n seeds_train=None, seeds_val=None, order_seg=1, order_data=3, deep_supervision_scales=None,\n soft_ds=False,\n classes=None, pin_memory=True, regions=None,\n use_nondetMultiThreadedAugmenter: bool = False,\n is_spatial_aug_only=False, reclip=None):\n\n # default_3D_augmentation_params: {'selected_data_channels': None, 'selected_seg_channels': [0], 'do_elastic': False, 'elastic_deform_alpha': (0.0, 900.0), 'elastic_deform_sigma': (9.0, 13.0), 'p_eldef': 0.2, 'do_scaling': True, 'scale_range': (0.7, 1.4), 'independent_scale_factor_for_each_axis': False, 'p_independent_scale_per_axis': 1, 'p_scale': 0.2, 'do_rotation': True, 'rotation_x': (-0.5235987755982988, 0.5235987755982988), 'rotation_y': (-0.5235987755982988, 0.5235987755982988), 'rotation_z': (-0.5235987755982988, 0.5235987755982988), 'rotation_p_per_axis': 1, 'p_rot': 0.2, 'random_crop': False, 'random_crop_dist_to_border': None, 'do_gamma': True, 'gamma_retain_stats': True, 'gamma_range': (0.7, 1.5), 'p_gamma': 0.3, 'do_mirror': True, 'mirror_axes': (0, 1, 2), 'dummy_2D': False, 'mask_was_used_for_normalization': OrderedDict([(0, False)]), 'border_mode_data': 'constant', 'all_segmentation_labels': None, 'move_last_seg_chanel_to_data': False, 'cascade_do_cascade_augmentations': False, 'cascade_random_binary_transform_p': 0.4, 'cascade_random_binary_transform_p_per_label': 1, 'cascade_random_binary_transform_size': (1, 8), 'cascade_remove_conn_comp_p': 0.2, 'cascade_remove_conn_comp_max_size_percent_threshold': 0.15, 'cascade_remove_conn_comp_fill_with_other_class_p': 0.0, 'do_additive_brightness': False, 'additive_brightness_p_per_sample': 0.15, 'additive_brightness_p_per_channel': 0.5, 'additive_brightness_mu': 0.0, 'additive_brightness_sigma': 0.1, 'num_threads': 12, 'num_cached_per_thread': 2, 'patch_size_for_spatialtransform': [64, 128, 128]} \n\n assert params.get('mirror') is None, \"old version of params, use new keyword do_mirror\"\n\n tr_transforms = []\n\n\n if params.get(\"selected_data_channels\") is not None:\n tr_transforms.append(DataChannelSelectionTransform(params.get(\"selected_data_channels\")))\n\n if params.get(\"selected_seg_channels\") is not None:\n tr_transforms.append(SegChannelSelectionTransform(params.get(\"selected_seg_channels\")))\n\n # don't do color augmentations while in 2d mode with 3d data because the color channel is overloaded!!\n if params.get(\"dummy_2D\") is not None and params.get(\"dummy_2D\"):\n ignore_axes = (0,)\n tr_transforms.append(Convert3DTo2DTransform())\n patch_size_spatial = patch_size[1:]\n else:\n patch_size_spatial = patch_size\n ignore_axes = None\n\n tr_transforms.append(SpatialTransform(\n patch_size_spatial, patch_center_dist_from_border=None,\n do_elastic_deform=params.get(\"do_elastic\"), alpha=params.get(\"elastic_deform_alpha\"),\n sigma=params.get(\"elastic_deform_sigma\"),\n do_rotation=params.get(\"do_rotation\"), angle_x=params.get(\"rotation_x\"), angle_y=params.get(\"rotation_y\"),\n angle_z=params.get(\"rotation_z\"), p_rot_per_axis=params.get(\"rotation_p_per_axis\"),\n do_scale=params.get(\"do_scaling\"), scale=params.get(\"scale_range\"),\n border_mode_data=params.get(\"border_mode_data\"), border_cval_data=0, order_data=order_data,\n border_mode_seg=\"constant\", border_cval_seg=border_val_seg,\n order_seg=order_seg, random_crop=params.get(\"random_crop\"), p_el_per_sample=params.get(\"p_eldef\"),\n p_scale_per_sample=params.get(\"p_scale\"), p_rot_per_sample=params.get(\"p_rot\"),\n independent_scale_for_each_axis=params.get(\"independent_scale_factor_for_each_axis\")\n ))\n\n if params.get(\"dummy_2D\"):\n tr_transforms.append(Convert2DTo3DTransform())\n\n # we need to put the color augmentations after the dummy 2d part (if applicable). Otherwise the overloaded color\n # channel gets in the way\n tr_transforms.append(GaussianNoiseTransform(p_per_sample=0.1)) # a kind of noise transform\n tr_transforms.append(GaussianBlurTransform((0.5, 1.), different_sigma_per_channel=True, p_per_sample=0.2, p_per_channel=0.5))\n tr_transforms.append(BrightnessMultiplicativeTransform(multiplier_range=(0.75, 1.25), p_per_sample=0.15))\n\n if params.get(\"do_additive_brightness\"):\n tr_transforms.append(BrightnessTransform(params.get(\"additive_brightness_mu\"),\n params.get(\"additive_brightness_sigma\"),\n True, p_per_sample=params.get(\"additive_brightness_p_per_sample\"),\n p_per_channel=params.get(\"additive_brightness_p_per_channel\")))\n\n tr_transforms.append(ContrastAugmentationTransform(p_per_sample=0.15))\n tr_transforms.append(SimulateLowResolutionTransform(zoom_range=(0.5, 1), per_channel=True,\n p_per_channel=0.5,\n order_downsample=0, order_upsample=3, p_per_sample=0.25,\n ignore_axes=ignore_axes))\n tr_transforms.append(\n GammaTransform(params.get(\"gamma_range\"), True, True, retain_stats=params.get(\"gamma_retain_stats\"),\n p_per_sample=0.1)) # inverted gamma, a kind of color transform\n\n if params.get(\"do_gamma\"):\n tr_transforms.append(\n GammaTransform(params.get(\"gamma_range\"), False, True, retain_stats=params.get(\"gamma_retain_stats\"),\n p_per_sample=params[\"p_gamma\"]))\n if params.get(\"do_mirror\") or params.get(\"mirror\"):\n tr_transforms.append(MirrorTransform(params.get(\"mirror_axes\")))\n\n if params.get(\"mask_was_used_for_normalization\") is not None:\n mask_was_used_for_normalization = params.get(\"mask_was_used_for_normalization\")\n tr_transforms.append(MaskTransform(mask_was_used_for_normalization, mask_idx_in_seg=0, set_outside_to=0))\n # Replaces all pixels in data_dict[input_key] that have value remove_label with replace_with and saves the result to data_dict[output_key]\n tr_transforms.append(RemoveLabelTransform(-1, 0))\n\n if params.get(\"move_last_seg_chanel_to_data\") is not None and params.get(\"move_last_seg_chanel_to_data\"): # only used for cascade\n print(\"only used for cascaded!\")\n raise NotImplementedError\n\n tr_transforms.append(RenameTransform('seg', 'target', True))\n\n if regions is not None:\n tr_transforms.append(ConvertSegmentationToRegionsTransform(regions, 'target', 'target'))\n\n if deep_supervision_scales is not None:\n if soft_ds:\n assert classes is not None\n tr_transforms.append(DownsampleSegForDSTransform3(deep_supervision_scales, 'target', 'target', classes))\n else:\n tr_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, input_key='target',\n output_key='target'))\n\n tr_transforms.append(NumpyToTensor(['data', 'target'], 'float'))\n tr_transforms = Compose(tr_transforms)\n\n if use_nondetMultiThreadedAugmenter:\n if NonDetMultiThreadedAugmenter is None:\n raise RuntimeError('NonDetMultiThreadedAugmenter is not yet available')\n batchgenerator_train = NonDetMultiThreadedAugmenter(dataloader_train, tr_transforms, params.get('num_threads'),\n params.get(\"num_cached_per_thread\"), seeds=seeds_train,\n pin_memory=pin_memory)\n else:\n batchgenerator_train = MultiThreadedAugmenter(dataloader_train, tr_transforms, params.get('num_threads'),\n params.get(\"num_cached_per_thread\"),\n seeds=seeds_train, pin_memory=pin_memory)\n # batchgenerator_train = SingleThreadedAugmenter(dataloader_train, tr_transforms)\n # import IPython;IPython.embed()\n\n val_transforms = []\n val_transforms.append(RemoveLabelTransform(-1, 0))\n if params.get(\"selected_data_channels\") is not None:\n val_transforms.append(DataChannelSelectionTransform(params.get(\"selected_data_channels\")))\n if params.get(\"selected_seg_channels\") is not None:\n val_transforms.append(SegChannelSelectionTransform(params.get(\"selected_seg_channels\")))\n\n if params.get(\"move_last_seg_chanel_to_data\") is not None and params.get(\"move_last_seg_chanel_to_data\"):\n print(\"only used for cascaded!\")\n raise NotImplementedError\n # val_transforms.append(MoveSegAsOneHotToData(1, params.get(\"all_segmentation_labels\"), 'seg', 'data'))\n\n\n val_transforms.append(RenameTransform('seg', 'target', True))\n\n if regions is not None:\n val_transforms.append(ConvertSegmentationToRegionsTransform(regions, 'target', 'target'))\n\n if deep_supervision_scales is not None:\n if soft_ds:\n assert classes is not None\n val_transforms.append(DownsampleSegForDSTransform3(deep_supervision_scales, 'target', 'target', classes))\n else:\n val_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, input_key='target',\n output_key='target'))\n\n val_transforms.append(NumpyToTensor(['data', 'target'], 'float'))\n val_transforms = Compose(val_transforms)\n\n if use_nondetMultiThreadedAugmenter:\n if NonDetMultiThreadedAugmenter is None:\n raise RuntimeError('NonDetMultiThreadedAugmenter is not yet available')\n batchgenerator_val = NonDetMultiThreadedAugmenter(dataloader_val, val_transforms,\n max(params.get('num_threads') // 2, 1),\n params.get(\"num_cached_per_thread\"),\n seeds=seeds_val, pin_memory=pin_memory)\n else:\n batchgenerator_val = MultiThreadedAugmenter(dataloader_val, val_transforms,\n max(params.get('num_threads') // 2, 1),\n params.get(\"num_cached_per_thread\"),\n seeds=seeds_val, pin_memory=pin_memory)\n # batchgenerator_val = SingleThreadedAugmenter(dataloader_val, val_transforms)\n return batchgenerator_train, batchgenerator_val" }, { "identifier": "MultipleOutputLoss2", "path": "nn_transunet/trainer/loss_functions.py", "snippet": "class MultipleOutputLoss2(nn.Module):\n def __init__(self, loss, weight_factors=None):\n \"\"\"\n use this if you have several outputs and ground truth (both list of same len) and the loss should be computed\n between them (x[0] and y[0], x[1] and y[1] etc)\n :param loss:\n :param weight_factors:\n \"\"\"\n super(MultipleOutputLoss2, self).__init__()\n self.weight_factors = weight_factors\n self.loss = loss\n\n def forward(self, x, y):\n assert isinstance(x, (tuple, list)), \"x must be either tuple or list\"\n assert isinstance(y, (tuple, list)), \"y must be either tuple or list\"\n if self.weight_factors is None:\n weights = [1] * len(x)\n else:\n weights = self.weight_factors\n\n l = weights[0] * self.loss(x[0], y[0])\n for i in range(1, len(x)):\n if weights[i] != 0:\n l += weights[i] * self.loss(x[i], y[i])\n return l" }, { "identifier": "maybe_to_torch", "path": "nn_transunet/trainer/network_trainer.py", "snippet": "def maybe_to_torch(d):\n if isinstance(d, list):\n d = [maybe_to_torch(i) if not isinstance(i, torch.Tensor) else i for i in d]\n elif not isinstance(d, torch.Tensor):\n d = torch.from_numpy(d).float()\n return d" }, { "identifier": "to_cuda", "path": "nn_transunet/trainer/network_trainer.py", "snippet": "def to_cuda(data, non_blocking=True, gpu_id=0):\n if isinstance(data, list):\n data = [i.cuda(gpu_id, non_blocking=non_blocking) for i in data]\n else:\n data = data.cuda(gpu_id, non_blocking=non_blocking)\n return data" }, { "identifier": "nnUNetTrainer", "path": "nn_transunet/trainer/nnUNetTrainer.py", "snippet": "class nnUNetTrainer(NetworkTrainer):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False):\n \"\"\"\n :param deterministic:\n :param fold: can be either [0 ... 5) for cross-validation, 'all' to train on all available training data or\n None if you wish to load some checkpoint and do inference only\n :param plans_file: the pkl file generated by preprocessing. This file will determine all design choices\n :param subfolder_with_preprocessed_data: must be a subfolder of dataset_directory (just the name of the folder,\n not the entire path). This is where the preprocessed data lies that will be used for network training. We made\n this explicitly available so that differently preprocessed data can coexist and the user can choose what to use.\n Can be None if you are doing inference only.\n :param output_folder: where to store parameters, plot progress and to the validation\n :param dataset_directory: the parent directory in which the preprocessed Task data is stored. This is required\n because the split information is stored in this directory. For running prediction only this input is not\n required and may be set to None\n :param batch_dice: compute dice loss for each sample and average over all samples in the batch or pretend the\n batch is a pseudo volume?\n :param stage: The plans file may contain several stages (used for lowres / highres / pyramid). Stage must be\n specified for training:\n if stage 1 exists then stage 1 is the high resolution stage, otherwise it's 0\n :param unpack_data: if False, npz preprocessed data will not be unpacked to npy. This consumes less space but\n is considerably slower! Running unpack_data=False with 2d should never be done!\n\n IMPORTANT: If you inherit from nnUNetTrainer and the init args change then you need to redefine self.init_args\n in your init accordingly. Otherwise checkpoints won't load properly!\n \"\"\"\n super(nnUNetTrainer, self).__init__(deterministic, fp16)\n self.unpack_data = unpack_data\n self.init_args = (plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, fp16)\n # set through arguments from init\n self.stage = stage\n self.experiment_name = self.__class__.__name__\n self.plans_file = plans_file\n self.output_folder = output_folder\n self.dataset_directory = dataset_directory\n self.output_folder_base = self.output_folder\n self.fold = fold\n self.pin_memory = True\n\n self.plans = None\n\n # if we are running inference only then the self.dataset_directory is set (due to checkpoint loading) but it\n # irrelevant\n if self.dataset_directory is not None and isdir(self.dataset_directory):\n self.gt_niftis_folder = join(\n self.dataset_directory, \"gt_segmentations\")\n else:\n self.gt_niftis_folder = None\n\n self.folder_with_preprocessed_data = None\n\n # set in self.initialize()\n\n self.dl_tr = self.dl_val = None\n self.num_input_channels = self.num_classes = self.net_pool_per_axis = self.patch_size = self.batch_size = \\\n self.threeD = self.base_num_features = self.intensity_properties = self.normalization_schemes = \\\n self.net_num_pool_op_kernel_sizes = self.net_conv_kernel_sizes = None # loaded automatically from plans_file\n\n self.basic_generator_patch_size = self.data_aug_params = self.transpose_forward = self.transpose_backward = None\n\n self.batch_dice = batch_dice\n self.loss = DC_and_CE_loss(\n {'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False}, {})\n # self.loss = PartiallyCrossEntropyLoss()\n\n self.online_eval_foreground_dc = []\n self.online_eval_tp = []\n self.online_eval_fp = []\n self.online_eval_fn = []\n\n self.classes = self.do_dummy_2D_aug = self.use_mask_for_norm = self.only_keep_largest_connected_component = \\\n self.min_region_size_per_class = self.min_size_per_class = None\n\n self.inference_pad_border_mode = \"constant\"\n self.inference_pad_kwargs = {'constant_values': 0}\n\n self.update_fold(fold)\n self.pad_all_sides = None\n\n self.lr_scheduler_eps = 1e-3\n self.lr_scheduler_patience = 30\n self.initial_lr = 1e-2\n # self.initial_lr = 1e-3\n self.weight_decay = 3e-5\n\n self.oversample_foreground_percent = 0.33\n\n self.conv_per_stage = None\n self.regions_class_order = None\n\n def update_fold(self, fold):\n \"\"\"\n used to swap between folds for inference (ensemble of models from cross-validation)\n DO NOT USE DURING TRAINING AS THIS WILL NOT UPDATE THE DATASET SPLIT AND THE DATA AUGMENTATION GENERATORS\n :param fold:\n :return:\n \"\"\"\n if fold is not None:\n if isinstance(fold, str):\n assert fold.startswith(\"all\"), \"if self.fold is a string then it must be \\'all\\'\"\n # assert fold == \"all\", \"if self.fold is a string then it must be \\'all\\'\"\n if self.output_folder.endswith(\"%s\" % str(self.fold)):\n self.output_folder = self.output_folder_base\n self.output_folder = join(self.output_folder, \"%s\" % str(fold))\n else:\n if self.output_folder.endswith(\"fold_%s\" % str(self.fold)):\n self.output_folder = self.output_folder_base\n self.output_folder = join(\n self.output_folder, \"fold_%s\" % str(fold))\n self.fold = fold\n\n def setup_DA_params(self):\n if self.threeD:\n self.data_aug_params = default_3D_augmentation_params\n if self.do_dummy_2D_aug:\n self.data_aug_params[\"dummy_2D\"] = True\n self.print_to_log_file(\"Using dummy2d data augmentation\")\n self.data_aug_params[\"elastic_deform_alpha\"] = \\\n default_2D_augmentation_params[\"elastic_deform_alpha\"]\n self.data_aug_params[\"elastic_deform_sigma\"] = \\\n default_2D_augmentation_params[\"elastic_deform_sigma\"]\n self.data_aug_params[\"rotation_x\"] = default_2D_augmentation_params[\"rotation_x\"]\n else:\n self.do_dummy_2D_aug = False\n if max(self.patch_size) / min(self.patch_size) > 1.5:\n default_2D_augmentation_params['rotation_x'] = (\n -15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi)\n self.data_aug_params = default_2D_augmentation_params\n self.data_aug_params[\"mask_was_used_for_normalization\"] = self.use_mask_for_norm\n\n if self.do_dummy_2D_aug:\n self.basic_generator_patch_size = get_patch_size(self.patch_size[1:],\n self.data_aug_params['rotation_x'],\n self.data_aug_params['rotation_y'],\n self.data_aug_params['rotation_z'],\n self.data_aug_params['scale_range'])\n self.basic_generator_patch_size = np.array(\n [self.patch_size[0]] + list(self.basic_generator_patch_size))\n else:\n self.basic_generator_patch_size = get_patch_size(self.patch_size, self.data_aug_params['rotation_x'],\n self.data_aug_params['rotation_y'],\n self.data_aug_params['rotation_z'],\n self.data_aug_params['scale_range'])\n\n self.data_aug_params['selected_seg_channels'] = [0]\n self.data_aug_params['patch_size_for_spatialtransform'] = self.patch_size\n\n def initialize(self, training=True, force_load_plans=False):\n \"\"\"\n For prediction of test cases just set training=False, this will prevent loading of training data and\n training batchgenerator initialization\n :param training:\n :return:\n \"\"\"\n\n maybe_mkdir_p(self.output_folder)\n\n if force_load_plans or (self.plans is None):\n self.load_plans_file()\n \n self.process_plans(self.plans)\n\n self.setup_DA_params()\n\n if training:\n self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] +\n \"_stage%d\" % self.stage)\n\n self.dl_tr, self.dl_val = self.get_basic_generators()\n if self.unpack_data:\n self.print_to_log_file(\"unpacking dataset\")\n unpack_dataset(self.folder_with_preprocessed_data)\n self.print_to_log_file(\"done\")\n else:\n self.print_to_log_file(\n \"INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you \"\n \"will wait all winter for your model to finish!\")\n \n self.tr_gen, self.val_gen = get_default_augmentation(self.dl_tr, self.dl_val,\n self.data_aug_params[\n 'patch_size_for_spatialtransform'],\n self.data_aug_params)\n self.print_to_log_file(\"TRAINING KEYS:\\n %s\" % (str(self.dataset_tr.keys())),\n also_print_to_console=False)\n self.print_to_log_file(\"VALIDATION KEYS:\\n %s\" % (str(self.dataset_val.keys())),\n also_print_to_console=False)\n else:\n pass\n self.initialize_network()\n self.initialize_optimizer_and_scheduler()\n # assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel))\n self.was_initialized = True\n\n def initialize_network(self):\n \"\"\"\n This is specific to the U-Net and must be adapted for other network architectures\n :return:\n \"\"\"\n # self.print_to_log_file(self.net_num_pool_op_kernel_sizes)\n # self.print_to_log_file(self.net_conv_kernel_sizes)\n\n net_numpool = len(self.net_num_pool_op_kernel_sizes)\n if self.threeD:\n conv_op = nn.Conv3d\n dropout_op = nn.Dropout3d\n norm_op = nn.InstanceNorm3d\n else:\n conv_op = nn.Conv2d\n dropout_op = nn.Dropout2d\n norm_op = nn.InstanceNorm2d\n norm_op_kwargs = {'eps': 1e-5, 'affine': True}\n dropout_op_kwargs = {'p': 0, 'inplace': True}\n net_nonlin = nn.LeakyReLU\n net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True}\n self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes, net_numpool,\n self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op,\n dropout_op_kwargs,\n net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(\n 1e-2),\n self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True)\n\n # self.network.inference_apply_nonlin = softmax_helper\n # self.network = UNet(self.num_input_channels, self.num_classes)\n # self.network = smp.Unet(encoder_name='resnet50', encoder_weights='imagenet',\n # in_channels=self.num_input_channels, classes=self.num_classes)\n # self.network = smp.DeepLabV3Plus(encoder_name='resnet50', encoder_weights='imagenet',\n # in_channels=self.num_input_channels, classes=self.num_classes)\n # self.network = Attention_UNet(feature_scale=2, n_classes=self.num_classes, is_deconv=True, in_channels=self.num_input_channels)\n # self.network = VNet(n_channels=self.num_input_channels, n_classes=self.num_classes)\n # self.network = NestedUNet(num_classes=self.num_classes, input_channels=self.num_input_channels)\n if torch.cuda.is_available():\n self.network.cuda()\n # checkpoint = torch.load(\"/mnt/lustre/luoxiangde.vendor/projects/nnUNetFrame/DATASET/pCE_model_latest.model\")\n # print(\"Load Weighted Successful\")\n # weights = checkpoint['state_dict']\n # self.network.load_state_dict(weights, strict=False)\n # self.network.half()\n\n # def initialize_optimizer_and_scheduler(self):\n # assert self.network is not None, \"self.initialize_network must be called first\"\n # self.optimizer = torch.optim.Adam(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay,\n # amsgrad=True)\n # self.lr_scheduler = lr_scheduler.ReduceLROnPlateau(self.optimizer, mode='min', factor=0.2,\n # patience=self.lr_scheduler_patience,\n # verbose=True, threshold=self.lr_scheduler_eps,\n # threshold_mode=\"abs\")\n def initialize_optimizer_and_scheduler(self):\n assert self.network is not None, \"self.initialize_network must be called first\"\n self.optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay,\n momentum=0.99, nesterov=True)\n self.lr_scheduler = None\n\n def save_debug_information(self):\n # saving some debug information\n dct = OrderedDict()\n for k in self.__dir__():\n if not k.startswith(\"__\"):\n if not callable(getattr(self, k)):\n dct[k] = str(getattr(self, k))\n del dct['plans']\n del dct['intensity_properties']\n del dct['dataset']\n del dct['dataset_tr']\n del dct['dataset_val']\n save_json(dct, join(self.output_folder, \"debug.json\"))\n\n import shutil\n\n shutil.copy(self.plans_file, join(\n self.output_folder_base, \"plans.pkl\"))\n\n def run_training(self):\n self.save_debug_information()\n super(nnUNetTrainer, self).run_training()\n\n def load_plans_file(self):\n \"\"\"\n This is what actually configures the entire experiment. The plans file is generated by experiment planning\n :return:\n \"\"\"\n self.plans = load_pickle(self.plans_file)\n\n\n def process_plans(self, plans):\n if self.stage is None:\n assert len(list(plans['plans_per_stage'].keys())) == 1, \\\n \"If self.stage is None then there can be only one stage in the plans file. That seems to not be the \" \\\n \"case. Please specify which stage of the cascade must be trained\"\n self.stage = list(plans['plans_per_stage'].keys())[0]\n self.plans = plans\n\n stage_plans = self.plans['plans_per_stage'][self.stage]\n self.batch_size = stage_plans['batch_size']\n # self.batch_size = 4\n self.net_pool_per_axis = stage_plans['num_pool_per_axis']\n self.patch_size = np.array(stage_plans['patch_size']).astype(int)\n self.do_dummy_2D_aug = stage_plans['do_dummy_2D_data_aug']\n\n if 'pool_op_kernel_sizes' not in stage_plans.keys():\n assert 'num_pool_per_axis' in stage_plans.keys()\n self.print_to_log_file(\n \"WARNING! old plans file with missing pool_op_kernel_sizes. Attempting to fix it...\")\n self.net_num_pool_op_kernel_sizes = []\n for i in range(max(self.net_pool_per_axis)):\n curr = []\n for j in self.net_pool_per_axis:\n if (max(self.net_pool_per_axis) - j) <= i:\n curr.append(2)\n else:\n curr.append(1)\n self.net_num_pool_op_kernel_sizes.append(curr)\n else:\n self.net_num_pool_op_kernel_sizes = stage_plans['pool_op_kernel_sizes']\n\n if 'conv_kernel_sizes' not in stage_plans.keys():\n self.print_to_log_file(\n \"WARNING! old plans file with missing conv_kernel_sizes. Attempting to fix it...\")\n self.net_conv_kernel_sizes = [\n [3] * len(self.net_pool_per_axis)] * (max(self.net_pool_per_axis) + 1)\n else:\n self.net_conv_kernel_sizes = stage_plans['conv_kernel_sizes']\n\n self.pad_all_sides = None # self.patch_size\n self.intensity_properties = plans['dataset_properties']['intensityproperties']\n self.normalization_schemes = plans['normalization_schemes']\n self.base_num_features = plans['base_num_features']\n self.num_input_channels = plans['num_modalities']\n # background is no longer in num_classes\n self.num_classes = plans['num_classes'] + 1\n self.classes = plans['all_classes']\n self.use_mask_for_norm = plans['use_mask_for_norm']\n self.only_keep_largest_connected_component = plans['keep_only_largest_region']\n self.min_region_size_per_class = plans['min_region_size_per_class']\n # DONT USE THIS. plans['min_size_per_class']\n self.min_size_per_class = None\n\n if plans.get('transpose_forward') is None or plans.get('transpose_backward') is None:\n print(\"WARNING! You seem to have data that was preprocessed with a previous version of nnU-Net. \"\n \"You should rerun preprocessing. We will proceed and assume that both transpose_foward \"\n \"and transpose_backward are [0, 1, 2]. If that is not correct then weird things will happen!\")\n plans['transpose_forward'] = [0, 1, 2]\n plans['transpose_backward'] = [0, 1, 2]\n self.transpose_forward = plans['transpose_forward']\n self.transpose_backward = plans['transpose_backward']\n\n if len(self.patch_size) == 2:\n self.threeD = False\n elif len(self.patch_size) == 3:\n self.threeD = True\n else:\n raise RuntimeError(\n \"invalid patch size in plans file: %s\" % str(self.patch_size))\n\n if \"conv_per_stage\" in plans.keys(): # this ha sbeen added to the plans only recently\n self.conv_per_stage = plans['conv_per_stage']\n else:\n self.conv_per_stage = 2\n\n def load_dataset(self):\n self.dataset = load_dataset(self.folder_with_preprocessed_data)\n\n def get_basic_generators(self):\n self.load_dataset()\n self.do_split()\n\n if self.threeD:\n # dl_tr = DataLoader3D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size,\n # False, oversample_foreground_percent=self.oversample_foreground_percent,\n # pad_mode=\"constant\", pad_sides=self.pad_all_sides, memmap_mode='r', labeled_cases=10)\n # dl_val = DataLoader3D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size, False,\n # oversample_foreground_percent=self.oversample_foreground_percent,\n # pad_mode=\"constant\", pad_sides=self.pad_all_sides, memmap_mode='r', labeled_cases=10)\n dl_tr = DataLoader3D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size,\n False, oversample_foreground_percent=self.oversample_foreground_percent,\n pad_mode=\"constant\", pad_sides=self.pad_all_sides, memmap_mode='r')\n dl_val = DataLoader3D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size, False,\n oversample_foreground_percent=self.oversample_foreground_percent,\n pad_mode=\"constant\", pad_sides=self.pad_all_sides, memmap_mode='r')\n else:\n dl_tr = DataLoader2D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size,\n oversample_foreground_percent=self.oversample_foreground_percent,\n pad_mode=\"constant\", pad_sides=self.pad_all_sides, memmap_mode='r')\n dl_val = DataLoader2D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size,\n oversample_foreground_percent=self.oversample_foreground_percent,\n pad_mode=\"constant\", pad_sides=self.pad_all_sides, memmap_mode='r')\n return dl_tr, dl_val\n\n\n def preprocess_patient(self, input_files):\n \"\"\"\n Used to predict new unseen data. Not used for the preprocessing of the training/test data\n :param input_files:\n :return:\n \"\"\"\n preprocessor_name = self.plans.get('preprocessor_name')\n if preprocessor_name is None:\n if self.threeD:\n preprocessor_name = \"GenericPreprocessor\"\n preprocessor_class = GenericPreprocessor\n else:\n preprocessor_name = \"PreprocessorFor2D\"\n preprocessor_class = PreprocessorFor2D\n if preprocessor_name == \"GenericPreprocessor\":\n preprocessor_class = GenericPreprocessor\n else:\n preprocessor_class = PreprocessorFor2D\n assert preprocessor_class is not None, \"Could not find preprocessor %s in nnunet.preprocessing\" % \\\n preprocessor_name\n preprocessor = preprocessor_class(self.normalization_schemes, self.use_mask_for_norm,\n self.transpose_forward, self.intensity_properties)\n\n d, s, properties = preprocessor.preprocess_test_case(input_files,\n self.plans['plans_per_stage'][self.stage][\n 'current_spacing'])\n return d, s, properties\n\n def preprocess_predict_nifti(self, input_files: List[str], output_file: str = None,\n softmax_ouput_file: str = None, mixed_precision: bool = True) -> None:\n \"\"\"\n Use this to predict new data\n :param input_files:\n :param output_file:\n :param softmax_ouput_file:\n :param mixed_precision:\n :return:\n \"\"\"\n print(\"preprocessing...\")\n d, s, properties = self.preprocess_patient(input_files)\n print(\"predicting...\")\n pred = self.predict_preprocessed_data_return_seg_and_softmax(d, do_mirroring=self.data_aug_params[\"do_mirror\"],\n mirror_axes=self.data_aug_params['mirror_axes'],\n use_sliding_window=True, step_size=0.5,\n use_gaussian=True, pad_border_mode='constant',\n pad_kwargs={\n 'constant_values': 0},\n verbose=True, all_in_gpu=False,\n mixed_precision=mixed_precision)[1]\n pred = pred.transpose([0] + [i + 1 for i in self.transpose_backward])\n\n if 'segmentation_export_params' in self.plans.keys():\n force_separate_z = self.plans['segmentation_export_params']['force_separate_z']\n interpolation_order = self.plans['segmentation_export_params']['interpolation_order']\n interpolation_order_z = self.plans['segmentation_export_params']['interpolation_order_z']\n else:\n force_separate_z = None\n interpolation_order = 1\n interpolation_order_z = 0\n\n print(\"resampling to original spacing and nifti export...\")\n save_segmentation_nifti_from_softmax(pred, output_file, properties, interpolation_order,\n self.regions_class_order, None, None, softmax_ouput_file,\n None, force_separate_z=force_separate_z,\n interpolation_order_z=interpolation_order_z)\n print(\"done\")\n\n def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True,\n mirror_axes: Tuple[int] = None,\n use_sliding_window: bool = True, step_size: float = 0.5,\n use_gaussian: bool = True, pad_border_mode: str = 'constant',\n pad_kwargs: dict = None, all_in_gpu: bool = False,\n verbose: bool = True, mixed_precision: bool = True) -> Tuple[\n np.ndarray, np.ndarray]:\n \"\"\"\n :param data:\n :param do_mirroring:\n :param mirror_axes:\n :param use_sliding_window:\n :param step_size:\n :param use_gaussian:\n :param pad_border_mode:\n :param pad_kwargs:\n :param all_in_gpu:\n :param verbose:\n :return:\n \"\"\"\n if pad_border_mode == 'constant' and pad_kwargs is None:\n pad_kwargs = {'constant_values': 0}\n\n if do_mirroring and mirror_axes is None:\n mirror_axes = self.data_aug_params['mirror_axes']\n\n if do_mirroring:\n assert self.data_aug_params[\"do_mirror\"], \"Cannot do mirroring as test time augmentation when training \" \\\n \"was done without mirroring\"\n\n # valid = list((SegmentationNetwork, nn.DataParallel))\n # print(self.network)\n # assert isinstance(self.network, tuple(valid))\n\n current_mode = self.network.training\n self.network.eval()\n ret = SegmentationNetwork.predict_3D(data, do_mirroring=do_mirroring, mirror_axes=mirror_axes,\n use_sliding_window=use_sliding_window, step_size=step_size,\n patch_size=self.patch_size, regions_class_order=self.regions_class_order,\n use_gaussian=use_gaussian, pad_border_mode=pad_border_mode,\n pad_kwargs=pad_kwargs, all_in_gpu=all_in_gpu, verbose=verbose,\n mixed_precision=mixed_precision)\n self.network.train(current_mode)\n return ret\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5,\n save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs: dict = None, run_postprocessing_on_folds: bool = True):\n \"\"\"\n if debug=True then the temporary files generated for postprocessing determination will be kept\n \"\"\"\n\n current_mode = self.network.training\n self.network.eval()\n\n assert self.was_initialized, \"must initialize, ideally with checkpoint (or train first)\"\n if self.dataset_val is None:\n self.load_dataset()\n self.do_split()\n\n if segmentation_export_kwargs is None:\n if 'segmentation_export_params' in self.plans.keys():\n force_separate_z = self.plans['segmentation_export_params']['force_separate_z']\n interpolation_order = self.plans['segmentation_export_params']['interpolation_order']\n interpolation_order_z = self.plans['segmentation_export_params']['interpolation_order_z']\n else:\n force_separate_z = None\n interpolation_order = 1\n interpolation_order_z = 0\n else:\n force_separate_z = segmentation_export_kwargs['force_separate_z']\n interpolation_order = segmentation_export_kwargs['interpolation_order']\n interpolation_order_z = segmentation_export_kwargs['interpolation_order_z']\n\n # predictions as they come from the network go here\n output_folder = join(self.output_folder, validation_folder_name)\n maybe_mkdir_p(output_folder)\n # this is for debug purposes\n my_input_args = {'do_mirroring': do_mirroring,\n 'use_sliding_window': use_sliding_window,\n 'step_size': step_size,\n 'save_softmax': save_softmax,\n 'use_gaussian': use_gaussian,\n 'overwrite': overwrite,\n 'validation_folder_name': validation_folder_name,\n 'debug': debug,\n 'all_in_gpu': all_in_gpu,\n 'segmentation_export_kwargs': segmentation_export_kwargs,\n }\n save_json(my_input_args, join(output_folder, \"validation_args.json\"))\n\n if do_mirroring:\n if not self.data_aug_params['do_mirror']:\n raise RuntimeError(\n \"We did not train with mirroring so you cannot do inference with mirroring enabled\")\n mirror_axes = self.data_aug_params['mirror_axes']\n else:\n mirror_axes = ()\n\n pred_gt_tuples = []\n\n export_pool = Pool(default_num_threads)\n results = []\n\n for k in self.dataset_val.keys():\n properties = load_pickle(self.dataset[k]['properties_file'])\n fname = properties['list_of_data_files'][0].split(\"/\")[-1][:-12]\n if overwrite or (not isfile(join(output_folder, fname + \".nii.gz\"))) or \\\n (save_softmax and not isfile(join(output_folder, fname + \".npz\"))):\n data = np.load(self.dataset[k]['data_file'])['data']\n\n print(k, data.shape)\n data[-1][data[-1] == -1] = 0\n\n softmax_pred = self.predict_preprocessed_data_return_seg_and_softmax(data[:-1],\n do_mirroring=do_mirroring,\n mirror_axes=mirror_axes,\n use_sliding_window=use_sliding_window,\n step_size=step_size,\n use_gaussian=use_gaussian,\n all_in_gpu=all_in_gpu,\n mixed_precision=self.fp16)[1]\n\n softmax_pred = softmax_pred.transpose(\n [0] + [i + 1 for i in self.transpose_backward])\n\n if save_softmax:\n softmax_fname = join(output_folder, fname + \".npz\")\n else:\n softmax_fname = None\n\n \"\"\"There is a problem with python process communication that prevents us from communicating obejcts\n larger than 2 GB between processes (basically when the length of the pickle string that will be sent is\n communicated by the multiprocessing.Pipe object then the placeholder (\\%i I think) does not allow for long\n enough strings (lol). This could be fixed by changing i to l (for long) but that would require manually\n patching system python code. We circumvent that problem here by saving softmax_pred to a npy file that will\n then be read (and finally deleted) by the Process. save_segmentation_nifti_from_softmax can take either\n filename or np.ndarray and will handle this automatically\"\"\"\n if np.prod(softmax_pred.shape) > (2e9 / 4 * 0.85): # *0.85 just to be save\n np.save(join(output_folder, fname + \".npy\"), softmax_pred)\n softmax_pred = join(output_folder, fname + \".npy\")\n\n results.append(export_pool.starmap_async(save_segmentation_nifti_from_softmax,\n ((softmax_pred, join(output_folder, fname + \".nii.gz\"),\n properties, interpolation_order, self.regions_class_order,\n None, None,\n softmax_fname, None, force_separate_z,\n interpolation_order_z),\n )\n )\n )\n\n pred_gt_tuples.append([join(output_folder, fname + \".nii.gz\"),\n join(self.gt_niftis_folder, fname + \".nii.gz\")])\n\n _ = [i.get() for i in results]\n self.print_to_log_file(\"finished prediction\")\n\n # evaluate raw predictions\n self.print_to_log_file(\"evaluation of raw predictions\")\n task = self.dataset_directory.split(\"/\")[-1]\n job_name = self.experiment_name\n _ = aggregate_scores(pred_gt_tuples, labels=list(range(self.num_classes)),\n json_output_file=join(\n output_folder, \"summary.json\"),\n json_name=job_name +\n \" val tiled %s\" % (str(use_sliding_window)),\n json_author=\"Fabian\",\n json_task=task, num_threads=default_num_threads)\n\n # if run_postprocessing_on_folds:\n # # in the old nnunet we would stop here. Now we add a postprocessing. This postprocessing can remove everything\n # # except the largest connected component for each class. To see if this improves results, we do this for all\n # # classes and then rerun the evaluation. Those classes for which this resulted in an improved dice score will\n # # have this applied during inference as well\n # self.print_to_log_file(\"determining postprocessing\")\n # determine_postprocessing(self.output_folder, self.gt_niftis_folder, validation_folder_name,\n # final_subf_name=validation_folder_name + \"_postprocessed\", debug=debug)\n # # after this the final predictions for the vlaidation set can be found in validation_folder_name_base + \"_postprocessed\"\n # # They are always in that folder, even if no postprocessing as applied!\n\n # detemining postprocesing on a per-fold basis may be OK for this fold but what if another fold finds another\n # postprocesing to be better? In this case we need to consolidate. At the time the consolidation is going to be\n # done we won't know what self.gt_niftis_folder was, so now we copy all the niftis into a separate folder to\n # be used later\n gt_nifti_folder = join(self.output_folder_base, \"gt_niftis\")\n maybe_mkdir_p(gt_nifti_folder)\n for f in subfiles(self.gt_niftis_folder, suffix=\".nii.gz\"):\n success = False\n attempts = 0\n e = None\n while not success and attempts < 10:\n try:\n shutil.copy(f, gt_nifti_folder)\n success = True\n except OSError as e:\n attempts += 1\n sleep(1)\n if not success:\n print(\"Could not copy gt nifti file %s into folder %s\" %\n (f, gt_nifti_folder))\n if e is not None:\n raise e\n\n self.network.train(current_mode)\n\n def run_online_evaluation(self, output, target):\n with torch.no_grad():\n num_classes = output.shape[1]\n output_softmax = softmax_helper(output)\n output_seg = output_softmax.argmax(1)\n target = target[:, 0]\n axes = tuple(range(1, len(target.shape)))\n tp_hard = torch.zeros(\n (target.shape[0], num_classes - 1)).to(output_seg.device.index)\n fp_hard = torch.zeros(\n (target.shape[0], num_classes - 1)).to(output_seg.device.index)\n fn_hard = torch.zeros(\n (target.shape[0], num_classes - 1)).to(output_seg.device.index)\n for c in range(1, num_classes):\n tp_hard[:, c - 1] = sum_tensor((output_seg == c).float()\n * (target == c).float(), axes=axes)\n fp_hard[:, c - 1] = sum_tensor((output_seg == c).float()\n * (target != c).float(), axes=axes)\n fn_hard[:, c - 1] = sum_tensor((output_seg != c).float()\n * (target == c).float(), axes=axes)\n\n tp_hard = tp_hard.sum(0, keepdim=False).detach().cpu().numpy()\n fp_hard = fp_hard.sum(0, keepdim=False).detach().cpu().numpy()\n fn_hard = fn_hard.sum(0, keepdim=False).detach().cpu().numpy()\n\n self.online_eval_foreground_dc.append(\n list((2 * tp_hard) / (2 * tp_hard + fp_hard + fn_hard + 1e-8)))\n self.online_eval_tp.append(list(tp_hard))\n self.online_eval_fp.append(list(fp_hard))\n self.online_eval_fn.append(list(fn_hard))\n\n def finish_online_evaluation(self):\n self.online_eval_tp = np.sum(self.online_eval_tp, 0)\n self.online_eval_fp = np.sum(self.online_eval_fp, 0)\n self.online_eval_fn = np.sum(self.online_eval_fn, 0)\n\n global_dc_per_class = [i for i in [2 * i / (2 * i + j + k) for i, j, k in\n zip(self.online_eval_tp, self.online_eval_fp, self.online_eval_fn)]\n if not np.isnan(i)]\n self.all_val_eval_metrics.append(np.mean(global_dc_per_class))\n\n self.print_to_log_file(\"Average global foreground Dice:\", [\n np.round(i, 4) for i in global_dc_per_class])\n self.print_to_log_file(\"(interpret this as an estimate for the Dice of the different classes. This is not \"\n \"exact.)\")\n\n self.online_eval_foreground_dc = []\n self.online_eval_tp = []\n self.online_eval_fp = []\n self.online_eval_fn = []\n\n def save_checkpoint(self, fname, save_optimizer=True):\n super(nnUNetTrainer, self).save_checkpoint(fname, save_optimizer)\n info = OrderedDict()\n info['init'] = self.init_args\n info['name'] = self.__class__.__name__\n info['class'] = str(self.__class__)\n info['plans'] = self.plans\n\n write_pickle(info, fname + \".pkl\")" }, { "identifier": "Generic_UNet", "path": "nn_transunet/networks/nnunet_model.py", "snippet": "class Generic_UNet(SegmentationNetwork):\n DEFAULT_BATCH_SIZE_3D = 2\n DEFAULT_PATCH_SIZE_3D = (64, 192, 160)\n SPACING_FACTOR_BETWEEN_STAGES = 2\n BASE_NUM_FEATURES_3D = 30\n MAX_NUMPOOL_3D = 999\n MAX_NUM_FILTERS_3D = 320\n\n DEFAULT_PATCH_SIZE_2D = (256, 256)\n BASE_NUM_FEATURES_2D = 30\n DEFAULT_BATCH_SIZE_2D = 50\n MAX_NUMPOOL_2D = 999\n MAX_FILTERS_2D = 480\n\n use_this_for_batch_size_computation_2D = 19739648\n use_this_for_batch_size_computation_3D = 520000000 # 505789440\n\n def __init__(self, input_channels, base_num_features, num_classes, num_pool, num_conv_per_stage=2,\n feat_map_mul_on_downscale=2, conv_op=nn.Conv2d,\n norm_op=nn.BatchNorm2d, norm_op_kwargs=None,\n dropout_op=nn.Dropout2d, dropout_op_kwargs=None,\n nonlin=nn.LeakyReLU, nonlin_kwargs=None, deep_supervision=True, dropout_in_localization=False,\n final_nonlin=softmax_helper, weightInitializer=InitWeights_He(1e-2), pool_op_kernel_sizes=None,\n conv_kernel_sizes=None,\n upscale_logits=False, convolutional_pooling=False, convolutional_upsampling=False,\n max_num_features=None, basic_block=ConvDropoutNormNonlin,\n seg_output_use_bias=False):\n \"\"\"\n basically more flexible than v1, architecture is the same\n\n Does this look complicated? Nah bro. Functionality > usability\n\n This does everything you need, including world peace.\n\n Questions? -> [email protected]\n \"\"\"\n super(Generic_UNet, self).__init__()\n self.convolutional_upsampling = convolutional_upsampling\n self.convolutional_pooling = convolutional_pooling\n self.upscale_logits = upscale_logits\n if nonlin_kwargs is None:\n nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True}\n if dropout_op_kwargs is None:\n dropout_op_kwargs = {'p': 0.5, 'inplace': True}\n if norm_op_kwargs is None:\n norm_op_kwargs = {'eps': 1e-5, 'affine': True, 'momentum': 0.1}\n\n self.conv_kwargs = {'stride': 1, 'dilation': 1, 'bias': True}\n\n self.nonlin = nonlin\n self.nonlin_kwargs = nonlin_kwargs\n self.dropout_op_kwargs = dropout_op_kwargs\n self.norm_op_kwargs = norm_op_kwargs\n self.weightInitializer = weightInitializer\n self.conv_op = conv_op\n self.norm_op = norm_op\n self.dropout_op = dropout_op\n self.num_classes = num_classes\n self.final_nonlin = final_nonlin\n self._deep_supervision = deep_supervision\n self.do_ds = deep_supervision\n\n if conv_op == nn.Conv2d:\n upsample_mode = 'bilinear'\n pool_op = nn.MaxPool2d\n transpconv = nn.ConvTranspose2d\n if pool_op_kernel_sizes is None:\n pool_op_kernel_sizes = [(2, 2)] * num_pool\n if conv_kernel_sizes is None:\n conv_kernel_sizes = [(3, 3)] * (num_pool + 1)\n elif conv_op == nn.Conv3d:\n upsample_mode = 'trilinear'\n pool_op = nn.MaxPool3d\n transpconv = nn.ConvTranspose3d\n if pool_op_kernel_sizes is None:\n pool_op_kernel_sizes = [(2, 2, 2)] * num_pool\n if conv_kernel_sizes is None:\n conv_kernel_sizes = [(3, 3, 3)] * (num_pool + 1)\n else:\n raise ValueError(\"unknown convolution dimensionality, conv op: %s\" % str(conv_op))\n\n self.input_shape_must_be_divisible_by = np.prod(pool_op_kernel_sizes, 0, dtype=np.int64)\n self.pool_op_kernel_sizes = pool_op_kernel_sizes\n self.conv_kernel_sizes = conv_kernel_sizes\n\n self.conv_pad_sizes = []\n for krnl in self.conv_kernel_sizes:\n self.conv_pad_sizes.append([1 if i == 3 else 0 for i in krnl])\n\n if max_num_features is None:\n if self.conv_op == nn.Conv3d:\n self.max_num_features = self.MAX_NUM_FILTERS_3D\n else:\n self.max_num_features = self.MAX_FILTERS_2D\n else:\n self.max_num_features = max_num_features\n\n self.conv_blocks_context = []\n self.conv_blocks_localization = []\n self.td = []\n self.tu = []\n self.seg_outputs = []\n\n output_features = base_num_features\n input_features = input_channels\n\n for d in range(num_pool):\n # determine the first stride\n if d != 0 and self.convolutional_pooling:\n first_stride = pool_op_kernel_sizes[d - 1]\n else:\n first_stride = None\n\n self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[d]\n self.conv_kwargs['padding'] = self.conv_pad_sizes[d]\n # add convolutions\n self.conv_blocks_context.append(StackedConvLayers(input_features, output_features, num_conv_per_stage,\n self.conv_op, self.conv_kwargs, self.norm_op,\n self.norm_op_kwargs, self.dropout_op,\n self.dropout_op_kwargs, self.nonlin, self.nonlin_kwargs,\n first_stride, basic_block=basic_block))\n if not self.convolutional_pooling:\n self.td.append(pool_op(pool_op_kernel_sizes[d]))\n input_features = output_features\n output_features = int(np.round(output_features * feat_map_mul_on_downscale))\n\n output_features = min(output_features, self.max_num_features)\n\n # now the bottleneck.\n # determine the first stride\n if self.convolutional_pooling:\n first_stride = pool_op_kernel_sizes[-1]\n else:\n first_stride = None\n\n # the output of the last conv must match the number of features from the skip connection if we are not using\n # convolutional upsampling. If we use convolutional upsampling then the reduction in feature maps will be\n # done by the transposed conv\n if self.convolutional_upsampling:\n final_num_features = output_features\n else:\n final_num_features = self.conv_blocks_context[-1].output_channels\n\n self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[num_pool]\n self.conv_kwargs['padding'] = self.conv_pad_sizes[num_pool]\n self.conv_blocks_context.append(nn.Sequential(\n StackedConvLayers(input_features, output_features, num_conv_per_stage - 1, self.conv_op, self.conv_kwargs,\n self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, self.nonlin,\n self.nonlin_kwargs, first_stride, basic_block=basic_block),\n StackedConvLayers(output_features, final_num_features, 1, self.conv_op, self.conv_kwargs,\n self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs, self.nonlin,\n self.nonlin_kwargs, basic_block=basic_block)))\n\n # if we don't want to do dropout in the localization pathway then we set the dropout prob to zero here\n if not dropout_in_localization:\n old_dropout_p = self.dropout_op_kwargs['p']\n self.dropout_op_kwargs['p'] = 0.0\n\n # now lets build the localization pathway\n for u in range(num_pool):\n nfeatures_from_down = final_num_features\n nfeatures_from_skip = self.conv_blocks_context[\n -(2 + u)].output_channels # self.conv_blocks_context[-1] is bottleneck, so start with -2\n n_features_after_tu_and_concat = nfeatures_from_skip * 2\n\n # the first conv reduces the number of features to match those of skip\n # the following convs work on that number of features\n # if not convolutional upsampling then the final conv reduces the num of features again\n if u != num_pool - 1 and not self.convolutional_upsampling:\n final_num_features = self.conv_blocks_context[-(3 + u)].output_channels\n else:\n final_num_features = nfeatures_from_skip\n\n if not self.convolutional_upsampling:\n self.tu.append(Upsample(scale_factor=pool_op_kernel_sizes[-(u + 1)], mode=upsample_mode))\n else:\n self.tu.append(transpconv(nfeatures_from_down, nfeatures_from_skip, pool_op_kernel_sizes[-(u + 1)],\n pool_op_kernel_sizes[-(u + 1)], bias=False))\n\n self.conv_kwargs['kernel_size'] = self.conv_kernel_sizes[- (u + 1)]\n self.conv_kwargs['padding'] = self.conv_pad_sizes[- (u + 1)]\n self.conv_blocks_localization.append(nn.Sequential(\n StackedConvLayers(n_features_after_tu_and_concat, nfeatures_from_skip, num_conv_per_stage - 1,\n self.conv_op, self.conv_kwargs, self.norm_op, self.norm_op_kwargs, self.dropout_op,\n self.dropout_op_kwargs, self.nonlin, self.nonlin_kwargs, basic_block=basic_block),\n StackedConvLayers(nfeatures_from_skip, final_num_features, 1, self.conv_op, self.conv_kwargs,\n self.norm_op, self.norm_op_kwargs, self.dropout_op, self.dropout_op_kwargs,\n self.nonlin, self.nonlin_kwargs, basic_block=basic_block)\n ))\n\n for ds in range(len(self.conv_blocks_localization)):\n self.seg_outputs.append(conv_op(self.conv_blocks_localization[ds][-1].output_channels, num_classes,\n 1, 1, 0, 1, 1, seg_output_use_bias))\n\n self.upscale_logits_ops = []\n cum_upsample = np.cumprod(np.vstack(pool_op_kernel_sizes), axis=0)[::-1]\n for usl in range(num_pool - 1):\n if self.upscale_logits:\n self.upscale_logits_ops.append(Upsample(scale_factor=tuple([int(i) for i in cum_upsample[usl + 1]]),\n mode=upsample_mode))\n else:\n self.upscale_logits_ops.append(lambda x: x)\n\n if not dropout_in_localization:\n self.dropout_op_kwargs['p'] = old_dropout_p\n\n # register all modules properly\n self.conv_blocks_localization = nn.ModuleList(self.conv_blocks_localization)\n self.conv_blocks_context = nn.ModuleList(self.conv_blocks_context)\n self.td = nn.ModuleList(self.td)\n self.tu = nn.ModuleList(self.tu)\n self.seg_outputs = nn.ModuleList(self.seg_outputs)\n if self.upscale_logits:\n self.upscale_logits_ops = nn.ModuleList(\n self.upscale_logits_ops) # lambda x:x is not a Module so we need to distinguish here\n\n if self.weightInitializer is not None:\n self.apply(self.weightInitializer)\n # self.apply(print_module_training_status)\n\n def forward(self, x):\n skips = []\n seg_outputs = []\n for d in range(len(self.conv_blocks_context) - 1):\n x = self.conv_blocks_context[d](x)\n skips.append(x)\n if not self.convolutional_pooling:\n x = self.td[d](x) # downsample\n\n x = self.conv_blocks_context[-1](x)\n\n\n for u in range(len(self.tu)):\n x = self.tu[u](x) # upsample\n x = torch.cat((x, skips[-(u + 1)]), dim=1)\n x = self.conv_blocks_localization[u](x)\n seg_outputs.append(self.final_nonlin(self.seg_outputs[u](x)))\n\n if self._deep_supervision and self.do_ds:\n return tuple([seg_outputs[-1]] + [i(j) for i, j in\n zip(list(self.upscale_logits_ops)[::-1], seg_outputs[:-1][::-1])])\n else:\n return seg_outputs[-1]\n\n @staticmethod\n def compute_approx_vram_consumption(patch_size, num_pool_per_axis, base_num_features, max_num_features,\n num_modalities, num_classes, pool_op_kernel_sizes, deep_supervision=False,\n conv_per_stage=2):\n \"\"\"\n This only applies for num_conv_per_stage and convolutional_upsampling=True\n not real vram consumption. just a constant term to which the vram consumption will be approx proportional\n (+ offset for parameter storage)\n :param deep_supervision:\n :param patch_size:\n :param num_pool_per_axis:\n :param base_num_features:\n :param max_num_features:\n :param num_modalities:\n :param num_classes:\n :param pool_op_kernel_sizes:\n :return:\n \"\"\"\n if not isinstance(num_pool_per_axis, np.ndarray):\n num_pool_per_axis = np.array(num_pool_per_axis)\n\n npool = len(pool_op_kernel_sizes)\n\n map_size = np.array(patch_size)\n tmp = np.int64((conv_per_stage * 2 + 1) * np.prod(map_size, dtype=np.int64) * base_num_features +\n num_modalities * np.prod(map_size, dtype=np.int64) +\n num_classes * np.prod(map_size, dtype=np.int64))\n\n num_feat = base_num_features\n\n for p in range(npool):\n for pi in range(len(num_pool_per_axis)):\n map_size[pi] /= pool_op_kernel_sizes[p][pi]\n num_feat = min(num_feat * 2, max_num_features)\n num_blocks = (conv_per_stage * 2 + 1) if p < (npool - 1) else conv_per_stage # conv_per_stage + conv_per_stage for the convs of encode/decode and 1 for transposed conv\n tmp += num_blocks * np.prod(map_size, dtype=np.int64) * num_feat\n if deep_supervision and p < (npool - 2):\n tmp += np.prod(map_size, dtype=np.int64) * num_classes\n # print(p, map_size, num_feat, tmp)\n return tmp" }, { "identifier": "default_2D_augmentation_params", "path": "nn_transunet/data/default_data_augmentation.py", "snippet": "def get_patch_size(final_patch_size, rot_x, rot_y, rot_z, scale_range):\ndef get_default_augmentation(dataloader_train, dataloader_val, patch_size, params=default_3D_augmentation_params,\n border_val_seg=-1, pin_memory=True,\n seeds_train=None, seeds_val=None, regions=None):" }, { "identifier": "unpack_dataset", "path": "nn_transunet/data/dataset_loading.py", "snippet": "def unpack_dataset(folder, threads=default_num_threads, key=\"data\"):\n \"\"\"\n unpacks all npz files in a folder to npy (whatever you want to have unpacked must be saved unter key)\n :param folder:\n :param threads:\n :param key:\n :return:\n \"\"\"\n p = Pool(threads)\n npz_files = subfiles(folder, True, None, \".npz\", True)\n p.map(convert_to_npy, zip(npz_files, [key] * len(npz_files)))\n p.close()\n p.join()" } ]
from collections import OrderedDict from typing import Tuple from ..data.data_augmentation_moreDA import get_moreDA_augmentation from ..trainer.loss_functions import MultipleOutputLoss2 from ..trainer.network_trainer import maybe_to_torch, to_cuda from ..trainer.nnUNetTrainer import nnUNetTrainer from ..networks.nnunet_model import Generic_UNet from ..data.default_data_augmentation import default_2D_augmentation_params, \ get_patch_size, default_3D_augmentation_params from ..data.dataset_loading import unpack_dataset from sklearn.model_selection import KFold from torch.cuda.amp import autocast from batchgenerators.utilities.file_and_folder_operations import * from torch import nn from loss_functions import DC_and_CE_loss from ..networks.transunet3d_model import Generic_TransUNet_max_ppbp import numpy as np import torch import torch.nn.functional as F
18,374
- self.lr_scheduler = None because we do poly_lr - deep supervision = True - i am sure I forgot something here Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though :return: """ # model_list = {'Generic_UNet': Generic_UNet} if self.model.startswith("Generic"): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} do_ds = not self.disable_ds if not do_ds: print("disable ds") if self.model == 'Generic_TransUNet_max_ppbp': self.network = Generic_TransUNet_max_ppbp(self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, do_ds, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, convolutional_upsampling= False if ('is_fam' in self.model_params.keys() and self.model_params['is_fam']) else True, # default True, patch_size=self.args.crop_size, **self.model_params) else: raise NotImplementedError if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper else: raise NotImplementedError def initialize_optimizer_and_scheduler(self): assert self.network is not None, "self.initialize_network must be called first" self.optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, momentum=0.99, nesterov=True) self.lr_scheduler = None def run_online_evaluation(self, output, target): """ due to deep supervision the return value and the reference are now lists of tensors. We only need the full resolution output because this is what we are interested in in the end. The others are ignored :param output: :param target: :return: """ target = target[0] output = output[0] return super().run_online_evaluation(output, target) def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True, validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False, segmentation_export_kwargs: dict = None, run_postprocessing_on_folds: bool = True): """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().validate(do_mirroring=do_mirroring, use_sliding_window=use_sliding_window, step_size=step_size, save_softmax=save_softmax, use_gaussian=use_gaussian, overwrite=overwrite, validation_folder_name=validation_folder_name, debug=debug, all_in_gpu=all_in_gpu, segmentation_export_kwargs=segmentation_export_kwargs, run_postprocessing_on_folds=run_postprocessing_on_folds) self.network.do_ds = ds return ret def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True, mirror_axes: Tuple[int] = None, use_sliding_window: bool = True, step_size: float = 0.5, use_gaussian: bool = True, pad_border_mode: str = 'constant', pad_kwargs: dict = None, all_in_gpu: bool = False, verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]: """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().predict_preprocessed_data_return_seg_and_softmax(data, do_mirroring=do_mirroring, mirror_axes=mirror_axes, use_sliding_window=use_sliding_window, step_size=step_size, use_gaussian=use_gaussian, pad_border_mode=pad_border_mode, pad_kwargs=pad_kwargs, all_in_gpu=all_in_gpu, verbose=verbose, mixed_precision=mixed_precision) self.network.do_ds = ds return ret def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False): """ gradient clipping improves training stability :param data_generator: :param do_backprop: :param run_online_evaluation: :return: """ data_dict = next(data_generator) data = data_dict['data'] target = data_dict['target']
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. softmax_helper = lambda x: F.softmax(x, 1) def poly_lr(epoch, max_epochs, initial_lr, exponent=0.9): return initial_lr * (1 - epoch / max_epochs)**exponent class InitWeights_He(object): def __init__(self, neg_slope=1e-2): self.neg_slope = neg_slope def __call__(self, module): if isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d): module.weight = nn.init.kaiming_normal_(module.weight, a=self.neg_slope) if module.bias is not None: module.bias = nn.init.constant_(module.bias, 0) class InitWeights_XavierUniform(object): def __init__(self, gain=1): self.gain = gain def __call__(self, module): if isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d): module.weight = nn.init.xavier_uniform_(module.weight, self.gain) if module.bias is not None: module.bias = nn.init.constant_(module.bias, 0) class nnUNetTrainerV2(nnUNetTrainer): """ Info for Fabian: same as internal nnUNetTrainerV2_2 """ def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False, input_size=(64, 160, 160),args=None): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic, fp16) if args is not None: self.input_size=input_size self.model = args.model self.resume = args.resume self.disable_ds=args.disable_ds self.max_num_epochs = args.max_num_epochs # set 1 gpu training self.initial_lr = args.initial_lr # 0.01 self.args = args if self.disable_ds: print("disable_ds") # print("not runnable for this feature! current nnunetV2 (w/o DDP) only support deep supervision version") # raise NotImplementedError else: print("runnning DDP, inheriting nnUNetTrainerV2") self.save_every = 1 # prev 50 # self.max_num_epochs = 1000 # self.initial_lr = 1e-2 self.deep_supervision_scales = None self.ds_loss_weights = None self.pin_memory = True def initialize(self, training=True, force_load_plans=False): """ - replaced get_default_augmentation with get_moreDA_augmentation - enforce to only run this code once - loss function wrapper for deep supervision :param training: :param force_load_plans: :return: """ if not self.was_initialized: maybe_mkdir_p(self.output_folder) if force_load_plans or (self.plans is None): self.load_plans_file() self.process_plans(self.plans) self.setup_DA_params() ################# Here we wrap the loss for deep supervision ############ # we need to know the number of outputs of the network net_numpool = len(self.net_num_pool_op_kernel_sizes) # we give each output a weight which decreases exponentially (division by 2) as the resolution decreases # this gives higher resolution outputs more weight in the loss weights = np.array([1 / (2 ** i) for i in range(net_numpool)]) # we don't use the lowest 2 outputs. Normalize weights so that they sum to 1 mask = np.array([True] + [True if i < net_numpool - 1 else False for i in range(1, net_numpool)]) weights[~mask] = 0 weights = weights / weights.sum() self.ds_loss_weights = weights if self.disable_ds: self.ds_loss_weights[0]=1 self.ds_loss_weights[1:]=0 self.loss = DC_and_CE_loss({'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False}, {}) else: # now wrap the loss self.loss = MultipleOutputLoss2(self.loss, self.ds_loss_weights) ################# END ################### self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] + "_stage%d" % self.stage) if training: self.dl_tr, self.dl_val = self.get_basic_generators() if self.unpack_data: print("unpacking dataset") unpack_dataset(self.folder_with_preprocessed_data) print("done") else: print( "INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you " "will wait all winter for your model to finish!") self.tr_gen, self.val_gen = get_moreDA_augmentation( self.dl_tr, self.dl_val, self.data_aug_params[ 'patch_size_for_spatialtransform'], self.data_aug_params, deep_supervision_scales=self.deep_supervision_scales, pin_memory=self.pin_memory, use_nondetMultiThreadedAugmenter=False ) self.print_to_log_file("TRAINING KEYS:\n %s" % (str(self.dataset_tr.keys())), also_print_to_console=False) self.print_to_log_file("VALIDATION KEYS:\n %s" % (str(self.dataset_val.keys())), also_print_to_console=False) else: pass self.initialize_network() self.initialize_optimizer_and_scheduler() # assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel)) else: self.print_to_log_file('self.was_initialized is True, not running self.initialize again') self.was_initialized = True def initialize_network(self): """ - momentum 0.99 - SGD instead of Adam - self.lr_scheduler = None because we do poly_lr - deep supervision = True - i am sure I forgot something here Known issue: forgot to set neg_slope=0 in InitWeights_He; should not make a difference though :return: """ # model_list = {'Generic_UNet': Generic_UNet} if self.model.startswith("Generic"): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d norm_op = nn.InstanceNorm2d norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} do_ds = not self.disable_ds if not do_ds: print("disable ds") if self.model == 'Generic_TransUNet_max_ppbp': self.network = Generic_TransUNet_max_ppbp(self.num_input_channels, self.base_num_features, self.num_classes, len(self.net_num_pool_op_kernel_sizes), self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, do_ds, False, lambda x: x, InitWeights_He(1e-2), self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, convolutional_upsampling= False if ('is_fam' in self.model_params.keys() and self.model_params['is_fam']) else True, # default True, patch_size=self.args.crop_size, **self.model_params) else: raise NotImplementedError if torch.cuda.is_available(): self.network.cuda() self.network.inference_apply_nonlin = softmax_helper else: raise NotImplementedError def initialize_optimizer_and_scheduler(self): assert self.network is not None, "self.initialize_network must be called first" self.optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay, momentum=0.99, nesterov=True) self.lr_scheduler = None def run_online_evaluation(self, output, target): """ due to deep supervision the return value and the reference are now lists of tensors. We only need the full resolution output because this is what we are interested in in the end. The others are ignored :param output: :param target: :return: """ target = target[0] output = output[0] return super().run_online_evaluation(output, target) def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True, validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False, segmentation_export_kwargs: dict = None, run_postprocessing_on_folds: bool = True): """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().validate(do_mirroring=do_mirroring, use_sliding_window=use_sliding_window, step_size=step_size, save_softmax=save_softmax, use_gaussian=use_gaussian, overwrite=overwrite, validation_folder_name=validation_folder_name, debug=debug, all_in_gpu=all_in_gpu, segmentation_export_kwargs=segmentation_export_kwargs, run_postprocessing_on_folds=run_postprocessing_on_folds) self.network.do_ds = ds return ret def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True, mirror_axes: Tuple[int] = None, use_sliding_window: bool = True, step_size: float = 0.5, use_gaussian: bool = True, pad_border_mode: str = 'constant', pad_kwargs: dict = None, all_in_gpu: bool = False, verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]: """ We need to wrap this because we need to enforce self.network.do_ds = False for prediction """ ds = self.network.do_ds self.network.do_ds = False ret = super().predict_preprocessed_data_return_seg_and_softmax(data, do_mirroring=do_mirroring, mirror_axes=mirror_axes, use_sliding_window=use_sliding_window, step_size=step_size, use_gaussian=use_gaussian, pad_border_mode=pad_border_mode, pad_kwargs=pad_kwargs, all_in_gpu=all_in_gpu, verbose=verbose, mixed_precision=mixed_precision) self.network.do_ds = ds return ret def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False): """ gradient clipping improves training stability :param data_generator: :param do_backprop: :param run_online_evaluation: :return: """ data_dict = next(data_generator) data = data_dict['data'] target = data_dict['target']
data = maybe_to_torch(data)
2
2023-10-11 05:19:25+00:00
24k
eai-lab/On-NAS
cifar_search.py
[ { "identifier": "genotypes", "path": "utils/genotypes.py", "snippet": "PRIMITIVES = [\n \"max_pool_3x3\",\n \"avg_pool_3x3\",\n \"skip_connect\", # identity\n \"sep_conv_3x3\",\n \"sep_conv_5x5\",\n \"dil_conv_3x3\",\n \"dil_conv_5x5\",\n \"none\",\n]\nPRIMITIVES_FEWSHOT = [\n \"max_pool_3x3\",\n \"avg_pool_3x3\",\n \"skip_connect\", # identity\n \"conv_1x5_5x1\",\n \"conv_3x3\",\n \"sep_conv_3x3\",\n # \"sep_conv_5x5\",\n \"dil_conv_3x3\",\n # \"dil_conv_5x5\",\n # \"none\",\n]\ndef to_dag(C_in, gene, reduction):\ndef from_str(s):\ndef parse(alpha, k, primitives=PRIMITIVES_FEWSHOT):\ndef parse_pairwise(alpha, alpha_pairwise, primitives=PRIMITIVES_FEWSHOT): # deprecated" }, { "identifier": "SearchCNNController", "path": "models/search_cnn.py", "snippet": "class SearchCNNController(nn.Module):\n \"\"\" SearchCNN controller supporting multi-gpu \"\"\"\n def __init__(\n self,\n \n C_in,\n C,\n n_classes,\n n_layers,\n config,\n n_nodes=4,\n reduction_layers=[],\n stem_multiplier=3,\n device_ids=None,\n normalizer=dict(),\n PRIMITIVES=None,\n feature_scale_rate=2,\n use_hierarchical_alphas=False, # deprecated\n use_pairwise_input_alphas=False,\n alpha_prune_threshold=0.0,\n ):\n super().__init__()\n self.n_nodes = n_nodes\n self.criterion = nn.CrossEntropyLoss()\n self.use_pairwise_input_alphas = use_pairwise_input_alphas\n self.use_hierarchical_alphas = use_hierarchical_alphas\n self.alpha_prune_threshold = alpha_prune_threshold\n \n if \"name\" not in normalizer.keys():\n normalizer[\"func\"] = SoftMax\n normalizer[\"params\"] = dict()\n normalizer[\"params\"][\"temp_anneal_mode\"] = None\n elif normalizer[\"name\"] == \"softmax\":\n normalizer[\"func\"] = SoftMax\n elif normalizer[\"name\"] == \"relusoftmax\":\n normalizer[\"func\"] = ReLUSoftMax\n elif normalizer[\"name\"] == \"gumbel_softmax\":\n normalizer[\"func\"] = GumbelSoftMax\n else:\n raise RuntimeError(f\"Unknown normalizer {normalizer['name']}\")\n self.normalizer = normalizer\n\n if device_ids is None:\n device_ids = list(range(torch.cuda.device_count()))\n self.device_ids = device_ids\n\n \n \n # initialize architect parameters: alphas\n if PRIMITIVES is None:\n PRIMITIVES = gt.PRIMITIVES\n\n self.primitives = PRIMITIVES\n n_ops = len(PRIMITIVES)\n\n self.alpha_normal = nn.ParameterList()\n self.alpha_reduce = nn.ParameterList()\n\n \n for i in range(n_nodes):\n # create alpha parameters over parallel operations\n self.alpha_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n self.alpha_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n \n \n\n \n assert not (\n use_hierarchical_alphas and use_pairwise_input_alphas\n ), \"Hierarchical and pairwise alphas exclude each other.\"\n\n self.alpha_pw_normal = None\n self.alpha_pw_reduce = None\n self.alpha_in_normal = None\n self.alpha_in_reduce = None\n if use_hierarchical_alphas: # deprecated\n # create alpha parameters the different input nodes for a cell, i.e. for each node in a\n # cell an additional distribution over the input nodes is introduced\n print(\"Using hierarchical alphas.\")\n\n self.alpha_in_normal = nn.ParameterList()\n self.alpha_in_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n self.alpha_in_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n self.alpha_in_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n\n elif use_pairwise_input_alphas:\n print(\"Using pairwise input alphas.\")\n\n self.alpha_pw_normal = nn.ParameterList()\n self.alpha_pw_reduce = nn.ParameterList()\n\n \n for i in range(n_nodes):\n num_comb = int(scipy.special.binom(i + 2, 2))\n self.alpha_pw_normal.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n self.alpha_pw_reduce.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n \n \n\n # setup alphas list\n self._alphas = []\n \n for n, p in self.named_parameters():\n if \"alpha\" in n:\n self._alphas.append((n, p))\n\n \n \n self.net = SearchCNN(\n \n C_in,\n C,\n n_classes,\n n_layers,\n config,\n n_nodes,\n reduction_layers,\n stem_multiplier,\n PRIMITIVES=self.primitives,\n feature_scale_rate=feature_scale_rate,\n )\n\n \n\n def apply_normalizer(self, alpha):\n return self.normalizer[\"func\"](alpha, self.normalizer[\"params\"])\n\n def _get_normalized_alphas(self):\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = None\n weights_pw_reduce = None\n weights_in_normal = None\n weights_in_reduce = None\n if self.alpha_in_normal is not None:\n weights_in_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_normal\n ]\n weights_in_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_reduce\n ]\n elif self.alpha_pw_normal is not None:\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n\n return (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n )\n\n def prune_alphas(self, prune_threshold=0.0, val=-10e8):\n \"\"\"Set the alphas with probability below prune_threshold to a large negative value\n\n Note:\n The prune_threshold applies to the alpha probabilities (after the softmax is\n applied) while `val` corresponds to the logit values (thus a large negative value\n corresponds to a low probability).\n \"\"\"\n\n # reset temperature for prunning\n model_has_normalizer = hasattr(self, \"normalizer\")\n if model_has_normalizer:\n curr_step_backup = self.normalizer[\"params\"][\"curr_step\"]\n self.normalizer[\"params\"][\"curr_step\"] = (\n self.normalizer[\"params\"][\"max_steps\"] - 1\n )\n\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n for idx in range(len(weights_normal)):\n # need to modify data because alphas are leaf variables\n self.alpha_normal[idx].data[weights_normal[idx] < prune_threshold] = val\n self.alpha_reduce[idx].data[weights_reduce[idx] < prune_threshold] = val\n\n # set curr_step back to original value\n self.normalizer[\"params\"][\"curr_step\"] = curr_step_backup\n\n def get_sparse_alphas_pw(self, alpha_prune_threshold=0.0):\n\n \"\"\"\n Convert alphas to zero-one-vectors under consideration of pairwise alphas\n\n\n :param alpha_prune_threshold: threshold for pruning\n\n :return: binary tensors with shape like alpha_normal and alpha_reduce, indicating whether an op is included in the\n sparsified one shot model\n \"\"\"\n\n assert (\n self.alpha_pw_normal is not None\n ), \"Error: function only availaible for pw models\"\n\n weights_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_normal\n ] # get normalized weights\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n\n weights_normal_sparse = list()\n\n # get all the pairs of inputs\n for node_idx, node_weights in enumerate(weights_normal):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_normal[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_normal[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_normal_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n ### same for reduction\n\n weights_reduce_sparse = list()\n\n for node_idx, node_weights in enumerate(weights_reduce):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_reduce[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_reduce[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_reduce_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n return weights_normal_sparse, weights_reduce_sparse\n\n def get_sparse_num_params(self, alpha_prune_threshold=0.0):\n \"\"\"Get number of parameters for sparse one-shot-model\n\n Returns:\n A torch tensor\n \"\"\"\n\n weights_normal, weights_reduce = self.get_sparse_alphas_pw(\n alpha_prune_threshold\n )\n # this returns tensors with only 0's and 1's depending on whether an op is used in the sparsified model\n\n # get none active ops/layer names\n\n # for normal cell\n none_active_ops_normal = list()\n for node_idx, node in enumerate(weights_normal):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_normal.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n # and for reduction cell\n none_active_ops_reduce = list()\n for node_idx, node in enumerate(weights_reduce):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_reduce.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n all_params = sum(\n p.numel() for p in self.net.parameters()\n ) # params of one-shot model\n\n # get normal and reduction layers\n normal_cells = list()\n red_cells = list()\n for lyr, cell in enumerate(self.net.cells):\n if cell.reduction:\n red_cells.append(lyr)\n else:\n normal_cells.append(lyr)\n\n # count params of non-active ops\n\n none_active_params = 0\n for layer_name, layer_weights in self.named_parameters():\n # check if layer is part of normal or reduction cell\n if \"net.cells.\" in layer_name: # layer part of cells at all?\n for cell in normal_cells: # normal cell?\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_normal\n\n # else reduction cell\n for cell in red_cells:\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_reduce\n\n if any(\n [none_active_op in layer_name for none_active_op in none_active_ops]\n ): # check if layer is part of none-active ops\n none_active_params += layer_weights.numel()\n\n active_params = all_params - none_active_params\n\n return active_params\n\n def drop_path_prob(self, p):\n \"\"\" Set drop path probability \"\"\"\n for module in self.net.modules():\n if isinstance(module, ops.DropPath_):\n module.p = p\n def forward(self, x, sparsify_input_alphas=None):\n \"\"\"Forward pass through the network\n\n Args:\n x: The input tensor\n sparsify_input_alphas: Whether to sparsify the alphas over the input nodes. Use `None`\n to not sparsify input alphas.\n For hierarchical alphas, `sparsify_input_alphas` should be a (float) threshold on\n the probability (i.e. between 0 and 1). Alphas above the threshold (and thus the\n corresponding input nodes) are kept.\n For pairwise alphas, if `sparsify_input_alphas` is larger than 0, then only the\n largest alpha is kept.\n Note that the sparsification is not be differentiable and thus cannot be used during\n training.\n\n Returns:\n The network output\n \"\"\"\n (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n ) = self._get_normalized_alphas()\n\n \n if len(self.device_ids) == 1 :\n output= self.net(\n x,\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n sparsify_input_alphas=sparsify_input_alphas,\n alpha_prune_threshold=self.alpha_prune_threshold,\n )\n return output\n\n \n # scatter x\n xs = nn.parallel.scatter(x, self.device_ids)\n # broadcast weights\n wnormal_copies = broadcast_list(weights_normal, self.device_ids)\n wreduce_copies = broadcast_list(weights_reduce, self.device_ids)\n if weights_in_normal is not None:\n wnormal_in_copies = broadcast_list(weights_in_normal, self.device_ids)\n wreduce_in_copies = broadcast_list(weights_in_reduce, self.device_ids)\n else:\n \n wnormal_in_copies = None\n wreduce_in_copies = None\n\n if weights_pw_normal is not None:\n wnormal_pw_copies = broadcast_list(weights_pw_normal, self.device_ids)\n wreduce_pw_copies = broadcast_list(weights_pw_reduce, self.device_ids)\n else:\n wnormal_pw_copies = None\n wreduce_pw_copies = None\n\n # replicate modules\n replicas = nn.parallel.replicate(self.net, self.device_ids)\n outputs = nn.parallel.parallel_apply(\n replicas,\n list(\n zip(\n xs,\n wnormal_copies,\n wreduce_copies,\n # wnormal_in_copies,\n # wreduce_in_copies,\n # wnormal_pw_copies,\n # wreduce_pw_copies,\n )\n ),\n devices=self.device_ids,\n )\n return nn.parallel.gather(outputs, self.device_ids[0])\n\n def loss(self, X, y):\n logits = self.forward(X)\n return self.criterion(logits, y)\n\n def print_alphas(self, logger):\n # remove formats\n org_formatters = []\n for handler in logger.handlers:\n org_formatters.append(handler.formatter)\n handler.setFormatter(logging.Formatter(\"%(message)s\"))\n\n normalizer = self.get_normalizer(deterministic=True)\n logger.info(\"####### ALPHA #######\")\n logger.info(\"# Alpha - normal\")\n for alpha in self.alpha_normal:\n logger.info(normalizer(alpha))\n\n logger.info(\"\\n# Alpha - reduce\")\n for alpha in self.alpha_reduce:\n logger.info(normalizer(alpha))\n logger.info(\"#####################\")\n\n # restore formats\n for handler, formatter in zip(logger.handlers, org_formatters):\n handler.setFormatter(formatter)\n\n def genotype(self):\n if self.use_pairwise_input_alphas:\n\n weights_pw_normal = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_reduce\n ]\n\n gene_normal = gt.parse_pairwise(\n self.alpha_normal, weights_pw_normal, primitives=self.primitives\n )\n gene_reduce = gt.parse_pairwise(\n self.alpha_reduce, weights_pw_reduce, primitives=self.primitives\n )\n\n elif self.use_hierarchical_alphas:\n raise NotImplementedError\n else:\n\n gene_normal = gt.parse(self.alpha_normal, k=2, primitives=self.primitives)\n gene_reduce = gt.parse(self.alpha_reduce, k=2, primitives=self.primitives)\n\n concat = range(2, 2 + self.n_nodes) # concat all intermediate nodes\n\n return gt.Genotype(\n normal=gene_normal,\n normal_concat=concat,\n reduce=gene_reduce,\n reduce_concat=concat,\n )\n\n def weights(self):\n return self.net.parameters()\n\n def named_weights(self):\n return self.net.named_parameters()\n\n def named_weights_with_net(self):\n return self.named_parameters()\n\n def alphas(self):\n for n, p in self._alphas:\n yield p\n\n def named_alphas(self):\n for n, p in self._alphas:\n yield n, p" }, { "identifier": "SearchCNNControllerPC", "path": "models/search_cnn_PC.py", "snippet": "class SearchCNNControllerPC(nn.Module):\n \"\"\" SearchCNN controller supporting multi-gpu \"\"\"\n\n def __init__(\n self,\n C_in,\n C,\n n_classes,\n n_layers,\n n_nodes=4,\n reduction_layers=[],\n stem_multiplier=3,\n device_ids=None,\n normalizer=dict(),\n PRIMITIVES=None,\n feature_scale_rate=2,\n use_hierarchical_alphas=False, # deprecated\n use_pairwise_input_alphas=False,\n use_pc_adaptation=False,\n alpha_prune_threshold=0.0,\n ):\n super().__init__()\n self.n_nodes = n_nodes\n self.criterion = nn.CrossEntropyLoss()\n self.use_pairwise_input_alphas = use_pairwise_input_alphas\n self.use_hierarchical_alphas = use_hierarchical_alphas\n self.alpha_prune_threshold = alpha_prune_threshold\n self.use_pc_adaptation = use_pc_adaptation\n if \"name\" not in normalizer.keys():\n normalizer[\"func\"] = SoftMax\n normalizer[\"params\"] = dict()\n normalizer[\"params\"][\"temp_anneal_mode\"] = None\n elif normalizer[\"name\"] == \"softmax\":\n normalizer[\"func\"] = SoftMax\n elif normalizer[\"name\"] == \"relusoftmax\":\n normalizer[\"func\"] = ReLUSoftMax\n elif normalizer[\"name\"] == \"gumbel_softmax\":\n normalizer[\"func\"] = GumbelSoftMax\n else:\n raise RuntimeError(f\"Unknown normalizer {normalizer['name']}\")\n self.normalizer = normalizer\n\n if device_ids is None:\n device_ids = list(range(torch.cuda.device_count()))\n self.device_ids = device_ids\n\n # initialize architect parameters: alphas\n if PRIMITIVES is None:\n PRIMITIVES = gt.PRIMITIVES\n\n self.primitives = PRIMITIVES\n n_ops = len(PRIMITIVES)\n\n self.alpha_normal = nn.ParameterList()\n self.alpha_reduce = nn.ParameterList()\n\n\n self.pc_beta_normal = nn.ParameterList()\n self.pc_beta_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n # create alpha parameters over parallel operations\n self.alpha_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n self.alpha_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2, n_ops)))\n\n assert not (\n use_hierarchical_alphas and use_pairwise_input_alphas\n ), \"Hierarchical and pairwise alphas exclude each other.\"\n\n self.alpha_pw_normal = None\n self.alpha_pw_reduce = None\n self.alpha_in_normal = None\n self.alpha_in_reduce = None\n self.pc_alpha_normal = None\n self.pc_alpha_reduce = None \n\n if use_hierarchical_alphas: # deprecated\n # create alpha parameters the different input nodes for a cell, i.e. for each node in a\n # cell an additional distribution over the input nodes is introduced\n print(\"Using hierarchical alphas.\")\n\n self.alpha_in_normal = nn.ParameterList()\n self.alpha_in_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n self.alpha_in_normal.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n self.alpha_in_reduce.append(nn.Parameter(1e-3 * torch.randn(i + 2)))\n\n elif use_pairwise_input_alphas:\n print(\"Using pairwise input alphas.\")\n\n self.alpha_pw_normal = nn.ParameterList()\n self.alpha_pw_reduce = nn.ParameterList()\n\n for i in range(n_nodes):\n num_comb = int(scipy.special.binom(i + 2, 2))\n self.alpha_pw_normal.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n self.alpha_pw_reduce.append(nn.Parameter(1e-3 * torch.randn(num_comb)))\n \n if use_pc_adaptation:\n # initialize pc_beta here\n # beta have to be [[2],[3],[4]]\n self.pc_alpha_normal = nn.ParameterList()\n self.pc_alpha_reduce = nn.ParameterList()\n for i in range(n_nodes):\n num_edges = i + 2\n self.pc_alpha_normal.append(nn.Parameter(1e-3 * torch.randn(num_edges)))\n self.pc_alpha_reduce.append(nn.Parameter(1e-3 * torch.randn(num_edges)))\n\n\n # setup alphas list\n self._alphas = []\n for n, p in self.named_parameters():\n if \"alpha\" in n:\n self._alphas.append((n, p))\n\n self.net = SearchCNNPC(\n C_in,\n C,\n n_classes,\n n_layers,\n n_nodes,\n reduction_layers,\n stem_multiplier,\n PRIMITIVES=self.primitives,\n feature_scale_rate=feature_scale_rate,\n )\n\n def apply_normalizer(self, alpha):\n return self.normalizer[\"func\"](alpha, self.normalizer[\"params\"])\n\n def _get_normalized_alphas(self):\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = None\n weights_pw_reduce = None\n weights_in_normal = None\n weights_in_reduce = None\n weights_pc_normal = None\n weights_pc_reduce = None\n\n if self.alpha_in_normal is not None:\n weights_in_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_normal\n ]\n weights_in_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_in_reduce\n ]\n elif self.alpha_pw_normal is not None:\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n if self.pc_alpha_normal is not None:\n weights_pc_normal = [\n self.apply_normalizer(alpha) for alpha in self.pc_alpha_normal\n ]\n weights_pc_reduce = [\n self.apply_normalizer(alpha) for alpha in self.pc_alpha_reduce\n ]\n return (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n weights_pc_normal,\n weights_pc_reduce,\n )\n\n def prune_alphas(self, prune_threshold=0.0, val=-10e8):\n \"\"\"Set the alphas with probability below prune_threshold to a large negative value\n\n Note:\n The prune_threshold applies to the alpha probabilities (after the softmax is\n applied) while `val` corresponds to the logit values (thus a large negative value\n corresponds to a low probability).\n \"\"\"\n\n # reset temperature for prunning\n model_has_normalizer = hasattr(self, \"normalizer\")\n if model_has_normalizer:\n curr_step_backup = self.normalizer[\"params\"][\"curr_step\"]\n self.normalizer[\"params\"][\"curr_step\"] = (\n self.normalizer[\"params\"][\"max_steps\"] - 1\n )\n\n weights_normal = [self.apply_normalizer(alpha) for alpha in self.alpha_normal]\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n for idx in range(len(weights_normal)):\n # need to modify data because alphas are leaf variables\n self.alpha_normal[idx].data[weights_normal[idx] < prune_threshold] = val\n self.alpha_reduce[idx].data[weights_reduce[idx] < prune_threshold] = val\n\n # set curr_step back to original value\n self.normalizer[\"params\"][\"curr_step\"] = curr_step_backup\n\n def get_sparse_alphas_pw(self, alpha_prune_threshold=0.0):\n\n \"\"\"\n Convert alphas to zero-one-vectors under consideration of pairwise alphas\n\n\n :param alpha_prune_threshold: threshold for pruning\n\n :return: binary tensors with shape like alpha_normal and alpha_reduce, indicating whether an op is included in the\n sparsified one shot model\n \"\"\"\n\n assert (\n self.alpha_pw_normal is not None\n ), \"Error: function only availaible for pw models\"\n\n weights_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_normal\n ] # get normalized weights\n weights_reduce = [self.apply_normalizer(alpha) for alpha in self.alpha_reduce]\n\n weights_pw_normal = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_normal\n ]\n\n weights_pw_reduce = [\n self.apply_normalizer(alpha) for alpha in self.alpha_pw_reduce\n ]\n\n weights_normal_sparse = list()\n\n # get all the pairs of inputs\n for node_idx, node_weights in enumerate(weights_normal):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_normal[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_normal[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_normal_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n ### same for reduction\n\n weights_reduce_sparse = list()\n\n for node_idx, node_weights in enumerate(weights_reduce):\n input_pairs = list()\n\n # get pairs of inputs correspeonding to indices in alpha_pw\n for input_1 in range(len(node_weights)):\n for input_2 in range(input_1 + 1, len(node_weights)):\n input_pairs.append([input_1, input_2])\n\n assert len(input_pairs) == len(\n weights_pw_reduce[node_idx]\n ), \"error: pairwise alpha length does not match pairwise terms length\"\n\n keep_inputs = list() # list of input nodes that are kept\n\n for input_pair_idx in range(len(input_pairs)):\n if (\n weights_pw_reduce[node_idx][input_pair_idx] >= alpha_prune_threshold\n ): # if pw weight larger than threshold keep input\n keep_inputs.extend(input_pairs[input_pair_idx])\n\n weights_reduce_sparse.append(\n torch.stack(\n [\n (weight >= alpha_prune_threshold).type(torch.float)\n if weight_idx in keep_inputs\n else torch.zeros_like(weight)\n for weight_idx, weight in enumerate(node_weights)\n ]\n )\n )\n\n return weights_normal_sparse, weights_reduce_sparse\n\n def get_sparse_num_params(self, alpha_prune_threshold=0.0):\n \"\"\"Get number of parameters for sparse one-shot-model\n\n Returns:\n A torch tensor\n \"\"\"\n\n weights_normal, weights_reduce = self.get_sparse_alphas_pw(\n alpha_prune_threshold\n )\n # this returns tensors with only 0's and 1's depending on whether an op is used in the sparsified model\n\n # get none active ops/layer names\n\n # for normal cell\n none_active_ops_normal = list()\n for node_idx, node in enumerate(weights_normal):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_normal.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n # and for reduction cell\n none_active_ops_reduce = list()\n for node_idx, node in enumerate(weights_reduce):\n for mixed_op_idx, mixed_op in enumerate(node):\n none_active_ops_idx = (mixed_op == 0.0).nonzero()\n for op in none_active_ops_idx:\n none_active_ops_reduce.append(\n str(node_idx)\n + \".\"\n + str(mixed_op_idx)\n + \"._ops.\"\n + str(int(op))\n )\n\n all_params = sum(\n p.numel() for p in self.net.parameters()\n ) # params of one-shot model\n\n # get normal and reduction layers\n normal_cells = list()\n red_cells = list()\n for lyr, cell in enumerate(self.net.cells):\n if cell.reduction:\n red_cells.append(lyr)\n else:\n normal_cells.append(lyr)\n\n # count params of non-active ops\n\n none_active_params = 0\n for layer_name, layer_weights in self.named_parameters():\n # check if layer is part of normal or reduction cell\n if \"net.cells.\" in layer_name: # layer part of cells at all?\n for cell in normal_cells: # normal cell?\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_normal\n\n # else reduction cell\n for cell in red_cells:\n if \"net.cells.\" + str(cell) in layer_name: # normal cell\n none_active_ops = none_active_ops_reduce\n\n if any(\n [none_active_op in layer_name for none_active_op in none_active_ops]\n ): # check if layer is part of none-active ops\n none_active_params += layer_weights.numel()\n\n active_params = all_params - none_active_params\n\n return active_params\n\n def drop_path_prob(self, p):\n \"\"\" Set drop path probability \"\"\"\n for module in self.net.modules():\n if isinstance(module, ops_7c.DropPath_):\n module.p = p\n\n def forward(self, x, sparsify_input_alphas=None):\n \"\"\"Forward pass through the network\n\n Args:\n x: The input tensor\n sparsify_input_alphas: Whether to sparsify the alphas over the input nodes. Use `None`\n to not sparsify input alphas.\n For hierarchical alphas, `sparsify_input_alphas` should be a (float) threshold on\n the probability (i.e. between 0 and 1). Alphas above the threshold (and thus the\n corresponding input nodes) are kept.\n For pairwise alphas, if `sparsify_input_alphas` is larger than 0, then only the\n largest alpha is kept.\n Note that the sparsification is not be differentiable and thus cannot be used during\n training.\n\n Returns:\n The network output\n \"\"\"\n\n (\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n weights_pc_normal,\n weights_pc_reduce,\n ) = self._get_normalized_alphas()\n\n if len(self.device_ids) == 1:\n return self.net(\n x,\n weights_normal,\n weights_reduce,\n weights_in_normal,\n weights_in_reduce,\n weights_pw_normal,\n weights_pw_reduce,\n weights_pc_normal,\n weights_pc_reduce,\n sparsify_input_alphas=sparsify_input_alphas,\n alpha_prune_threshold=self.alpha_prune_threshold,\n )\n\n # scatter x\n xs = nn.parallel.scatter(x, self.device_ids)\n # broadcast weights\n wnormal_copies = broadcast_list(weights_normal, self.device_ids)\n wreduce_copies = broadcast_list(weights_reduce, self.device_ids)\n\n if weights_in_normal is not None:\n wnormal_in_copies = broadcast_list(weights_in_normal, self.device_ids)\n wreduce_in_copies = broadcast_list(weights_in_reduce, self.device_ids)\n else:\n wnormal_in_copies = None\n wreduce_in_copies = None\n\n if weights_pw_normal is not None:\n wnormal_pw_copies = broadcast_list(weights_pw_normal, self.device_ids)\n wreduce_pw_copies = broadcast_list(weights_pw_reduce, self.device_ids)\n else:\n wnormal_pw_copies = None\n wreduce_pw_copies = None\n\n # replicate modules\n replicas = nn.parallel.replicate(self.net, self.device_ids)\n outputs = nn.parallel.parallel_apply(\n replicas,\n list(\n zip(\n xs,\n wnormal_copies,\n wreduce_copies,\n wnormal_in_copies,\n wreduce_in_copies,\n wnormal_pw_copies,\n wreduce_pw_copies,\n )\n ),\n devices=self.device_ids,\n )\n return nn.parallel.gather(outputs, self.device_ids[0])\n\n def loss(self, X, y):\n logits = self.forward(X)\n return self.criterion(logits, y)\n\n def print_alphas(self, logger):\n # remove formats\n org_formatters = []\n for handler in logger.handlers:\n org_formatters.append(handler.formatter)\n handler.setFormatter(logging.Formatter(\"%(message)s\"))\n\n normalizer = self.get_normalizer(deterministic=True)\n logger.info(\"####### ALPHA #######\")\n logger.info(\"# Alpha - normal\")\n for alpha in self.alpha_normal:\n logger.info(normalizer(alpha))\n\n logger.info(\"\\n# Alpha - reduce\")\n for alpha in self.alpha_reduce:\n logger.info(normalizer(alpha))\n logger.info(\"#####################\")\n\n # restore formats\n for handler, formatter in zip(logger.handlers, org_formatters):\n handler.setFormatter(formatter)\n\n def genotype(self):\n if self.use_pairwise_input_alphas:\n\n weights_pw_normal = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_normal\n ]\n weights_pw_reduce = [\n F.softmax(alpha, dim=-1) for alpha in self.alpha_pw_reduce\n ]\n\n gene_normal = gt.parse_pairwise(\n self.alpha_normal, weights_pw_normal, primitives=self.primitives\n )\n gene_reduce = gt.parse_pairwise(\n self.alpha_reduce, weights_pw_reduce, primitives=self.primitives\n )\n\n elif self.use_hierarchical_alphas:\n raise NotImplementedError\n else:\n\n gene_normal = gt.parse(self.alpha_normal, k=2, primitives=self.primitives)\n gene_reduce = gt.parse(self.alpha_reduce, k=2, primitives=self.primitives)\n\n concat = range(2, 2 + self.n_nodes) # concat all intermediate nodes\n\n return gt.Genotype(\n normal=gene_normal,\n normal_concat=concat,\n reduce=gene_reduce,\n reduce_concat=concat,\n )\n\n def weights(self):\n return self.net.parameters()\n\n def named_weights(self):\n return self.net.named_parameters()\n\n def named_weights_with_net(self):\n return self.named_parameters()\n\n def alphas(self):\n for n, p in self._alphas:\n yield p\n\n def named_alphas(self):\n for n, p in self._alphas:\n yield n, p" }, { "identifier": "Darts", "path": "task_optimizer/darts.py", "snippet": "class Darts:\n def __init__(self, model, config, do_schedule_lr=False):\n\n self.config = config\n self.config.logger = None\n self.model = model\n self.do_schedule_lr = do_schedule_lr\n self.task_train_steps = config.task_train_steps\n self.test_task_train_steps = config.test_task_train_steps\n self.warm_up_epochs = config.warm_up_epochs\n self.eval_switch = 0\n self.pprevious_grads = 0\n # weights optimizer\n\n self.w_optim = torch.optim.Adam(\n self.model.weights(),\n lr=self.config.w_lr,\n betas=(0.0, 0.999), # config.w_momentum,\n weight_decay=self.config.w_weight_decay,\n ) #\n\n # architecture optimizer\n self.a_optim = torch.optim.Adam(\n model.alphas(),\n self.config.alpha_lr,\n betas=(0.0, 0.999),\n weight_decay=self.config.alpha_weight_decay,\n )\n self.architect = Architect(\n self.model,\n self.config.w_momentum,\n self.config.w_weight_decay,\n self.config.use_first_order_darts,\n )\n def step(\n self,\n task,\n epoch,\n global_progress=\"\",\n test_phase=False,\n alpha_logger=None,\n sparsify_input_alphas=None,\n ):\n \n\n\n log_alphas = False\n\n if test_phase:\n top1_logger = self.config.top1_logger_test\n losses_logger = self.config.losses_logger_test\n train_steps = self.config.test_task_train_steps\n arch_adap_steps = int(train_steps * self.config.test_adapt_steps)\n \n if alpha_logger is not None:\n log_alphas = True\n\n else:\n top1_logger = self.config.top1_logger\n losses_logger = self.config.losses_logger\n train_steps = self.config.task_train_steps\n arch_adap_steps = train_steps\n \n\n \n\n lr = self.config.w_lr\n\n if self.config.w_task_anneal:\n for group in self.w_optim.param_groups:\n group[\"lr\"] = self.config.w_lr\n\n w_task_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n self.w_optim, train_steps, eta_min=0.0\n )\n else:\n w_task_lr_scheduler = None\n\n if self.config.a_task_anneal:\n for group in self.a_optim.param_groups:\n group[\"lr\"] = self.config.alpha_lr\n\n a_task_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n self.a_optim, arch_adap_steps, eta_min=0.0\n )\n\n else:\n a_task_lr_scheduler = None\n\n model_has_normalizer = hasattr(self.model, \"normalizer\")\n if model_has_normalizer:\n self.model.normalizer[\"params\"][\"curr_step\"] = 0.0\n self.architect.v_net.normalizer[\"params\"][\"curr_step\"] = 0.0\n self.model.normalizer[\"params\"][\"max_steps\"] = float(arch_adap_steps)\n self.architect.v_net.normalizer[\"params\"][\"max_steps\"] = float(\n arch_adap_steps\n )\n from tqdm import tqdm\n if self.config.drop_path_prob > 0.0:\n if not test_phase or self.config.use_drop_path_in_meta_testing:\n self.model.drop_path_prob(self.config.drop_path_prob)\n\n p_bar = tqdm(range(train_steps))\n self.config.total_steps = train_steps * len(task.train_loader)\n \n\n\n for train_step in p_bar: # task train_steps = epochs per task\n warm_up = (\n epoch < self.warm_up_epochs\n ) # if epoch < warm_up_epochs, do warm up\n if (\n train_step >= arch_adap_steps\n ): # no architecture adap after arch_adap_steps steps\n warm_up = 1\n\n if w_task_lr_scheduler is not None:\n w_task_lr_scheduler.step()\n\n if a_task_lr_scheduler is not None:\n a_task_lr_scheduler.step()\n torch.cuda.reset_peak_memory_stats(device=0)\n \n task_specific_model = train( \n task,\n self.model,\n self.architect,\n self.w_optim,\n self.a_optim,\n lr,\n global_progress,\n self.config,\n warm_up,\n test_phase\n )\n mem = torch.cuda.memory_stats(0)['allocated_bytes.all.peak']/(1024**2)\n p_bar.set_postfix({\"Memory\" : f\"{mem : .2f}\",\"Task average\":f\"{self.config.top1_logger_test.avg:.1%}\"})\n if train_step == 9:\n self.config.memory_snap = mem\n if (\n model_has_normalizer\n and train_step < (arch_adap_steps - 1)\n and not warm_up\n ): \n self.model.normalizer[\"params\"][\"curr_step\"] += 1\n self.architect.v_net.normalizer[\"params\"][\"curr_step\"] += 1\n\n w_task = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_weight)\n for layer_name, layer_weight in self.model.named_weights()\n # if layer_weight.grad is not None\n }\n )\n a_task = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_alpha)\n for layer_name, layer_alpha in self.model.named_alphas()\n # if layer_alpha.grad is not None\n }\n )\n\n \n w_task_bot = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_weight)\n for layer_name, layer_weight in task_specific_model.named_weights()\n \n }\n )\n a_task_bot = OrderedDict(\n {\n layer_name: copy.deepcopy(layer_alpha)\n for layer_name, layer_alpha in task_specific_model.named_alphas()\n \n }\n )\n # Log genotype\n genotype = self.model.genotype()\n\n if log_alphas:\n alpha_logger[\"normal_relaxed\"].append(\n copy.deepcopy(self.model.alpha_normal)\n )\n alpha_logger[\"reduced_relaxed\"].append(\n copy.deepcopy(self.model.alpha_reduce)\n )\n alpha_logger[\"all_alphas\"].append(a_task)\n alpha_logger[\"normal_hierarchical\"].append(\n copy.deepcopy(self.model.alpha_in_normal)\n )\n alpha_logger[\"reduced_hierarchical\"].append(\n copy.deepcopy(self.model.alpha_in_reduce)\n )\n alpha_logger[\"normal_pairwise\"].append(\n copy.deepcopy(self.model.alpha_pw_normal)\n )\n alpha_logger[\"reduced_pairwise\"].append(\n copy.deepcopy(self.model.alpha_pw_reduce)\n )\n\n # for test data evaluation, turn off drop path\n if self.config.drop_path_prob > 0.0:\n self.model.drop_path_prob(0.0)\n little_switch = 0\n\n if self.config.naivenaive:\n little_switch = 1\n with torch.no_grad():\n self.config.naivenaive = 1\n self.config.eval_switch = 1\n self.config.cell_phase = 3\n\n for batch_idx, batch in enumerate(task.test_loader):\n \n x_test, y_test = batch\n x_test = x_test.to(self.config.device, non_blocking=True)\n y_test = y_test.to(self.config.device, non_blocking=True)\n if isinstance(self.model, SearchCNNController):\n logits = self.model(\n x_test, sparsify_input_alphas=sparsify_input_alphas\n )\n else:\n logits = self.model(x_test)\n loss = self.model.criterion(logits, y_test)\n\n y_test_pred = logits.softmax(dim=1)\n now = time.strftime('%c', time.localtime(time.time()))\n prec1, prec5 = utils.accuracy(logits, y_test, self.config, topk=(1, 5))\n losses_logger.update(loss.item(), 1)\n top1_logger.update(prec1.item(), 1)\n \n self.config.naivenaive = 0 \n self.config.eval_switch = 0\n self.config.cell_phase = 3 \n\n if little_switch == 1:\n self.config.naivenaive = 1\n \n task_info = namedtuple(\n \"task_info\",\n [\n \"genotype\",\n \"top1\",\n \"w_task\",\n \"a_task\",\n \"loss\",\n \"y_test_pred\",\n \"sparse_num_params\",\n \"w_task_bot\",\n \"a_task_bot\"\n ],\n )\n task_info.w_task = w_task\n task_info.a_task = a_task\n task_info.loss = loss\n y_test_pred = y_test_pred\n task_info.y_test_pred = y_test_pred\n task_info.genotype = genotype\n # task_info.top1 = top1\n\n # task_info.sparse_num_params = self.model.get_sparse_num_params(\n # self.model.alpha_prune_threshold\n # )\n task_info.w_task_bot = w_task_bot\n task_info.a_task_bot = a_task_bot\n\n return task_info" }, { "identifier": "Architect", "path": "task_optimizer/darts.py", "snippet": "class Architect:\n \"\"\" Compute gradients of alphas \"\"\"\n\n def __init__(self, net, w_momentum, w_weight_decay, use_first_order_darts):\n \"\"\"\n Args:\n net\n w_momentum: weights momentum\n \"\"\"\n self.net = net\n self.v_net = copy.deepcopy(net)\n self.w_momentum = w_momentum\n self.w_weight_decay = w_weight_decay\n self.use_first_order_darts = use_first_order_darts\n self.pprevious_grads = list()\n \n\n def virtual_step(self, train_X, train_y, xi, w_optim):\n \"\"\"\n Compute unrolled weight w' (virtual step)\n\n Step process:\n 1) forward\n 2) calc loss\n 3) compute gradient (by backprop)\n 4) update gradient\n\n Args:\n xi: learning rate for virtual gradient step (same as weights lr)\n w_optim: weights optimizer\n \"\"\"\n # forward & calc loss\n loss = self.net.loss(train_X, train_y) # L_train(w)\n\n # compute gradient\n gradients = torch.autograd.grad(loss, self.net.weights())\n\n \n \n\n\n\n \n # do virtual step (update gradient)\n # below operations do not need gradient tracking\n with torch.no_grad():\n # dict key is not the value, but the pointer. So original network weight have to\n # be iterated also.\n for w, vw, g in zip(self.net.weights(), self.v_net.weights(), gradients):\n m = w_optim.state[w].get(\"momentum_buffer\", 0.0) * self.w_momentum\n vw.copy_(w - xi * (m + g + self.w_weight_decay * w))\n\n # synchronize alphas\n for a, va in zip(self.net.alphas(), self.v_net.alphas()):\n va.copy_(a)\n\n def backward(self, train_X, train_y, val_X, val_y, xi, w_optim):\n \"\"\"Compute loss and backward its gradients\n Args:\n xi: learning rate for virtual gradient step (same as net lr)\n w_optim: weights optimizer - for virtual step\n \"\"\"\n # calc unrolled loss\n loss = self.v_net.loss(val_X, val_y) # L_val(w`)\n # compute gradient\n v_alphas = tuple(self.v_net.alphas())\n v_weights = tuple(self.v_net.weights())\n v_grads = torch.autograd.grad(loss, v_alphas + v_weights, allow_unused=True)\n dalpha = v_grads[: len(v_alphas)]\n dw = v_grads[len(v_alphas) :]\n\n \n\n if self.use_first_order_darts: # use first oder approximation for darts\n \n with torch.no_grad():\n for alpha, da in zip(self.net.alphas(), dalpha):\n alpha.grad = da\n \n\n else: # 2nd order DARTS\n\n hessian = self.compute_hessian(dw, train_X, train_y)\n\n # update final gradient = dalpha - xi*hessian\n with torch.no_grad():\n for alpha, da, h in zip(self.net.alphas(), dalpha, hessian):\n alpha.grad = da - xi * h\n\n\n\n\n def partial_alpha_backward(self,config, train_X, train_y, val_X, val_y, xi, w_optim):\n \"\"\"Compute loss and backward its gradients\n Args:\n \n xi: learning rate for virtual gradient step (same as net lr)\n w_optim: weights optimizer - for virtual step\n \"\"\"\n # compute gradient\n grad_output_sum = copy.deepcopy(self.v_net.net.config.alpha_previous_grad)\n \n if config.residual_flag == 1:\n pprevious_grad = copy.deepcopy(self.v_net.net.config.alpha_pprevious_grad)\n self.pprevious_grads.append(pprevious_grad) \n \n latent = self.v_net(val_X)\n\n\n v_alphas = tuple(self.v_net.alphas())\n v_weights = tuple(self.v_net.weights())\n\n if config.residual_flag == 1:\n try:\n if self.v_net.net.config.cell_phase == 1:\n grad_output_sum = torch.add(self.pprevious_grads[0],grad_output_sum)\n\n elif self.v_net.net.config.cell_phase == 0:\n grad_output_sum = torch.add(self.pprevious_grads[1],grad_output_sum)\n except:\n print(f\"Shape error,{grad_output_sum.shape} was the desired shape but you got {self.pprevious_grads[0].shape} or {self.pprevious_grads[1].shape}.\")\n print(\"Bypassing residual flag.\")\n\n v_grads = torch.autograd.grad(latent, v_alphas + v_weights, grad_outputs=grad_output_sum, allow_unused=True) \n dalpha = v_grads[: len(v_alphas)]\n dw = v_grads[len(v_alphas) :]\n \n \n\n if self.use_first_order_darts: # use first oder approximation for darts\n \n with torch.no_grad():\n for alpha, da in zip(self.net.alphas(), dalpha):\n if alpha.grad is not None and da is not None:\n alpha.grad.data.add_(da)\n else:\n alpha.grad= da\n\n else: # 2nd order DARTS\n\n hessian = self.compute_hessian(dw, train_X, train_y)\n\n # update final gradient = dalpha - xi*hessian\n with torch.no_grad():\n for alpha, da, h in zip(self.net.alphas(), dalpha, hessian):\n alpha.grad = da - xi * h\n\n def compute_hessian(self, dw, train_X, train_y):\n \"\"\"\n dw = dw` { L_val(w`, alpha) }\n w+ = w + eps * dw\n w- = w - eps * dw\n hessian = (dalpha { L_train(w+, alpha) } - dalpha { L_train(w-, alpha) }) / (2*eps)\n eps = 0.01 / ||dw||\n \"\"\"\n norm = torch.cat([w.view(-1) for w in dw]).norm()\n eps = 0.01 / norm\n \n # w+ = w + eps*dw`\n with torch.no_grad():\n for p, d in zip(self.net.weights(), dw):\n p += eps * d\n\n # dalpha { L_train(w+) }\n loss = self.net.loss(train_X, train_y)\n dalpha_pos = torch.autograd.grad(loss, self.net.alphas())\n\n # w- = w - eps*dw`\n with torch.no_grad():\n for p, d in zip(self.net.weights(), dw):\n p -= 2.0 * eps * d\n\n # dalpha { L_train(w-) }\n loss = self.net.loss(train_X, train_y)\n dalpha_neg = torch.autograd.grad(loss, self.net.alphas())\n\n # recover w\n with torch.no_grad():\n for p, d in zip(self.net.weights(), dw):\n p += eps * d\n\n hessian = [(p - n) / 2.0 * eps for p, n in zip(dalpha_pos, dalpha_neg)]\n return hessian" }, { "identifier": "train", "path": "task_optimizer/darts.py", "snippet": "def train(\n task,\n model,\n architect,\n w_optim,\n alpha_optim,\n lr,\n global_progress,\n config,\n warm_up=False,\n test_phase = False\n):\n model.train()\n pprevious_grads = list()\n initial_model = copy.deepcopy(model)\n \n p_bar_monitor = (enumerate(zip(task.train_loader, task.valid_loader)))#\n for step, ((train_X, train_y), (val_X, val_y)) in p_bar_monitor:\n\n start = torch.cuda.Event(enable_timing=True)\n end = torch.cuda.Event(enable_timing=True)\n start.record()\n \n train_X, train_y = train_X.to(config.device), train_y.to(config.device)\n val_X, val_y = val_X.to(config.device), val_y.to(config.device)\n N = train_X.size(0)\n initial_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()]\n \n if config.light_exp == 1:\n\n if config.meta_model != \"pc_adaptation\" and config.meta_model != \"pure_darts\" and config.dataset != \"cifar10\" and config.dataset != \"cifar100\":\n config.cell_phase = config.layers -1\n architect.v_net.net.config.cell_phase = config.layers -1\n # phase 2. architect step (alpha)\n prohibited_list = config.prohibited_list\n if config.naivenaive != 1 and config.eval_switch != 1 and config.meta_model != \"pc_adaptation\" and config.meta_model != \"pure_darts\" and config.dataset not in prohibited_list:\n\n w_optim.zero_grad()\n alpha_optim.zero_grad()\n train_X, train_y = train_X.chunk(config.split_num), train_y.chunk(config.split_num)\n val_X,val_y = val_X.chunk(config.split_num), val_y.chunk(config.split_num)\n \n for (train_X_chunk, train_y_chunk) ,(val_X_chunk,val_y_chunk) in zip(zip(train_X,train_y),zip(val_X,val_y)):\n config.cell_phase = config.layers -1\n architect.v_net.net.config.cell_phase = config.layers -1\n for phase in range(config.layers):\n \n if not warm_up: # only update alphas outside warm up phase\n if config.do_unrolled_architecture_steps:\n architect.virtual_step(train_X_chunk, train_y_chunk, lr, w_optim) # (calc w`)\n \n if config.cell_phase == config.layers -1:\n architect.v_net.net.cells[config.cell_phase].alpha_switch = 1 \n architect.backward(train_X_chunk, train_y_chunk, val_X_chunk, val_y_chunk, lr, w_optim)\n \n \n else:\n architect.v_net.net.cells[config.cell_phase].alpha_switch = 1\n architect.partial_alpha_backward(config, train_X_chunk, train_y_chunk, val_X_chunk, val_y_chunk, lr, w_optim) \n \n \n model.net.alpha_switch = 0\n architect.v_net.net.alpha_switch = 0\n\n # phase 1. child network step (w)\n if config.cell_phase == config.layers -1:\n w_optim.zero_grad()\n logits = model(train_X_chunk)\n loss = model.criterion(logits, train_y_chunk)\n loss_monitor = loss.item()\n loss.backward()\n nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) \n w_optim.step()\n\n\n else:\n w_optim.zero_grad()\n output_grad_sum = copy.deepcopy(config.previous_grad)\n pprevious_grad = copy.deepcopy(config.pprevious_grad)\n pprevious_grads.append(pprevious_grad)\n\n if config.residual_flag == 1:\n if config.cell_phase == 1:\n if pprevious_grads[0].shape != output_grad_sum.shape:\n output_grad_sum = output_grad_sum\n else:\n output_grad_sum = torch.add(pprevious_grads[0],output_grad_sum)\n elif config.cell_phase == 0:\n if pprevious_grads[1].shape != output_grad_sum.shape:\n output_grad_sum = output_grad_sum\n else:\n output_grad_sum = torch.add(pprevious_grads[1],output_grad_sum)\n latent = model(train_X_chunk)\n\n\n \n try:\n latent.backward(output_grad_sum)\n \n except:\n if output_grad_sum is not None:\n print(\"batch passed,\",output_grad_sum.shape, \" was the shape of grad saved\")\n print(\"what we had to save was this shape, \", latent.shape )\n print(f\"And this was the phase.{config.cell_phase} what can be the problem here ? \")\n else:\n print(\"output was none. Why?\")\n pass\n nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip)\n \n\n \n config.cell_phase -= 1\n architect.v_net.net.config.cell_phase -= 1\n alpha_optim.step() \n w_optim.step()\n \n\n \n \n \n\n else:\n if not warm_up: # only update alphas outside warm up phase\n alpha_optim.zero_grad()\n \n if config.do_unrolled_architecture_steps:\n architect.virtual_step(train_X, train_y, lr, w_optim) # (calc w`)\n \n architect.backward(train_X, train_y, val_X, val_y, lr, w_optim)\n alpha_optim.step()\n \n\n \n w_optim.zero_grad()\n \n logits = model(train_X)\n \n loss = model.criterion(logits, train_y)\n loss.backward()\n nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip)\n w_optim.step()\n\n \n \n\n\n end.record()\n torch.cuda.synchronize()\n config.computing_time += start.elapsed_time(end)\n \n config.total_steps -= 1\n pprevious_grads = list()\n architect.pprevious_grads = list()\n \n if config.alpha_expect and config.meta_model != 'pc_adaptation':\n if len(config.alpha_grad_footprints) <= 5:\n\n learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()]\n alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha)\n config.alpha_grad_footprints.append(alpha_grad) \n\n\n else:\n \n learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()]\n alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha)\n \n config.alpha_grad_footprints.pop(0) \n config.alpha_grad_footprints.append(alpha_grad) \n\n config.alpha_sample_metrics = _exp_alpha_metric(initial_alpha,config)\n architect.v_net.net.config.alpha_sample_metrics = config.alpha_sample_metrics\n\n ###################################################################################\n\n\n task_specific_model = copy.deepcopy(model)\n task_specific_model = get_diff_for_const_bottom(initial_model,task_specific_model)\n \n return task_specific_model" } ]
import os import torch import torch.nn as nn import numpy as np import utils.utils as utils import random import time import pandas as pd import copy import argparse from utils import genotypes as gt from models.search_cnn import SearchCNNController from models.search_cnn_PC import SearchCNNControllerPC from task_optimizer.darts import Darts,Architect from task_optimizer.darts import train as d_train from tqdm import tqdm from tqdm import tqdm
15,557
""" Search cell """ ''' Based on https://github.com/boschresearch/metanas which is licensed under GNU Affero General Public License, ''' device = torch.device("cuda") # tensorboard def _init_alpha_normalizer(name, task_train_steps, t_max, t_min, temp_anneal_mode): normalizer = dict() normalizer["name"] = name normalizer["params"] = dict() normalizer["params"]["curr_step"] = 0.0 # current step for scheduling normalizer normalizer["params"]["max_steps"] = float( task_train_steps ) # for scheduling normalizer normalizer["params"]["t_max"] = t_max normalizer["params"]["t_min"] = t_min normalizer["params"]["temp_anneal_mode"] = temp_anneal_mode # temperature annealing return normalizer def main(config): # set default gpu device id torch.cuda.set_device(config.gpus[0]) # set seed np.random.seed(config.seed) torch.manual_seed(config.seed) torch.cuda.manual_seed_all(config.seed) random.seed(config.seed) torch.backends.cudnn.benchmark = True # get data with meta info input_size, input_channels, n_classes, train_data = utils.get_data( config.dataset, config.data_path, cutout_length=0, validation=False) _,_,_,_,test_data = utils.get_data(config.dataset, config.data_path, cutout_length=0, validation=True) # input my model architecture here normalizer = _init_alpha_normalizer( config.normalizer, config.task_train_steps, config.normalizer_t_max, config.normalizer_t_min, config.normalizer_temp_anneal_mode, ) net_crit = nn.CrossEntropyLoss().to(device)
""" Search cell """ ''' Based on https://github.com/boschresearch/metanas which is licensed under GNU Affero General Public License, ''' device = torch.device("cuda") # tensorboard def _init_alpha_normalizer(name, task_train_steps, t_max, t_min, temp_anneal_mode): normalizer = dict() normalizer["name"] = name normalizer["params"] = dict() normalizer["params"]["curr_step"] = 0.0 # current step for scheduling normalizer normalizer["params"]["max_steps"] = float( task_train_steps ) # for scheduling normalizer normalizer["params"]["t_max"] = t_max normalizer["params"]["t_min"] = t_min normalizer["params"]["temp_anneal_mode"] = temp_anneal_mode # temperature annealing return normalizer def main(config): # set default gpu device id torch.cuda.set_device(config.gpus[0]) # set seed np.random.seed(config.seed) torch.manual_seed(config.seed) torch.cuda.manual_seed_all(config.seed) random.seed(config.seed) torch.backends.cudnn.benchmark = True # get data with meta info input_size, input_channels, n_classes, train_data = utils.get_data( config.dataset, config.data_path, cutout_length=0, validation=False) _,_,_,_,test_data = utils.get_data(config.dataset, config.data_path, cutout_length=0, validation=True) # input my model architecture here normalizer = _init_alpha_normalizer( config.normalizer, config.task_train_steps, config.normalizer_t_max, config.normalizer_t_min, config.normalizer_temp_anneal_mode, ) net_crit = nn.CrossEntropyLoss().to(device)
model = SearchCNNController(
1
2023-10-08 02:42:27+00:00
24k
LukeForeverYoung/UReader
serve/model_worker.py
[ { "identifier": "IO", "path": "serve/io_utils.py", "snippet": "class IO:\n @staticmethod\n def register(options):\n pass\n\n def open(self, path: str, mode: str):\n raise NotImplementedError\n\n def exists(self, path: str) -> bool:\n raise NotImplementedError\n\n def move(self, src: str, dst: str):\n raise NotImplementedError\n\n def copy(self, src: str, dst: str):\n raise NotImplementedError\n\n def makedirs(self, path: str, exist_ok=True):\n raise NotImplementedError\n\n def remove(self, path: str):\n raise NotImplementedError\n\n def listdir(self, path: str, recursive=False, full_path=False, contains=None):\n raise NotImplementedError\n\n def isdir(self, path: str) -> bool:\n raise NotImplementedError\n\n def isfile(self, path: str) -> bool:\n raise NotImplementedError\n\n def abspath(self, path: str) -> str:\n raise NotImplementedError\n\n def last_modified(self, path: str) -> datetime:\n raise NotImplementedError\n\n def md5(self, path: str) -> str:\n hash_md5 = hashlib.md5()\n with self.open(path, 'rb') as f:\n for chunk in iter(lambda: f.read(4096), b''):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n re_remote = re.compile(r'(oss|https?)://')\n\n def islocal(self, path: str) -> bool:\n return not self.re_remote.match(path.lstrip())" }, { "identifier": "DefaultIO", "path": "serve/io_utils.py", "snippet": "class DefaultIO(IO):\n __name__ = 'DefaultIO'\n\n def _check_path(self, path):\n if not self.islocal(path):\n raise RuntimeError(\n 'Credentials must be provided to use oss path. '\n 'Make sure you have created \"user/modules/oss_credentials.py\" according to ReadMe.')\n\n def open(self, path, mode='r'):\n self._check_path(path)\n path = self.abspath(path)\n return open(path, mode=mode)\n\n def exists(self, path):\n self._check_path(path)\n path = self.abspath(path)\n return os.path.exists(path)\n\n def move(self, src, dst):\n self._check_path(src)\n self._check_path(dst)\n src = self.abspath(src)\n dst = self.abspath(dst)\n shutil.move(src, dst)\n\n def copy(self, src, dst):\n self._check_path(src)\n self._check_path(dst)\n src = self.abspath(src)\n dst = self.abspath(dst)\n try:\n shutil.copyfile(src, dst)\n except shutil.SameFileError:\n pass\n\n def makedirs(self, path, exist_ok=True):\n self._check_path(path)\n path = self.abspath(path)\n os.makedirs(path, exist_ok=exist_ok)\n\n def remove(self, path):\n self._check_path(path)\n path = self.abspath(path)\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n\n def listdir(self, path, recursive=False, full_path=False, contains=None):\n self._check_path(path)\n path = self.abspath(path)\n contains = contains or ''\n if recursive:\n files = (os.path.join(dp, f) if full_path else f for dp, dn, fn in os.walk(path) for f in fn)\n files = [file for file in files if contains in file]\n else:\n files = os.listdir(path)\n if full_path:\n files = [os.path.join(path, file) for file in files if contains in file]\n return files\n\n def isdir(self, path):\n return os.path.isdir(path)\n\n def isfile(self, path):\n return os.path.isfile(path)\n\n def abspath(self, path):\n return os.path.abspath(path)\n\n def last_modified(self, path):\n return datetime.fromtimestamp(os.path.getmtime(path))" }, { "identifier": "OSS", "path": "serve/io_utils.py", "snippet": "class OSS(DefaultIO):\n \"Mixed IO module to support both system-level and OSS IO methods\"\n __name__ = 'OSS'\n\n def __init__(self, access_key_id: str, access_key_secret: str, region_bucket: List[List[str]]):\n \"\"\"\n the value of \"region_bucket\" should be something like [[\"cn-hangzhou\", \"<yourBucketName>\"], [\"cn-zhangjiakou\", \"<yourBucketName>\"]],\n specifying your buckets and corresponding regions\n \"\"\"\n from oss2 import Auth, Bucket, ObjectIterator\n super().__init__()\n self.ObjectIterator = ObjectIterator\n self.auth = Auth(access_key_id, access_key_secret)\n self.buckets = {\n bucket_name: Bucket(self.auth, f'http://oss-{region}.aliyuncs.com', bucket_name)\n for region, bucket_name in region_bucket\n }\n self.oss_pattern = re.compile(r'oss://([^/]+)/(.+)')\n\n def _split_name(self, path):\n m = self.oss_pattern.match(path)\n if not m:\n raise IOError(f'invalid oss path: \"{path}\", should be \"oss://<bucket_name>/path\"')\n bucket_name, path = m.groups()\n return bucket_name, path\n\n def _split(self, path):\n bucket_name, path = self._split_name(path)\n try:\n bucket = self.buckets[bucket_name]\n except KeyError:\n raise IOError(f'Bucket {bucket_name} not registered in oss_credentials.py')\n return bucket, path\n\n def open(self, full_path, mode='r'):\n if not full_path.startswith('oss://'):\n return super().open(full_path, mode)\n\n bucket, path = self._split(full_path)\n with mute_stderr():\n path_exists = bucket.object_exists(path)\n if 'w' in mode:\n if path_exists:\n bucket.delete_object(path)\n if 'b' in mode:\n return BinaryOSSFile(bucket, path)\n return OSSFile(bucket, path)\n elif mode == 'a':\n position = bucket.head_object(path).content_length if path_exists else 0\n return OSSFile(bucket, path, position=position)\n else:\n if not path_exists:\n raise FileNotFoundError(full_path)\n obj = bucket.get_object(path)\n # auto cache large files to avoid memory issues\n # if obj.content_length > 30 * 1024 ** 2: # 30M\n # from da.utils import cache_file\n # path = cache_file(full_path)\n # return super().open(path, mode)\n if mode == 'rb':\n # TODO for a large file, this will load the whole file into memory\n return NullContextWrapper(BytesIO(obj.read()))\n else:\n assert mode == 'r'\n return NullContextWrapper(StringIO(obj.read().decode()))\n\n def exists(self, path):\n if not path.startswith('oss://'):\n return super().exists(path)\n\n bucket, _path = self._split(path)\n # if file exists\n exists = self._file_exists(bucket, _path)\n # if directory exists\n if not exists:\n try:\n self.listdir(path)\n exists = True\n except FileNotFoundError:\n pass\n return exists\n\n def _file_exists(self, bucket, path):\n with mute_stderr():\n return bucket.object_exists(path)\n\n def move(self, src, dst):\n if not src.startswith('oss://') and not dst.startswith('oss://'):\n return super().move(src, dst)\n self.copy(src, dst)\n self.remove(src)\n\n def copy(self, src, dst):\n cloud_src = src.startswith('oss://')\n cloud_dst = dst.startswith('oss://')\n if not cloud_src and not cloud_dst:\n return super().copy(src, dst)\n\n # download\n if cloud_src and not cloud_dst:\n bucket, src = self._split(src)\n obj = bucket.get_object(src)\n if obj.content_length > 100 * 1024 ** 2: # 100M\n from tqdm import tqdm\n progress = None\n\n def callback(i, n):\n nonlocal progress\n if progress is None:\n progress = tqdm(total=n, unit='B', unit_scale=True, unit_divisor=1024, leave=False,\n desc=f'downloading')\n progress.update(i - progress.n)\n\n bucket.get_object_to_file(src, dst, progress_callback=callback)\n if progress is not None:\n progress.close()\n else:\n bucket.get_object_to_file(src, dst)\n return\n bucket, dst = self._split(dst)\n # upload\n if cloud_dst and not cloud_src:\n bucket.put_object_from_file(dst, src)\n return\n # copy between oss paths\n if src != dst:\n src_bucket_name, src = self._split_name(src)\n bucket.copy_object(src_bucket_name, src, dst)\n # TODO: support large file copy\n # https://help.aliyun.com/document_detail/88465.html?spm=a2c4g.11174283.6.882.4d157da2mgp3xc\n\n def listdir(self, path, recursive=False, full_path=False, contains=None):\n if not path.startswith('oss://'):\n return super().listdir(path, recursive, full_path, contains)\n\n bucket, path = self._split(path)\n path = path.rstrip('/') + '/'\n files = [obj.key for obj in self.ObjectIterator(bucket, prefix=path, delimiter='' if recursive else '/')]\n try:\n files.remove(path)\n except ValueError:\n pass\n if full_path:\n files = [f'oss://{bucket.bucket_name}/{file}' for file in files]\n else:\n files = [file[len(path):] for file in files]\n if not files:\n raise FileNotFoundError(f'No such directory: oss://{bucket.bucket_name}/{path}')\n files = [file for file in files if (contains or '') in file]\n return files\n\n def remove(self, path):\n if not path.startswith('oss://'):\n return super().remove(path)\n\n if self.isfile(path):\n paths = [path]\n else:\n paths = self.listdir(path, recursive=True, full_path=True)\n for path in paths:\n bucket, path = self._split(path)\n bucket.delete_object(path)\n\n def makedirs(self, path, exist_ok=True):\n # there is no need to create directory in oss\n if not path.startswith('oss://'):\n return super().makedirs(path)\n\n def isdir(self, path):\n if not path.startswith('oss://'):\n return super().isdir(path)\n return self.exists(path.rstrip('/') + '/')\n\n def isfile(self, path):\n if not path.startswith('oss://'):\n return super().isdir(path)\n return self.exists(path) and not self.isdir(path)\n\n def abspath(self, path):\n if not path.startswith('oss://'):\n return super().abspath(path)\n return path\n\n def authorize(self, path):\n if not path.startswith('oss://'):\n raise ValueError('Only oss path can use \"authorize\"')\n import oss2\n bucket, path = self._split(path)\n bucket.put_object_acl(path, oss2.OBJECT_ACL_PUBLIC_READ)\n\n def last_modified(self, path):\n if not path.startswith('oss://'):\n return super().last_modified(path)\n bucket, path = self._split(path)\n return datetime.strptime(\n bucket.get_object_meta(path).headers['Last-Modified'],\n r'%a, %d %b %Y %H:%M:%S %Z'\n ) + timedelta(hours=8)" }, { "identifier": "MplugOwlProcessor", "path": "mplug_owl/processing_mplug_owl.py", "snippet": "class MplugOwlProcessor(ProcessorMixin):\n attributes = []\n tokenizer_class = (\"MplugOwlTokenizer\")\n\n def __init__(self, image_processor=None, tokenizer=None, **kwargs):\n super().__init__(**kwargs)\n self.tokens_to_generate = 0\n self.image_processor = image_processor\n self.tokenizer = tokenizer\n self.add_BOS = True\n\n def __call__(self, text=None, images=None, return_tensors=None, **kwargs):\n args = get_args()\n if text is None and images is None:\n raise ValueError(\"You have to specify either text or images. Both cannot be none.\")\n\n if images is not None:\n if not isinstance(images, list):\n images = [images]\n # image_features, = self.image_processor(images, return_tensors=return_tensors, **kwargs)\n process_results = [self.image_processor(image=image, text=None) for image in images]\n if len(process_results)>0 and len(process_results[0][0].shape) == 4:\n # 图片被切分成了多块 默认是doc场景\n text_list = text.split('<image>')\n images = []\n patch_positions = []\n text = text_list[0]\n for ri, (image_input, text_input, patch_position) in enumerate(process_results):\n images.append(image_input)\n patch_positions.append(patch_position)\n if args.patch_pos_embed_type == 'pre':\n # 对于pre处理 v2t最终输出的是一张图的token\n text += '<image>'\n else:\n # 对于post处理 v2t最终输出的是多图\n text += '<image>'*image_input.shape[0]\n text += text_list[ri+1]\n images = torch.cat(images, dim=0)\n patch_positions = torch.cat(patch_positions, dim=0)\n else:\n # 如果没有切片 则正常stack 并创建patch position = num_image (0,0)的patch id以保持一致\n images = [_[0] for _ in process_results]\n images = torch.stack(images, dim=0)\n patch_positions = torch.zeros(images.shape[0],2).long()\n text = text\n if text is not None:\n encoding = tokenize_prompts(\n prompts=[text],\n tokens_to_generate=self.tokens_to_generate,\n add_BOS=self.add_BOS,\n tokenizer=self.tokenizer,\n ignore_dist=True,\n **kwargs,\n )\n # encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)\n\n \n if text is not None and images is not None:\n encoding[\"pixel_values\"] = images\n encoding[\"patch_positions\"] = patch_position\n return BatchEncoding(data=encoding)\n elif text is not None:\n return BatchEncoding(data=encoding)\n else:\n return BatchEncoding(data=dict(pixel_values=images, patch_position=patch_position), tensor_type=return_tensors)\n\n def batch_decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please\n refer to the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.batch_decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)\n\n def decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to\n the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)" }, { "identifier": "MplugOwlImageProcessor", "path": "mplug_owl/processing_mplug_owl.py", "snippet": "class MplugOwlImageProcessor(CLIPImageProcessor):\n pass" }, { "identifier": "MplugOwlForConditionalGeneration", "path": "mplug_owl/modeling_mplug_owl.py", "snippet": "class MplugOwlForConditionalGeneration(MplugOwlPreTrainedModel):\n config_class = MplugOwlConfig\n main_input_name = \"pixel_values\"\n\n def __init__(self, config: MplugOwlConfig):\n super().__init__(config)\n\n self.vision_model = MplugOwlVisionModel(config.vision_config)\n\n self.query_tokens = nn.Parameter(\n torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size)\n )\n self.num_queries = config.num_query_tokens\n self.abstractor = MplugOwlVisualAbstractorModel(\n config.visual_abstractor_config, config.text_config.hidden_size\n )\n language_model = AutoModelForCausalLM.from_config(config.text_config)\n self.language_model = language_model\n\n # Initialize weights and apply final processing\n self.post_init()\n self.main_input_name = \"input_ids\"\n from transformers import GenerationConfig\n\n self.generation_config = GenerationConfig(\n max_length=512, do_sample=True, top_k=3, pad_token_id=0, unk_token_id=0, bos_token_id=1, eos_token_id=2\n )\n\n def get_input_embeddings(self):\n return self.language_model.get_input_embeddings()\n\n def set_input_embeddings(self, value):\n self.language_model.set_input_embeddings(value)\n\n def set_output_embeddings(self, new_embeddings):\n self.language_model.set_output_embeddings(new_embeddings)\n\n def get_output_embeddings(self) -> nn.Module:\n return self.language_model.get_output_embeddings()\n\n def get_encoder(self):\n return self.language_model.get_encoder()\n\n def get_decoder(self):\n return self.language_model.get_decoder()\n\n def _tie_weights(self):\n if not self.config.use_decoder_only_language_model:\n self.language_model.encoder.embed_tokens = self.language_model.shared\n self.language_model.decoder.embed_tokens = self.language_model.shared\n\n def _preprocess_accelerate(self):\n r\"\"\"\n Some pre-processing hacks to make the model `accelerate` compatible. Check\n https://github.com/huggingface/transformers/pull/21707 for more details.\n \"\"\"\n hf_device_map = self.hf_device_map\n\n if len(hf_device_map) > 1 and \"language_model\" not in hf_device_map and torch.cuda.device_count() > 1:\n # warn users about unexpected behavior when using multi-GPU + mPLUG-Owl + `accelerate`.\n logger.warning(\n \"The `language_model` is not in the `hf_device_map` dictionary and you are running your script\"\n \" in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`.\"\n \" Please pass a `device_map` that contains `language_model` to remove this warning.\"\n \" Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for\"\n \" more details on creating a `device_map` for large models.\",\n )\n\n if hasattr(self.language_model, \"_hf_hook\"):\n self.language_model._hf_hook.io_same_device = True # For `generate` compatibility\n\n @add_start_docstrings_to_model_forward(MPLUG_OWL_INPUTS_DOCSTRING)\n @replace_return_docstrings(\n output_type=MplugOwlForConditionalGenerationModelOutput, config_class=MplugOwlVisionConfig\n )\n def forward(\n self,\n pixel_values: torch.FloatTensor,\n input_ids: torch.FloatTensor,\n num_images,\n non_padding_mask: Optional[torch.LongTensor] = None,\n non_media_mask: Optional[torch.LongTensor] = None,\n prompt_mask: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n patch_positions=None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, MplugOwlForConditionalGenerationModelOutput]:\n r\"\"\"\n Returns:\n\n SFT example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import MplugOwlProcessor, MplugOwlForConditionalGeneration\n >>> import torch\n\n >>> device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n >>> processor = MplugOwlProcessor.from_pretrained(\"MAGAer13/mplug-owl-llama-7b\")\n >>> model = MplugOwlForConditionalGeneration.from_pretrained(\n ... \"MAGAer13/mplug-owl-llama-7b\", torch_dtype=torch.float16\n ... )\n >>> model.to(device) # doctest: +IGNORE_RESULT\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> prompt = [\n ... \"The following is a conversation between a curious human and AI assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.\\nHuman: <image>\\nHuman: how many cats are there?\\nAI: \"\n ... ]\n >>> inputs = processor(images=[image], text=prompt, return_tensors=\"pt\").to(device, torch.float16)\n\n >>> generated_ids = model.generate(**inputs)\n >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()\n >>> print(generated_text)\n There are two cats in the image.\n ```\"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # get text embedding\n text_tokens_ = input_ids.clone()\n batch_size = input_ids.shape[0]\n # labels = text_tokens_[:, 1:].clone().contiguous()\n\n media_token_indices = [\n # [:-1] since we would not use the last token for embedding\n get_media_indices(text_tokens_[i][:-1], self.num_queries)\n for i in range(batch_size)\n ]\n text_tokens_[text_tokens_ < 0] = 1 # Not used\n # text_tokens = text_tokens_[:, :-1].contiguous()\n text_embeds = self.get_input_embeddings()(text_tokens_) # Temporally Embedding\n\n if pixel_values is not None:\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n\n image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n\n query_features = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n )[\"last_hidden_state\"]\n torch.ones(query_features.size()[:-1], dtype=torch.long).to(query_features.device)\n img_seq_length = query_features.shape[1]\n\n num_images_per_sample = num_images.long().cpu().tolist()\n\n text_chunk_embeds = []\n img_idx = 0\n for b in range(batch_size):\n start = 0\n result = []\n if len(media_token_indices[b]) > 0:\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(text_embeds[b, start:pos])\n result.append(query_features[img_idx + i])\n start = pos + img_seq_length\n if start < text_embeds.shape[1]:\n result.append(text_embeds[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n\n # Actual Input Embeddings\n input_embeds = torch.stack(text_chunk_embeds, dim=0)\n\n # Create causal mask and position ids\n _, loss_mask, position_ids = get_ltor_masks_and_position_ids_from_embeddings(input_embeds)\n\n # Calculate the loss_mask\n non_padding_mask = non_padding_mask.long()\n non_media_mask = non_media_mask.long()\n prompt_mask = prompt_mask.long() # TODO How to deal with prompt mask\n # from icecream import ic\n # non_padding_mask = non_padding_mask[:,:-1]\n # non_media_mask = non_media_mask[:,:-1]\n # prompt_mask = prompt_mask[:,:-1]\n # attention_mask = attention_mask[:,:-1]\n loss_mask = loss_mask[:, :-1]\n\n loss_mask = loss_mask * non_padding_mask * non_media_mask * prompt_mask\n labels[:, 1:][loss_mask != 1] = -100\n # Forward into GPT\n outputs = self.language_model(\n inputs_embeds=input_embeds,\n attention_mask=attention_mask,\n labels=labels,\n return_dict=return_dict,\n output_attentions=self.config.output_attentions,\n )\n outputs.loss = (outputs.loss * loss_mask.view(-1)\n ).sum()/loss_mask.sum()\n return outputs\n\n @torch.no_grad()\n def generate(\n self,\n pixel_values: torch.FloatTensor = None,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n patch_positions=None,\n isdecoder=True,\n **generate_kwargs,\n ) -> torch.LongTensor:\n \"\"\"\n Overrides `generate` function to be able to use the model as a conditional generator.\n\n Args:\n pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):\n Input images to be processed.\n input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n The sequence used as a prompt for the generation.\n attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n Mask to avoid performing attention on padding token indices\n\n Returns:\n captions (list): A list of strings of length batch_size * num_captions.\n \"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n if input_ids is None:\n return self.language_model.generate(attention_mask=attention_mask, **generate_kwargs)\n\n if attention_mask is None:\n attention_mask = input_ids.new_ones(*input_ids.shape)\n\n batch_size = input_ids.size(0)\n media_token_indices = [get_media_indices(input_ids[i], self.num_queries) for i in range(batch_size)]\n input_ids = input_ids.clone() # prevent inplace modify\n input_ids[input_ids < 0] = 0 # Not used\n\n if hasattr(self, \"hf_device_map\"):\n # preprocess for `accelerate`\n self._preprocess_accelerate()\n batch_size = input_ids.shape[0]\n # get text embedding\n inputs_embeds = self.get_input_embeddings()(input_ids)\n # get visual embedding\n if pixel_values is not None:\n pixel_values = pixel_values.to(input_ids.device)\n with torch.no_grad():\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n image_attention_mask = torch.ones(\n image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device\n )\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n query_outputs = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n return_dict=True,\n )\n query_output = query_outputs[\"last_hidden_state\"]\n image_embeds = query_output\n img_seq_length = image_embeds.shape[1]\n\n # ===================\n # Get actual input embeddings\n # ===================\n text_chunk_embeds = []\n text_chunk_attns = []\n img_idx = 0\n\n for b in range(batch_size):\n start = 0\n result = []\n result_attn = []\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(inputs_embeds[b, start:pos])\n result_attn.append(attention_mask[b, start:pos])\n result.append(image_embeds[img_idx + i])\n result_attn.append(torch.ones(image_embeds[img_idx + i].shape[0], device=inputs_embeds.device))\n start = pos + img_seq_length\n if start < inputs_embeds.shape[1]:\n result.append(inputs_embeds[b, start:])\n result_attn.append(attention_mask[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n text_chunk_attns.append(torch.cat(result_attn, dim=0))\n inputs_embeds = torch.stack(text_chunk_embeds, dim=0)\n attention_mask = torch.stack(text_chunk_attns, dim=0)\n\n outputs = self.language_model.generate(\n inputs_embeds=inputs_embeds,\n # input_ids=input_ids,\n attention_mask=attention_mask,\n **generate_kwargs,\n )\n\n return outputs\n\n def prepare_inputs_for_generation(\n self, input_ids, pixel_values=None, past_key_values=None, attention_mask=None, **model_kwargs\n ):\n input_shape = input_ids.shape\n # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly\n if attention_mask is None:\n attention_mask = input_ids.new_ones(input_shape)\n\n # # cut decoder_input_ids if past_key_values is used\n # if past_key_values is not None:\n # input_ids = input_ids[:, -1:]\n\n return {\n \"input_ids\": input_ids,\n \"pixel_values\": pixel_values,\n \"attention_mask\": attention_mask,\n \"is_decoder\": True,\n }" }, { "identifier": "MplugOwlConfig", "path": "mplug_owl/configuration_mplug_owl.py", "snippet": "class MplugOwlConfig(PretrainedConfig):\n r\"\"\"\n [`MplugOwlConfig`] is the configuration class to store the configuration of a [`MplugOwlForConditionalGeneration`].\n It is used to instantiate a mPLUG-Owl model according to the specified arguments, defining the vision model,\n Q-Former model and language model configs. Instantiating a configuration with the defaults will yield a similar\n configuration to that of the mPLUG-Owl [x-plug/x_plug-llama-7b](https://huggingface.co/x-plug/x_plug-llama-7b)\n architecture.\n\n Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the\n documentation from [`PretrainedConfig`] for more information.\n\n Args:\n vision_config (`dict`, *optional*):\n Dictionary of configuration options used to initialize [`MplugOwlVisionConfig`].\n visual_abstractor_config (`dict`, *optional*):\n Dictionary of configuration options used to initialize [`MplugOwlVisualAbstractorConfig`].\n text_config (`dict`, *optional*):\n Dictionary of configuration options used to initialize any [`PretrainedConfig`].\n num_query_tokens (`int`, *optional*, defaults to 32):\n The number of query tokens passed through the Transformer.\n\n kwargs (*optional*):\n Dictionary of keyword arguments.\n\n Example:\n\n ```python\n >>> from transformers import (\n ... MplugOwlVisionConfig,\n ... MplugOwlVisualAbstractorConfig,\n ... OPTConfig,\n ... MplugOwlConfig,\n ... MplugOwlForConditionalGeneration,\n ... )\n\n >>> # Initializing a MplugOwlConfig with x-plug/x_plug-llama-7b style configuration\n >>> configuration = MplugOwlConfig()\n\n >>> # Initializing a MplugOwlForConditionalGeneration (with random weights) from the x-plug/x_plug-llama-7b style configuration\n >>> model = MplugOwlForConditionalGeneration(configuration)\n\n >>> # Accessing the model configuration\n >>> configuration = model.config\n\n >>> # We can also initialize a MplugOwlConfig from a MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig and any PretrainedConfig\n\n >>> # Initializing mPLUG-Owl vision, mPLUG-Owl Q-Former and language model configurations\n >>> vision_config = MplugOwlVisionConfig()\n >>> visual_abstractor_config = MplugOwlVisualAbstractorConfig()\n >>> text_config = OPTConfig()\n\n >>> config = MplugOwlConfig.from_text_vision_configs(vision_config, visual_abstractor_config, text_config)\n ```\"\"\"\n model_type = \"mplug-owl\"\n is_composition = True\n\n def __init__(\n self, vision_config=None, visual_abstractor_config=None, text_config=None, num_query_tokens=64, **kwargs\n ):\n super().__init__(**kwargs)\n if vision_config is None:\n vision_config = MplugOwlVisionConfig().to_dict()\n logger.info(\"vision_config is None.\")\n\n if visual_abstractor_config is None:\n visual_abstractor_config = {}\n logger.info(\"abstractor_config is None. \")\n\n if text_config is None:\n # we use LLAMA 7b by default\n from transformers.llama.configuration_llama import LlamaConfig\n\n text_config = LlamaConfig(pad_token_id=2).to_dict()\n logger.info(\"text_config is None.\")\n\n self.vision_config = MplugOwlVisionConfig(**vision_config)\n self.visual_abstractor_config = MplugOwlVisualAbstractorConfig(**visual_abstractor_config)\n # self.visual_abstractor_config.layer_norm_eps = 1e-6\n text_model_type = text_config[\"model_type\"] if \"model_type\" in text_config else \"llama\"\n self.text_config = CONFIG_MAPPING[text_model_type](**text_config)\n\n self.tie_word_embeddings = self.text_config.tie_word_embeddings\n self.is_encoder_decoder = self.text_config.is_encoder_decoder\n\n self.num_query_tokens = num_query_tokens\n # self.visual_abstractor_config.encoder_hidden_size = self.vision_config.hidden_size\n self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES\n self.initializer_factor = 1.0\n self.initializer_range = 0.02\n\n for attr in dir(self.text_config):\n if not hasattr(self, attr):\n setattr(self, attr, getattr(self.text_config, attr))\n\n @classmethod\n def from_vision_visual_abstractor_text_configs(\n cls,\n vision_config: MplugOwlVisionConfig,\n visual_abstractor_config: MplugOwlVisualAbstractorConfig,\n text_config: PretrainedConfig,\n **kwargs,\n ):\n r\"\"\"\n Instantiate a [`MplugOwlConfig`] (or a derived class) from a mPLUG-Owl vision model, Q-Former and language\n model configurations.\n\n Returns:\n [`MplugOwlConfig`]: An instance of a configuration object\n \"\"\"\n\n return cls(\n vision_config=vision_config.to_dict(),\n visual_abstractor_config=visual_abstractor_config.to_dict(),\n text_config=text_config.to_dict(),\n **kwargs,\n )\n\n def to_dict(self):\n \"\"\"\n Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].\n\n Returns:\n `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,\n \"\"\"\n output = copy.deepcopy(self.__dict__)\n output[\"vision_config\"] = self.vision_config.to_dict()\n output[\"visual_abstractor_config\"] = self.visual_abstractor_config.to_dict()\n output[\"text_config\"] = self.text_config.to_dict()\n output[\"model_type\"] = self.__class__.model_type\n return output" }, { "identifier": "MplugOwlTokenizer", "path": "mplug_owl/tokenization_mplug_owl.py", "snippet": "class MplugOwlTokenizer(LlamaTokenizer):\n def __init__(\n self,\n vocab_file,\n unk_token=\"<unk>\",\n bos_token=\"<s>\",\n eos_token=\"</s>\",\n pad_token=\"<unk>\",\n sp_model_kwargs=None,\n add_bos_token=False,\n add_eos_token=False,\n clean_up_tokenization_spaces=False,\n **kwargs,\n ):\n super().__init__(\n vocab_file,\n unk_token,\n bos_token,\n eos_token,\n pad_token,\n sp_model_kwargs,\n add_bos_token,\n add_eos_token,\n clean_up_tokenization_spaces,\n **kwargs,\n )\n self.eod_id = self.eos_token_id" }, { "identifier": "post_process_output", "path": "serve/model_utils.py", "snippet": "def post_process_output(text):\n text = text.strip()\n pattern = re.compile(\n r\"<unk>|<pad>|<s>|</s>|\\[PAD\\]|<\\|endoftext\\|>|\\[UNK\\]|\\[CLS\\]|\\[MASK\\]|<\\|startofpiece\\|>|<\\|endofpiece\\|>|\\[gMASK\\]|\\[sMASK\\]\"\n )\n text = pattern.sub(\"\", text.strip()).strip()\n return text" }, { "identifier": "Stream", "path": "serve/model_utils.py", "snippet": "class Stream(transformers.StoppingCriteria):\n def __init__(self, callback_func=None):\n self.callback_func = callback_func\n\n def __call__(self, input_ids, scores) -> bool:\n if self.callback_func is not None:\n self.callback_func(input_ids[0])\n return False" }, { "identifier": "Iteratorize", "path": "serve/model_utils.py", "snippet": "class Iteratorize:\n\n \"\"\"\n Transforms a function that takes a callback\n into a lazy iterator (generator).\n \"\"\"\n\n def __init__(self, func, kwargs={}, callback=None):\n self.mfunc = func\n self.c_callback = callback\n self.q = Queue()\n self.sentinel = object()\n self.kwargs = kwargs\n self.stop_now = False\n\n def _callback(val):\n if self.stop_now:\n raise ValueError\n self.q.put(val)\n\n def gentask():\n try:\n ret = self.mfunc(callback=_callback, **self.kwargs)\n except ValueError:\n pass\n except:\n traceback.print_exc()\n pass\n\n self.q.put(self.sentinel)\n if self.c_callback:\n self.c_callback(ret)\n\n self.thread = Thread(target=gentask)\n self.thread.start()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n obj = self.q.get(True, None)\n if obj is self.sentinel:\n raise StopIteration\n else:\n return obj\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.stop_now = True" }, { "identifier": "MplugOwlProcessor", "path": "mplug_owl/processing_mplug_owl.py", "snippet": "class MplugOwlProcessor(ProcessorMixin):\n attributes = []\n tokenizer_class = (\"MplugOwlTokenizer\")\n\n def __init__(self, image_processor=None, tokenizer=None, **kwargs):\n super().__init__(**kwargs)\n self.tokens_to_generate = 0\n self.image_processor = image_processor\n self.tokenizer = tokenizer\n self.add_BOS = True\n\n def __call__(self, text=None, images=None, return_tensors=None, **kwargs):\n args = get_args()\n if text is None and images is None:\n raise ValueError(\"You have to specify either text or images. Both cannot be none.\")\n\n if images is not None:\n if not isinstance(images, list):\n images = [images]\n # image_features, = self.image_processor(images, return_tensors=return_tensors, **kwargs)\n process_results = [self.image_processor(image=image, text=None) for image in images]\n if len(process_results)>0 and len(process_results[0][0].shape) == 4:\n # 图片被切分成了多块 默认是doc场景\n text_list = text.split('<image>')\n images = []\n patch_positions = []\n text = text_list[0]\n for ri, (image_input, text_input, patch_position) in enumerate(process_results):\n images.append(image_input)\n patch_positions.append(patch_position)\n if args.patch_pos_embed_type == 'pre':\n # 对于pre处理 v2t最终输出的是一张图的token\n text += '<image>'\n else:\n # 对于post处理 v2t最终输出的是多图\n text += '<image>'*image_input.shape[0]\n text += text_list[ri+1]\n images = torch.cat(images, dim=0)\n patch_positions = torch.cat(patch_positions, dim=0)\n else:\n # 如果没有切片 则正常stack 并创建patch position = num_image (0,0)的patch id以保持一致\n images = [_[0] for _ in process_results]\n images = torch.stack(images, dim=0)\n patch_positions = torch.zeros(images.shape[0],2).long()\n text = text\n if text is not None:\n encoding = tokenize_prompts(\n prompts=[text],\n tokens_to_generate=self.tokens_to_generate,\n add_BOS=self.add_BOS,\n tokenizer=self.tokenizer,\n ignore_dist=True,\n **kwargs,\n )\n # encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)\n\n \n if text is not None and images is not None:\n encoding[\"pixel_values\"] = images\n encoding[\"patch_positions\"] = patch_position\n return BatchEncoding(data=encoding)\n elif text is not None:\n return BatchEncoding(data=encoding)\n else:\n return BatchEncoding(data=dict(pixel_values=images, patch_position=patch_position), tensor_type=return_tensors)\n\n def batch_decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please\n refer to the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.batch_decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)\n\n def decode(self, skip_special_tokens=True, *args, **kwargs):\n \"\"\"\n This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to\n the docstring of this method for more information.\n \"\"\"\n return self.tokenizer.decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)" }, { "identifier": "MplugOwlForConditionalGeneration", "path": "mplug_owl/modeling_mplug_owl.py", "snippet": "class MplugOwlForConditionalGeneration(MplugOwlPreTrainedModel):\n config_class = MplugOwlConfig\n main_input_name = \"pixel_values\"\n\n def __init__(self, config: MplugOwlConfig):\n super().__init__(config)\n\n self.vision_model = MplugOwlVisionModel(config.vision_config)\n\n self.query_tokens = nn.Parameter(\n torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size)\n )\n self.num_queries = config.num_query_tokens\n self.abstractor = MplugOwlVisualAbstractorModel(\n config.visual_abstractor_config, config.text_config.hidden_size\n )\n language_model = AutoModelForCausalLM.from_config(config.text_config)\n self.language_model = language_model\n\n # Initialize weights and apply final processing\n self.post_init()\n self.main_input_name = \"input_ids\"\n from transformers import GenerationConfig\n\n self.generation_config = GenerationConfig(\n max_length=512, do_sample=True, top_k=3, pad_token_id=0, unk_token_id=0, bos_token_id=1, eos_token_id=2\n )\n\n def get_input_embeddings(self):\n return self.language_model.get_input_embeddings()\n\n def set_input_embeddings(self, value):\n self.language_model.set_input_embeddings(value)\n\n def set_output_embeddings(self, new_embeddings):\n self.language_model.set_output_embeddings(new_embeddings)\n\n def get_output_embeddings(self) -> nn.Module:\n return self.language_model.get_output_embeddings()\n\n def get_encoder(self):\n return self.language_model.get_encoder()\n\n def get_decoder(self):\n return self.language_model.get_decoder()\n\n def _tie_weights(self):\n if not self.config.use_decoder_only_language_model:\n self.language_model.encoder.embed_tokens = self.language_model.shared\n self.language_model.decoder.embed_tokens = self.language_model.shared\n\n def _preprocess_accelerate(self):\n r\"\"\"\n Some pre-processing hacks to make the model `accelerate` compatible. Check\n https://github.com/huggingface/transformers/pull/21707 for more details.\n \"\"\"\n hf_device_map = self.hf_device_map\n\n if len(hf_device_map) > 1 and \"language_model\" not in hf_device_map and torch.cuda.device_count() > 1:\n # warn users about unexpected behavior when using multi-GPU + mPLUG-Owl + `accelerate`.\n logger.warning(\n \"The `language_model` is not in the `hf_device_map` dictionary and you are running your script\"\n \" in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`.\"\n \" Please pass a `device_map` that contains `language_model` to remove this warning.\"\n \" Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for\"\n \" more details on creating a `device_map` for large models.\",\n )\n\n if hasattr(self.language_model, \"_hf_hook\"):\n self.language_model._hf_hook.io_same_device = True # For `generate` compatibility\n\n @add_start_docstrings_to_model_forward(MPLUG_OWL_INPUTS_DOCSTRING)\n @replace_return_docstrings(\n output_type=MplugOwlForConditionalGenerationModelOutput, config_class=MplugOwlVisionConfig\n )\n def forward(\n self,\n pixel_values: torch.FloatTensor,\n input_ids: torch.FloatTensor,\n num_images,\n non_padding_mask: Optional[torch.LongTensor] = None,\n non_media_mask: Optional[torch.LongTensor] = None,\n prompt_mask: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.LongTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n labels: Optional[torch.LongTensor] = None,\n patch_positions=None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, MplugOwlForConditionalGenerationModelOutput]:\n r\"\"\"\n Returns:\n\n SFT example:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import MplugOwlProcessor, MplugOwlForConditionalGeneration\n >>> import torch\n\n >>> device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n >>> processor = MplugOwlProcessor.from_pretrained(\"MAGAer13/mplug-owl-llama-7b\")\n >>> model = MplugOwlForConditionalGeneration.from_pretrained(\n ... \"MAGAer13/mplug-owl-llama-7b\", torch_dtype=torch.float16\n ... )\n >>> model.to(device) # doctest: +IGNORE_RESULT\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> prompt = [\n ... \"The following is a conversation between a curious human and AI assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.\\nHuman: <image>\\nHuman: how many cats are there?\\nAI: \"\n ... ]\n >>> inputs = processor(images=[image], text=prompt, return_tensors=\"pt\").to(device, torch.float16)\n\n >>> generated_ids = model.generate(**inputs)\n >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()\n >>> print(generated_text)\n There are two cats in the image.\n ```\"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # get text embedding\n text_tokens_ = input_ids.clone()\n batch_size = input_ids.shape[0]\n # labels = text_tokens_[:, 1:].clone().contiguous()\n\n media_token_indices = [\n # [:-1] since we would not use the last token for embedding\n get_media_indices(text_tokens_[i][:-1], self.num_queries)\n for i in range(batch_size)\n ]\n text_tokens_[text_tokens_ < 0] = 1 # Not used\n # text_tokens = text_tokens_[:, :-1].contiguous()\n text_embeds = self.get_input_embeddings()(text_tokens_) # Temporally Embedding\n\n if pixel_values is not None:\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n\n image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n\n query_features = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n )[\"last_hidden_state\"]\n torch.ones(query_features.size()[:-1], dtype=torch.long).to(query_features.device)\n img_seq_length = query_features.shape[1]\n\n num_images_per_sample = num_images.long().cpu().tolist()\n\n text_chunk_embeds = []\n img_idx = 0\n for b in range(batch_size):\n start = 0\n result = []\n if len(media_token_indices[b]) > 0:\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(text_embeds[b, start:pos])\n result.append(query_features[img_idx + i])\n start = pos + img_seq_length\n if start < text_embeds.shape[1]:\n result.append(text_embeds[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n\n # Actual Input Embeddings\n input_embeds = torch.stack(text_chunk_embeds, dim=0)\n\n # Create causal mask and position ids\n _, loss_mask, position_ids = get_ltor_masks_and_position_ids_from_embeddings(input_embeds)\n\n # Calculate the loss_mask\n non_padding_mask = non_padding_mask.long()\n non_media_mask = non_media_mask.long()\n prompt_mask = prompt_mask.long() # TODO How to deal with prompt mask\n # from icecream import ic\n # non_padding_mask = non_padding_mask[:,:-1]\n # non_media_mask = non_media_mask[:,:-1]\n # prompt_mask = prompt_mask[:,:-1]\n # attention_mask = attention_mask[:,:-1]\n loss_mask = loss_mask[:, :-1]\n\n loss_mask = loss_mask * non_padding_mask * non_media_mask * prompt_mask\n labels[:, 1:][loss_mask != 1] = -100\n # Forward into GPT\n outputs = self.language_model(\n inputs_embeds=input_embeds,\n attention_mask=attention_mask,\n labels=labels,\n return_dict=return_dict,\n output_attentions=self.config.output_attentions,\n )\n outputs.loss = (outputs.loss * loss_mask.view(-1)\n ).sum()/loss_mask.sum()\n return outputs\n\n @torch.no_grad()\n def generate(\n self,\n pixel_values: torch.FloatTensor = None,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n patch_positions=None,\n isdecoder=True,\n **generate_kwargs,\n ) -> torch.LongTensor:\n \"\"\"\n Overrides `generate` function to be able to use the model as a conditional generator.\n\n Args:\n pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):\n Input images to be processed.\n input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n The sequence used as a prompt for the generation.\n attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n Mask to avoid performing attention on padding token indices\n\n Returns:\n captions (list): A list of strings of length batch_size * num_captions.\n \"\"\"\n if pixel_values is not None:\n pixel_values = pixel_values.to(self.vision_model.embeddings.cls_token.data.dtype)\n if input_ids is None:\n return self.language_model.generate(attention_mask=attention_mask, **generate_kwargs)\n\n if attention_mask is None:\n attention_mask = input_ids.new_ones(*input_ids.shape)\n\n batch_size = input_ids.size(0)\n media_token_indices = [get_media_indices(input_ids[i], self.num_queries) for i in range(batch_size)]\n input_ids = input_ids.clone() # prevent inplace modify\n input_ids[input_ids < 0] = 0 # Not used\n\n if hasattr(self, \"hf_device_map\"):\n # preprocess for `accelerate`\n self._preprocess_accelerate()\n batch_size = input_ids.shape[0]\n # get text embedding\n inputs_embeds = self.get_input_embeddings()(input_ids)\n # get visual embedding\n if pixel_values is not None:\n pixel_values = pixel_values.to(input_ids.device)\n with torch.no_grad():\n image_embeds = self.vision_model(pixel_values, patch_positions=patch_positions, return_dict=True).last_hidden_state\n image_attention_mask = torch.ones(\n image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device\n )\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n query_outputs = self.abstractor(\n query_embeds=query_tokens,\n encoder_hidden_states=image_embeds,\n encoder_attention_mask=image_attention_mask,\n patch_positions=patch_positions,\n return_dict=True,\n )\n query_output = query_outputs[\"last_hidden_state\"]\n image_embeds = query_output\n img_seq_length = image_embeds.shape[1]\n\n # ===================\n # Get actual input embeddings\n # ===================\n text_chunk_embeds = []\n text_chunk_attns = []\n img_idx = 0\n\n for b in range(batch_size):\n start = 0\n result = []\n result_attn = []\n for i, pos in enumerate(media_token_indices[b][0]):\n if pos > start:\n result.append(inputs_embeds[b, start:pos])\n result_attn.append(attention_mask[b, start:pos])\n result.append(image_embeds[img_idx + i])\n result_attn.append(torch.ones(image_embeds[img_idx + i].shape[0], device=inputs_embeds.device))\n start = pos + img_seq_length\n if start < inputs_embeds.shape[1]:\n result.append(inputs_embeds[b, start:])\n result_attn.append(attention_mask[b, start:])\n\n img_idx += media_token_indices[b][1]\n text_chunk_embeds.append(torch.cat(result, dim=0))\n text_chunk_attns.append(torch.cat(result_attn, dim=0))\n inputs_embeds = torch.stack(text_chunk_embeds, dim=0)\n attention_mask = torch.stack(text_chunk_attns, dim=0)\n\n outputs = self.language_model.generate(\n inputs_embeds=inputs_embeds,\n # input_ids=input_ids,\n attention_mask=attention_mask,\n **generate_kwargs,\n )\n\n return outputs\n\n def prepare_inputs_for_generation(\n self, input_ids, pixel_values=None, past_key_values=None, attention_mask=None, **model_kwargs\n ):\n input_shape = input_ids.shape\n # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly\n if attention_mask is None:\n attention_mask = input_ids.new_ones(input_shape)\n\n # # cut decoder_input_ids if past_key_values is used\n # if past_key_values is not None:\n # input_ids = input_ids[:, -1:]\n\n return {\n \"input_ids\": input_ids,\n \"pixel_values\": pixel_values,\n \"attention_mask\": attention_mask,\n \"is_decoder\": True,\n }" }, { "identifier": "build_processors", "path": "pipeline/data_utils/processors/builder.py", "snippet": "def build_processors(processors_cfg):\n processors = dict()\n for task, processor in processors_cfg.items():\n processors[task] = build_from_cfg(processor, PROCESSORS)\n ic(type(processors[task]))\n return processors" } ]
from PIL import Image from io import BytesIO from .io_utils import IO, DefaultIO, OSS from mplug_owl.processing_mplug_owl import MplugOwlProcessor, MplugOwlImageProcessor from mplug_owl.modeling_mplug_owl import MplugOwlForConditionalGeneration from mplug_owl.configuration_mplug_owl import MplugOwlConfig from mplug_owl.tokenization_mplug_owl import MplugOwlTokenizer from transformers import GenerationConfig from .model_utils import post_process_output, Stream, Iteratorize from pathlib import Path from mplug_owl.processing_mplug_owl import MplugOwlProcessor from mplug_owl.modeling_mplug_owl import MplugOwlForConditionalGeneration from pipeline.data_utils.processors.builder import build_processors from pipeline.data_utils.processors import * from transformers.models.llama.tokenization_llama import LlamaTokenizer from icecream import ic import torch import gradio as gr import logging import sys import os import json import requests import datetime import uuid import base64 import time import sys import transformers
14,674
sys.path.append("..") server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" # from pipeline.data_utils.xgpt3_dataset import ImageIO # class ImageProcessor(object): # def __init__(self, resolution=224, tokenizer=None): # normalize = transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) # # self.transform = transforms.Compose([ # # transforms.Resize((resolution, resolution),interpolation=Image.BICUBIC), # # transforms.ToTensor(), # # normalize, # # ]) # from megatron.data.processors import doc_processor # processor_class = os.environ.get('DocProcessor','DocSFTProcessor') # self.transform = getattr(doc_processor,processor_class)() # self.image_io = ImageIO() # self.tokenizer=tokenizer # def __call__(self, image_paths, prompts): # if isinstance(image_paths, str): # image_paths = [image_paths] # images = [] # images = self.image_io._load_img(image_paths) # images = [self.transform(image, None) for image in images] # image_input, text_input, patch_position # patch_position = [_[2] for _ in images] # images = [_[0] for _ in images] # text_list = prompts[0].split('<image>') # text = text_list[0] # for ri, image in enumerate(images): # if args.patch_pos_embed_type == 'pre': # # 对于pre处理 v2t最终输出的是一张图的token # text += '<image>' # else: # # 对于post处理 v2t最终输出的是多图 # text += '<image>'*image.shape[0] # text += text_list[ri+1] # images = torch.cat(images, dim=0) # patch_position = torch.cat(patch_position, dim=0) # print(text) # ic(images.shape) # ic(patch_position.shape) # from mplug_owl.processing_mplug_owl import tokenize_prompts # input_ids = tokenize_prompts(text, tokenizer=self.tokenizer, return_tensors='pt') # return { # "pixel_values": images, # 'patch_position': patch_position, # "input_ids": input_ids # } class mPLUG_Owl_Server: def __init__( self, base_model='MAGAer13/mplug-owl-llama-7b', log_dir='./', load_in_8bit=False, bf16=True, device="cuda", io=None, config=None, ): self.log_dir = log_dir self.config = config self.image_processor = build_processors(config['valid_processors'])['sft'] self.tokenizer = LlamaTokenizer.from_pretrained(base_model) self.processor = MplugOwlProcessor(self.image_processor, self.tokenizer)
sys.path.append("..") server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" # from pipeline.data_utils.xgpt3_dataset import ImageIO # class ImageProcessor(object): # def __init__(self, resolution=224, tokenizer=None): # normalize = transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) # # self.transform = transforms.Compose([ # # transforms.Resize((resolution, resolution),interpolation=Image.BICUBIC), # # transforms.ToTensor(), # # normalize, # # ]) # from megatron.data.processors import doc_processor # processor_class = os.environ.get('DocProcessor','DocSFTProcessor') # self.transform = getattr(doc_processor,processor_class)() # self.image_io = ImageIO() # self.tokenizer=tokenizer # def __call__(self, image_paths, prompts): # if isinstance(image_paths, str): # image_paths = [image_paths] # images = [] # images = self.image_io._load_img(image_paths) # images = [self.transform(image, None) for image in images] # image_input, text_input, patch_position # patch_position = [_[2] for _ in images] # images = [_[0] for _ in images] # text_list = prompts[0].split('<image>') # text = text_list[0] # for ri, image in enumerate(images): # if args.patch_pos_embed_type == 'pre': # # 对于pre处理 v2t最终输出的是一张图的token # text += '<image>' # else: # # 对于post处理 v2t最终输出的是多图 # text += '<image>'*image.shape[0] # text += text_list[ri+1] # images = torch.cat(images, dim=0) # patch_position = torch.cat(patch_position, dim=0) # print(text) # ic(images.shape) # ic(patch_position.shape) # from mplug_owl.processing_mplug_owl import tokenize_prompts # input_ids = tokenize_prompts(text, tokenizer=self.tokenizer, return_tensors='pt') # return { # "pixel_values": images, # 'patch_position': patch_position, # "input_ids": input_ids # } class mPLUG_Owl_Server: def __init__( self, base_model='MAGAer13/mplug-owl-llama-7b', log_dir='./', load_in_8bit=False, bf16=True, device="cuda", io=None, config=None, ): self.log_dir = log_dir self.config = config self.image_processor = build_processors(config['valid_processors'])['sft'] self.tokenizer = LlamaTokenizer.from_pretrained(base_model) self.processor = MplugOwlProcessor(self.image_processor, self.tokenizer)
self.model = MplugOwlForConditionalGeneration.from_pretrained(
12
2023-10-08 06:29:02+00:00
24k
LeapLabTHU/Rank-DETR
projects/dino_eva/configs/models/dino_r50.py
[ { "identifier": "HungarianMatcher", "path": "detrex/modeling/matcher/matcher.py", "snippet": "class HungarianMatcher(nn.Module):\n \"\"\"HungarianMatcher which computes an assignment between targets and predictions.\n\n For efficiency reasons, the targets don't include the no_object. Because of this, in general,\n there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,\n while the others are un-matched (and thus treated as non-objects).\n\n Args:\n cost_class (float): The relative weight of the classification error\n in the matching cost. Default: 1.\n cost_bbox (float): The relative weight of the L1 error of the bounding box\n coordinates in the matching cost. Default: 1.\n cost_giou (float): This is the relative weight of the giou loss of\n the bounding box in the matching cost. Default: 1.\n cost_class_type (str): How the classification error is calculated.\n Choose from ``[\"ce_cost\", \"focal_loss_cost\"]``. Default: \"focal_loss_cost\".\n alpha (float): Weighting factor in range (0, 1) to balance positive vs\n negative examples in focal loss. Default: 0.25.\n gamma (float): Exponent of modulating factor (1 - p_t) to balance easy vs\n hard examples in focal loss. Default: 2.\n \"\"\"\n\n def __init__(\n self,\n cost_class: float = 1,\n cost_bbox: float = 1,\n cost_giou: float = 1,\n cost_class_type: str = \"focal_loss_cost\",\n alpha: float = 0.25,\n gamma: float = 2.0,\n ):\n super().__init__()\n self.cost_class = cost_class\n self.cost_bbox = cost_bbox\n self.cost_giou = cost_giou\n self.cost_class_type = cost_class_type\n self.alpha = alpha\n self.gamma = gamma\n assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, \"all costs cant be 0\"\n assert cost_class_type in {\n \"ce_cost\",\n \"focal_loss_cost\",\n }, \"only support ce loss or focal loss for computing class cost\"\n\n @torch.no_grad()\n def forward(self, outputs, targets):\n \"\"\"Forward function for `HungarianMatcher` which performs the matching.\n\n Args:\n outputs (Dict[str, torch.Tensor]): This is a dict that contains at least these entries:\n\n - ``\"pred_logits\"``: Tensor of shape (bs, num_queries, num_classes) with the classification logits.\n - ``\"pred_boxes\"``: Tensor of shape (bs, num_queries, 4) with the predicted box coordinates.\n\n targets (List[Dict[str, torch.Tensor]]): This is a list of targets (len(targets) = batch_size),\n where each target is a dict containing:\n\n - ``\"labels\"``: Tensor of shape (num_target_boxes, ) (where num_target_boxes is the number of ground-truth objects in the target) containing the class labels. # noqa\n - ``\"boxes\"``: Tensor of shape (num_target_boxes, 4) containing the target box coordinates.\n\n Returns:\n list[torch.Tensor]: A list of size batch_size, containing tuples of `(index_i, index_j)` where:\n\n - ``index_i`` is the indices of the selected predictions (in order)\n - ``index_j`` is the indices of the corresponding selected targets (in order)\n\n For each batch element, it holds: `len(index_i) = len(index_j) = min(num_queries, num_target_boxes)`\n \"\"\"\n bs, num_queries = outputs[\"pred_logits\"].shape[:2]\n\n # We flatten to compute the cost matrices in a batch\n if self.cost_class_type == \"ce_cost\":\n out_prob = (\n outputs[\"pred_logits\"].flatten(0, 1).softmax(-1)\n ) # [batch_size * num_queries, num_classes]\n elif self.cost_class_type == \"focal_loss_cost\":\n out_prob = (\n outputs[\"pred_logits\"].flatten(0, 1).sigmoid()\n ) # [batch_size * num_queries, num_classes]\n\n out_bbox = outputs[\"pred_boxes\"].flatten(0, 1) # [batch_size * num_queries, 4]\n\n # Also concat the target labels and boxes\n tgt_ids = torch.cat([v[\"labels\"] for v in targets])\n tgt_bbox = torch.cat([v[\"boxes\"] for v in targets])\n\n # Compute the classification cost.\n if self.cost_class_type == \"ce_cost\":\n # Compute the classification cost. Contrary to the loss, we don't use the NLL,\n # but approximate it in 1 - proba[target class].\n # The 1 is a constant that doesn't change the matching, it can be ommitted.\n cost_class = -out_prob[:, tgt_ids]\n elif self.cost_class_type == \"focal_loss_cost\":\n alpha = self.alpha\n gamma = self.gamma\n neg_cost_class = (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log())\n pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())\n cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]\n\n # Compute the L1 cost between boxes\n cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)\n\n # Compute the giou cost betwen boxes\n cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))\n\n # Final cost matrix\n C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou\n C = C.view(bs, num_queries, -1).cpu()\n\n sizes = [len(v[\"boxes\"]) for v in targets]\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]\n return [\n (torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64))\n for i, j in indices\n ]\n\n def __repr__(self, _repr_indent=4):\n head = \"Matcher \" + self.__class__.__name__\n body = [\n \"cost_class: {}\".format(self.cost_class),\n \"cost_bbox: {}\".format(self.cost_bbox),\n \"cost_giou: {}\".format(self.cost_giou),\n \"cost_class_type: {}\".format(self.cost_class_type),\n \"focal cost alpha: {}\".format(self.alpha),\n \"focal cost gamma: {}\".format(self.gamma),\n ]\n lines = [head] + [\" \" * _repr_indent + line for line in body]\n return \"\\n\".join(lines)" }, { "identifier": "ChannelMapper", "path": "detrex/modeling/neck/channel_mapper.py", "snippet": "class ChannelMapper(nn.Module):\n \"\"\"Channel Mapper for reduce/increase channels of backbone features. Modified\n from `mmdet <https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/necks/channel_mapper.py>`_.\n\n This is used to reduce/increase the channels of backbone features.\n\n Args:\n input_shape (Dict[str, ShapeSpec]): A dict which contains the backbone features meta infomation,\n e.g. ``input_shape = {\"res5\": ShapeSpec(channels=2048)}``.\n in_features (List[str]): A list contains the keys which maps the features output from the backbone,\n e.g. ``in_features = [\"res\"]``.\n out_channels (int): Number of output channels for each scale.\n kernel_size (int, optional): Size of the convolving kernel for each scale.\n Default: 3.\n stride (int, optional): Stride of convolution for each scale. Default: 1.\n bias (bool, optional): If True, adds a learnable bias to the output of each scale.\n Default: True.\n groups (int, optional): Number of blocked connections from input channels to\n output channels for each scale. Default: 1.\n dilation (int, optional): Spacing between kernel elements for each scale.\n Default: 1.\n norm_layer (nn.Module, optional): The norm layer used for each scale. Default: None.\n activation (nn.Module, optional): The activation layer used for each scale. Default: None.\n num_outs (int, optional): Number of output feature maps. There will be ``extra_convs`` when\n ``num_outs`` is larger than the length of ``in_features``. Default: None.\n\n Examples:\n >>> import torch\n >>> import torch.nn as nn\n >>> from detrex.modeling import ChannelMapper\n >>> from detectron2.modeling import ShapeSpec\n >>> input_features = {\n ... \"p0\": torch.randn(1, 128, 128, 128),\n ... \"p1\": torch.randn(1, 256, 64, 64),\n ... \"p2\": torch.randn(1, 512, 32, 32),\n ... \"p3\": torch.randn(1, 1024, 16, 16),\n ... }\n >>> input_shapes = {\n ... \"p0\": ShapeSpec(channels=128),\n ... \"p1\": ShapeSpec(channels=256),\n ... \"p2\": ShapeSpec(channels=512),\n ... \"p3\": ShapeSpec(channels=1024),\n ... }\n >>> in_features = [\"p0\", \"p1\", \"p2\", \"p3\"]\n >>> neck = ChannelMapper(\n ... input_shapes=input_shapes,\n ... in_features=in_features,\n ... out_channels=256,\n ... norm_layer=nn.GroupNorm(num_groups=32, num_channels=256)\n >>> outputs = neck(input_features)\n >>> for i in range(len(outputs)):\n ... print(f\"output[{i}].shape = {outputs[i].shape}\")\n output[0].shape = torch.Size([1, 256, 128, 128])\n output[1].shape = torch.Size([1, 256, 64, 64])\n output[2].shape = torch.Size([1, 256, 32, 32])\n output[3].shape = torch.Size([1, 256, 16, 16])\n \"\"\"\n\n def __init__(\n self,\n input_shapes: Dict[str, ShapeSpec],\n in_features: List[str],\n out_channels: int,\n kernel_size: int = 3,\n stride: int = 1,\n bias: bool = True,\n groups: int = 1,\n dilation: int = 1,\n norm_layer: nn.Module = None,\n activation: nn.Module = None,\n num_outs: int = None,\n **kwargs,\n ):\n super(ChannelMapper, self).__init__()\n self.extra_convs = None\n\n in_channels_per_feature = [input_shapes[f].channels for f in in_features]\n\n if num_outs is None:\n num_outs = len(input_shapes)\n\n self.convs = nn.ModuleList()\n for in_channel in in_channels_per_feature:\n self.convs.append(\n ConvNormAct(\n in_channels=in_channel,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=(kernel_size - 1) // 2,\n bias=bias,\n groups=groups,\n dilation=dilation,\n norm_layer=copy.deepcopy(norm_layer),\n activation=copy.deepcopy(activation),\n )\n )\n\n if num_outs > len(in_channels_per_feature):\n self.extra_convs = nn.ModuleList()\n for i in range(len(in_channels_per_feature), num_outs):\n if i == len(in_channels_per_feature):\n in_channel = in_channels_per_feature[-1]\n else:\n in_channel = out_channels\n self.extra_convs.append(\n ConvNormAct(\n in_channels=in_channel,\n out_channels=out_channels,\n kernel_size=3,\n stride=2,\n padding=1,\n bias=bias,\n groups=groups,\n dilation=dilation,\n norm_layer=copy.deepcopy(norm_layer),\n activation=copy.deepcopy(activation),\n )\n )\n\n self.input_shapes = input_shapes\n self.in_features = in_features\n self.out_channels = out_channels\n\n def forward(self, inputs):\n \"\"\"Forward function for ChannelMapper\n\n Args:\n inputs (Dict[str, torch.Tensor]): The backbone feature maps.\n\n Return:\n tuple(torch.Tensor): A tuple of the processed features.\n \"\"\"\n assert len(inputs) == len(self.convs)\n outs = [self.convs[i](inputs[self.in_features[i]]) for i in range(len(inputs))]\n if self.extra_convs:\n for i in range(len(self.extra_convs)):\n if i == 0:\n outs.append(self.extra_convs[0](inputs[self.in_features[-1]]))\n else:\n outs.append(self.extra_convs[i](outs[-1]))\n return tuple(outs)" }, { "identifier": "PositionEmbeddingSine", "path": "detrex/layers/position_embedding.py", "snippet": "class PositionEmbeddingSine(nn.Module):\n \"\"\"Sinusoidal position embedding used in DETR model.\n\n Please see `End-to-End Object Detection with Transformers\n <https://arxiv.org/pdf/2005.12872>`_ for more details.\n\n Args:\n num_pos_feats (int): The feature dimension for each position along\n x-axis or y-axis. The final returned dimension for each position\n is 2 times of the input value.\n temperature (int, optional): The temperature used for scaling\n the position embedding. Default: 10000.\n scale (float, optional): A scale factor that scales the position\n embedding. The scale will be used only when `normalize` is True.\n Default: 2*pi.\n eps (float, optional): A value added to the denominator for numerical\n stability. Default: 1e-6.\n offset (float): An offset added to embed when doing normalization.\n normalize (bool, optional): Whether to normalize the position embedding.\n Default: False.\n \"\"\"\n\n def __init__(\n self,\n num_pos_feats: int = 64,\n temperature: int = 10000,\n scale: float = 2 * math.pi,\n eps: float = 1e-6,\n offset: float = 0.0,\n normalize: bool = False,\n ):\n super().__init__()\n if normalize:\n assert isinstance(scale, (float, int)), (\n \"when normalize is set,\"\n \"scale should be provided and in float or int type, \"\n f\"found {type(scale)}\"\n )\n self.num_pos_feats = num_pos_feats\n self.temperature = temperature\n self.normalize = normalize\n self.scale = scale\n self.eps = eps\n self.offset = offset\n\n def forward(self, mask: torch.Tensor, **kwargs) -> torch.Tensor:\n \"\"\"Forward function for `PositionEmbeddingSine`.\n\n Args:\n mask (torch.Tensor): ByteTensor mask. Non-zero values representing\n ignored positions, while zero values means valid positions\n for the input tensor. Shape as `(bs, h, w)`.\n\n Returns:\n torch.Tensor: Returned position embedding with\n shape `(bs, num_pos_feats * 2, h, w)`\n \"\"\"\n assert mask is not None\n not_mask = ~mask\n y_embed = not_mask.cumsum(1, dtype=torch.float32)\n x_embed = not_mask.cumsum(2, dtype=torch.float32)\n if self.normalize:\n y_embed = (y_embed + self.offset) / (y_embed[:, -1:, :] + self.eps) * self.scale\n x_embed = (x_embed + self.offset) / (x_embed[:, :, -1:] + self.eps) * self.scale\n dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=mask.device)\n dim_t = self.temperature ** (\n 2 * torch.div(dim_t, 2, rounding_mode=\"floor\") / self.num_pos_feats\n )\n pos_x = x_embed[:, :, :, None] / dim_t\n pos_y = y_embed[:, :, :, None] / dim_t\n\n # use view as mmdet instead of flatten for dynamically exporting to ONNX\n B, H, W = mask.size()\n pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).view(\n B, H, W, -1\n )\n pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).view(\n B, H, W, -1\n )\n pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)\n return pos" }, { "identifier": "DINOTransformerEncoder", "path": "projects/dino_eva/modeling/dino_transformer.py", "snippet": "class DINOTransformerEncoder(TransformerLayerSequence):\n def __init__(\n self,\n embed_dim: int = 256,\n num_heads: int = 8,\n feedforward_dim: int = 1024,\n attn_dropout: float = 0.1,\n ffn_dropout: float = 0.1,\n num_layers: int = 6,\n post_norm: bool = False,\n num_feature_levels: int = 4,\n use_checkpoint: bool = False,\n ):\n super(DINOTransformerEncoder, self).__init__(\n transformer_layers=BaseTransformerLayer(\n attn=MultiScaleDeformableAttention(\n embed_dim=embed_dim,\n num_heads=num_heads,\n dropout=attn_dropout,\n batch_first=True,\n num_levels=num_feature_levels,\n ),\n ffn=FFN(\n embed_dim=embed_dim,\n feedforward_dim=feedforward_dim,\n output_dim=embed_dim,\n num_fcs=2,\n ffn_drop=ffn_dropout,\n ),\n norm=nn.LayerNorm(embed_dim),\n operation_order=(\"self_attn\", \"norm\", \"ffn\", \"norm\"),\n ),\n num_layers=num_layers,\n )\n self.embed_dim = self.layers[0].embed_dim\n self.pre_norm = self.layers[0].pre_norm\n\n if post_norm:\n self.post_norm_layer = nn.LayerNorm(self.embed_dim)\n else:\n self.post_norm_layer = None\n\n # use encoder checkpoint\n if use_checkpoint:\n for layer in self.layers:\n layer = checkpoint_wrapper(layer)\n\n def forward(\n self,\n query,\n key,\n value,\n query_pos=None,\n key_pos=None,\n attn_masks=None,\n query_key_padding_mask=None,\n key_padding_mask=None,\n **kwargs,\n ):\n\n for layer in self.layers:\n query = layer(\n query,\n key,\n value,\n query_pos=query_pos,\n attn_masks=attn_masks,\n query_key_padding_mask=query_key_padding_mask,\n key_padding_mask=key_padding_mask,\n **kwargs,\n )\n\n if self.post_norm_layer is not None:\n query = self.post_norm_layer(query)\n return query" }, { "identifier": "DINOTransformerDecoder", "path": "projects/dino_eva/modeling/dino_transformer.py", "snippet": "class DINOTransformerDecoder(TransformerLayerSequence):\n def __init__(\n self,\n embed_dim: int = 256,\n num_heads: int = 8,\n feedforward_dim: int = 1024,\n attn_dropout: float = 0.1,\n ffn_dropout: float = 0.1,\n num_layers: int = 6,\n return_intermediate: bool = True,\n num_feature_levels: int = 4,\n look_forward_twice: bool = True,\n use_checkpoint: bool = True,\n ):\n super(DINOTransformerDecoder, self).__init__(\n transformer_layers=BaseTransformerLayer(\n attn=[\n MultiheadAttention(\n embed_dim=embed_dim,\n num_heads=num_heads,\n attn_drop=attn_dropout,\n batch_first=True,\n ),\n MultiScaleDeformableAttention(\n embed_dim=embed_dim,\n num_heads=num_heads,\n dropout=attn_dropout,\n batch_first=True,\n num_levels=num_feature_levels,\n ),\n ],\n ffn=FFN(\n embed_dim=embed_dim,\n feedforward_dim=feedforward_dim,\n output_dim=embed_dim,\n ffn_drop=ffn_dropout,\n ),\n norm=nn.LayerNorm(embed_dim),\n operation_order=(\"self_attn\", \"norm\", \"cross_attn\", \"norm\", \"ffn\", \"norm\"),\n ),\n num_layers=num_layers,\n )\n self.return_intermediate = return_intermediate\n\n self.ref_point_head = MLP(2 * embed_dim, embed_dim, embed_dim, 2)\n\n self.bbox_embed = None\n self.class_embed = None\n self.look_forward_twice = look_forward_twice\n self.norm = nn.LayerNorm(embed_dim)\n\n # decoder checkpoint\n if use_checkpoint:\n for layer in self.layers:\n layer = checkpoint_wrapper(layer)\n\n def forward(\n self,\n query,\n key,\n value,\n query_pos=None,\n key_pos=None,\n attn_masks=None,\n query_key_padding_mask=None,\n key_padding_mask=None,\n reference_points=None, # num_queries, 4. normalized.\n valid_ratios=None,\n **kwargs,\n ):\n output = query\n bs, num_queries, _ = output.size()\n if reference_points.dim() == 2:\n reference_points = reference_points.unsqueeze(0).repeat(bs, 1, 1) # bs, num_queries, 4\n\n intermediate = []\n intermediate_reference_points = []\n for layer_idx, layer in enumerate(self.layers):\n if reference_points.shape[-1] == 4:\n reference_points_input = (\n reference_points[:, :, None]\n * torch.cat([valid_ratios, valid_ratios], -1)[:, None]\n )\n else:\n assert reference_points.shape[-1] == 2\n reference_points_input = reference_points[:, :, None] * valid_ratios[:, None]\n\n query_sine_embed = get_sine_pos_embed(reference_points_input[:, :, 0, :])\n query_pos = self.ref_point_head(query_sine_embed)\n\n output = layer(\n output,\n key,\n value,\n query_pos=query_pos,\n key_pos=key_pos,\n query_sine_embed=query_sine_embed,\n attn_masks=attn_masks,\n query_key_padding_mask=query_key_padding_mask,\n key_padding_mask=key_padding_mask,\n reference_points=reference_points_input,\n **kwargs,\n )\n\n if self.bbox_embed is not None:\n tmp = self.bbox_embed[layer_idx](output)\n if reference_points.shape[-1] == 4:\n new_reference_points = tmp + inverse_sigmoid(reference_points)\n new_reference_points = new_reference_points.sigmoid()\n else:\n assert reference_points.shape[-1] == 2\n new_reference_points = tmp\n new_reference_points[..., :2] = tmp[..., :2] + inverse_sigmoid(reference_points)\n new_reference_points = new_reference_points.sigmoid()\n reference_points = new_reference_points.detach()\n\n if self.return_intermediate:\n intermediate.append(self.norm(output))\n if self.look_forward_twice:\n intermediate_reference_points.append(new_reference_points)\n else:\n intermediate_reference_points.append(reference_points)\n\n if self.return_intermediate:\n return torch.stack(intermediate), torch.stack(intermediate_reference_points)\n\n return output, reference_points" }, { "identifier": "DINOTransformer", "path": "projects/dino_eva/modeling/dino_transformer.py", "snippet": "class DINOTransformer(nn.Module):\n \"\"\"Transformer module for DINO\n\n Args:\n encoder (nn.Module): encoder module.\n decoder (nn.Module): decoder module.\n as_two_stage (bool): whether to use two-stage transformer. Default False.\n num_feature_levels (int): number of feature levels. Default 4.\n two_stage_num_proposals (int): number of proposals in two-stage transformer. Default 900.\n \"\"\"\n\n def __init__(\n self,\n encoder=None,\n decoder=None,\n num_feature_levels=4,\n two_stage_num_proposals=900,\n learnt_init_query=True,\n ):\n super(DINOTransformer, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n self.num_feature_levels = num_feature_levels\n self.two_stage_num_proposals = two_stage_num_proposals\n\n self.embed_dim = self.encoder.embed_dim\n\n self.level_embeds = nn.Parameter(torch.Tensor(self.num_feature_levels, self.embed_dim))\n self.learnt_init_query = learnt_init_query\n if self.learnt_init_query:\n self.tgt_embed = nn.Embedding(self.two_stage_num_proposals, self.embed_dim)\n self.enc_output = nn.Linear(self.embed_dim, self.embed_dim)\n self.enc_output_norm = nn.LayerNorm(self.embed_dim)\n\n self.init_weights()\n\n def init_weights(self):\n for p in self.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n for m in self.modules():\n if isinstance(m, MultiScaleDeformableAttention):\n m.init_weights()\n nn.init.normal_(self.level_embeds)\n\n def gen_encoder_output_proposals(self, memory, memory_padding_mask, spatial_shapes):\n N, S, C = memory.shape\n proposals = []\n _cur = 0\n for lvl, (H, W) in enumerate(spatial_shapes):\n mask_flatten_ = memory_padding_mask[:, _cur : (_cur + H * W)].view(N, H, W, 1)\n valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1)\n valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1)\n\n grid_y, grid_x = torch.meshgrid(\n torch.linspace(0, H - 1, H, dtype=torch.float32, device=memory.device),\n torch.linspace(0, W - 1, W, dtype=torch.float32, device=memory.device),\n )\n grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1)\n\n scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N, 1, 1, 2)\n grid = (grid.unsqueeze(0).expand(N, -1, -1, -1) + 0.5) / scale\n wh = torch.ones_like(grid) * 0.05 * (2.0**lvl)\n proposal = torch.cat((grid, wh), -1).view(N, -1, 4)\n proposals.append(proposal)\n _cur += H * W\n\n output_proposals = torch.cat(proposals, 1)\n output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(\n -1, keepdim=True\n )\n output_proposals = torch.log(output_proposals / (1 - output_proposals))\n output_proposals = output_proposals.masked_fill(\n memory_padding_mask.unsqueeze(-1), float(\"inf\")\n )\n output_proposals = output_proposals.masked_fill(~output_proposals_valid, float(\"inf\"))\n\n output_memory = memory\n output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0))\n output_memory = output_memory.masked_fill(~output_proposals_valid, float(0))\n output_memory = self.enc_output_norm(self.enc_output(output_memory))\n return output_memory, output_proposals\n\n @staticmethod\n def get_reference_points(spatial_shapes, valid_ratios, device):\n \"\"\"Get the reference points used in decoder.\n\n Args:\n spatial_shapes (Tensor): The shape of all\n feature maps, has shape (num_level, 2).\n valid_ratios (Tensor): The ratios of valid\n points on the feature map, has shape\n (bs, num_levels, 2)\n device (obj:`device`): The device where\n reference_points should be.\n\n Returns:\n Tensor: reference points used in decoder, has \\\n shape (bs, num_keys, num_levels, 2).\n \"\"\"\n reference_points_list = []\n for lvl, (H, W) in enumerate(spatial_shapes):\n # TODO check this 0.5\n ref_y, ref_x = torch.meshgrid(\n torch.linspace(0.5, H - 0.5, H, dtype=torch.float32, device=device),\n torch.linspace(0.5, W - 0.5, W, dtype=torch.float32, device=device),\n )\n ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H)\n ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W)\n ref = torch.stack((ref_x, ref_y), -1)\n reference_points_list.append(ref)\n reference_points = torch.cat(reference_points_list, 1)\n reference_points = reference_points[:, :, None] * valid_ratios[:, None]\n return reference_points\n\n def get_valid_ratio(self, mask):\n \"\"\"Get the valid ratios of feature maps of all levels.\"\"\"\n _, H, W = mask.shape\n valid_H = torch.sum(~mask[:, :, 0], 1)\n valid_W = torch.sum(~mask[:, 0, :], 1)\n valid_ratio_h = valid_H.float() / H\n valid_ratio_w = valid_W.float() / W\n valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1)\n return valid_ratio\n\n def forward(\n self,\n multi_level_feats,\n multi_level_masks,\n multi_level_pos_embeds,\n query_embed,\n attn_masks,\n **kwargs,\n ):\n feat_flatten = []\n mask_flatten = []\n lvl_pos_embed_flatten = []\n spatial_shapes = []\n for lvl, (feat, mask, pos_embed) in enumerate(\n zip(multi_level_feats, multi_level_masks, multi_level_pos_embeds)\n ):\n bs, c, h, w = feat.shape\n spatial_shape = (h, w)\n spatial_shapes.append(spatial_shape)\n\n feat = feat.flatten(2).transpose(1, 2) # bs, hw, c\n mask = mask.flatten(1)\n pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c\n lvl_pos_embed = pos_embed + self.level_embeds[lvl].view(1, 1, -1)\n lvl_pos_embed_flatten.append(lvl_pos_embed)\n feat_flatten.append(feat)\n mask_flatten.append(mask)\n feat_flatten = torch.cat(feat_flatten, 1)\n mask_flatten = torch.cat(mask_flatten, 1)\n lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1)\n spatial_shapes = torch.as_tensor(\n spatial_shapes, dtype=torch.long, device=feat_flatten.device\n )\n level_start_index = torch.cat(\n (spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1])\n )\n valid_ratios = torch.stack([self.get_valid_ratio(m) for m in multi_level_masks], 1)\n\n reference_points = self.get_reference_points(\n spatial_shapes, valid_ratios, device=feat.device\n )\n\n memory = self.encoder(\n query=feat_flatten,\n key=None,\n value=None,\n query_pos=lvl_pos_embed_flatten,\n query_key_padding_mask=mask_flatten,\n spatial_shapes=spatial_shapes,\n reference_points=reference_points, # bs, num_token, num_level, 2\n level_start_index=level_start_index,\n valid_ratios=valid_ratios,\n **kwargs,\n )\n\n output_memory, output_proposals = self.gen_encoder_output_proposals(\n memory, mask_flatten, spatial_shapes\n )\n # output_memory: bs, num_tokens, c\n # output_proposals: bs, num_tokens, 4. unsigmoided.\n\n enc_outputs_class = self.decoder.class_embed[self.decoder.num_layers](output_memory)\n enc_outputs_coord_unact = (\n self.decoder.bbox_embed[self.decoder.num_layers](output_memory) + output_proposals\n ) # unsigmoided.\n\n topk = self.two_stage_num_proposals\n topk_proposals = torch.topk(enc_outputs_class.max(-1)[0], topk, dim=1)[1]\n\n # extract region proposal boxes\n topk_coords_unact = torch.gather(\n enc_outputs_coord_unact, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)\n ) # unsigmoided.\n reference_points = topk_coords_unact.detach().sigmoid()\n if query_embed[1] is not None:\n reference_points = torch.cat([query_embed[1].sigmoid(), reference_points], 1)\n init_reference_out = reference_points\n\n # extract region features\n target_unact = torch.gather(\n output_memory, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1])\n )\n if self.learnt_init_query:\n target = self.tgt_embed.weight[None].repeat(bs, 1, 1)\n else:\n target = target_unact.detach()\n if query_embed[0] is not None:\n target = torch.cat([query_embed[0], target], 1)\n\n # decoder\n inter_states, inter_references = self.decoder(\n query=target, # bs, num_queries, embed_dims\n key=memory, # bs, num_tokens, embed_dims\n value=memory, # bs, num_tokens, embed_dims\n query_pos=None,\n key_padding_mask=mask_flatten, # bs, num_tokens\n reference_points=reference_points, # num_queries, 4\n spatial_shapes=spatial_shapes, # nlvl, 2\n level_start_index=level_start_index, # nlvl\n valid_ratios=valid_ratios, # bs, nlvl, 2\n attn_masks=attn_masks,\n **kwargs,\n )\n\n inter_references_out = inter_references\n return (\n inter_states,\n init_reference_out,\n inter_references_out,\n target_unact,\n topk_coords_unact.sigmoid(),\n )" }, { "identifier": "DINO", "path": "projects/dino_eva/modeling/dino.py", "snippet": "class DINO(nn.Module):\n \"\"\"Implement DAB-Deformable-DETR in `DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR\n <https://arxiv.org/abs/2203.03605>`_.\n\n Code is modified from the `official github repo\n <https://github.com/IDEA-Research/DINO>`_.\n\n Args:\n backbone (nn.Module): backbone module\n position_embedding (nn.Module): position embedding module\n neck (nn.Module): neck module to handle the intermediate outputs features\n transformer (nn.Module): transformer module\n embed_dim (int): dimension of embedding\n num_classes (int): Number of total categories.\n num_queries (int): Number of proposal dynamic anchor boxes in Transformer\n criterion (nn.Module): Criterion for calculating the total losses.\n pixel_mean (List[float]): Pixel mean value for image normalization.\n Default: [123.675, 116.280, 103.530].\n pixel_std (List[float]): Pixel std value for image normalization.\n Default: [58.395, 57.120, 57.375].\n aux_loss (bool): Whether to calculate auxiliary loss in criterion. Default: True.\n select_box_nums_for_evaluation (int): the number of topk candidates\n slected at postprocess for evaluation. Default: 300.\n device (str): Training device. Default: \"cuda\".\n \"\"\"\n\n def __init__(\n self,\n backbone: nn.Module,\n position_embedding: nn.Module,\n neck: nn.Module,\n transformer: nn.Module,\n embed_dim: int,\n num_classes: int,\n num_queries: int,\n criterion: nn.Module,\n pixel_mean: List[float] = [123.675, 116.280, 103.530],\n pixel_std: List[float] = [58.395, 57.120, 57.375],\n aux_loss: bool = True,\n select_box_nums_for_evaluation: int = 300,\n device=\"cuda\",\n dn_number: int = 100,\n label_noise_ratio: float = 0.2,\n box_noise_scale: float = 1.0,\n input_format: Optional[str] = \"RGB\",\n vis_period: int = 0,\n ):\n super().__init__()\n # define backbone and position embedding module\n self.backbone = backbone\n self.position_embedding = position_embedding\n\n # define neck module\n self.neck = neck\n\n # number of dynamic anchor boxes and embedding dimension\n self.num_queries = num_queries\n self.embed_dim = embed_dim\n\n # define transformer module\n self.transformer = transformer\n\n # define classification head and box head\n self.class_embed = nn.Linear(embed_dim, num_classes)\n self.bbox_embed = MLP(embed_dim, embed_dim, 4, 3)\n self.num_classes = num_classes\n\n # where to calculate auxiliary loss in criterion\n self.aux_loss = aux_loss\n self.criterion = criterion\n\n # denoising\n self.label_enc = nn.Embedding(num_classes, embed_dim)\n self.dn_number = dn_number\n self.label_noise_ratio = label_noise_ratio\n self.box_noise_scale = box_noise_scale\n\n # normalizer for input raw images\n self.device = device\n self.pixel_mean = torch.Tensor(pixel_mean).to(self.device).view(3, 1, 1)\n self.pixel_std = torch.Tensor(pixel_std).to(self.device).view(3, 1, 1)\n self.normalizer = lambda x: (x - self.pixel_mean) / self.pixel_std\n\n # initialize weights\n prior_prob = 0.01\n bias_value = -math.log((1 - prior_prob) / prior_prob)\n self.class_embed.bias.data = torch.ones(num_classes) * bias_value\n nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)\n nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)\n for _, neck_layer in self.neck.named_modules():\n if isinstance(neck_layer, nn.Conv2d):\n nn.init.xavier_uniform_(neck_layer.weight, gain=1)\n nn.init.constant_(neck_layer.bias, 0)\n\n # if two-stage, the last class_embed and bbox_embed is for region proposal generation\n num_pred = transformer.decoder.num_layers + 1\n self.class_embed = nn.ModuleList([copy.deepcopy(self.class_embed) for i in range(num_pred)])\n self.bbox_embed = nn.ModuleList([copy.deepcopy(self.bbox_embed) for i in range(num_pred)])\n nn.init.constant_(self.bbox_embed[0].layers[-1].bias.data[2:], -2.0)\n\n # two-stage\n self.transformer.decoder.class_embed = self.class_embed\n self.transformer.decoder.bbox_embed = self.bbox_embed\n\n # hack implementation for two-stage\n for bbox_embed_layer in self.bbox_embed:\n nn.init.constant_(bbox_embed_layer.layers[-1].bias.data[2:], 0.0)\n\n # set topk boxes selected for inference\n self.select_box_nums_for_evaluation = select_box_nums_for_evaluation\n\n # the period for visualizing training samples\n self.input_format = input_format\n self.vis_period = vis_period\n if vis_period > 0:\n assert input_format is not None, \"input_format is required for visualization!\"\n\n\n def _move_to_current_device(self, x):\n return move_device_like(x, self.pixel_mean)\n\n\n def forward(self, batched_inputs):\n \"\"\"Forward function of `DINO` which excepts a list of dict as inputs.\n\n Args:\n batched_inputs (List[dict]): A list of instance dict, and each instance dict must consists of:\n - dict[\"image\"] (torch.Tensor): The unnormalized image tensor.\n - dict[\"height\"] (int): The original image height.\n - dict[\"width\"] (int): The original image width.\n - dict[\"instance\"] (detectron2.structures.Instances):\n Image meta informations and ground truth boxes and labels during training.\n Please refer to\n https://detectron2.readthedocs.io/en/latest/modules/structures.html#detectron2.structures.Instances\n for the basic usage of Instances.\n\n Returns:\n dict: Returns a dict with the following elements:\n - dict[\"pred_logits\"]: the classification logits for all queries (anchor boxes in DAB-DETR).\n with shape ``[batch_size, num_queries, num_classes]``\n - dict[\"pred_boxes\"]: The normalized boxes coordinates for all queries in format\n ``(x, y, w, h)``. These values are normalized in [0, 1] relative to the size of\n each individual image (disregarding possible padding). See PostProcess for information\n on how to retrieve the unnormalized bounding box.\n - dict[\"aux_outputs\"]: Optional, only returned when auxilary losses are activated. It is a list of\n dictionnaries containing the two above keys for each decoder layer.\n \"\"\"\n images, img_size = self.preprocess_image(batched_inputs)\n\n if self.training:\n batch_size, _, H, W = images.tensor.shape\n img_masks = images.tensor.new_ones(batch_size, H, W)\n for img_id in range(batch_size):\n img_h, img_w = batched_inputs[img_id][\"instances\"].image_size\n img_masks[img_id, :img_h, :img_w] = 0\n else:\n batch_size, _, H, W = images.tensor.shape\n img_masks = images.tensor.new_ones(batch_size, H, W)\n for img_id in range(batch_size):\n img_h, img_w = img_size[img_id][0], img_size[img_id][1]\n img_masks[img_id, :img_h, :img_w] = 0\n\n # original features\n features = self.backbone(images.tensor) # output feature dict\n\n # project backbone features to the reuired dimension of transformer\n # we use multi-scale features in DINO\n multi_level_feats = self.neck(features)\n multi_level_masks = []\n multi_level_position_embeddings = []\n for feat in multi_level_feats:\n multi_level_masks.append(\n F.interpolate(img_masks[None], size=feat.shape[-2:]).to(torch.bool).squeeze(0)\n )\n multi_level_position_embeddings.append(self.position_embedding(multi_level_masks[-1]))\n\n # denoising preprocessing\n # prepare label query embedding\n if self.training:\n gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n targets = self.prepare_targets(gt_instances)\n input_query_label, input_query_bbox, attn_mask, dn_meta = self.prepare_for_cdn(\n targets,\n dn_number=self.dn_number,\n label_noise_ratio=self.label_noise_ratio,\n box_noise_scale=self.box_noise_scale,\n num_queries=self.num_queries,\n num_classes=self.num_classes,\n hidden_dim=self.embed_dim,\n label_enc=self.label_enc,\n )\n else:\n input_query_label, input_query_bbox, attn_mask, dn_meta = None, None, None, None\n query_embeds = (input_query_label, input_query_bbox)\n\n # feed into transformer\n (\n inter_states,\n init_reference,\n inter_references,\n enc_state,\n enc_reference, # [0..1]\n ) = self.transformer(\n multi_level_feats,\n multi_level_masks,\n multi_level_position_embeddings,\n query_embeds,\n attn_masks=[attn_mask, None],\n )\n # hack implementation for distributed training\n inter_states[0] += self.label_enc.weight[0, 0] * 0.0\n\n # Calculate output coordinates and classes.\n outputs_classes = []\n outputs_coords = []\n for lvl in range(inter_states.shape[0]):\n if lvl == 0:\n reference = init_reference\n else:\n reference = inter_references[lvl - 1]\n reference = inverse_sigmoid(reference)\n outputs_class = self.class_embed[lvl](inter_states[lvl])\n tmp = self.bbox_embed[lvl](inter_states[lvl])\n if reference.shape[-1] == 4:\n tmp += reference\n else:\n assert reference.shape[-1] == 2\n tmp[..., :2] += reference\n outputs_coord = tmp.sigmoid()\n outputs_classes.append(outputs_class)\n outputs_coords.append(outputs_coord)\n outputs_class = torch.stack(outputs_classes)\n # tensor shape: [num_decoder_layers, bs, num_query, num_classes]\n outputs_coord = torch.stack(outputs_coords)\n # tensor shape: [num_decoder_layers, bs, num_query, 4]\n\n # denoising postprocessing\n if dn_meta is not None:\n outputs_class, outputs_coord = self.dn_post_process(\n outputs_class, outputs_coord, dn_meta\n )\n\n # prepare for loss computation\n output = {\"pred_logits\": outputs_class[-1], \"pred_boxes\": outputs_coord[-1]}\n if self.aux_loss:\n output[\"aux_outputs\"] = self._set_aux_loss(outputs_class, outputs_coord)\n\n # prepare two stage output\n interm_coord = enc_reference\n interm_class = self.transformer.decoder.class_embed[-1](enc_state)\n output[\"enc_outputs\"] = {\"pred_logits\": interm_class, \"pred_boxes\": interm_coord}\n\n if self.training:\n # visualize training samples\n if self.vis_period > 0:\n storage = get_event_storage()\n if storage.iter % self.vis_period == 0:\n box_cls = output[\"pred_logits\"]\n box_pred = output[\"pred_boxes\"]\n results = self.inference(box_cls, box_pred, images.image_sizes)\n self.visualize_training(batched_inputs, results)\n \n # compute loss\n loss_dict = self.criterion(output, targets, dn_meta)\n weight_dict = self.criterion.weight_dict\n for k in loss_dict.keys():\n if k in weight_dict:\n loss_dict[k] *= weight_dict[k]\n return loss_dict\n else:\n box_cls = output[\"pred_logits\"]\n box_pred = output[\"pred_boxes\"]\n results = self.inference(box_cls, box_pred, images.image_sizes)\n processed_results = []\n for results_per_image, input_per_image, image_size in zip(\n results, batched_inputs, images.image_sizes\n ):\n height = input_per_image.get(\"height\", image_size[0])\n width = input_per_image.get(\"width\", image_size[1])\n r = detector_postprocess(results_per_image, height, width)\n processed_results.append({\"instances\": r})\n return processed_results\n\n def visualize_training(self, batched_inputs, results):\n from detectron2.utils.visualizer import Visualizer\n\n storage = get_event_storage()\n max_vis_box = 20\n\n for input, results_per_image in zip(batched_inputs, results):\n img = input[\"image\"]\n img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)\n v_gt = Visualizer(img, None)\n v_gt = v_gt.overlay_instances(boxes=input[\"instances\"].gt_boxes)\n anno_img = v_gt.get_image()\n v_pred = Visualizer(img, None)\n v_pred = v_pred.overlay_instances(\n boxes=results_per_image.pred_boxes[:max_vis_box].tensor.detach().cpu().numpy()\n )\n pred_img = v_pred.get_image()\n vis_img = np.concatenate((anno_img, pred_img), axis=1)\n vis_img = vis_img.transpose(2, 0, 1)\n vis_name = \"Left: GT bounding boxes; Right: Predicted boxes\"\n storage.put_image(vis_name, vis_img)\n break # only visualize one image in a batch\n\n\n @torch.jit.unused\n def _set_aux_loss(self, outputs_class, outputs_coord):\n # this is a workaround to make torchscript happy, as torchscript\n # doesn't support dictionary with non-homogeneous values, such\n # as a dict having both a Tensor and a list.\n return [\n {\"pred_logits\": a, \"pred_boxes\": b}\n for a, b in zip(outputs_class[:-1], outputs_coord[:-1])\n ]\n\n def prepare_for_cdn(\n self,\n targets,\n dn_number,\n label_noise_ratio,\n box_noise_scale,\n num_queries,\n num_classes,\n hidden_dim,\n label_enc,\n ):\n \"\"\"\n A major difference of DINO from DN-DETR is that the author process pattern embedding pattern embedding\n in its detector\n forward function and use learnable tgt embedding, so we change this function a little bit.\n :param dn_args: targets, dn_number, label_noise_ratio, box_noise_scale\n :param training: if it is training or inference\n :param num_queries: number of queires\n :param num_classes: number of classes\n :param hidden_dim: transformer hidden dim\n :param label_enc: encode labels in dn\n :return:\n \"\"\"\n if dn_number <= 0:\n return None, None, None, None\n # positive and negative dn queries\n dn_number = dn_number * 2\n known = [(torch.ones_like(t[\"labels\"])).cuda() for t in targets]\n batch_size = len(known)\n known_num = [sum(k) for k in known]\n if int(max(known_num)) == 0:\n return None, None, None, None\n\n dn_number = dn_number // (int(max(known_num) * 2))\n\n if dn_number == 0:\n dn_number = 1\n unmask_bbox = unmask_label = torch.cat(known)\n labels = torch.cat([t[\"labels\"] for t in targets])\n boxes = torch.cat([t[\"boxes\"] for t in targets])\n batch_idx = torch.cat(\n [torch.full_like(t[\"labels\"].long(), i) for i, t in enumerate(targets)]\n )\n\n known_indice = torch.nonzero(unmask_label + unmask_bbox)\n known_indice = known_indice.view(-1)\n\n known_indice = known_indice.repeat(2 * dn_number, 1).view(-1)\n known_labels = labels.repeat(2 * dn_number, 1).view(-1)\n known_bid = batch_idx.repeat(2 * dn_number, 1).view(-1)\n known_bboxs = boxes.repeat(2 * dn_number, 1)\n known_labels_expaned = known_labels.clone()\n known_bbox_expand = known_bboxs.clone()\n\n if label_noise_ratio > 0:\n p = torch.rand_like(known_labels_expaned.float())\n chosen_indice = torch.nonzero(p < (label_noise_ratio * 0.5)).view(\n -1\n ) # half of bbox prob\n new_label = torch.randint_like(\n chosen_indice, 0, num_classes\n ) # randomly put a new one here\n known_labels_expaned.scatter_(0, chosen_indice, new_label)\n single_padding = int(max(known_num))\n\n pad_size = int(single_padding * 2 * dn_number)\n positive_idx = (\n torch.tensor(range(len(boxes))).long().cuda().unsqueeze(0).repeat(dn_number, 1)\n )\n positive_idx += (torch.tensor(range(dn_number)) * len(boxes) * 2).long().cuda().unsqueeze(1)\n positive_idx = positive_idx.flatten()\n negative_idx = positive_idx + len(boxes)\n if box_noise_scale > 0:\n known_bbox_ = torch.zeros_like(known_bboxs)\n known_bbox_[:, :2] = known_bboxs[:, :2] - known_bboxs[:, 2:] / 2\n known_bbox_[:, 2:] = known_bboxs[:, :2] + known_bboxs[:, 2:] / 2\n\n diff = torch.zeros_like(known_bboxs)\n diff[:, :2] = known_bboxs[:, 2:] / 2\n diff[:, 2:] = known_bboxs[:, 2:] / 2\n\n rand_sign = (\n torch.randint_like(known_bboxs, low=0, high=2, dtype=torch.float32) * 2.0 - 1.0\n )\n rand_part = torch.rand_like(known_bboxs)\n rand_part[negative_idx] += 1.0\n rand_part *= rand_sign\n known_bbox_ = known_bbox_ + torch.mul(rand_part, diff).cuda() * box_noise_scale\n known_bbox_ = known_bbox_.clamp(min=0.0, max=1.0)\n known_bbox_expand[:, :2] = (known_bbox_[:, :2] + known_bbox_[:, 2:]) / 2\n known_bbox_expand[:, 2:] = known_bbox_[:, 2:] - known_bbox_[:, :2]\n\n m = known_labels_expaned.long().to(\"cuda\")\n input_label_embed = label_enc(m)\n input_bbox_embed = inverse_sigmoid(known_bbox_expand)\n\n padding_label = torch.zeros(pad_size, hidden_dim).cuda()\n padding_bbox = torch.zeros(pad_size, 4).cuda()\n\n input_query_label = padding_label.repeat(batch_size, 1, 1)\n input_query_bbox = padding_bbox.repeat(batch_size, 1, 1)\n\n map_known_indice = torch.tensor([]).to(\"cuda\")\n if len(known_num):\n map_known_indice = torch.cat(\n [torch.tensor(range(num)) for num in known_num]\n ) # [1,2, 1,2,3]\n map_known_indice = torch.cat(\n [map_known_indice + single_padding * i for i in range(2 * dn_number)]\n ).long()\n if len(known_bid):\n input_query_label[(known_bid.long(), map_known_indice)] = input_label_embed\n input_query_bbox[(known_bid.long(), map_known_indice)] = input_bbox_embed\n\n tgt_size = pad_size + num_queries\n attn_mask = torch.ones(tgt_size, tgt_size).to(\"cuda\") < 0\n # match query cannot see the reconstruct\n attn_mask[pad_size:, :pad_size] = True\n # reconstruct cannot see each other\n for i in range(dn_number):\n if i == 0:\n attn_mask[\n single_padding * 2 * i : single_padding * 2 * (i + 1),\n single_padding * 2 * (i + 1) : pad_size,\n ] = True\n if i == dn_number - 1:\n attn_mask[\n single_padding * 2 * i : single_padding * 2 * (i + 1), : single_padding * i * 2\n ] = True\n else:\n attn_mask[\n single_padding * 2 * i : single_padding * 2 * (i + 1),\n single_padding * 2 * (i + 1) : pad_size,\n ] = True\n attn_mask[\n single_padding * 2 * i : single_padding * 2 * (i + 1), : single_padding * 2 * i\n ] = True\n\n dn_meta = {\n \"single_padding\": single_padding * 2,\n \"dn_num\": dn_number,\n }\n\n return input_query_label, input_query_bbox, attn_mask, dn_meta\n\n def dn_post_process(self, outputs_class, outputs_coord, dn_metas):\n if dn_metas and dn_metas[\"single_padding\"] > 0:\n padding_size = dn_metas[\"single_padding\"] * dn_metas[\"dn_num\"]\n output_known_class = outputs_class[:, :, :padding_size, :]\n output_known_coord = outputs_coord[:, :, :padding_size, :]\n outputs_class = outputs_class[:, :, padding_size:, :]\n outputs_coord = outputs_coord[:, :, padding_size:, :]\n\n out = {\"pred_logits\": output_known_class[-1], \"pred_boxes\": output_known_coord[-1]}\n if self.aux_loss:\n out[\"aux_outputs\"] = self._set_aux_loss(output_known_class, output_known_coord)\n dn_metas[\"output_known_lbs_bboxes\"] = out\n return outputs_class, outputs_coord\n\n def preprocess_image(self, batched_inputs):\n \"\"\"\n Normalize, pad and batch the input images.\n \"\"\"\n images = [self._move_to_current_device(x[\"image\"]) for x in batched_inputs]\n images = [(x - self.pixel_mean) / self.pixel_std for x in images]\n \n img_size = [[img.shape[1], img.shape[2]] for img in images]\n\n # TODO: modify square_size when necessary to avoid negative padding\n max_size = 0\n for img in images:\n _, h, w = img.shape\n if max(h, w) > max_size:\n max_size = max(h, w)\n padding_constraints = copy.deepcopy(self.backbone.padding_constraints)\n if 'square_size' in self.backbone.padding_constraints:\n square_size = self.backbone.padding_constraints['square_size']\n if square_size < max_size and square_size != 0:\n warnings.warn(\"square_size={}, is smaller than max_size={} in batch\".format(\n self.backbone.padding_constraints['square_size'], max_size))\n padding_constraints['square_size'] = max_size\n\n images = ImageList.from_tensors(\n images,\n self.backbone.size_divisibility,\n padding_constraints=padding_constraints,\n )\n return images, img_size\n\n def inference(self, box_cls, box_pred, image_sizes):\n \"\"\"\n Arguments:\n box_cls (Tensor): tensor of shape (batch_size, num_queries, K).\n The tensor predicts the classification probability for each query.\n box_pred (Tensor): tensors of shape (batch_size, num_queries, 4).\n The tensor predicts 4-vector (x,y,w,h) box\n regression values for every queryx\n image_sizes (List[torch.Size]): the input image sizes\n\n Returns:\n results (List[Instances]): a list of #images elements.\n \"\"\"\n assert len(box_cls) == len(image_sizes)\n results = []\n\n # box_cls.shape: 1, 300, 80\n # box_pred.shape: 1, 300, 4\n prob = box_cls.sigmoid()\n topk_values, topk_indexes = torch.topk(\n prob.view(box_cls.shape[0], -1), self.select_box_nums_for_evaluation, dim=1\n )\n scores = topk_values\n topk_boxes = torch.div(topk_indexes, box_cls.shape[2], rounding_mode=\"floor\")\n labels = topk_indexes % box_cls.shape[2]\n\n boxes = torch.gather(box_pred, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))\n\n # For each box we assign the best class or the second best if the best on is `no_object`.\n # scores, labels = F.softmax(box_cls, dim=-1)[:, :, :-1].max(-1)\n\n for i, (scores_per_image, labels_per_image, box_pred_per_image, image_size) in enumerate(\n zip(scores, labels, boxes, image_sizes)\n ):\n result = Instances(image_size)\n result.pred_boxes = Boxes(box_cxcywh_to_xyxy(box_pred_per_image))\n\n result.pred_boxes.scale(scale_x=image_size[1], scale_y=image_size[0])\n result.scores = scores_per_image\n result.pred_classes = labels_per_image\n results.append(result)\n return results\n\n def prepare_targets(self, targets):\n new_targets = []\n for targets_per_image in targets:\n h, w = targets_per_image.image_size\n image_size_xyxy = torch.as_tensor([w, h, w, h], dtype=torch.float, device=self.device)\n gt_classes = targets_per_image.gt_classes\n gt_boxes = targets_per_image.gt_boxes.tensor / image_size_xyxy\n gt_boxes = box_xyxy_to_cxcywh(gt_boxes)\n new_targets.append({\"labels\": gt_classes, \"boxes\": gt_boxes})\n return new_targets" }, { "identifier": "DINOCriterion", "path": "projects/dino_eva/modeling/dn_criterion.py", "snippet": "class DINOCriterion(TwoStageCriterion):\n \"\"\"This class computes the loss for DETR.\n The process happens in two steps:\n 1) we compute hungarian assignment between ground truth boxes and the outputs of the model\n 2) we supervise each pair of matched ground-truth / prediction (supervise class and box)\n \"\"\"\n\n def forward(self, outputs, targets, dn_metas=None):\n \"\"\"This performs the loss computation.\n Parameters:\n outputs: dict of tensors, see the output specification of the model for the format\n targets: list of dicts, such that len(targets) == batch_size.\n The expected keys in each dict depends on the losses applied, see each loss' doc\n \"\"\"\n losses = super(DINOCriterion, self).forward(outputs, targets)\n # import pdb;pdb.set_trace()\n num_boxes = sum(len(t[\"labels\"]) for t in targets)\n num_boxes = torch.as_tensor(\n [num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device\n )\n if is_dist_avail_and_initialized():\n torch.distributed.all_reduce(num_boxes)\n num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()\n\n # Compute all the requested losses\n\n aux_num = 0\n if \"aux_outputs\" in outputs:\n aux_num = len(outputs[\"aux_outputs\"])\n dn_losses = self.compute_dn_loss(dn_metas, targets, aux_num, num_boxes)\n losses.update(dn_losses)\n\n return losses\n\n def compute_dn_loss(self, dn_metas, targets, aux_num, num_boxes):\n \"\"\"\n compute dn loss in criterion\n Args:\n dn_metas: a dict for dn information\n training: training or inference flag\n aux_num: aux loss number\n focal_alpha: for focal loss\n \"\"\"\n losses = {}\n if dn_metas and \"output_known_lbs_bboxes\" in dn_metas:\n output_known_lbs_bboxes, dn_num, single_padding = (\n dn_metas[\"output_known_lbs_bboxes\"],\n dn_metas[\"dn_num\"],\n dn_metas[\"single_padding\"],\n )\n dn_idx = []\n for i in range(len(targets)):\n if len(targets[i][\"labels\"]) > 0:\n t = torch.arange(0, len(targets[i][\"labels\"])).long().cuda()\n t = t.unsqueeze(0).repeat(dn_num, 1)\n tgt_idx = t.flatten()\n output_idx = (\n torch.tensor(range(dn_num)) * single_padding\n ).long().cuda().unsqueeze(1) + t\n output_idx = output_idx.flatten()\n else:\n output_idx = tgt_idx = torch.tensor([]).long().cuda()\n\n dn_idx.append((output_idx, tgt_idx))\n l_dict = {}\n for loss in self.losses:\n kwargs = {}\n if \"labels\" in loss:\n kwargs = {\"log\": False}\n l_dict.update(\n self.get_loss(\n loss, output_known_lbs_bboxes, targets, dn_idx, num_boxes * dn_num, **kwargs\n )\n )\n\n l_dict = {k + \"_dn\": v for k, v in l_dict.items()}\n losses.update(l_dict)\n else:\n losses[\"loss_bbox_dn\"] = torch.as_tensor(0.0).to(\"cuda\")\n losses[\"loss_giou_dn\"] = torch.as_tensor(0.0).to(\"cuda\")\n losses[\"loss_class_dn\"] = torch.as_tensor(0.0).to(\"cuda\")\n\n for i in range(aux_num):\n # dn aux loss\n l_dict = {}\n if dn_metas and \"output_known_lbs_bboxes\" in dn_metas:\n output_known_lbs_bboxes_aux = output_known_lbs_bboxes[\"aux_outputs\"][i]\n for loss in self.losses:\n kwargs = {}\n if \"labels\" in loss:\n kwargs = {\"log\": False}\n l_dict.update(\n self.get_loss(\n loss,\n output_known_lbs_bboxes_aux,\n targets,\n dn_idx,\n num_boxes * dn_num,\n **kwargs,\n )\n )\n l_dict = {k + f\"_dn_{i}\": v for k, v in l_dict.items()}\n else:\n l_dict[\"loss_bbox_dn\"] = torch.as_tensor(0.0).to(\"cuda\")\n l_dict[\"loss_giou_dn\"] = torch.as_tensor(0.0).to(\"cuda\")\n l_dict[\"loss_class_dn\"] = torch.as_tensor(0.0).to(\"cuda\")\n l_dict = {k + f\"_{i}\": v for k, v in l_dict.items()}\n losses.update(l_dict)\n return losses" } ]
import copy import torch.nn as nn from detectron2.modeling.backbone import ResNet, BasicStem from detectron2.layers import ShapeSpec from detectron2.config import LazyCall as L from detrex.modeling.matcher import HungarianMatcher from detrex.modeling.neck import ChannelMapper from detrex.layers import PositionEmbeddingSine from projects.dino_eva.modeling import ( DINO, DINOTransformerEncoder, DINOTransformerDecoder, DINOTransformer, DINOCriterion, )
16,111
model = L(DINO)( backbone=L(ResNet)( stem=L(BasicStem)(in_channels=3, out_channels=64, norm="FrozenBN"), stages=L(ResNet.make_default_stages)( depth=50, stride_in_1x1=False, norm="FrozenBN", ), out_features=["res3", "res4", "res5"], freeze_at=1, ), position_embedding=L(PositionEmbeddingSine)( num_pos_feats=128, temperature=10000, normalize=True, offset=-0.5, ), neck=L(ChannelMapper)( input_shapes={ "res3": ShapeSpec(channels=512), "res4": ShapeSpec(channels=1024), "res5": ShapeSpec(channels=2048), }, in_features=["res3", "res4", "res5"], out_channels=256, num_outs=4, kernel_size=1, norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), ),
model = L(DINO)( backbone=L(ResNet)( stem=L(BasicStem)(in_channels=3, out_channels=64, norm="FrozenBN"), stages=L(ResNet.make_default_stages)( depth=50, stride_in_1x1=False, norm="FrozenBN", ), out_features=["res3", "res4", "res5"], freeze_at=1, ), position_embedding=L(PositionEmbeddingSine)( num_pos_feats=128, temperature=10000, normalize=True, offset=-0.5, ), neck=L(ChannelMapper)( input_shapes={ "res3": ShapeSpec(channels=512), "res4": ShapeSpec(channels=1024), "res5": ShapeSpec(channels=2048), }, in_features=["res3", "res4", "res5"], out_channels=256, num_outs=4, kernel_size=1, norm_layer=L(nn.GroupNorm)(num_groups=32, num_channels=256), ),
transformer=L(DINOTransformer)(
5
2023-10-12 03:02:25+00:00
24k
sakemin/cog-musicgen-remixer
predict.py
[ { "identifier": "MultiBandDiffusion", "path": "audiocraft/models/multibanddiffusion.py", "snippet": "class MultiBandDiffusion:\n \"\"\"Sample from multiple diffusion models.\n\n Args:\n DPs (list of DiffusionProcess): Diffusion processes.\n codec_model (CompressionModel): Underlying compression model used to obtain discrete tokens.\n \"\"\"\n def __init__(self, DPs: tp.List[DiffusionProcess], codec_model: CompressionModel) -> None:\n self.DPs = DPs\n self.codec_model = codec_model\n self.device = next(self.codec_model.parameters()).device\n\n @property\n def sample_rate(self) -> int:\n return self.codec_model.sample_rate\n\n @staticmethod\n def get_mbd_musicgen(device=None):\n \"\"\"Load our diffusion models trained for MusicGen.\"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n path = 'facebook/multiband-diffusion'\n filename = 'mbd_musicgen_32khz.th'\n name = 'facebook/musicgen-small'\n codec_model = load_compression_model(name, device=device)\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n @staticmethod\n def get_mbd_24khz(bw: float = 3.0, pretrained: bool = True,\n device: tp.Optional[tp.Union[torch.device, str]] = None,\n n_q: tp.Optional[int] = None):\n \"\"\"Get the pretrained Models for MultibandDiffusion.\n\n Args:\n bw (float): Bandwidth of the compression model.\n pretrained (bool): Whether to use / download if necessary the models.\n device (torch.device or str, optional): Device on which the models are loaded.\n n_q (int, optional): Number of quantizers to use within the compression model.\n \"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n assert bw in [1.5, 3.0, 6.0], f\"bandwidth {bw} not available\"\n if n_q is not None:\n assert n_q in [2, 4, 8]\n assert {1.5: 2, 3.0: 4, 6.0: 8}[bw] == n_q, \\\n f\"bandwidth and number of codebooks missmatch to use n_q = {n_q} bw should be {n_q * (1.5 / 2)}\"\n n_q = {1.5: 2, 3.0: 4, 6.0: 8}[bw]\n codec_model = CompressionSolver.model_from_checkpoint(\n '//pretrained/facebook/encodec_24khz', device=device)\n codec_model.set_num_codebooks(n_q)\n codec_model = codec_model.to(device)\n path = 'facebook/multiband-diffusion'\n filename = f'mbd_comp_{n_q}.pt'\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n return MultiBandDiffusion(DPs, codec_model)\n\n @torch.no_grad()\n def get_condition(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor:\n \"\"\"Get the conditioning (i.e. latent reprentatios of the compression model) from a waveform.\n Args:\n wav (torch.Tensor): The audio that we want to extract the conditioning from\n sample_rate (int): sample rate of the audio\"\"\"\n if sample_rate != self.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.sample_rate)\n codes, scale = self.codec_model.encode(wav)\n assert scale is None, \"Scaled compression models not supported.\"\n emb = self.get_emb(codes)\n return emb\n\n @torch.no_grad()\n def get_emb(self, codes: torch.Tensor):\n \"\"\"Get latent representation from the discrete codes\n Argrs:\n codes (torch.Tensor): discrete tokens\"\"\"\n emb = self.codec_model.decode_latent(codes)\n return emb\n\n def generate(self, emb: torch.Tensor, size: tp.Optional[torch.Size] = None,\n step_list: tp.Optional[tp.List[int]] = None):\n \"\"\"Generate Wavform audio from the latent embeddings of the compression model\n Args:\n emb (torch.Tensor): Conditioning embeddinds\n size (none torch.Size): size of the output\n if None this is computed from the typical upsampling of the model\n step_list (optional list[int]): list of Markov chain steps, defaults to 50 linearly spaced step.\n \"\"\"\n if size is None:\n upsampling = int(self.codec_model.sample_rate / self.codec_model.frame_rate)\n size = torch.Size([emb.size(0), self.codec_model.channels, emb.size(-1) * upsampling])\n assert size[0] == emb.size(0)\n out = torch.zeros(size).to(self.device)\n for DP in self.DPs:\n out += DP.generate(condition=emb, step_list=step_list, initial_noise=torch.randn_like(out))\n return out\n\n def re_eq(self, wav: torch.Tensor, ref: torch.Tensor, n_bands: int = 32, strictness: float = 1):\n \"\"\"match the eq to the encodec output by matching the standard deviation of some frequency bands\n Args:\n wav (torch.Tensor): audio to equalize\n ref (torch.Tensor):refenrence audio from which we match the spectrogram.\n n_bands (int): number of bands of the eq\n strictness (float): how strict the the matching. 0 is no matching, 1 is exact matching.\n \"\"\"\n split = julius.SplitBands(n_bands=n_bands, sample_rate=self.codec_model.sample_rate).to(wav.device)\n bands = split(wav)\n bands_ref = split(ref)\n out = torch.zeros_like(ref)\n for i in range(n_bands):\n out += bands[i] * (bands_ref[i].std() / bands[i].std()) ** strictness\n return out\n\n def regenerate(self, wav: torch.Tensor, sample_rate: int):\n \"\"\"Regenerate a wavform through compression and diffusion regeneration.\n Args:\n wav (torch.Tensor): Original 'ground truth' audio\n sample_rate (int): sample rate of the input (and output) wav\n \"\"\"\n if sample_rate != self.codec_model.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.codec_model.sample_rate)\n emb = self.get_condition(wav, sample_rate=self.codec_model.sample_rate)\n size = wav.size()\n out = self.generate(emb, size=size)\n if sample_rate != self.codec_model.sample_rate:\n out = julius.resample_frac(out, self.codec_model.sample_rate, sample_rate)\n return out\n\n def tokens_to_wav(self, tokens: torch.Tensor, n_bands: int = 32):\n \"\"\"Generate Waveform audio with diffusion from the discrete codes.\n Args:\n tokens (torch.Tensor): discrete codes\n n_bands (int): bands for the eq matching.\n \"\"\"\n wav_encodec = self.codec_model.decode(tokens)\n condition = self.get_emb(tokens)\n wav_diffusion = self.generate(emb=condition, size=wav_encodec.size())\n return self.re_eq(wav=wav_diffusion, ref=wav_encodec, n_bands=n_bands)" }, { "identifier": "MusicGen", "path": "audiocraft/models/musicgen.py", "snippet": "class MusicGen:\n \"\"\"MusicGen main model with convenient generation API.\n\n Args:\n name (str): name of the model.\n compression_model (CompressionModel): Compression model\n used to map audio to invertible discrete representations.\n lm (LMModel): Language model over discrete representations.\n max_duration (float, optional): maximum duration the model can produce,\n otherwise, inferred from the training params.\n \"\"\"\n def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel,\n max_duration: tp.Optional[float] = None):\n self.name = name\n self.compression_model = compression_model\n self.lm = lm\n self.cfg: tp.Optional[omegaconf.DictConfig] = None\n # Just to be safe, let's put everything in eval mode.\n self.compression_model.eval()\n self.lm.eval()\n\n if hasattr(lm, 'cfg'):\n cfg = lm.cfg\n assert isinstance(cfg, omegaconf.DictConfig)\n self.cfg = cfg\n\n if self.cfg is not None:\n self.compression_model = get_wrapped_compression_model(self.compression_model, self.cfg)\n\n if max_duration is None:\n if self.cfg is not None:\n max_duration = lm.cfg.dataset.segment_duration # type: ignore\n else:\n raise ValueError(\"You must provide max_duration when building directly MusicGen\")\n assert max_duration is not None\n self.max_duration: float = max_duration\n self.device = next(iter(lm.parameters())).device\n\n self.generation_params: dict = {}\n self.set_generation_params(duration=15) # 15 seconds by default\n self._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None\n if self.device.type == 'cpu':\n self.autocast = TorchAutocast(enabled=False)\n else:\n self.autocast = TorchAutocast(\n enabled=True, device_type=self.device.type, dtype=torch.float16)\n\n @property\n def frame_rate(self) -> float:\n \"\"\"Roughly the number of AR steps per seconds.\"\"\"\n return self.compression_model.frame_rate\n\n @property\n def sample_rate(self) -> int:\n \"\"\"Sample rate of the generated audio.\"\"\"\n return self.compression_model.sample_rate\n\n @property\n def audio_channels(self) -> int:\n \"\"\"Audio channels of the generated audio.\"\"\"\n return self.compression_model.channels\n\n @staticmethod\n def get_pretrained(name: str = 'facebook/musicgen-melody', device=None):\n \"\"\"Return pretrained model, we provide four models:\n - facebook/musicgen-small (300M), text to music,\n # see: https://huggingface.co/facebook/musicgen-small\n - facebook/musicgen-medium (1.5B), text to music,\n # see: https://huggingface.co/facebook/musicgen-medium\n - facebook/musicgen-melody (1.5B) text to music and text+melody to music,\n # see: https://huggingface.co/facebook/musicgen-melody\n - facebook/musicgen-large (3.3B), text to music,\n # see: https://huggingface.co/facebook/musicgen-large\n \"\"\"\n if device is None:\n if torch.cuda.device_count():\n device = 'cuda'\n else:\n device = 'cpu'\n\n if name == 'debug':\n # used only for unit tests\n compression_model = get_debug_compression_model(device)\n lm = get_debug_lm_model(device)\n return MusicGen(name, compression_model, lm, max_duration=30)\n\n if name in _HF_MODEL_CHECKPOINTS_MAP:\n warnings.warn(\n \"MusicGen pretrained model relying on deprecated checkpoint mapping. \" +\n f\"Please use full pre-trained id instead: facebook/musicgen-{name}\")\n name = _HF_MODEL_CHECKPOINTS_MAP[name]\n\n lm = load_lm_model(name, device=device)\n compression_model = load_compression_model(name, device=device)\n if 'self_wav' in lm.condition_provider.conditioners:\n lm.condition_provider.conditioners['self_wav'].match_len_on_eval = True\n lm.condition_provider.conditioners['self_wav']._use_masking = False\n\n return MusicGen(name, compression_model, lm)\n\n def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,\n top_p: float = 0.0, temperature: float = 1.0,\n duration: float = 30.0, cfg_coef: float = 3.0,\n two_step_cfg: bool = False, extend_stride: float = 18):\n \"\"\"Set the generation parameters for MusicGen.\n\n Args:\n use_sampling (bool, optional): Use sampling if True, else do argmax decoding. Defaults to True.\n top_k (int, optional): top_k used for sampling. Defaults to 250.\n top_p (float, optional): top_p used for sampling, when set to 0 top_k is used. Defaults to 0.0.\n temperature (float, optional): Softmax temperature parameter. Defaults to 1.0.\n duration (float, optional): Duration of the generated waveform. Defaults to 30.0.\n cfg_coef (float, optional): Coefficient used for classifier free guidance. Defaults to 3.0.\n two_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,\n instead of batching together the two. This has some impact on how things\n are padded but seems to have little impact in practice.\n extend_stride: when doing extended generation (i.e. more than 30 seconds), by how much\n should we extend the audio each time. Larger values will mean less context is\n preserved, and shorter value will require extra computations.\n \"\"\"\n assert extend_stride < self.max_duration, \"Cannot stride by more than max generation duration.\"\n self.extend_stride = extend_stride\n self.duration = duration\n self.generation_params = {\n 'use_sampling': use_sampling,\n 'temp': temperature,\n 'top_k': top_k,\n 'top_p': top_p,\n 'cfg_coef': cfg_coef,\n 'two_step_cfg': two_step_cfg,\n }\n\n def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):\n \"\"\"Override the default progress callback.\"\"\"\n self._progress_callback = progress_callback\n\n def generate_unconditional(self, num_samples: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples in an unconditional manner.\n\n Args:\n num_samples (int): Number of samples to be generated.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n descriptions: tp.List[tp.Optional[str]] = [None] * num_samples\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate(self, descriptions: tp.List[str], progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_with_chroma(self, descriptions: tp.List[str], melody_wavs: MelodyType,\n melody_sample_rate: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=melody_wavs)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation(self, prompt: torch.Tensor, prompt_sample_rate: int,\n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, prompt)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_continuation_with_audio_token(self, prompt, \n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt, melody_wavs=melody_wavs)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_audio_chroma(self, prompt, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None, melody_wavs=melody_wavs)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_text_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_text_chroma(self, prompt, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_with_text_chroma(self, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n @torch.no_grad()\n def _prepare_tokens_and_attributes(\n self,\n descriptions: tp.Sequence[tp.Optional[str]],\n prompt: tp.Optional[torch.Tensor],\n melody_wavs: tp.Optional[tp.Union[MelodyList,tp.List[str]]] = None, bpm: tp.Optional[tp.Union[float,int,tp.List[float],tp.List[int]]] = None, meter:tp.Optional[tp.Union[int,tp.List[int]]] = None\n ) -> tp.Tuple[tp.List[ConditioningAttributes], tp.Optional[torch.Tensor]]:\n \"\"\"Prepare model inputs.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n melody_wavs (torch.Tensor, optional): A batch of waveforms\n used as melody conditioning. Defaults to None.\n \"\"\"\n attributes = [\n ConditioningAttributes(text={'description': description})\n for description in descriptions]\n\n if melody_wavs is None:\n for attr in attributes:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n else:\n if 'self_wav' not in self.lm.condition_provider.conditioners:\n raise RuntimeError(\"This model doesn't support melody conditioning. \"\n \"Use the `melody` model.\")\n assert len(melody_wavs) == len(descriptions), \\\n f\"number of melody wavs must match number of descriptions! \" \\\n f\"got melody len={len(melody_wavs)}, and descriptions len={len(descriptions)}\"\n\n if bpm is not None and (isinstance(bpm, int) or isinstance(bpm, float)):\n bpm = [bpm for i in range(len(melody_wavs))]\n elif bpm is not None and isinstance(bpm, tp.List):\n assert len(melody_wavs) == len(bpm)\n\n if meter is not None and (isinstance(meter, int) or isinstance(meter, float)):\n meter = [meter for i in range(len(melody_wavs))]\n elif meter is not None and isinstance(meter, tp.List):\n assert len(melody_wavs) == len(meter)\n\n for attr, melody, i in zip(attributes, melody_wavs, range(len(melody_wavs))):\n if melody is None:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n elif isinstance(melody, torch.Tensor):\n attr.wav['self_wav'] = WavCondition(\n melody[None].to(device=self.device),\n torch.tensor([melody.shape[-1]], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n )\n else :\n attr.wav['self_wav'] = WavChordTextCondition(\n [melody],\n torch.tensor([self.duration*self.sample_rate], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n bpm = [bpm[i]],\n meter = [meter[i]]\n )\n\n if prompt is not None:\n if descriptions is not None:\n assert len(descriptions) == len(prompt), \"Prompt and nb. descriptions doesn't match\"\n prompt = prompt.to(self.device)\n prompt_tokens, scale = self.compression_model.encode(prompt)\n assert scale is None\n else:\n prompt_tokens = None\n return attributes, prompt_tokens\n\n def _generate_tokens(self, attributes: tp.List[ConditioningAttributes],\n prompt_tokens: tp.Optional[torch.Tensor], progress: bool = False) -> torch.Tensor:\n \"\"\"Generate discrete audio tokens given audio prompt and/or conditions.\n\n Args:\n attributes (list of ConditioningAttributes): Conditions used for generation (text/melody).\n prompt_tokens (torch.Tensor, optional): Audio prompt used for continuation.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n Returns:\n torch.Tensor: Generated audio, of shape [B, C, T], T is defined by the generation params.\n \"\"\"\n total_gen_len = int(self.duration * self.frame_rate)\n max_prompt_len = int(min(self.duration, self.max_duration) * self.frame_rate)\n current_gen_offset: int = 0\n\n def _progress_callback(generated_tokens: int, tokens_to_generate: int):\n generated_tokens += current_gen_offset\n if self._progress_callback is not None:\n # Note that total_gen_len might be quite wrong depending on the\n # codebook pattern used, but with delay it is almost accurate.\n self._progress_callback(generated_tokens, total_gen_len)\n else:\n print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\\r')\n\n if prompt_tokens is not None:\n assert max_prompt_len >= prompt_tokens.shape[-1], \\\n \"Prompt is longer than audio to generate\"\n\n callback = None\n if progress:\n callback = _progress_callback\n\n if self.duration <= self.max_duration:\n # generate by sampling from LM, simple case.\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=total_gen_len, **self.generation_params)\n\n else:\n # now this gets a bit messier, we need to handle prompts,\n # melody conditioning etc.\n ref_wavs = [attr.wav['self_wav'] for attr in attributes]\n all_tokens = []\n if prompt_tokens is None:\n prompt_length = 0\n else:\n all_tokens.append(prompt_tokens)\n prompt_length = prompt_tokens.shape[-1]\n\n stride_tokens = int(self.frame_rate * self.extend_stride)\n step = 0\n\n while current_gen_offset + prompt_length < total_gen_len:\n self.lm.condition_provider.conditioners['self_wav'].set_continuation_count(self.extend_stride/self.max_duration, step) #For text based chord conditioning\n time_offset = current_gen_offset / self.frame_rate\n chunk_duration = min(self.duration - time_offset, self.max_duration)\n max_gen_len = int(chunk_duration * self.frame_rate)\n for attr, ref_wav in zip(attributes, ref_wavs):\n if isinstance(ref_wav, WavCondition):\n wav_length = ref_wav.length.item()\n if wav_length == 0:\n continue\n # We will extend the wav periodically if it not long enough.\n # we have to do it here rather than in conditioners.py as otherwise\n # we wouldn't have the full wav.\n initial_position = int(time_offset * self.sample_rate)\n wav_target_length = int(self.max_duration * self.sample_rate)\n positions = torch.arange(initial_position,\n initial_position + wav_target_length, device=self.device)\n attr.wav['self_wav'] = WavCondition(\n ref_wav[0][..., positions % wav_length],\n torch.full_like(ref_wav[1], wav_target_length),\n [self.sample_rate] * ref_wav[0].size(0),\n [None], [0.])\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=max_gen_len, **self.generation_params)\n if prompt_tokens is None:\n all_tokens.append(gen_tokens)\n else:\n all_tokens.append(gen_tokens[:, :, prompt_tokens.shape[-1]:])\n prompt_tokens = gen_tokens[:, :, stride_tokens:]\n prompt_length = prompt_tokens.shape[-1]\n current_gen_offset += stride_tokens\n step = step + 1\n\n gen_tokens = torch.cat(all_tokens, dim=-1)\n return gen_tokens\n\n def generate_audio(self, gen_tokens: torch.Tensor):\n \"\"\"Generate Audio from tokens\"\"\"\n assert gen_tokens.dim() == 3\n with torch.no_grad():\n gen_audio = self.compression_model.decode(gen_tokens, None)\n return gen_audio" }, { "identifier": "CompressionSolver", "path": "audiocraft/solvers/compression.py", "snippet": "class CompressionSolver(base.StandardSolver):\n \"\"\"Solver for compression task.\n\n The compression task combines a set of perceptual and objective losses\n to train an EncodecModel (composed of an encoder-decoder and a quantizer)\n to perform high fidelity audio reconstruction.\n \"\"\"\n def __init__(self, cfg: omegaconf.DictConfig):\n super().__init__(cfg)\n self.rng: torch.Generator # set at each epoch\n self.adv_losses = builders.get_adversarial_losses(self.cfg)\n self.aux_losses = nn.ModuleDict()\n self.info_losses = nn.ModuleDict()\n assert not cfg.fsdp.use, \"FSDP not supported by CompressionSolver.\"\n loss_weights = dict()\n for loss_name, weight in self.cfg.losses.items():\n if loss_name in ['adv', 'feat']:\n for adv_name, _ in self.adv_losses.items():\n loss_weights[f'{loss_name}_{adv_name}'] = weight\n elif weight > 0:\n self.aux_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n loss_weights[loss_name] = weight\n else:\n self.info_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n self.balancer = builders.get_balancer(loss_weights, self.cfg.balancer)\n self.register_stateful('adv_losses')\n\n @property\n def best_metric_name(self) -> tp.Optional[str]:\n # best model is the last for the compression model\n return None\n\n def build_model(self):\n \"\"\"Instantiate model and optimizer.\"\"\"\n # Model and optimizer\n self.model = models.builders.get_compression_model(self.cfg).to(self.device)\n self.optimizer = builders.get_optimizer(self.model.parameters(), self.cfg.optim)\n self.register_stateful('model', 'optimizer')\n self.register_best_state('model')\n self.register_ema('model')\n\n def build_dataloaders(self):\n \"\"\"Instantiate audio dataloaders for each stage.\"\"\"\n self.dataloaders = builders.get_audio_datasets(self.cfg)\n\n def show(self):\n \"\"\"Show the compression model and employed adversarial loss.\"\"\"\n self.logger.info(f\"Compression model with {self.model.quantizer.total_codebooks} codebooks:\")\n self.log_model_summary(self.model)\n self.logger.info(\"Adversarial loss:\")\n self.log_model_summary(self.adv_losses)\n self.logger.info(\"Auxiliary losses:\")\n self.logger.info(self.aux_losses)\n self.logger.info(\"Info losses:\")\n self.logger.info(self.info_losses)\n\n def run_step(self, idx: int, batch: torch.Tensor, metrics: dict):\n \"\"\"Perform one training or valid step on a given batch.\"\"\"\n x = batch.to(self.device)\n y = x.clone()\n\n qres = self.model(x)\n assert isinstance(qres, quantization.QuantizedResult)\n y_pred = qres.x\n # Log bandwidth in kb/s\n metrics['bandwidth'] = qres.bandwidth.mean()\n\n if self.is_training:\n d_losses: dict = {}\n if len(self.adv_losses) > 0 and torch.rand(1, generator=self.rng).item() <= 1 / self.cfg.adversarial.every:\n for adv_name, adversary in self.adv_losses.items():\n disc_loss = adversary.train_adv(y_pred, y)\n d_losses[f'd_{adv_name}'] = disc_loss\n metrics['d_loss'] = torch.sum(torch.stack(list(d_losses.values())))\n metrics.update(d_losses)\n\n balanced_losses: dict = {}\n other_losses: dict = {}\n\n # penalty from quantization\n if qres.penalty is not None and qres.penalty.requires_grad:\n other_losses['penalty'] = qres.penalty # penalty term from the quantizer\n\n # adversarial losses\n for adv_name, adversary in self.adv_losses.items():\n adv_loss, feat_loss = adversary(y_pred, y)\n balanced_losses[f'adv_{adv_name}'] = adv_loss\n balanced_losses[f'feat_{adv_name}'] = feat_loss\n\n # auxiliary losses\n for loss_name, criterion in self.aux_losses.items():\n loss = criterion(y_pred, y)\n balanced_losses[loss_name] = loss\n\n # weighted losses\n metrics.update(balanced_losses)\n metrics.update(other_losses)\n metrics.update(qres.metrics)\n\n if self.is_training:\n # backprop losses that are not handled by balancer\n other_loss = torch.tensor(0., device=self.device)\n if 'penalty' in other_losses:\n other_loss += other_losses['penalty']\n if other_loss.requires_grad:\n other_loss.backward(retain_graph=True)\n ratio1 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio1, torch.Tensor)\n metrics['ratio1'] = ratio1.sqrt()\n\n # balancer losses backward, returns effective training loss\n # with effective weights at the current batch.\n metrics['g_loss'] = self.balancer.backward(balanced_losses, y_pred)\n # add metrics corresponding to weight ratios\n metrics.update(self.balancer.metrics)\n ratio2 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio2, torch.Tensor)\n metrics['ratio2'] = ratio2.sqrt()\n\n # optim\n flashy.distrib.sync_model(self.model)\n if self.cfg.optim.max_norm:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.cfg.optim.max_norm\n )\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n # informative losses only\n info_losses: dict = {}\n with torch.no_grad():\n for loss_name, criterion in self.info_losses.items():\n loss = criterion(y_pred, y)\n info_losses[loss_name] = loss\n\n metrics.update(info_losses)\n\n # aggregated GAN losses: this is useful to report adv and feat across different adversarial loss setups\n adv_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('adv')]\n if len(adv_losses) > 0:\n metrics['adv'] = torch.sum(torch.stack(adv_losses))\n feat_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('feat')]\n if len(feat_losses) > 0:\n metrics['feat'] = torch.sum(torch.stack(feat_losses))\n\n return metrics\n\n def run_epoch(self):\n # reset random seed at the beginning of the epoch\n self.rng = torch.Generator()\n self.rng.manual_seed(1234 + self.epoch)\n # run epoch\n super().run_epoch()\n\n def evaluate(self):\n \"\"\"Evaluate stage. Runs audio reconstruction evaluation.\"\"\"\n self.model.eval()\n evaluate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['evaluate']\n updates = len(loader)\n lp = self.log_progress(f'{evaluate_stage_name} inference', loader, total=updates, updates=self.log_updates)\n average = flashy.averager()\n\n pendings = []\n ctx = multiprocessing.get_context('spawn')\n with get_pool_executor(self.cfg.evaluate.num_workers, mp_context=ctx) as pool:\n for idx, batch in enumerate(lp):\n x = batch.to(self.device)\n with torch.no_grad():\n qres = self.model(x)\n\n y_pred = qres.x.cpu()\n y = batch.cpu() # should already be on CPU but just in case\n pendings.append(pool.submit(evaluate_audio_reconstruction, y_pred, y, self.cfg))\n\n metrics_lp = self.log_progress(f'{evaluate_stage_name} metrics', pendings, updates=self.log_updates)\n for pending in metrics_lp:\n metrics = pending.result()\n metrics = average(metrics)\n\n metrics = flashy.distrib.average_metrics(metrics, len(loader))\n return metrics\n\n def generate(self):\n \"\"\"Generate stage.\"\"\"\n self.model.eval()\n sample_manager = SampleManager(self.xp, map_reference_to_sample_id=True)\n generate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['generate']\n updates = len(loader)\n lp = self.log_progress(generate_stage_name, loader, total=updates, updates=self.log_updates)\n\n for batch in lp:\n reference, _ = batch\n reference = reference.to(self.device)\n with torch.no_grad():\n qres = self.model(reference)\n assert isinstance(qres, quantization.QuantizedResult)\n\n reference = reference.cpu()\n estimate = qres.x.cpu()\n sample_manager.add_samples(estimate, self.epoch, ground_truth_wavs=reference)\n\n flashy.distrib.barrier()\n\n def load_from_pretrained(self, name: str) -> dict:\n model = models.CompressionModel.get_pretrained(name)\n if isinstance(model, models.DAC):\n raise RuntimeError(\"Cannot fine tune a DAC model.\")\n elif isinstance(model, models.HFEncodecCompressionModel):\n self.logger.warning('Trying to automatically convert a HuggingFace model '\n 'to AudioCraft, this might fail!')\n state = model.model.state_dict()\n new_state = {}\n for k, v in state.items():\n if k.startswith('decoder.layers') and '.conv.' in k and '.block.' not in k:\n # We need to determine if this a convtr or a regular conv.\n layer = int(k.split('.')[2])\n if isinstance(model.model.decoder.layers[layer].conv, torch.nn.ConvTranspose1d):\n\n k = k.replace('.conv.', '.convtr.')\n k = k.replace('encoder.layers.', 'encoder.model.')\n k = k.replace('decoder.layers.', 'decoder.model.')\n k = k.replace('conv.', 'conv.conv.')\n k = k.replace('convtr.', 'convtr.convtr.')\n k = k.replace('quantizer.layers.', 'quantizer.vq.layers.')\n k = k.replace('.codebook.', '._codebook.')\n new_state[k] = v\n state = new_state\n elif isinstance(model, models.EncodecModel):\n state = model.state_dict()\n else:\n raise RuntimeError(f\"Cannot fine tune model type {type(model)}.\")\n return {\n 'best_state': {'model': state}\n }\n\n @staticmethod\n def model_from_checkpoint(checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a CompressionModel from a given checkpoint path or dora sig.\n This method is a convenient endpoint to load a CompressionModel to use in other solvers.\n\n Args:\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n This also supports pre-trained models by using a path of the form //pretrained/NAME.\n See `model_from_pretrained` for a list of supported pretrained models.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n checkpoint_path = str(checkpoint_path)\n if checkpoint_path.startswith('//pretrained/'):\n name = checkpoint_path.split('/', 3)[-1]\n return models.CompressionModel.get_pretrained(name, device)\n logger = logging.getLogger(__name__)\n logger.info(f\"Loading compression model from checkpoint: {checkpoint_path}\")\n _checkpoint_path = checkpoint.resolve_checkpoint_path(checkpoint_path, use_fsdp=False)\n assert _checkpoint_path is not None, f\"Could not resolve compression model checkpoint path: {checkpoint_path}\"\n state = checkpoint.load_checkpoint(_checkpoint_path)\n assert state is not None and 'xp.cfg' in state, f\"Could not load compression model from ckpt: {checkpoint_path}\"\n cfg = state['xp.cfg']\n cfg.device = device\n compression_model = models.builders.get_compression_model(cfg).to(device)\n assert compression_model.sample_rate == cfg.sample_rate, \"Compression model sample rate should match\"\n\n assert 'best_state' in state and state['best_state'] != {}\n assert 'exported' not in state, \"When loading an exported checkpoint, use the //pretrained/ prefix.\"\n compression_model.load_state_dict(state['best_state']['model'])\n compression_model.eval()\n logger.info(\"Compression model loaded!\")\n return compression_model\n\n @staticmethod\n def wrapped_model_from_checkpoint(cfg: omegaconf.DictConfig,\n checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a wrapped CompressionModel from a given checkpoint path or dora sig.\n\n Args:\n cfg (omegaconf.DictConfig): Configuration to read from for wrapped mode.\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n compression_model = CompressionSolver.model_from_checkpoint(checkpoint_path, device)\n compression_model = models.builders.get_wrapped_compression_model(compression_model, cfg)\n return compression_model" }, { "identifier": "load_compression_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_compression_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_compression_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n if 'pretrained' in pkg:\n return CompressionModel.get_pretrained(pkg['pretrained'], device=device)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n model = builders.get_compression_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n return model" }, { "identifier": "load_lm_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_lm_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_lm_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n if cfg.device == 'cpu':\n cfg.dtype = 'float32'\n else:\n cfg.dtype = 'float16'\n _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path')\n _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path')\n _delete_param(cfg, 'conditioners.args.merge_text_conditions_p')\n _delete_param(cfg, 'conditioners.args.drop_desc_p')\n model = builders.get_lm_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n model.cfg = cfg\n return model" }, { "identifier": "audio_write", "path": "audiocraft/data/audio.py", "snippet": "def audio_write(stem_name: tp.Union[str, Path],\n wav: torch.Tensor, sample_rate: int,\n format: str = 'wav', mp3_rate: int = 320, ogg_rate: tp.Optional[int] = None,\n normalize: bool = True, strategy: str = 'peak', peak_clip_headroom_db: float = 1,\n rms_headroom_db: float = 18, loudness_headroom_db: float = 14,\n loudness_compressor: bool = False,\n log_clipping: bool = True, make_parent_dir: bool = True,\n add_suffix: bool = True) -> Path:\n \"\"\"Convenience function for saving audio to disk. Returns the filename the audio was written to.\n\n Args:\n stem_name (str or Path): Filename without extension which will be added automatically.\n wav (torch.Tensor): Audio data to save.\n sample_rate (int): Sample rate of audio data.\n format (str): Either \"wav\", \"mp3\", \"ogg\", or \"flac\".\n mp3_rate (int): kbps when using mp3s.\n ogg_rate (int): kbps when using ogg/vorbis. If not provided, let ffmpeg decide for itself.\n normalize (bool): if `True` (default), normalizes according to the prescribed\n strategy (see after). If `False`, the strategy is only used in case clipping\n would happen.\n strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak',\n i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square\n with extra headroom to avoid clipping. 'clip' just clips.\n peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy.\n rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger\n than the `peak_clip` one to avoid further clipping.\n loudness_headroom_db (float): Target loudness for loudness normalization.\n loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'.\n when strategy is 'loudness' log_clipping (bool): If True, basic logging on stderr when clipping still\n occurs despite strategy (only for 'rms').\n make_parent_dir (bool): Make parent directory if it doesn't exist.\n Returns:\n Path: Path of the saved audio.\n \"\"\"\n assert wav.dtype.is_floating_point, \"wav is not floating point\"\n if wav.dim() == 1:\n wav = wav[None]\n elif wav.dim() > 2:\n raise ValueError(\"Input wav should be at most 2 dimension.\")\n assert wav.isfinite().all()\n wav = normalize_audio(wav, normalize, strategy, peak_clip_headroom_db,\n rms_headroom_db, loudness_headroom_db, loudness_compressor,\n log_clipping=log_clipping, sample_rate=sample_rate,\n stem_name=str(stem_name))\n if format == 'mp3':\n suffix = '.mp3'\n flags = ['-f', 'mp3', '-c:a', 'libmp3lame', '-b:a', f'{mp3_rate}k']\n elif format == 'wav':\n suffix = '.wav'\n flags = ['-f', 'wav', '-c:a', 'pcm_s16le']\n elif format == 'ogg':\n suffix = '.ogg'\n flags = ['-f', 'ogg', '-c:a', 'libvorbis']\n if ogg_rate is not None:\n flags += ['-b:a', f'{ogg_rate}k']\n elif format == 'flac':\n suffix = '.flac'\n flags = ['-f', 'flac']\n else:\n raise RuntimeError(f\"Invalid format {format}. Only wav or mp3 are supported.\")\n if not add_suffix:\n suffix = ''\n path = Path(str(stem_name) + suffix)\n if make_parent_dir:\n path.parent.mkdir(exist_ok=True, parents=True)\n try:\n _piping_to_ffmpeg(path, wav, sample_rate, flags)\n except Exception:\n if path.exists():\n # we do not want to leave half written files around.\n path.unlink()\n raise\n return path" }, { "identifier": "get_lm_model", "path": "audiocraft/models/builders.py", "snippet": "def get_lm_model(cfg: omegaconf.DictConfig) -> LMModel:\n \"\"\"Instantiate a transformer LM.\"\"\"\n if cfg.lm_model == 'transformer_lm':\n kwargs = dict_from_config(getattr(cfg, 'transformer_lm'))\n n_q = kwargs['n_q']\n q_modeling = kwargs.pop('q_modeling', None)\n codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern')\n attribute_dropout = dict_from_config(getattr(cfg, 'attribute_dropout'))\n cls_free_guidance = dict_from_config(getattr(cfg, 'classifier_free_guidance'))\n cfg_prob, cfg_coef = cls_free_guidance['training_dropout'], cls_free_guidance['inference_coef']\n fuser = get_condition_fuser(cfg)\n condition_provider = get_conditioner_provider(kwargs[\"dim\"], cfg).to(cfg.device)\n if len(fuser.fuse2cond['cross']) > 0: # enforce cross-att programmatically\n kwargs['cross_attention'] = True\n if codebooks_pattern_cfg.modeling is None:\n assert q_modeling is not None, \\\n \"LM model should either have a codebook pattern defined or transformer_lm.q_modeling\"\n codebooks_pattern_cfg = omegaconf.OmegaConf.create(\n {'modeling': q_modeling, 'delay': {'delays': list(range(n_q))}}\n )\n pattern_provider = get_codebooks_pattern_provider(n_q, codebooks_pattern_cfg)\n return LMModel(\n pattern_provider=pattern_provider,\n condition_provider=condition_provider,\n fuser=fuser,\n cfg_dropout=cfg_prob,\n cfg_coef=cfg_coef,\n attribute_dropout=attribute_dropout,\n dtype=getattr(torch, cfg.dtype),\n device=cfg.device,\n **kwargs\n ).to(cfg.device)\n else:\n raise KeyError(f\"Unexpected LM model {cfg.lm_model}\")" } ]
import os import random import torchaudio import typing as tp import numpy as np import torch import librosa import subprocess import math import allin1 import pytsmod as tsm import shutil import shutil from typing import Optional from cog import BasePredictor, Input, Path from audiocraft.models import MusicGen, MultiBandDiffusion from audiocraft.solvers.compression import CompressionSolver from audiocraft.models.loaders import ( load_compression_model, load_lm_model, ) from audiocraft.data.audio import audio_write from audiocraft.models.builders import get_lm_model from omegaconf import OmegaConf from audiocraft.modules.btc.btc_model import BTC_model from audiocraft.modules.btc.utils.mir_eval_modules import idx2chord from demucs.audio import convert_audio from demucs.apply import apply_model
14,633
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p') lm = get_lm_model(loaded['xp.cfg']) lm.load_state_dict(loaded['model']) lm.eval() lm.cfg = cfg compression_model = CompressionSolver.model_from_checkpoint(cfg.compression_model_checkpoint, device=device)
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p') lm = get_lm_model(loaded['xp.cfg']) lm.load_state_dict(loaded['model']) lm.eval() lm.cfg = cfg compression_model = CompressionSolver.model_from_checkpoint(cfg.compression_model_checkpoint, device=device)
return MusicGen(f"{os.getenv('COG_USERNAME')}/musicgen-chord", compression_model, lm)
1
2023-10-09 09:55:24+00:00
24k
oracle/guardian-ai
tests/unitary/test_fairness_metrics.py
[ { "identifier": "ConsistencyScorer", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "class ConsistencyScorer(_SimpleDatasetFairnessScorer):\n \"\"\"\n Measures the consistency of a dataset.\n\n Consistency is measured as the number of ratio of instances that have a\n different label from the k=5 nearest neighbors.\n\n Perfect score\n A perfect score for this metric is 0, meaning that the dataset does\n not have different labels for instances that are similar to one another.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import ConsistencyScorer\n scorer = ConsistencyScorer(['race', 'sex'])\n scorer(X=X, y_true=y_true)\n scorer(None, X, y_true)\n \"\"\"\n\n def __init__(self, protected_attributes: Union[pd.Series, np.ndarray, List, str]):\n super().__init__(protected_attributes=protected_attributes, metric=consistency)" }, { "identifier": "DatasetStatisticalParityScorer", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "class DatasetStatisticalParityScorer(_DatasetFairnessScorer):\n \"\"\"\n Measures the statistical parity [1] of a dataset. Statistical parity (also\n known as Base Rate or Disparate Impact) for a dataset states that a dataset\n is unbiased if the label is independent of the protected attribute.\n\n For each subgroup, statistical parity is computed as the ratio of positive\n labels in a subgroup.\n\n Statistical Parity (also known as Base Rate or Disparate Impact) is\n calculated as PL / N, where PL and N are the number of Positive Labels and\n total number of instances, respectively.\n\n Perfect score\n A perfect score for this metric means that the dataset does not have\n a different ratio of positive labels for a subgroup than it does for\n the rest of the subgroups. For example, if the protected attributes\n are race and sex, then a perfect statistical parity would mean that\n all combinations of values for race and sex have identical ratios of\n positive labels. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n\n References\n ----------\n [1] `Cynthia Dwork et al. \"Fairness Through Awareness\". Innovations in\n Theoretical Computer Science. 2012. <https://arxiv.org/abs/1104.3913>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import DatasetStatisticalParityScorer\n scorer = DatasetStatisticalParityScorer(['race', 'sex'])\n scorer(X=X, y_true=y_true)\n scorer(None, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=dataset_statistical_parity,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "SmoothedEDFScorer", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "class SmoothedEDFScorer(_SimpleDatasetFairnessScorer):\n \"\"\"\n Measures the smoothed Empirical Differential Fairness (EDF) of a dataset, as\n proposed by Foulds et al. [1].\n\n Smoothed EDF returns the minimal exponential deviation of positive target\n ratios comparing a subgroup to the rest of the subgroups.\n\n This metric is related to :class:`.DatasetStatisticalParity` with\n `reduction='max'` and `distance_measure='ratio'`, with the only difference\n being that :class:`.SmoothedEDFScorer` returns a logarithmic value instead.\n\n Perfect score\n A perfect score for this metric is 0, meaning that the dataset does\n not have a different ratio of positive labels for a subgroup than\n it does for the rest of the subgroups. For example, if the\n protected attributes are race and sex, then a perfect smoothed EDF\n would mean that all combinations of values for race and sex have\n identical ratios of positive labels.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n\n References\n ----------\n [1] `Foulds, James R., et al. \"An intersectional definition of fairness.\"\n 2020 IEEE 36th International Conference on Data Engineering (ICDE).\n IEEE, 2020. <https://arxiv.org/abs/1807.08362>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import SmoothedEDFScorer\n scorer = SmoothedEDFScorer(['race', 'sex'])\n scorer(X=X, y_true=y_true)\n scorer(None, X, y_true)\n \"\"\"\n\n def __init__(self, protected_attributes: Union[pd.Series, np.ndarray, List, str]):\n super().__init__(protected_attributes=protected_attributes, metric=smoothed_edf)" }, { "identifier": "consistency", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "def consistency(y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame):\n \"\"\"\n Measures the consistency of a dataset.\n\n For more details, refer to :class:`.ConsistencyScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import consistency\n subgroups = X[['race', 'sex']]\n consistency(y_true, subgroups)\n \"\"\"\n # Need to read with [0] because consistency returns an array of size 1.\n return _simple_dataset_metric(y_true, subgroups, metric=\"consistency\")[0]" }, { "identifier": "dataset_statistical_parity", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "def dataset_statistical_parity(\n y_true: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: str = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the statistical parity of a dataset.\n\n For more details, refer to :class:`.DatasetStatisticalParityScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import dataset_statistical_parity\n subgroups = X[['race', 'sex']]\n dataset_statistical_parity(y_true, subgroups)\n \"\"\"\n return _dataset_metric(\n y_true,\n subgroups,\n metric=\"base_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "smoothed_edf", "path": "guardian_ai/fairness/metrics/dataset.py", "snippet": "def smoothed_edf(y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame):\n \"\"\"\n Measures the smoothed Empirical Differential Fairness (EDF) of a dataset, as\n proposed by Foulds et al. [1].\n\n For more details, refer to :class:`.SmoothedEDFScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n\n References\n ----------\n [1] `Foulds, James R., et al. \"An intersectional definition of fairness.\"\n 2020 IEEE 36th International Conference on Data Engineering (ICDE).\n IEEE, 2020. <https://arxiv.org/abs/1807.08362>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import smoothed_edf\n subgroups = X[['race', 'sex']]\n smoothed_edf(y_true, subgroups)\n \"\"\"\n return _simple_dataset_metric(\n y_true, subgroups, metric=\"smoothed_empirical_differential_fairness\"\n )" }, { "identifier": "EqualizedOddsScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class EqualizedOddsScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's true positive and false positive rates\n between subgroups and the rest of the subgroups.\n\n The disparity is measured by comparing the true positive and false positive\n rates on instances of a subgroup against the rest of the subgroups.\n\n True Positive Rate (also known as TPR, recall, or sensitivity) is\n calculated as TP / (TP + FN), where TP and FN are the number of true\n positives and false negatives, respectively.\n\n False Positive Rate (also known as FPR or fall-out) is calculated as\n FP / (FP + TN), where FP and TN are the number of false positives and\n true negatives, respectively.\n\n Equalized Odds [1] is computed by taking the maximum distance between\n TPR and FPR for a subgroup against the rest of the subgroups.\n\n Perfect score\n A perfect score for this metric means that the model has the same TPR and\n FPR when comparing a subgroup to the rest of the subgroups. For example,\n if the protected attributes are race and sex, then a perfect\n Equalized Odds disparity would mean that all combinations of values for\n race and sex have identical TPR and FPR. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Moritz Hardt et al. \"Equality of Opportunity in Supervised Learning\".\n Advances in Neural Information Processing Systems. 2016.\n <https://arxiv.org/pdf/1610.02413.pdf>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import EqualizedOddsScorer\n scorer = EqualizedOddsScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=equalized_odds,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "ErrorRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class ErrorRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's error rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the error rate on\n instances of a subgroup against the rest of the subgroups.\n\n Error Rate (also known as inaccuracy) is calculated as\n (FP + FN) / N, where FP and FN are the number of false positives and\n false negatives, respectively, while N is the total Number of\n instances.\n\n Perfect score\n A perfect score for this metric means that the model does not make more\n mistakes for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect error rate disparity would\n mean that all combinations of values for race and sex have identical\n error rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import ErrorRateScorer\n scorer = ErrorRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=error_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalseDiscoveryRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalseDiscoveryRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false discovery rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n discovery rate on instances of a subgroup against the rest of the\n subgroups.\n\n False Discovery Rate (also known as FDR) is calculated as\n FP / (FP + TP), where FP and TP are the number of false positives and\n true positives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not make more\n mistakes on the positive class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false discovery rate disparity\n would mean that all combinations of values for race and sex have identical\n false discovery rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalseDiscoveryRateScorer\n scorer = FalseDiscoveryRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_discovery_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalseNegativeRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalseNegativeRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false negative rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n negative rate on instances of a subgroup against the rest of the subgroups.\n\n False Negative Rate [1] (also known as FNR or miss rate) is calculated as\n FN / (FN + TP), where FN and TP are the number of false negatives and\n true positives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not incorrectly\n predict the negative class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false negative rate disparity\n would mean that all combinations of values for race and sex have identical\n false negative rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Alexandra Chouldechova. \"Fair Prediction with Disparate Impact: A Study\n of Bias in Recidivism Prediction Instruments\". Big Data (2016).\n <https://www.liebertpub.com/doi/10.1089/big.2016.0047>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalseNegativeRateScorer\n scorer = FalseNegativeRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_negative_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalseOmissionRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalseOmissionRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false omission rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n omission rate on instances of a subgroup against the rest of the subgroups.\n\n False Omission Rate (also known as FOR) is calculated as\n FN / (FN + TN), where FN and TN are the number of false negatives and\n true negatives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not make more\n mistakes on the negative class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false omission rate disparity\n would mean that all combinations of values for race and sex have identical\n false omission rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalseOmissionRateScorer\n scorer = FalseOmissionRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_omission_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "FalsePositiveRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class FalsePositiveRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's false positive rate between all subgroup pairs.\n\n For each subgroup, the disparity is measured by comparing the false\n positive rate on instances of a subgroup against the rest of the subgroups.\n\n False Positive Rate [1] (also known as FPR or fall-out) is calculated as\n FP / (FP + TN), where FP and TN are the number of false positives and\n true negatives, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not incorrectly\n predict the positive class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect false positive rate disparity\n would mean that all combinations of values for race and sex have identical\n false positive rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Alexandra Chouldechova. \"Fair Prediction with Disparate Impact: A Study\n of Bias in Recidivism Prediction Instruments\". Big Data (2016).\n <https://www.liebertpub.com/doi/10.1089/big.2016.0047>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import FalsePositiveRateScorer\n scorer = FalsePositiveRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=false_positive_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "ModelStatisticalParityScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class ModelStatisticalParityScorer(_ModelFairnessScorer): # noqa: D412\n \"\"\"\n Measure the statistical parity [1] of a model's output between all subgroup pairs.\n\n Statistical parity (also known as Base Rate or Disparate Impact) states that\n a predictor is unbiased if the prediction is independent of the protected\n attribute.\n\n Statistical Parity is calculated as PP / N, where PP and N are the number of\n Positive Predictions and total Number of predictions made, respectively.\n\n Perfect score\n A perfect score for this metric means that the model does not predict\n positively any of the subgroups at a different rate than it does for the\n rest of the subgroups. For example, if the protected attributes are race\n and sex, then a perfect statistical parity would mean that all combinations\n of values for race and sex have identical ratios of positive predictions.\n Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n\n References\n ----------\n [1] `Cynthia Dwork et al. \"Fairness Through Awareness\". Innovations in\n Theoretical Computer Science. 2012. <https://arxiv.org/abs/1104.3913>`_\n\n Examples\n --------\n\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import ModelStatisticalParityScorer\n\n scorer = ModelStatisticalParityScorer(['race', 'sex'])\n scorer(model, X, y_true)\n\n This metric does not require `y_true`. It can also be called using\n\n .. code-block:: python\n\n scorer(model, X)\n \"\"\" # noqa: D412\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=model_statistical_parity,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )\n\n def __call__(\n self,\n model: Any,\n X: pd.DataFrame,\n y_true: Optional[Union[pd.Series, np.ndarray, List]] = None,\n supplementary_features: Optional[pd.DataFrame] = None,\n ):\n \"\"\"\n Compute the metric using a model's predictions on a given array\n of instances ``X``.\n\n Parameters\n ----------\n model: Any\n Object that implements a `predict(X)` function to collect\n categorical predictions.\n X : pandas.DataFrame\n Array of instances to compute the metric on.\n y_true : pandas.Series, numpy.ndarray, list, or None, default=None\n Array of groundtruth labels.\n supplementary_features : pandas.DataFrame, or None, default=None\n Array of supplementary features for each instance. Used in case\n one attribute in ``self.protected_attributes`` is not contained by\n ``X`` (e.g. if the protected attribute is not used by the model).\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to ``self.reduction``.\n\n\n Raises\n ------\n GuardianAIValueError\n - if a feature is present in both ``X``\n and ``supplementary_features``.\n\n \"\"\"\n y_pred = model.predict(X)\n\n subgroups = self._get_check_subgroups(X, supplementary_features)\n\n return self.metric(\n y_true, y_pred, subgroups, self.distance_measure, self.reduction\n )" }, { "identifier": "TheilIndexScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class TheilIndexScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's predictions according to groundtruth\n labels, as proposed by Speicher et al. [1].\n\n Intuitively, the Theil Index can be thought of as a measure of the\n divergence between a subgroup's different error distributions (i.e. false\n positives and false negatives) against the rest of the subgroups.\n\n Perfect score\n The perfect score for this metric is 0, meaning that the model does not\n have a different error distribution for any subgroup when compared to the\n rest of the subgroups. For example, if the protected attributes are\n race and sex, then a perfect Theil Index disparity would mean that all\n combinations of values for race and sex have identical error\n distributions.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str or None, default=None\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Speicher, Till, et al. \"A unified approach to quantifying algorithmic\n unfairness: Measuring individual & group unfairness via inequality indices.\"\n Proceedings of the 24th ACM SIGKDD international conference on knowledge\n discovery & data mining. 2018. <https://arxiv.org/abs/1807.00787>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import TheilIndexScorer\n scorer = TheilIndexScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: Optional[str] = None,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=theil_index,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=True,\n )" }, { "identifier": "TruePositiveRateScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class TruePositiveRateScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's true positive rate between\n all subgroup pairs (also known as equal opportunity).\n\n For each subgroup, the disparity is measured by comparing the true positive\n rate on instances of a subgroup against the rest of the subgroups.\n\n True Positive Rate [1] (also known as TPR, recall, or sensitivity) is\n calculated as TP / (TP + FN), where TP and FN are the number of true\n positives and false negatives, respectively.\n\n\n Perfect score\n A perfect score for this metric means that the model does not correctly\n predict the positive class for any of the subgroups more often than it\n does for the rest of the subgroups. For example, if the protected\n attributes are race and sex, then a perfect true positive rate disparity\n would mean that all combinations of values for race and sex have\n identical true positive rates. Perfect values are:\n\n - 1 if using ``'ratio'`` as ``distance_measure``.\n - 0 if using ``'diff'`` as ``distance_measure``.\n\n Parameters\n ----------\n protected_attributes: pandas.Series, numpy.ndarray, list, str\n Array of attributes or single attribute that should be treated as\n protected. If an attribute is protected, then all of its unique\n values are considered as subgroups.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n References\n ----------\n [1] `Moritz Hardt et al. \"Equality of Opportunity in Supervised Learning\".\n Advances in Neural Information Processing Systems. 2016.\n <https://arxiv.org/pdf/1610.02413.pdf>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import TruePositiveRateScorer\n scorer = TruePositiveRateScorer(['race', 'sex'])\n scorer(model, X, y_true)\n \"\"\"\n\n def __init__(\n self,\n protected_attributes: Union[pd.Series, np.ndarray, List, str],\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n ):\n super().__init__(\n protected_attributes=protected_attributes,\n metric=true_positive_rate,\n distance_measure=distance_measure,\n reduction=reduction,\n allow_distance_measure_none=False,\n )" }, { "identifier": "equalized_odds", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def equalized_odds(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's true positive and false positive rates\n between subgroups and the rest of the subgroups.\n\n For more details, refer to :class:`.EqualizedOddsScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import equalized_odds\n subgroups = X[['race', 'sex']]\n equalized_odds(y_true, y_pred, subgroups)\n \"\"\"\n tpr = true_positive_rate(\n y_true,\n y_pred,\n subgroups,\n distance_measure=distance_measure,\n reduction=reduction,\n )\n\n fpr = false_positive_rate(\n y_true,\n y_pred,\n subgroups,\n distance_measure=distance_measure,\n reduction=reduction,\n )\n if isinstance(tpr, dict):\n eq_odds = {}\n for key in tpr:\n eq_odds[key] = np.nanmax([tpr[key], fpr[key]])\n else:\n eq_odds = np.nanmax([tpr, fpr])\n\n return eq_odds" }, { "identifier": "error_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def error_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's error rate between all subgroup pairs.\n\n For more details, refer to :class:`.ErrorRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import error_rate\n subgroups = X[['race', 'sex']]\n error_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"error_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_discovery_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_discovery_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false discovery rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalseDiscoveryRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_discovery_rate\n subgroups = X[['race', 'sex']]\n false_discovery_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_discovery_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_negative_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_negative_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false negative rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalseNegativeRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_negative_rate\n subgroups = X[['race', 'sex']]\n false_negative_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_negative_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_omission_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_omission_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false omission rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalseOmissionRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_omission_rate\n subgroups = X[['race', 'sex']]\n false_omission_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_omission_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "false_positive_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def false_positive_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's false positive rate between all subgroup pairs.\n\n For more details, refer to :class:`.FalsePositiveRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import false_positive_rate\n subgroups = X[['race', 'sex']]\n false_positive_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"false_positive_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "model_statistical_parity", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def model_statistical_parity(\n y_true: Optional[Union[pd.Series, np.ndarray, List]] = None,\n y_pred: Optional[Union[pd.Series, np.ndarray, List]] = None,\n subgroups: Optional[pd.DataFrame] = None,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measure the statistical parity of a model's output between all subgroup pairs.\n\n For more details, refer to :class:`.ModelStatisticalParityScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list or None, default=None\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list or None, default=None\n Array of model predictions.\n subgroups : pandas.DataFrame or None, default=None\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n Raises\n ------\n GuardianAIValueError\n If Value of None is received for either `y_pred` or `subgroups`.\n\n Examples\n --------\n\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import model_statistical_parity\n subgroups = X[['race', 'sex']]\n model_statistical_parity(y_true, y_pred, subgroups)\n\n This metric does not require `y_true`. It can also be called using\n\n .. code-block:: python\n\n model_statistical_parity(None, y_pred, subgroups)\n model_statistical_parity(y_pred=y_pred, subgroups=subgroups)\n \"\"\" # noqa: D412\n\n if y_pred is None or subgroups is None:\n raise GuardianAIValueError(\n \"Value of None was received for either `y_pred` or `subgroups`. \"\n \"This may be due to calling the metric using only 2 positional \"\n \"arguments. If this is the case, either call the function by \"\n \"passing ``None`` as the first argument or use named arguments for \"\n \"`y_pred` and `subgroups`.\"\n )\n\n return _model_metric(\n None,\n y_pred,\n subgroups,\n metric=\"selection_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=True,\n allow_distance_measure_none=False,\n )" }, { "identifier": "theil_index", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def theil_index(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: Optional[str] = None,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's predictions according to groundtruth\n labels, as proposed by Speicher et al. [1].\n\n For more details, refer to :class:`.TheilIndexScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str or None, default=None\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n Raises\n ------\n GuardianAIValueError\n If distance_measure values are given to Theil Index.\n\n References\n ----------\n [1]: `Speicher, Till, et al. \"A unified approach to quantifying algorithmic\n unfairness: Measuring individual & group unfairness via inequality indices.\"\n Proceedings of the 24th ACM SIGKDD international conference on knowledge\n discovery & data mining. 2018. <https://arxiv.org/abs/1807.00787>`_\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import theil_index\n subgroups = X[['race', 'sex']]\n theil_index(y_true, y_pred, subgroups)\n \"\"\"\n\n if distance_measure is not None and not isinstance(\n distance_measure, _DistanceMetric\n ):\n raise GuardianAIValueError(\n \"Theil Index does not accept distance_measure values. It should\"\n \"always be set to ``None``.\"\n )\n\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"between_group_theil_index\",\n distance_measure=None,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=True,\n )" }, { "identifier": "true_positive_rate", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "def true_positive_rate(\n y_true: Union[pd.Series, np.ndarray, List],\n y_pred: Union[pd.Series, np.ndarray, List],\n subgroups: pd.DataFrame,\n distance_measure: str = DEFAULT_DISTANCE,\n reduction: Optional[str] = DEFAULT_REDUCTION,\n):\n \"\"\"\n Measures the disparity of a model's true positive rate between all subgroup pairs.\n\n For more details, refer to :class:`.TruePositiveRateScorer`.\n\n Parameters\n ----------\n y_true : pandas.Series, numpy.ndarray, list\n Array of groundtruth labels.\n y_pred : pandas.Series, numpy.ndarray, list\n Array of model predictions.\n subgroups : pandas.DataFrame\n Dataframe containing protected attributes for each instance.\n distance_measure : str, default='diff'\n Determines the distance used to compare a subgroup's metric against\n the rest of the subgroups. Possible values are:\n\n * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed.\n * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``.\n reduction : str or None, default='mean'\n Determines how to reduce scores on all subgroups to a single output.\n Possible values are:\n\n * ``'max'``: Returns the maximal value among all subgroup metrics.\n * ``'mean'``: Returns the mean over all subgroup metrics.\n * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict.\n\n Returns\n -------\n float, dict\n The computed metric value, with format according to `reduction`.\n\n\n Examples\n --------\n .. code-block:: python\n\n from guardian_ai.fairness.metrics import true_positive_rate\n subgroups = X[['race', 'sex']]\n true_positive_rate(y_true, y_pred, subgroups)\n \"\"\"\n return _model_metric(\n y_true,\n y_pred,\n subgroups,\n metric=\"true_positive_rate\",\n distance_measure=distance_measure,\n reduction=reduction,\n allow_y_true_none=False,\n allow_distance_measure_none=False,\n )" }, { "identifier": "GuardianAITypeError", "path": "guardian_ai/utils/exception.py", "snippet": "class GuardianAITypeError(TypeError, GuardianAIError):\n \"\"\"Exception raised for generic type issues.\"\"\"\n\n pass" }, { "identifier": "GuardianAIValueError", "path": "guardian_ai/utils/exception.py", "snippet": "class GuardianAIValueError(ValueError, GuardianAIError):\n \"\"\"Exception raised for unexpected values.\"\"\"\n\n pass" }, { "identifier": "get_dummy_dataset", "path": "tests/utils.py", "snippet": "def get_dummy_dataset(\n n_samples=5000,\n n_features=10,\n n_classes=2,\n types=[str, float, bool, int],\n content=[],\n contain_null=False,\n null_ratio=0.3,\n dtime_types=[],\n tz_aware=False,\n reg_range=10.0,\n cat_range=30,\n random_seed=9999,\n imb_factor=1.0,\n task=\"classification\",\n **kwargs,\n):\n \"\"\"\n Generates a dummy dataset and returns its corresponding ope/oml\n dataframe:\n dataset shape n_samples x n_features.\n\n types: column types you wish to generate (random number of columns=\n n_features types are generated, with at least one of each type).\n\n content: list of tuples (dtype, feature) specifying bad column\n features. Features can be 'const' - to make all values in column\n constant, or value between 0 and 1 which indicates percentage of\n missing values in a column\n\n dtime_types: datetime column types to generate. Acceptable types\n are: ['datetime', 'date', 'time', 'timedelta', 'datetimetz']\n\n n_classes: number of target classes (only used for classification)\n\n reg_range: range of target for regression datasets, not used for\n classification\n\n cat_range: maximum number of unique values for the categorical\n features\n\n imb_factor: ~ class_ratio = minority_class_size/majority_class_size\n approximately controls dataset target imbalance\n (only used for classification).\n\n \"\"\"\n np.random.seed(random_seed)\n allowed_dtime_types = [\n \"datetime\",\n \"date\",\n \"time\",\n \"timedelta\",\n \"datetimez\",\n \"Timestamp\",\n ]\n\n # sanity checks\n assert (\n n_samples >= n_classes\n ), \"Number of samples has to be greater than num of classes\"\n assert (imb_factor > 0) and (\n imb_factor <= 1.0\n ), \"imb_factor has to be in range of (0, 1.0]\"\n assert len(types) == len(set(types)), \"types inside the list must be unique\"\n assert len(dtime_types) == len(\n set(dtime_types)\n ), \"dtime_types inside the list must be unique\"\n assert (\n len(dtime_types) + len(types) <= n_features\n ), \"provided number of feature types is more than n_features\"\n assert task in [\n \"classification\",\n \"regression\",\n \"anomaly_detection\",\n ], \"Task must be one of classification or regression\"\n assert all(\n x for x in dtime_types if x in allowed_dtime_types\n ), \"dtime_types: {} outside of allowed: {}\".format(dtime_types, allowed_dtime_types)\n\n extra_types, extra_feats, extra_cols = [], [], 0\n if content != []:\n extra_cols = len(content)\n extra_types = [x for x, _ in content]\n extra_feats = [x for _, x in content]\n\n # target labels for the dataset\n if task == \"classification\" or task == \"anomaly_detection\":\n # assign class counts based on geometric distribution of classes based on imb_factor\n class_weights = np.geomspace(imb_factor, 1.0, num=n_classes)\n class_counts = [\n max(1, int(n_samples * x / np.sum(class_weights))) for x in class_weights\n ]\n class_excess = np.sum(class_counts) - n_samples\n class_counts[-1] -= class_excess\n\n # create labels based on class counts and shuffle them\n y = np.hstack(\n [np.full((1, count), cl) for cl, count in enumerate(class_counts)]\n ).ravel()\n np.random.shuffle(y.astype(int))\n y = y.tolist()\n elif task == \"regression\":\n # noise between (-reg_range/2, reg_range/2) for regression\n y = reg_range * np.random.random(size=(1, n_samples, 1)) + reg_range / 2.0\n y = y.reshape(1, n_samples).ravel().tolist()\n\n # tally total number of features\n all_feat_types = types + dtime_types + extra_types\n total_feat_types = len(types) + len(dtime_types)\n if total_feat_types > 0:\n feat_col_types = np.random.choice(\n range(0, total_feat_types), size=n_features - total_feat_types\n ).tolist()\n feat_col_types += list(\n range(0, total_feat_types)\n ) # to ensure at least one of each type\n\n else:\n feat_col_types = []\n feat_col_types += list(range(total_feat_types, total_feat_types + len(extra_types)))\n features = []\n col_types = []\n tz = {}\n # extra_features provided in content, and certain datetime columns are handled differently\n # they get added as pandas Series or DataFrames to rest of features in the end\n special_cols_num, special_pd_df = [], []\n extra_features = pd.DataFrame()\n for i, t in enumerate(feat_col_types):\n assert t < total_feat_types + len(extra_types)\n typ = all_feat_types[t]\n if typ is str:\n high_val = np.random.randint(3, cat_range)\n feat = np.random.randint(0, high_val, size=n_samples).tolist()\n feat = [\"STR{}\".format(val) for val in feat]\n elif typ is int:\n low_val = np.random.randint(-50000, -10)\n high_val = np.random.randint(10, 50000)\n feat = np.random.randint(low_val, high_val, size=n_samples).tolist()\n elif typ is float:\n feat = np.random.rand(n_samples).tolist()\n elif typ is bool:\n feat = np.random.randint(0, 2, size=n_samples).tolist()\n feat = [bool(val) for val in feat]\n elif typ in allowed_dtime_types:\n if typ == \"datetime\":\n # generating random datetime\n deltas = random.sample(range(1, 172800000), n_samples)\n d1 = datetime.datetime.now() - datetime.timedelta(days=2000)\n d2 = datetime.datetime.now()\n generated_datetime = []\n for d in deltas:\n generated_datetime.append(d1 + datetime.timedelta(seconds=d))\n feat = generated_datetime\n elif typ == \"timedelta\":\n feat = n_samples * [datetime.timedelta()]\n elif typ == \"time\":\n feat = n_samples * [datetime.time()]\n elif typ == \"date\":\n feat = n_samples * [datetime.date(2019, 9, 11)]\n elif typ == \"datetimez\":\n special_cols_num.append(i)\n special_pd_df.append(\n pd.date_range(start=0, periods=n_samples, tz=\"UTC\")\n )\n feat = n_samples * [\n datetime.date(2019, 9, 11)\n ] # needs to be handled in special way b/c it's already pandas obj\n else:\n raise Exception(\"Unrecognized datetime type of column\")\n else:\n raise Exception(\"Unrecognized type of column\")\n\n # If index reached the last extra_col number of feature types, start modifying features\n # and adding them to extra_features DataFrame instead of list of features\n if extra_cols > 0 and i >= (len(feat_col_types) - extra_cols):\n feat_idx = i - (len(feat_col_types) - extra_cols)\n if isinstance(extra_feats[feat_idx], numbers.Number):\n # missing values given by extra_feats[feat_idx] percentage of instances\n assert (\n extra_feats[feat_idx] <= 1.0 and extra_feats[feat_idx] >= 0\n ), \"feature in content has to be ratio between 0 and 1\"\n ids = np.random.choice(\n range(0, n_samples), size=int(extra_feats[feat_idx] * n_samples)\n ).astype(int)\n dtype = map_col_types([extra_types[feat_idx].__name__])[0]\n feat = pd.Series(data=np.array(feat), dtype=dtype)\n feat[ids] = np.nan\n elif extra_feats[feat_idx] == \"const\":\n # constant column, set all rows to be same as the first instance\n dtype = map_col_types([extra_types[feat_idx].__name__])[0]\n feat = pd.Series(data=np.array(feat), dtype=dtype)\n feat = feat[0]\n extra_features[i] = feat\n else: # add features to the list\n features.append(feat)\n col_types.append(type(feat[0]).__name__)\n\n # if task == 'regression':\n # # Add scaled target column for regression so that score is positive\n # features.append([-0.5*x for x in y])\n # col_types.append('float') # target column type is int\n\n # Add target column and convert all types to pandas dtypes\n features.append(y)\n col_types.append(\n \"int\" if task == \"classification\" else \"float\"\n ) # target column type is int\n pd_col_types = map_col_types(col_types)\n pd_df = pd.DataFrame(features).T # transpose to get samples x features\n num_feats = len(features) - 1\n columns = list(range(0, num_feats)) if num_feats > 0 else []\n columns = columns + [\"target\"]\n pd_df.columns = columns # rename columns\n\n # handle special column from datettime: replace placeholder with pandas.date_range columns\n for i, col in enumerate(special_cols_num):\n pd_df[col] = special_pd_df[i]\n pd_col_types[col] = pd_df.dtypes[col]\n\n # assign datatypes to pd dataframe for non-datetime types\n columns_types_all = list(zip(columns, pd_col_types))\n columns_types_nodtime = [\n (name, typ)\n for (name, typ) in columns_types_all\n if typ not in allowed_dtime_types\n ]\n columns_types_dtime = [\n (name, typ) for (name, typ) in columns_types_all if typ in allowed_dtime_types\n ]\n pd_df = pd_df.astype(dict(columns_types_nodtime)) # cast types on non-dtime columns\n\n # assign datatypes to pd dataframe only for datetime types\n for col, col_type in columns_types_dtime:\n if col_type == \"timedelta\":\n pd_df[col] = pd.to_timedelta(pd_df[col], errors=\"coerce\")\n elif col_type == \"datetimez\":\n pd_df[col] = pd_df[col]\n elif col_type == \"datetime\":\n pd_df[col] = pd.to_datetime(pd_df[col], errors=\"coerce\")\n if contain_null:\n pd_df[col] = generate_null(pd_df[col], null_ratio)\n if tz_aware:\n tz[str(col)] = pytz.all_timezones[\n np.random.randint(len(pytz.all_timezones))\n ]\n else:\n pd_df[col] = pd.to_timedelta(pd_df[col], errors=\"coerce\")\n\n # add extra features columns that were provided by content\n pd_df[pd_df.shape[1] + extra_features.columns] = extra_features\n\n # Convert all the column names to string type (mainly for FS min_features [] tests)\n pd_df.columns = [str(col) for col in pd_df.columns]\n\n if tz_aware:\n return pd_df.drop([\"target\"], axis=1), pd_df[\"target\"], tz\n else:\n return pd_df.drop([\"target\"], axis=1), pd_df[\"target\"]" } ]
import math import numpy as np import pandas as pd import pytest import sklearn from sklearn.pipeline import Pipeline from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import OneHotEncoder from guardian_ai.fairness.metrics.dataset import ( ConsistencyScorer, DatasetStatisticalParityScorer, SmoothedEDFScorer, consistency, dataset_statistical_parity, smoothed_edf, ) from guardian_ai.fairness.metrics.model import ( EqualizedOddsScorer, ErrorRateScorer, FalseDiscoveryRateScorer, FalseNegativeRateScorer, FalseOmissionRateScorer, FalsePositiveRateScorer, ModelStatisticalParityScorer, TheilIndexScorer, TruePositiveRateScorer, equalized_odds, error_rate, false_discovery_rate, false_negative_rate, false_omission_rate, false_positive_rate, model_statistical_parity, theil_index, true_positive_rate, ) from guardian_ai.utils.exception import GuardianAITypeError, GuardianAIValueError from tests.utils import get_dummy_dataset
18,492
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2023 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ @pytest.fixture(scope="module", autouse=True) def init(): np.random.seed(12345) def is_close(a, b): return math.isclose(a, b, rel_tol=1e-5) def approx_dict(d): return pytest.approx(d, rel=1e-5) MODEL_X_Y_SCORERS = { "model_statistical_parity_scorer": ModelStatisticalParityScorer, "true_positive_rate_scorer": TruePositiveRateScorer, "false_positive_rate_scorer": FalsePositiveRateScorer, "false_negative_rate_scorer": FalseNegativeRateScorer, "false_omission_rate_scorer": FalseOmissionRateScorer, "false_discovery_rate_scorer": FalseDiscoveryRateScorer, "error_rate_scorer": ErrorRateScorer, "equalized_odds_scorer": EqualizedOddsScorer, "theil_index_scorer": TheilIndexScorer, } MODEL_SUBGROUPS_SCORERS = { "model_statistical_parity_scorer": model_statistical_parity,
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2023 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ @pytest.fixture(scope="module", autouse=True) def init(): np.random.seed(12345) def is_close(a, b): return math.isclose(a, b, rel_tol=1e-5) def approx_dict(d): return pytest.approx(d, rel=1e-5) MODEL_X_Y_SCORERS = { "model_statistical_parity_scorer": ModelStatisticalParityScorer, "true_positive_rate_scorer": TruePositiveRateScorer, "false_positive_rate_scorer": FalsePositiveRateScorer, "false_negative_rate_scorer": FalseNegativeRateScorer, "false_omission_rate_scorer": FalseOmissionRateScorer, "false_discovery_rate_scorer": FalseDiscoveryRateScorer, "error_rate_scorer": ErrorRateScorer, "equalized_odds_scorer": EqualizedOddsScorer, "theil_index_scorer": TheilIndexScorer, } MODEL_SUBGROUPS_SCORERS = { "model_statistical_parity_scorer": model_statistical_parity,
"true_positive_rate_scorer": true_positive_rate,
23
2023-10-09 09:48:50+00:00
24k
jiangjiechen/auction-arena
app.py
[ { "identifier": "create_items", "path": "src/item_base.py", "snippet": "def create_items(item_info_jsl):\n '''\n item_info: a list of dict (name, price, desc, id)\n '''\n item_info_jsl = LoadJsonL(item_info_jsl)\n item_list = []\n for info in item_info_jsl:\n item_list.append(Item(**info))\n return item_list" }, { "identifier": "Bidder", "path": "src/bidder_base.py", "snippet": "class Bidder(BaseModel):\n name: str\n model_name: str \n budget: int \n desire: str\n plan_strategy: str\n temperature: float = 0.7\n overestimate_percent: int = 10\n correct_belief: bool\n enable_learning: bool = False\n \n llm: BaseLanguageModel = None\n openai_cost = 0\n llm_token_count = 0\n \n verbose: bool = False\n auction_hash: str = ''\n\n system_message: str = ''\n original_budget: int = 0\n\n # working memory\n profit: int = 0\n cur_item_id = 0\n items: list = []\n dialogue_history: list = [] # for gradio UI display\n llm_prompt_history: list = [] # for tracking llm calling\n items_won = []\n bid_history: list = [] # history of the bidding of a single item\n plan_instruct: str = '' # instruction for planning\n cur_plan: str = '' # current plan\n status_quo: dict = {} # belief of budget and profit, self and others\n withdraw: bool = False # state of withdraw\n learnings: str = '' # learnings from previous biddings. If given, then use it to guide the rest of the auction.\n max_bid_cnt: int = 4 # Rule Bidder: maximum number of bids on one item (K = 1 starting bid + K-1 increase bid)\n rule_bid_cnt: int = 0 # Rule Bidder: count of bids on one item\n\n # belief tracking\n failed_bid_cnt: int = 0 # count of failed bids (overspending)\n total_bid_cnt: int = 0 # count of total bids\n self_belief_error_cnt: int = 0\n total_self_belief_cnt: int = 0\n other_belief_error_cnt: int = 0\n total_other_belief_cnt: int = 0\n \n engagement_count: int = 0\n budget_history = []\n profit_history = []\n budget_error_history = []\n profit_error_history = []\n win_bid_error_history = []\n engagement_history = defaultdict(int)\n all_bidders_status = {} # track others' profit\n changes_of_plan = []\n \n # not used\n input_box: str = None\n need_input = False\n semaphore = 0\n\n class Config:\n arbitrary_types_allowed = True\n\n def __repr__(self):\n return self.name\n\n def __str__(self):\n return self.name\n \n @classmethod\n def create(cls, **data):\n instance = cls(**data)\n instance._post_init()\n return instance\n\n def _post_init(self):\n self.original_budget = self.budget\n self.system_message = SYSTEM_MESSAGE.format(\n name=self.name,\n desire_desc=DESIRE_DESC[self.desire],\n )\n self._parse_llm()\n self.dialogue_history += [\n SystemMessage(content=self.system_message), \n AIMessage(content='')\n ]\n self.budget_history.append(self.budget)\n self.profit_history.append(self.profit)\n\n def _parse_llm(self):\n if 'gpt-' in self.model_name:\n self.llm = ChatOpenAI(model=self.model_name, temperature=self.temperature, max_retries=30, request_timeout=1200)\n elif 'claude' in self.model_name:\n self.llm = ChatAnthropic(model=self.model_name, temperature=self.temperature, default_request_timeout=1200)\n elif 'bison' in self.model_name:\n self.llm = ChatGooglePalm(model_name=f'models/{self.model_name}', temperature=self.temperature)\n elif 'rule' in self.model_name or 'human' in self.model_name:\n self.llm = None\n else:\n raise NotImplementedError(self.model_name)\n \n # def _rotate_openai_org(self):\n # # use two organizations to avoid rate limit\n # if os.environ.get('OPENAI_ORGANIZATION_1') and os.environ.get('OPENAI_ORGANIZATION_2'):\n # return random.choice([os.environ.get('OPENAI_ORGANIZATION_1'), os.environ.get('OPENAI_ORGANIZATION_2')])\n # else:\n # return None\n \n def _run_llm_standalone(self, messages: list):\n \n with get_openai_callback() as cb:\n for i in range(6):\n try:\n input_token_num = self.llm.get_num_tokens_from_messages(messages)\n if 'claude' in self.model_name: # anthropic's claude\n result = self.llm(messages, max_tokens_to_sample=2048)\n elif 'bison' in self.model_name: # google's palm-2\n max_tokens = min(max(3900 - input_token_num, 192), 2048)\n if isinstance(self.llm, ChatVertexAI):\n result = self.llm(messages, max_output_tokens=max_tokens)\n else:\n result = self.llm(messages)\n elif 'gpt' in self.model_name: # openai\n if 'gpt-3.5-turbo' in self.model_name and '16k' not in self.model_name:\n max_tokens = max(3900 - input_token_num, 192)\n else:\n # gpt-4\n # self.llm.openai_organization = self._rotate_openai_org()\n max_tokens = max(8000 - input_token_num, 192)\n result = self.llm(messages, max_tokens=max_tokens)\n elif 'llama' in self.model_name.lower():\n raise NotImplementedError\n else:\n raise NotImplementedError\n break\n except:\n print(f'Retrying for {self.model_name} ({i+1}/6), wait for {2**(i+1)} sec...')\n time.sleep(2**(i+1))\n self.openai_cost += cb.total_cost\n self.llm_token_count = self.llm.get_num_tokens_from_messages(messages)\n return result.content\n\n def _get_estimated_value(self, item):\n value = item.true_value * (1 + self.overestimate_percent / 100)\n return int(value)\n \n def _get_cur_item(self, key=None):\n if self.cur_item_id < len(self.items):\n if key is not None:\n return self.items[self.cur_item_id].__dict__[key]\n else:\n return self.items[self.cur_item_id]\n else:\n return 'no item left'\n \n def _get_next_item(self, key=None):\n if self.cur_item_id + 1 < len(self.items):\n if key is not None:\n return self.items[self.cur_item_id + 1].__dict__[key]\n else:\n return self.items[self.cur_item_id + 1]\n else:\n return 'no item left'\n \n def _get_remaining_items(self, as_str=False):\n remain_items = self.items[self.cur_item_id + 1:]\n if as_str:\n return ', '.join([item.name for item in remain_items])\n else:\n return remain_items\n \n def _get_items_value_str(self, items: List[Item]):\n if not isinstance(items, list):\n items = [items]\n items_info = ''\n for i, item in enumerate(items):\n estimated_value = self._get_estimated_value(item)\n _info = f\"{i+1}. {item}, starting price is ${item.price}. Your estimated value for this item is ${estimated_value}.\\n\"\n items_info += _info\n return items_info.strip()\n \n # ********** Main Instructions and Functions ********** #\n \n def learn_from_prev_auction(self, past_learnings, past_auction_log):\n if not self.enable_learning or 'rule' in self.model_name or 'human' in self.model_name:\n return ''\n \n instruct_learn = INSTRUCT_LEARNING_TEMPLATE.format(\n past_auction_log=past_auction_log,\n past_learnings=past_learnings)\n\n result = self._run_llm_standalone([HumanMessage(content=instruct_learn)])\n self.dialogue_history += [\n HumanMessage(content=instruct_learn),\n AIMessage(content=result),\n ]\n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in [HumanMessage(content=instruct_learn)]],\n 'result': result,\n 'tag': 'learn_0'\n })\n \n self.learnings = '\\n'.join(extract_numbered_list(result))\n if self.learnings != '':\n self.system_message += f\"\\n\\nHere are your key learning points and practical tips from a previous auction. You can use them to guide this auction:\\n```\\n{self.learnings}\\n```\"\n \n if self.verbose:\n print(f\"Learn from previous auction: {self.name} ({self.model_name}).\")\n return result\n\n def _choose_items(self, budget, items: List[Item]):\n '''\n Choose items within budget for rule bidders.\n Cheap ones first if maximize_items, expensive ones first if maximize_profit.\n '''\n sorted_items = sorted(items, key=lambda x: self._get_estimated_value(x), \n reverse=self.desire == 'maximize_profit')\n \n chosen_items = []\n i = 0\n while budget >= 0 and i < len(sorted_items):\n item = sorted_items[i]\n if item.price <= budget:\n chosen_items.append(item)\n budget -= item.price\n i += 1\n \n return chosen_items\n \n def get_plan_instruct(self, items: List[Item]):\n self.items = items\n plan_instruct = INSTRUCT_PLAN_TEMPLATE.format(\n bidder_name=self.name, \n budget=self.budget, \n item_num=len(items), \n items_info=self._get_items_value_str(items), \n desire_desc=DESIRE_DESC[self.desire],\n learning_statement='' if not self.enable_learning else _LEARNING_STATEMENT\n )\n return plan_instruct\n \n def init_plan(self, plan_instruct: str):\n '''\n Plan for bidding with auctioneer's instruction and items information for customize estimated value.\n plan = plan(system_message, instruct_plan)\n '''\n if 'rule' in self.model_name: \n # self.cur_plan = ', '.join([x.name for x in self._choose_items(self.budget, self.items)])\n # self.dialogue_history += [\n # HumanMessage(content=plan_instruct),\n # AIMessage(content=self.cur_plan),\n # ]\n # return self.cur_plan\n return ''\n\n self.status_quo = {\n 'remaining_budget': self.budget,\n 'total_profits': {bidder: 0 for bidder in self.all_bidders_status.keys()},\n 'winning_bids': {bidder: {} for bidder in self.all_bidders_status.keys()},\n }\n\n if self.plan_strategy == 'none':\n self.plan_instruct = ''\n self.cur_plan = ''\n return None\n\n system_msg = SystemMessage(content=self.system_message)\n plan_msg = HumanMessage(content=plan_instruct)\n messages = [system_msg, plan_msg]\n result = self._run_llm_standalone(messages)\n \n if self.verbose:\n print(get_colored_text(plan_msg.content, 'red'))\n print(get_colored_text(result, 'green'))\n \n self.dialogue_history += [\n plan_msg,\n AIMessage(content=result),\n ]\n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': result,\n 'tag': 'plan_0'\n })\n self.cur_plan = result\n self.plan_instruct = plan_instruct\n \n self.changes_of_plan.append([\n f\"{self.cur_item_id} (Initial)\", \n False, \n json.dumps(extract_jsons_from_text(result)[-1]),\n ])\n \n if self.verbose:\n print(f\"Plan: {self.name} ({self.model_name}) for {self._get_cur_item()}.\")\n return result\n \n def get_rebid_instruct(self, auctioneer_msg: str):\n self.dialogue_history += [\n HumanMessage(content=auctioneer_msg),\n AIMessage(content='')\n ]\n return auctioneer_msg\n\n def get_bid_instruct(self, auctioneer_msg: str, bid_round: int):\n auctioneer_msg = auctioneer_msg.replace(self.name, f'You ({self.name})')\n \n bid_instruct = INSTRUCT_BID_TEMPLATE.format(\n auctioneer_msg=auctioneer_msg, \n bidder_name=self.name,\n cur_item=self._get_cur_item(),\n estimated_value=self._get_estimated_value(self._get_cur_item()),\n desire_desc=DESIRE_DESC[self.desire],\n learning_statement='' if not self.enable_learning else _LEARNING_STATEMENT\n )\n if bid_round == 0:\n if self.plan_strategy in ['static', 'none']:\n # if static planner, then no replanning is needed. status quo is updated in replanning. thus need to add status quo in bid instruct.\n bid_instruct = f\"\"\"The status quo of this auction so far is:\\n\"{json.dumps(self.status_quo, indent=4)}\"\\n\\n{bid_instruct}\\n---\\n\"\"\"\n else:\n bid_instruct = f'Now, the auctioneer says: \"{auctioneer_msg}\"'\n \n self.dialogue_history += [\n HumanMessage(content=bid_instruct),\n AIMessage(content='')\n ]\n return bid_instruct\n \n def bid_rule(self, cur_bid: int, min_markup_pct: float = 0.1):\n '''\n :param cur_bid: current highest bid\n :param min_markup_pct: minimum percentage for bid increase\n :param max_bid_cnt: maximum number of bids on one item (K = 1 starting bid + K-1 increase bid)\n '''\n # dialogue history already got bid_instruction.\n cur_item = self._get_cur_item()\n \n if cur_bid <= 0:\n next_bid = cur_item.price\n else:\n next_bid = cur_bid + min_markup_pct * cur_item.price\n \n if self.budget - next_bid >= 0 and self.rule_bid_cnt < self.max_bid_cnt:\n msg = int(next_bid)\n self.rule_bid_cnt += 1\n else:\n msg = -1\n \n content = f'The current highest bid for {cur_item.name} is ${cur_bid}. '\n content += \"I'm out!\" if msg < 0 else f\"I bid ${msg}! (Rule generated)\"\n self.dialogue_history += [\n HumanMessage(content=''),\n AIMessage(content=content)\n ]\n \n return msg\n \n def bid(self, bid_instruct):\n '''\n Bid for an item with auctioneer's instruction and bidding history.\n bid_history = bid(system_message, instruct_plan, plan, bid_history)\n '''\n if self.model_name == 'rule':\n return ''\n \n bid_msg = HumanMessage(content=bid_instruct)\n \n if self.plan_strategy == 'none':\n messages = [SystemMessage(content=self.system_message)]\n else:\n messages = [SystemMessage(content=self.system_message),\n HumanMessage(content=self.plan_instruct),\n AIMessage(content=self.cur_plan)]\n \n self.bid_history += [bid_msg]\n messages += self.bid_history\n \n result = self._run_llm_standalone(messages)\n \n self.bid_history += [AIMessage(content=result)]\n\n self.dialogue_history += [\n HumanMessage(content=''),\n AIMessage(content=result)\n ]\n \n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': result,\n 'tag': f'bid_{self.cur_item_id}'\n })\n \n if self.verbose:\n print(get_colored_text(bid_instruct, 'yellow'))\n print(get_colored_text(result, 'green'))\n \n print(f\"Bid: {self.name} ({self.model_name}) for {self._get_cur_item()}.\")\n self.total_bid_cnt += 1\n \n return result\n\n def get_summarize_instruct(self, bidding_history: str, hammer_msg: str, win_lose_msg: str):\n instruct = INSTRUCT_SUMMARIZE_TEMPLATE.format(\n cur_item=self._get_cur_item(), \n bidding_history=bidding_history, \n hammer_msg=hammer_msg.strip(), \n win_lose_msg=win_lose_msg.strip(), \n bidder_name=self.name,\n prev_status=self._status_json_to_text(self.status_quo),\n )\n return instruct\n\n def summarize(self, instruct_summarize: str):\n '''\n Update belief/status quo\n status_quo = summarize(system_message, bid_history, prev_status + instruct_summarize)\n '''\n self.budget_history.append(self.budget)\n self.profit_history.append(self.profit)\n \n if self.model_name == 'rule': \n self.rule_bid_cnt = 0 # reset bid count for rule bidder\n return ''\n \n messages = [SystemMessage(content=self.system_message)]\n # messages += self.bid_history\n summ_msg = HumanMessage(content=instruct_summarize)\n messages.append(summ_msg)\n\n status_quo_text = self._run_llm_standalone(messages)\n \n self.dialogue_history += [summ_msg, AIMessage(content=status_quo_text)]\n self.bid_history += [summ_msg, AIMessage(content=status_quo_text)]\n \n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': status_quo_text,\n 'tag': f'summarize_{self.cur_item_id}'\n })\n\n cnt = 0\n while cnt <= 3:\n sanity_msg = self._sanity_check_status_json(extract_jsons_from_text(status_quo_text)[-1])\n if sanity_msg == '':\n # pass sanity check then track beliefs\n consistency_msg = self._belief_tracking(status_quo_text)\n else:\n sanity_msg = f'- {sanity_msg}'\n consistency_msg = ''\n \n if sanity_msg != '' or (consistency_msg != '' and self.correct_belief):\n err_msg = f\"As {self.name}, here are some error(s) of your summary of the status JSON:\\n{sanity_msg.strip()}\\n{consistency_msg.strip()}\\n\\nPlease revise the status JSON based on the errors. Don't apologize. Just give me the revised status JSON.\".strip()\n \n # print(f\"{self.name}: revising status quo for the {cnt} time:\")\n # print(get_colored_text(err_msg, 'green'))\n # print(get_colored_text(status_quo_text, 'red'))\n \n messages += [AIMessage(content=status_quo_text), \n HumanMessage(content=err_msg)]\n status_quo_text = self._run_llm_standalone(messages)\n self.dialogue_history += [\n HumanMessage(content=err_msg),\n AIMessage(content=status_quo_text),\n ]\n cnt += 1\n else:\n break\n \n self.status_quo = extract_jsons_from_text(status_quo_text)[-1]\n\n if self.verbose:\n print(get_colored_text(instruct_summarize, 'blue'))\n print(get_colored_text(status_quo_text, 'green'))\n \n print(f\"Summarize: {self.name} ({self.model_name}) for {self._get_cur_item()}.\")\n \n return status_quo_text\n \n def get_replan_instruct(self):\n instruct = INSTRUCT_REPLAN_TEMPLATE.format(\n status_quo=self._status_json_to_text(self.status_quo),\n remaining_items_info=self._get_items_value_str(self._get_remaining_items()),\n bidder_name=self.name,\n desire_desc=DESIRE_DESC[self.desire],\n learning_statement='' if not self.enable_learning else _LEARNING_STATEMENT\n )\n return instruct\n\n def replan(self, instruct_replan: str):\n '''\n plan = replan(system_message, instruct_plan, prev_plan, status_quo + (learning) + instruct_replan)\n '''\n if self.model_name == 'rule': \n self.withdraw = False\n self.cur_item_id += 1\n return ''\n \n if self.plan_strategy in ['none', 'static']:\n self.bid_history = [] # clear bid history\n self.cur_item_id += 1\n self.withdraw = False\n return 'Skip replanning for bidders with static or no plan.'\n \n replan_msg = HumanMessage(content=instruct_replan)\n \n messages = [SystemMessage(content=self.system_message),\n HumanMessage(content=self.plan_instruct),\n AIMessage(content=self.cur_plan)]\n messages.append(replan_msg)\n\n result = self._run_llm_standalone(messages)\n \n new_plan_dict = extract_jsons_from_text(result)[-1]\n cnt = 0\n while len(new_plan_dict) == 0 and cnt < 2:\n err_msg = 'Your response does not contain a JSON-format priority list for items. Please revise your plan.'\n messages += [\n AIMessage(content=result),\n HumanMessage(content=err_msg),\n ]\n result = self._run_llm_standalone(messages)\n new_plan_dict = extract_jsons_from_text(result)[-1]\n \n self.dialogue_history += [\n HumanMessage(content=err_msg),\n AIMessage(content=result),\n ]\n cnt += 1\n \n old_plan_dict = extract_jsons_from_text(self.cur_plan)[-1]\n self.changes_of_plan.append([\n f\"{self.cur_item_id + 1} ({self._get_cur_item('name')})\", \n self._change_of_plan(old_plan_dict, new_plan_dict),\n json.dumps(new_plan_dict)\n ])\n \n self.plan_instruct = instruct_replan\n self.cur_plan = result\n self.withdraw = False\n self.bid_history = [] # clear bid history\n self.cur_item_id += 1\n\n self.dialogue_history += [\n replan_msg,\n AIMessage(content=result),\n ]\n self.llm_prompt_history.append({\n 'messages': [{x.type: x.content} for x in messages],\n 'result': result,\n 'tag': f'plan_{self.cur_item_id}'\n })\n \n if self.verbose:\n print(get_colored_text(instruct_replan, 'blue'))\n print(get_colored_text(result, 'green'))\n\n print(f\"Replan: {self.name} ({self.model_name}).\")\n return result\n \n def _change_of_plan(self, old_plan: dict, new_plan: dict):\n for k in new_plan:\n if new_plan[k] != old_plan.get(k, None):\n return True\n return False\n \n # *********** Belief Tracking and Sanity Check *********** #\n \n def bid_sanity_check(self, bid_price, prev_round_max_bid, min_markup_pct):\n # can't bid more than budget or less than previous highest bid\n if bid_price < 0:\n msg = None\n else:\n min_bid_increase = int(min_markup_pct * self._get_cur_item('price'))\n if bid_price > self.budget:\n msg = f\"you don't have insufficient budget (${self.budget} left)\"\n elif bid_price < self._get_cur_item('price'):\n msg = f\"your bid is lower than the starting bid (${self._get_cur_item('price')})\"\n elif bid_price < prev_round_max_bid + min_bid_increase:\n msg = f\"you must advance previous highest bid (${prev_round_max_bid}) by at least ${min_bid_increase} ({int(100 * min_markup_pct)}%).\"\n else:\n msg = None\n return msg\n\n def rebid_for_failure(self, fail_instruct: str):\n result = self.bid(fail_instruct)\n self.failed_bid_cnt += 1\n return result\n \n def _sanity_check_status_json(self, data: dict):\n if data == {}:\n return \"Error: No parsible JSON in your response. Possibly due to missing a closing curly bracket '}', or unpasible values (e.g., 'profit': 1000 + 400, instead of 'profit': 1400).\"\n\n # Check if all expected top-level keys are present\n expected_keys = [\"remaining_budget\", \"total_profits\", \"winning_bids\"]\n for key in expected_keys:\n if key not in data:\n return f\"Error: Missing '{key}' field in the status JSON.\"\n\n # Check if \"remaining_budget\" is a number\n if not isinstance(data[\"remaining_budget\"], (int, float)):\n return \"Error: 'remaining_budget' should be a number, and only about your remaining budget.\"\n\n # Check if \"total_profits\" is a dictionary with numbers as values\n if not isinstance(data[\"total_profits\"], dict):\n return \"Error: 'total_profits' should be a dictionary of every bidder.\"\n for bidder, profit in data[\"total_profits\"].items():\n if not isinstance(profit, (int, float)):\n return f\"Error: Profit for {bidder} should be a number.\"\n\n # Check if \"winning_bids\" is a dictionary and that each bidder's entry is a dictionary with numbers\n if not isinstance(data[\"winning_bids\"], dict):\n return \"Error: 'winning_bids' should be a dictionary.\"\n for bidder, bids in data[\"winning_bids\"].items():\n if not isinstance(bids, dict):\n return f\"Error: Bids for {bidder} should be a dictionary.\"\n for item, amount in bids.items():\n if not isinstance(amount, (int, float)):\n return f\"Error: Amount for {item} under {bidder} should be a number.\"\n\n # If everything is fine\n return \"\"\n \n def _status_json_to_text(self, data: dict):\n if 'rule' in self.model_name: return ''\n \n # Extract and format remaining budget\n structured_text = f\"* Remaining Budget: ${data.get('remaining_budget', 'unknown')}\\n\\n\"\n \n # Extract and format total profits for each bidder\n structured_text += \"* Total Profits:\\n\"\n if data.get('total_profits'):\n for bidder, profit in data['total_profits'].items():\n structured_text += f\" * {bidder}: ${profit}\\n\"\n \n # Extract and list the winning bids for each item by each bidder\n structured_text += \"\\n* Winning Bids:\\n\"\n if data.get('winning_bids'):\n for bidder, bids in data['winning_bids'].items():\n structured_text += f\" * {bidder}:\\n\"\n if bids:\n for item, amount in bids.items():\n structured_text += f\" * {item}: ${amount}\\n\"\n else:\n structured_text += f\" * No winning bids\\n\"\n \n return structured_text.strip()\n\n def _belief_tracking(self, status_text: str):\n '''\n Parse status quo and check if the belief is correct.\n '''\n belief_json = extract_jsons_from_text(status_text)[-1]\n # {\"remaining_budget\": 8000, \"total_profits\": {\"Bidder 1\": 1300, \"Bidder 2\": 1800, \"Bidder 3\": 0}, \"winning_bids\": {\"Bidder 1\": {\"Item 2\": 1200, \"Item 3\": 1000}, \"Bidder 2\": {\"Item 1\": 2000}, \"Bidder 3\": {}}}\n budget_belief = belief_json['remaining_budget']\n profits_belief = belief_json['total_profits']\n winning_bids = belief_json['winning_bids']\n\n msg = ''\n # track belief of budget\n self.total_self_belief_cnt += 1\n if budget_belief != self.budget:\n msg += f'- Your belief of budget is wrong: you have ${self.budget} left, but you think you have ${budget_belief} left.\\n'\n self.self_belief_error_cnt += 1\n self.budget_error_history.append([\n self._get_cur_item('name'),\n budget_belief,\n self.budget,\n ])\n \n # track belief of profits\n for bidder_name, profit in profits_belief.items():\n if self.all_bidders_status.get(bidder_name) is None:\n # due to a potentially unreasonable parsing\n continue\n \n if self.name in bidder_name: \n bidder_name = self.name\n self.total_self_belief_cnt += 1\n else:\n self.total_other_belief_cnt += 1\n \n real_profit = self.all_bidders_status[bidder_name]['profit']\n \n if profit != real_profit:\n if self.name == bidder_name:\n self.self_belief_error_cnt += 1\n else:\n self.other_belief_error_cnt += 1\n\n msg += f'- Your belief of total profit of {bidder_name} is wrong: {bidder_name} has earned ${real_profit} so far, but you think {bidder_name} has earned ${profit}.\\n'\n\n # add to history\n self.profit_error_history.append([\n f\"{bidder_name} ({self._get_cur_item('name')})\",\n profit,\n real_profit\n ])\n\n # track belief of winning bids\n for bidder_name, items_won_dict in winning_bids.items():\n if self.all_bidders_status.get(bidder_name) is None:\n # due to a potentially unreasonable parsing\n continue\n\n real_items_won = self.all_bidders_status[bidder_name]['items_won']\n # items_won = [(item, bid_price), ...)]\n \n items_won_list = list(items_won_dict.keys())\n real_items_won_list = [str(x) for x, _ in real_items_won]\n \n if self.name in bidder_name:\n self.total_self_belief_cnt += 1\n else:\n self.total_other_belief_cnt += 1\n \n if not item_list_equal(items_won_list, real_items_won_list):\n if bidder_name == self.name:\n self.self_belief_error_cnt += 1\n _bidder_name = f'you'\n else:\n self.other_belief_error_cnt += 1\n _bidder_name = bidder_name\n \n msg += f\"- Your belief of winning items of {bidder_name} is wrong: {bidder_name} won {real_items_won}, but you think {bidder_name} won {items_won_dict}.\\n\"\n\n self.win_bid_error_history.append([\n f\"{_bidder_name} ({self._get_cur_item('name')})\",\n ', '.join(items_won_list),\n ', '.join(real_items_won_list)\n ])\n \n return msg\n \n def win_bid(self, item: Item, bid: int):\n self.budget -= bid\n self.profit += item.true_value - bid\n self.items_won += [[item, bid]]\n msg = f\"Congratuations! You won {item} at ${bid}.\"# Now you have ${self.budget} left. Your total profit so far is ${self.profit}.\"\n return msg\n \n def lose_bid(self, item: Item):\n return f\"You lost {item}.\"# Now, you have ${self.budget} left. Your total profit so far is ${self.profit}.\"\n \n # set the profit information of other bidders\n def set_all_bidders_status(self, all_bidders_status: dict):\n self.all_bidders_status = all_bidders_status.copy()\n\n def set_withdraw(self, bid: int):\n if bid < 0: # withdraw\n self.withdraw = True\n elif bid == 0: # enable discount and bid again\n self.withdraw = False\n else: # normal bid\n self.withdraw = False\n self.engagement_count += 1\n self.engagement_history[self._get_cur_item('name')] += 1\n \n # ****************** Logging ****************** #\n \n # def _parse_hedging(self, plan: str): # deprecated\n # prompt = PARSE_HEDGE_INSTRUCTION.format(\n # item_name=self._get_cur_item(), \n # plan=plan)\n \n # with get_openai_callback() as cb:\n # llm = ChatOpenAI(model='gpt-3.5-turbo-0613', temperature=0)\n # result = llm([HumanMessage(content=prompt)]).content\n # self.openai_cost += cb.total_cost\n # # parse a number, which could be a digit\n # hedge_percent = re.findall(r'\\d+\\.?\\d*%', result)\n # if len(hedge_percent) > 0:\n # hedge_percent = hedge_percent[0].replace('%', '')\n # else:\n # hedge_percent = 0\n # return float(hedge_percent)\n \n def profit_report(self):\n '''\n Personal profit report at the end of an auction.\n '''\n msg = f\"* {self.name}, starting with ${self.original_budget}, has won {len(self.items_won)} items in this auction, with a total profit of ${self.profit}.:\\n\"\n profit = 0\n for item, bid in self.items_won:\n profit += item.true_value - bid\n msg += f\" * Won {item} at ${bid} over ${item.price}, with a true value of ${item.true_value}.\\n\"\n return msg.strip()\n \n def to_monitors(self, as_json=False):\n # budget, profit, items_won, tokens\n if len(self.items_won) == 0 and not as_json: \n items_won = [['', 0, 0]]\n else:\n items_won = []\n for item, bid in self.items_won:\n items_won.append([str(item), bid, item.true_value])\n \n profit_error_history = self.profit_error_history if self.profit_error_history != [] or as_json else [['', '', '']]\n win_bid_error_history = self.win_bid_error_history if self.win_bid_error_history != [] or as_json else [['', '', '']]\n budget_error_history = self.budget_error_history if self.budget_error_history != [] or as_json else [['', '']]\n changes_of_plan = self.changes_of_plan if self.changes_of_plan != [] or as_json else [['', '', '']]\n \n if as_json:\n return {\n 'auction_hash': self.auction_hash,\n 'bidder_name': self.name,\n 'model_name': self.model_name,\n 'desire': self.desire,\n 'plan_strategy': self.plan_strategy,\n 'overestimate_percent': self.overestimate_percent,\n 'temperature': self.temperature,\n 'correct_belief': self.correct_belief,\n 'enable_learning': self.enable_learning,\n 'budget': self.original_budget,\n 'money_left': self.budget,\n 'profit': self.profit,\n 'items_won': items_won,\n 'tokens_used': self.llm_token_count,\n 'openai_cost': round(self.openai_cost, 2),\n 'failed_bid_cnt': self.failed_bid_cnt,\n 'self_belief_error_cnt': self.self_belief_error_cnt,\n 'other_belief_error_cnt': self.other_belief_error_cnt,\n 'failed_bid_rate': round(self.failed_bid_cnt / (self.total_bid_cnt+1e-8), 2),\n 'self_error_rate': round(self.self_belief_error_cnt / (self.total_self_belief_cnt+1e-8), 2),\n 'other_error_rate': round(self.other_belief_error_cnt / (self.total_other_belief_cnt+1e-8), 2),\n 'engagement_count': self.engagement_count,\n 'engagement_history': self.engagement_history,\n 'changes_of_plan': changes_of_plan,\n 'budget_error_history': budget_error_history,\n 'profit_error_history': profit_error_history,\n 'win_bid_error_history': win_bid_error_history,\n 'history': self.llm_prompt_history\n }\n else:\n return [\n self.budget, \n self.profit, \n items_won, \n self.llm_token_count, \n round(self.openai_cost, 2), \n round(self.failed_bid_cnt / (self.total_bid_cnt+1e-8), 2), \n round(self.self_belief_error_cnt / (self.total_self_belief_cnt+1e-8), 2), \n round(self.other_belief_error_cnt / (self.total_other_belief_cnt+1e-8), 2), \n self.engagement_count,\n draw_plot(f\"{self.name} ({self.model_name})\", self.budget_history, self.profit_history), \n changes_of_plan,\n budget_error_history,\n profit_error_history, \n win_bid_error_history\n ]\n\n def dialogue_to_chatbot(self):\n # chatbot: [[Human, AI], [], ...]\n # only dialogue will be sent to LLMs. chatbot is just for display.\n assert len(self.dialogue_history) % 2 == 0\n chatbot = []\n for i in range(0, len(self.dialogue_history), 2):\n # if exceeds the length of dialogue, append the last message\n human_msg = self.dialogue_history[i].content\n ai_msg = self.dialogue_history[i+1].content\n if ai_msg == '': ai_msg = None\n if human_msg == '': human_msg = None\n chatbot.append([human_msg, ai_msg])\n return chatbot" }, { "identifier": "HumanBidder", "path": "src/human_bidder.py", "snippet": "class HumanBidder(Bidder):\n name: str\n human_name: str = \"Adam\"\n budget: int\n auction_hash: str\n \n cur_item_id = 0\n items: list = []\n withdraw: bool = False\n \n engagement_count: int = 0\n original_budget: int = 0\n profit: int = 0\n items_won = []\n \n all_bidders_status = {} # track others' profit\n \n # essential for demo\n need_input: bool = False\n semaphore: int = 0 # if needs input, then semaphore is set as 1, else waits.\n input_box: str = None # global variable for accepting user input\n \n # not used\n model_name: str = 'human'\n openai_cost = 0\n desire = ''\n plan_strategy = ''\n correct_belief = True\n \n class Config:\n arbitrary_types_allowed = True\n \n def get_plan_instruct(self, items: List[Item]):\n self.items = items\n plan_instruct = \"As {bidder_name}, you have a total budget of ${budget}. This auction has a total of {item_num} items to be sequentially presented, they are:\\n{items_info}\".format(\n bidder_name=self.name, \n budget=self.budget, \n item_num=len(items), \n items_info=self._get_items_value_str(items)\n )\n return plan_instruct\n \n def init_plan(self, plan_instruct: str):\n # Human = auctioneer, AI = bidder\n self.dialogue_history += [\n HumanMessage(content=plan_instruct),\n AIMessage(content='(Getting ready...)')\n ]\n return ''\n \n def get_bid_instruct(self, auctioneer_msg, bid_round):\n self.dialogue_history += [\n HumanMessage(content=auctioneer_msg), \n AIMessage(content='')\n ]\n return auctioneer_msg\n \n def bid(self, bid_instruct):\n # wait for the cue to handle user input\n while self.semaphore <= 0:\n time.sleep(1)\n \n self.dialogue_history += [\n HumanMessage(content=''),\n AIMessage(content=self.input_box)\n ]\n self.semaphore -= 1\n self.need_input = False\n return self.input_box\n \n def get_summarize_instruct(self, bidding_history: str, hammer_msg: str, win_lose_msg: str):\n instruct_summarize = f\"{bidding_history}\\n\\n{hammer_msg}\\n{win_lose_msg}\"\n return instruct_summarize\n \n def summarize(self, instruct_summarize: str):\n self.dialogue_history += [\n HumanMessage(content=instruct_summarize),\n AIMessage(content='(Taking notes...)')\n ]\n self.budget_history.append(self.budget)\n self.profit_history.append(self.profit)\n return ''\n \n def get_replan_instruct(self):\n return ''\n\n def replan(self, instruct_replan):\n self.withdraw = False\n self.cur_item_id += 1\n return ''\n \n def to_monitors(self, as_json=False):\n items_won = []\n for item, bid in self.items_won:\n items_won.append([str(item), bid, item.true_value])\n if as_json:\n return {\n 'auction_hash': self.auction_hash,\n 'bidder_name': self.name,\n 'human_name': self.human_name,\n 'model_name': self.model_name,\n 'budget': self.original_budget,\n 'money_left': self.budget,\n 'profit': self.profit,\n 'items_won': items_won,\n 'engagement_count': self.engagement_count,\n }\n else:\n return [\n self.budget, \n self.profit, \n items_won, \n 0, \n 0, \n round(self.failed_bid_cnt / (self.total_bid_cnt+1e-8), 2), \n 0, \n 0, \n self.engagement_count,\n draw_plot(f\"{self.name} ({self.model_name})\", self.budget_history, self.profit_history), \n [],\n [],\n [], \n []\n ]" }, { "identifier": "Auctioneer", "path": "src/auctioneer_base.py", "snippet": "class Auctioneer(BaseModel):\n enable_discount: bool = False\n items: List[Item] = []\n cur_item: Item = None\n highest_bidder: Bidder = None\n highest_bid: int = -1\n bidding_history = defaultdict(list) # history about the bidding war of one item\n items_queue: List[Item] = [] # updates when a item is taken.\n auction_logs = defaultdict(list) # history about the bidding war of all items\n openai_cost = 0\n prev_round_max_bid: int = -1\n min_bid: int = 0\n fail_to_sell = False\n min_markup_pct = 0.1\n\n class Config:\n arbitrary_types_allowed = True\n \n def init_items(self, items: List[Item]):\n for item in items:\n # reset discounted price\n item.reset_price()\n self.items = items\n self.items_queue = items.copy()\n\n def summarize_items_info(self):\n desc = ''\n for item in self.items:\n desc += f\"- {item.get_desc()}\\n\"\n return desc.strip()\n \n def present_item(self):\n cur_item = self.items_queue.pop(0)\n self.cur_item = cur_item\n return cur_item\n \n def shuffle_items(self):\n random.shuffle(self.items)\n self.items_queue = self.items.copy()\n \n def record_bid(self, bid_info: dict, bid_round: int):\n '''\n Save the bidding history for each round, log the highest bidder and highest bidding\n '''\n # bid_info: {'bidder': xxx, 'bid': xxx, 'raw_msg': xxx}\n self.bidding_history[bid_round].append(bid_info)\n for hist in self.bidding_history[bid_round]:\n if hist['bid'] > 0:\n if self.highest_bid < hist['bid']:\n self.highest_bid = hist['bid']\n self.highest_bidder = hist['bidder']\n elif self.highest_bid == hist['bid']:\n # random if there's a tie\n self.highest_bidder = random.choice([self.highest_bidder, hist['bidder']])\n self.auction_logs[f\"{self.cur_item.get_desc()}\"].append(\n {'bidder': bid_info['bidder'], \n 'bid': bid_info['bid'], \n 'bid_round': bid_round})\n\n def _biddings_to_string(self, bid_round: int):\n '''\n Return a string that summarizes the bidding history in a round\n '''\n # bid_hist_text = '' if bid_round == 0 else f'- {self.highest_bidder}: ${self.highest_bid}\\n'\n bid_hist_text = ''\n for js in self.bidding_history[bid_round]:\n if js['bid'] < 0:\n bid_hist_text += f\"- {js['bidder']} withdrew\\n\"\n else:\n bid_hist_text += f\"- {js['bidder']}: ${js['bid']}\\n\"\n return bid_hist_text.strip()\n \n def all_bidding_history_to_string(self):\n bid_hist_text = ''\n for bid_round in self.bidding_history:\n bid_hist_text += f\"Round {bid_round}:\\n{self._biddings_to_string(bid_round)}\\n\\n\"\n return bid_hist_text.strip()\n\n def ask_for_bid(self, bid_round: int):\n '''\n Ask for bid, return the message to be sent to bidders\n '''\n if self.highest_bidder is None:\n if bid_round > 0:\n msg = f\"Seeing as we've had no takers at the initial price, we're going to lower the starting bid to ${self.cur_item.price} for {self.cur_item.name} to spark some interest! Do I have any takers?\"\n else:\n remaining_items = [self.cur_item.name] + [item.name for item in self.items_queue]\n msg = f\"Attention, bidders! {len(remaining_items)} item(s) left, they are: {', '.join(remaining_items)}.\\n\\nNow, please bid on {self.cur_item}. The starting price for bidding for {self.cur_item} is ${self.cur_item.price}. Anyone interested in this item?\"\n else:\n bidding_history = self._biddings_to_string(bid_round - 1)\n msg = f\"Thank you! This is the {p.ordinal(bid_round)} round of bidding for this item:\\n{bidding_history}\\n\\nNow we have ${self.highest_bid} from {self.highest_bidder.name} for {self.cur_item.name}. The minimum increase over this highest bid is ${int(self.cur_item.price * self.min_markup_pct)}. Do I have any advance on ${self.highest_bid}?\"\n return msg\n \n def ask_for_rebid(self, fail_msg: str, bid_price: int):\n return f\"Your bid of ${bid_price} failed, because {fail_msg}: You must reconsider your bid.\"\n\n def get_hammer_msg(self):\n if self.highest_bidder is None:\n return f\"Since no one bid on {self.cur_item.name}, we'll move on to the next item.\"\n else:\n return f\"Sold! {self.cur_item} to {self.highest_bidder} at ${self.highest_bid}! The true value for {self.cur_item} is ${self.cur_item.true_value}.\"# Thus {self.highest_bidder}'s profit by winning this item is ${self.cur_item.true_value - self.highest_bid}.\"\n\n def check_hammer(self, bid_round: int):\n # check if the item is sold\n self.fail_to_sell = False\n num_bid = self._num_bids_in_round(bid_round)\n\n # highest_bidder has already been updated in record_bid().\n # so when num_bid == 0 & highest_bidder is None, it means no one bid on this item\n if self.highest_bidder is None:\n if num_bid == 0:\n # failed to sell, as there is no highest bidder\n self.fail_to_sell = True\n if self.enable_discount and bid_round < 3:\n # lower the starting price by 50%. discoutn only applies to the first 3 rounds\n self.cur_item.lower_price(0.5)\n is_sold = False\n else:\n is_sold = True\n else:\n # won't happen\n raise ValueError(f\"highest_bidder is None but num_bid is {num_bid}\")\n else:\n if self.prev_round_max_bid < 0 and num_bid == 1:\n # only one bidder in the first round \n is_sold = True\n else:\n self.prev_round_max_bid = self.highest_bid\n is_sold = self._num_bids_in_round(bid_round) == 0\n return is_sold\n \n def _num_bids_in_round(self, bid_round: int):\n # check if there is no bid in the current round\n cnt = 0\n for hist in self.bidding_history[bid_round]:\n if hist['bid'] > 0:\n cnt += 1\n return cnt\n\n def hammer_fall(self):\n print(f'* Sold! {self.cur_item} (${self.cur_item.true_value}) goes to {self.highest_bidder} at ${self.highest_bid}.')\n self.auction_logs[f\"{self.cur_item.get_desc()}\"].append({\n 'bidder': self.highest_bidder, \n 'bid': f\"{self.highest_bid} (${self.cur_item.true_value})\", # no need for the first $, as it will be added in the self.log()\n 'bid_round': 'Hammer price (true value)'})\n self.cur_item = None\n self.highest_bidder = None\n self.highest_bid = -1\n self.bidding_history = defaultdict(list)\n self.prev_round_max_bid = -1\n self.fail_to_sell = False\n\n def end_auction(self):\n return len(self.items_queue) == 0\n \n def gather_all_status(self, bidders: List[Bidder]):\n status = {}\n for bidder in bidders:\n status[bidder.name] = {\n 'profit': bidder.profit, \n 'items_won': bidder.items_won\n }\n return status\n\n def parse_bid(self, text: str):\n prompt = PARSE_BID_INSTRUCTION.format(response=text)\n with get_openai_callback() as cb:\n llm = ChatOpenAI(model='gpt-3.5-turbo-0613', temperature=0)\n result = llm([HumanMessage(content=prompt)]).content\n self.openai_cost += cb.total_cost\n \n bid_number = re.findall(r'\\$?\\d+', result.replace(',', ''))\n # find number in the result\n if '-1' in result:\n return -1\n elif len(bid_number) > 0:\n return int(bid_number[-1].replace('$', ''))\n else:\n print('* Rebid:', text)\n return None\n\n def log(self, bidder_personal_reports: list = [], show_model_name=True):\n ''' example\n Apparatus H, starting at $1000.\n\n 1st bid:\n Bidder 1 (gpt-3.5-turbo-16k-0613): $1200\n Bidder 2 (gpt-3.5-turbo-16k-0613): $1100\n Bidder 3 (gpt-3.5-turbo-16k-0613): Withdrawn\n Bidder 4 (gpt-3.5-turbo-16k-0613): $1200\n \n 2nd bid:\n Bidder 1 (gpt-3.5-turbo-16k-0613): Withdrawn\n Bidder 2 (gpt-3.5-turbo-16k-0613): Withdrawn\n \n Hammer price:\n Bidder 4 (gpt-3.5-turbo-16k-0613): $1200\n '''\n markdown_output = \"## Auction Log\\n\\n\"\n for i, (item, bids) in enumerate(self.auction_logs.items()):\n markdown_output += f\"### {i+1}. {item}\\n\\n\"\n cur_bid_round = -1\n for i, bid in enumerate(bids):\n if bid['bid_round'] != cur_bid_round:\n cur_bid_round = bid['bid_round']\n if isinstance(bid['bid_round'], int):\n markdown_output += f\"\\n#### {p.ordinal(bid['bid_round']+1)} bid:\\n\\n\"\n else:\n markdown_output += f\"\\n#### {bid['bid_round']}:\\n\\n\"\n bid_price = f\"${bid['bid']}\" if bid['bid'] != -1 else 'Withdrew'\n if isinstance(bid['bidder'], Bidder) or isinstance(bid['bidder'], HumanBidder):\n if show_model_name:\n markdown_output += f\"* {bid['bidder']} ({bid['bidder'].model_name}): {bid_price}\\n\"\n else:\n markdown_output += f\"* {bid['bidder']}: {bid_price}\\n\"\n else:\n markdown_output += f\"* None bid\\n\"\n markdown_output += \"\\n\"\n \n if len(bidder_personal_reports) != 0:\n markdown_output += f\"\\n## Personal Report\"\n for report in bidder_personal_reports:\n markdown_output += f\"\\n\\n{report}\"\n return markdown_output.strip()\n \n def finish_auction(self):\n self.auction_logs = defaultdict(list)\n self.cur_item = None\n self.highest_bidder = None\n self.highest_bid = -1\n self.bidding_history = defaultdict(list)\n self.items_queue = []\n self.items = []\n self.prev_round_max_bid = -1\n self.fail_to_sell = False\n self.min_bid = 0" }, { "identifier": "run_auction", "path": "auction_workflow.py", "snippet": "def run_auction(\n auction_hash: str, \n auctioneer: Auctioneer, \n bidder_list: List[Bidder], \n thread_num: int, \n yield_for_demo=True,\n log_dir=LOG_DIR,\n repeat_num=0,\n memo_file=None):\n \n # bidder_list[0].verbose=True\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n # ***************** Learn Round ****************\n for bidder in bidder_list:\n if bidder.enable_learning and memo_file:\n # if no prev memo file, then no need to learn.\n if os.path.exists(memo_file):\n with open(memo_file) as f:\n data = json.load(f)\n past_learnings = data['learnings'][bidder.name]\n past_auction_log = data['auction_log']\n bidder.learn_from_prev_auction(past_learnings, past_auction_log)\n \n # ***************** Plan Round *****************\n # init bidder profit\n bidder_profit_info = auctioneer.gather_all_status(bidder_list)\n for bidder in bidder_list:\n bidder.set_all_bidders_status(bidder_profit_info)\n\n plan_instructs = [bidder.get_plan_instruct(auctioneer.items) for bidder in bidder_list]\n\n bidding_multithread(bidder_list, plan_instructs, func_type='plan', thread_num=thread_num)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n bar = tqdm(total=len(auctioneer.items_queue), desc='Auction Progress')\n while not auctioneer.end_auction():\n cur_item = auctioneer.present_item()\n \n bid_round = 0\n while True:\n # ***************** Bid Round ***************** \n auctioneer_msg = auctioneer.ask_for_bid(bid_round)\n _bidder_list = []\n _bid_instruct_list = []\n # remove highest bidder and withdrawn bidders\n for bidder in bidder_list:\n if bidder is auctioneer.highest_bidder or bidder.withdraw:\n bidder.need_input = False\n continue\n else:\n bidder.need_input = True # enable input from demo\n instruct = bidder.get_bid_instruct(auctioneer_msg, bid_round)\n _bidder_list.append(bidder)\n _bid_instruct_list.append(instruct)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + enable_human_box(bidder_list)\n \n _msgs = bidding_multithread(_bidder_list, _bid_instruct_list, func_type='bid', thread_num=thread_num)\n\n for i, (msg, bidder) in enumerate(zip(_msgs, _bidder_list)):\n if bidder.model_name == 'rule':\n bid_price = bidder.bid_rule(auctioneer.prev_round_max_bid, auctioneer.min_markup_pct)\n else:\n bid_price = parse_bid_price(auctioneer, bidder, msg)\n\n # can't bid more than budget or less than previous highest bid\n while True:\n fail_msg = bidder.bid_sanity_check(bid_price, auctioneer.prev_round_max_bid, auctioneer.min_markup_pct)\n if fail_msg is None: \n break\n else:\n bidder.need_input = True # enable input from demo\n auctioneer_msg = auctioneer.ask_for_rebid(fail_msg=fail_msg, bid_price=bid_price)\n rebid_instruct = bidder.get_rebid_instruct(auctioneer_msg)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n msg = bidder.rebid_for_failure(rebid_instruct)\n bid_price = parse_bid_price(auctioneer, bidder, msg)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n bidder.set_withdraw(bid_price)\n auctioneer.record_bid({'bidder': bidder, 'bid': bid_price, 'raw_msg': msg}, bid_round)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n \n is_sold = auctioneer.check_hammer(bid_round)\n bid_round += 1\n if is_sold: \n break\n else:\n if auctioneer.fail_to_sell and auctioneer.enable_discount:\n for bidder in bidder_list:\n bidder.set_withdraw(0) # back in the game\n\n # ***************** Summarize ***************** \n summarize_instruct_list = []\n for bidder in bidder_list:\n if bidder is auctioneer.highest_bidder:\n win_lose_msg = bidder.win_bid(cur_item, auctioneer.highest_bid)\n else:\n win_lose_msg = bidder.lose_bid(cur_item)\n msg = bidder.get_summarize_instruct(\n bidding_history=auctioneer.all_bidding_history_to_string(),\n hammer_msg=auctioneer.get_hammer_msg(),\n win_lose_msg=win_lose_msg\n )\n summarize_instruct_list.append(msg)\n\n # record profit information of all bidders for each bidder\n # (not used in the auction, just for belief tracking evaluation)\n bidder_profit_info = auctioneer.gather_all_status(bidder_list)\n for bidder in bidder_list:\n bidder.set_all_bidders_status(bidder_profit_info)\n \n bidding_multithread(bidder_list, summarize_instruct_list, func_type='summarize', thread_num=thread_num)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n\n # ***************** Replan *****************\n if len(auctioneer.items_queue) > 0: # no need to replan if all items are sold\n replan_instruct_list = [bidder.get_replan_instruct(\n # bidding_history=auctioneer.all_bidding_history_to_string(), \n # hammer_msg=auctioneer.get_hammer_msg()\n ) for bidder in bidder_list]\n bidding_multithread(bidder_list, replan_instruct_list, func_type='replan', thread_num=thread_num)\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log()] + [disable_gr, disable_gr] + disable_all_box(bidder_list)\n\n auctioneer.hammer_fall()\n bar.update(1)\n\n total_cost = sum([b.openai_cost for b in bidder_list]) + auctioneer.openai_cost\n bidder_reports = [bidder.profit_report() for bidder in bidder_list]\n \n if yield_for_demo:\n chatbot_list = bidders_to_chatbots(bidder_list, profit_report=True)\n yield [bidder_list] + chatbot_list + monitor_all(bidder_list) + [auctioneer.log(bidder_reports) + f'\\n## Total Cost: ${total_cost}'] + [disable_gr, enable_gr] + disable_all_box(bidder_list)\n \n memo = {'auction_log': auctioneer.log(show_model_name=False),\n 'memo_text': bidder_reports,\n 'profit': {bidder.name: bidder.profit for bidder in bidder_list},\n 'total_cost': total_cost,\n 'learnings': {bidder.name: bidder.learnings for bidder in bidder_list},\n 'model_info': {bidder.name: bidder.model_name for bidder in bidder_list}}\n log_bidders(log_dir, auction_hash, bidder_list, repeat_num, memo)\n \n auctioneer.finish_auction()\n \n if not yield_for_demo:\n yield total_cost" }, { "identifier": "make_auction_hash", "path": "auction_workflow.py", "snippet": "def make_auction_hash():\n return str(int(time.time()))" }, { "identifier": "chunks", "path": "utils.py", "snippet": "def chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i : i + n]" }, { "identifier": "reset_state_list", "path": "utils.py", "snippet": "def reset_state_list(*states):\n empty = [None for _ in states[1:]]\n return [[]] + empty" } ]
import os import gradio as gr from app_modules.presets import * from app_modules.overwrites import * from app_modules.utils import * from src.item_base import create_items from src.bidder_base import Bidder from src.human_bidder import HumanBidder from src.auctioneer_base import Auctioneer from auction_workflow import run_auction, make_auction_hash from utils import chunks, reset_state_list
15,736
BIDDER_NUM = 4 items = create_items('data/items_demo.jsonl') def auction_loop_app(*args): global items bidder_list = args[0] # gr.State() -> session state items_id = args[1] os.environ['OPENAI_API_KEY'] = args[2] if args[2] != '' else os.environ.get('OPENAI_API_KEY', '') os.environ['ANTHROPIC_API_KEY'] = args[3] if args[3] != '' else os.environ.get('ANTHROPIC_API_KEY', '') thread_num = args[4] item_shuffle = args[5] enable_discount = args[6] min_markup_pct = args[7] args = args[8:] auction_hash = make_auction_hash() items_to_bid = [items[i] for i in items_id] auctioneer = Auctioneer(enable_discount=enable_discount, min_markup_pct=min_markup_pct) auctioneer.init_items(items_to_bid) if item_shuffle: auctioneer.shuffle_items() # must correspond to the order in app's parameters input_keys = [ 'chatbot', 'model_name', 'desire', 'plan_strategy', 'budget', 'correct_belief', 'enable_learning', 'temperature', 'overestimate_percent', ] # convert flatten list into a json list input_jsl = [] for i, chunk in enumerate(chunks(args, len(input_keys))): js = {'name': f"Bidder {i+1}", 'auction_hash': auction_hash} for k, v in zip(input_keys, chunk): js[k] = v input_jsl.append(js) for js in input_jsl: js.pop('chatbot') if 'human' in js['model_name']:
BIDDER_NUM = 4 items = create_items('data/items_demo.jsonl') def auction_loop_app(*args): global items bidder_list = args[0] # gr.State() -> session state items_id = args[1] os.environ['OPENAI_API_KEY'] = args[2] if args[2] != '' else os.environ.get('OPENAI_API_KEY', '') os.environ['ANTHROPIC_API_KEY'] = args[3] if args[3] != '' else os.environ.get('ANTHROPIC_API_KEY', '') thread_num = args[4] item_shuffle = args[5] enable_discount = args[6] min_markup_pct = args[7] args = args[8:] auction_hash = make_auction_hash() items_to_bid = [items[i] for i in items_id] auctioneer = Auctioneer(enable_discount=enable_discount, min_markup_pct=min_markup_pct) auctioneer.init_items(items_to_bid) if item_shuffle: auctioneer.shuffle_items() # must correspond to the order in app's parameters input_keys = [ 'chatbot', 'model_name', 'desire', 'plan_strategy', 'budget', 'correct_belief', 'enable_learning', 'temperature', 'overestimate_percent', ] # convert flatten list into a json list input_jsl = [] for i, chunk in enumerate(chunks(args, len(input_keys))): js = {'name': f"Bidder {i+1}", 'auction_hash': auction_hash} for k, v in zip(input_keys, chunk): js[k] = v input_jsl.append(js) for js in input_jsl: js.pop('chatbot') if 'human' in js['model_name']:
bidder_list.append(HumanBidder.create(**js))
2
2023-10-08 09:30:57+00:00
24k
sakemin/cog-musicgen-chord
predict.py
[ { "identifier": "CompressionSolver", "path": "audiocraft/solvers/compression.py", "snippet": "class CompressionSolver(base.StandardSolver):\n \"\"\"Solver for compression task.\n\n The compression task combines a set of perceptual and objective losses\n to train an EncodecModel (composed of an encoder-decoder and a quantizer)\n to perform high fidelity audio reconstruction.\n \"\"\"\n def __init__(self, cfg: omegaconf.DictConfig):\n super().__init__(cfg)\n self.rng: torch.Generator # set at each epoch\n self.adv_losses = builders.get_adversarial_losses(self.cfg)\n self.aux_losses = nn.ModuleDict()\n self.info_losses = nn.ModuleDict()\n assert not cfg.fsdp.use, \"FSDP not supported by CompressionSolver.\"\n loss_weights = dict()\n for loss_name, weight in self.cfg.losses.items():\n if loss_name in ['adv', 'feat']:\n for adv_name, _ in self.adv_losses.items():\n loss_weights[f'{loss_name}_{adv_name}'] = weight\n elif weight > 0:\n self.aux_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n loss_weights[loss_name] = weight\n else:\n self.info_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n self.balancer = builders.get_balancer(loss_weights, self.cfg.balancer)\n self.register_stateful('adv_losses')\n\n @property\n def best_metric_name(self) -> tp.Optional[str]:\n # best model is the last for the compression model\n return None\n\n def build_model(self):\n \"\"\"Instantiate model and optimizer.\"\"\"\n # Model and optimizer\n self.model = models.builders.get_compression_model(self.cfg).to(self.device)\n self.optimizer = builders.get_optimizer(self.model.parameters(), self.cfg.optim)\n self.register_stateful('model', 'optimizer')\n self.register_best_state('model')\n self.register_ema('model')\n\n def build_dataloaders(self):\n \"\"\"Instantiate audio dataloaders for each stage.\"\"\"\n self.dataloaders = builders.get_audio_datasets(self.cfg)\n\n def show(self):\n \"\"\"Show the compression model and employed adversarial loss.\"\"\"\n self.logger.info(f\"Compression model with {self.model.quantizer.total_codebooks} codebooks:\")\n self.log_model_summary(self.model)\n self.logger.info(\"Adversarial loss:\")\n self.log_model_summary(self.adv_losses)\n self.logger.info(\"Auxiliary losses:\")\n self.logger.info(self.aux_losses)\n self.logger.info(\"Info losses:\")\n self.logger.info(self.info_losses)\n\n def run_step(self, idx: int, batch: torch.Tensor, metrics: dict):\n \"\"\"Perform one training or valid step on a given batch.\"\"\"\n x = batch.to(self.device)\n y = x.clone()\n\n qres = self.model(x)\n assert isinstance(qres, quantization.QuantizedResult)\n y_pred = qres.x\n # Log bandwidth in kb/s\n metrics['bandwidth'] = qres.bandwidth.mean()\n\n if self.is_training:\n d_losses: dict = {}\n if len(self.adv_losses) > 0 and torch.rand(1, generator=self.rng).item() <= 1 / self.cfg.adversarial.every:\n for adv_name, adversary in self.adv_losses.items():\n disc_loss = adversary.train_adv(y_pred, y)\n d_losses[f'd_{adv_name}'] = disc_loss\n metrics['d_loss'] = torch.sum(torch.stack(list(d_losses.values())))\n metrics.update(d_losses)\n\n balanced_losses: dict = {}\n other_losses: dict = {}\n\n # penalty from quantization\n if qres.penalty is not None and qres.penalty.requires_grad:\n other_losses['penalty'] = qres.penalty # penalty term from the quantizer\n\n # adversarial losses\n for adv_name, adversary in self.adv_losses.items():\n adv_loss, feat_loss = adversary(y_pred, y)\n balanced_losses[f'adv_{adv_name}'] = adv_loss\n balanced_losses[f'feat_{adv_name}'] = feat_loss\n\n # auxiliary losses\n for loss_name, criterion in self.aux_losses.items():\n loss = criterion(y_pred, y)\n balanced_losses[loss_name] = loss\n\n # weighted losses\n metrics.update(balanced_losses)\n metrics.update(other_losses)\n metrics.update(qres.metrics)\n\n if self.is_training:\n # backprop losses that are not handled by balancer\n other_loss = torch.tensor(0., device=self.device)\n if 'penalty' in other_losses:\n other_loss += other_losses['penalty']\n if other_loss.requires_grad:\n other_loss.backward(retain_graph=True)\n ratio1 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio1, torch.Tensor)\n metrics['ratio1'] = ratio1.sqrt()\n\n # balancer losses backward, returns effective training loss\n # with effective weights at the current batch.\n metrics['g_loss'] = self.balancer.backward(balanced_losses, y_pred)\n # add metrics corresponding to weight ratios\n metrics.update(self.balancer.metrics)\n ratio2 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio2, torch.Tensor)\n metrics['ratio2'] = ratio2.sqrt()\n\n # optim\n flashy.distrib.sync_model(self.model)\n if self.cfg.optim.max_norm:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.cfg.optim.max_norm\n )\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n # informative losses only\n info_losses: dict = {}\n with torch.no_grad():\n for loss_name, criterion in self.info_losses.items():\n loss = criterion(y_pred, y)\n info_losses[loss_name] = loss\n\n metrics.update(info_losses)\n\n # aggregated GAN losses: this is useful to report adv and feat across different adversarial loss setups\n adv_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('adv')]\n if len(adv_losses) > 0:\n metrics['adv'] = torch.sum(torch.stack(adv_losses))\n feat_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('feat')]\n if len(feat_losses) > 0:\n metrics['feat'] = torch.sum(torch.stack(feat_losses))\n\n return metrics\n\n def run_epoch(self):\n # reset random seed at the beginning of the epoch\n self.rng = torch.Generator()\n self.rng.manual_seed(1234 + self.epoch)\n # run epoch\n super().run_epoch()\n\n def evaluate(self):\n \"\"\"Evaluate stage. Runs audio reconstruction evaluation.\"\"\"\n self.model.eval()\n evaluate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['evaluate']\n updates = len(loader)\n lp = self.log_progress(f'{evaluate_stage_name} inference', loader, total=updates, updates=self.log_updates)\n average = flashy.averager()\n\n pendings = []\n ctx = multiprocessing.get_context('spawn')\n with get_pool_executor(self.cfg.evaluate.num_workers, mp_context=ctx) as pool:\n for idx, batch in enumerate(lp):\n x = batch.to(self.device)\n with torch.no_grad():\n qres = self.model(x)\n\n y_pred = qres.x.cpu()\n y = batch.cpu() # should already be on CPU but just in case\n pendings.append(pool.submit(evaluate_audio_reconstruction, y_pred, y, self.cfg))\n\n metrics_lp = self.log_progress(f'{evaluate_stage_name} metrics', pendings, updates=self.log_updates)\n for pending in metrics_lp:\n metrics = pending.result()\n metrics = average(metrics)\n\n metrics = flashy.distrib.average_metrics(metrics, len(loader))\n return metrics\n\n def generate(self):\n \"\"\"Generate stage.\"\"\"\n self.model.eval()\n sample_manager = SampleManager(self.xp, map_reference_to_sample_id=True)\n generate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['generate']\n updates = len(loader)\n lp = self.log_progress(generate_stage_name, loader, total=updates, updates=self.log_updates)\n\n for batch in lp:\n reference, _ = batch\n reference = reference.to(self.device)\n with torch.no_grad():\n qres = self.model(reference)\n assert isinstance(qres, quantization.QuantizedResult)\n\n reference = reference.cpu()\n estimate = qres.x.cpu()\n sample_manager.add_samples(estimate, self.epoch, ground_truth_wavs=reference)\n\n flashy.distrib.barrier()\n\n def load_from_pretrained(self, name: str) -> dict:\n model = models.CompressionModel.get_pretrained(name)\n if isinstance(model, models.DAC):\n raise RuntimeError(\"Cannot fine tune a DAC model.\")\n elif isinstance(model, models.HFEncodecCompressionModel):\n self.logger.warning('Trying to automatically convert a HuggingFace model '\n 'to AudioCraft, this might fail!')\n state = model.model.state_dict()\n new_state = {}\n for k, v in state.items():\n if k.startswith('decoder.layers') and '.conv.' in k and '.block.' not in k:\n # We need to determine if this a convtr or a regular conv.\n layer = int(k.split('.')[2])\n if isinstance(model.model.decoder.layers[layer].conv, torch.nn.ConvTranspose1d):\n\n k = k.replace('.conv.', '.convtr.')\n k = k.replace('encoder.layers.', 'encoder.model.')\n k = k.replace('decoder.layers.', 'decoder.model.')\n k = k.replace('conv.', 'conv.conv.')\n k = k.replace('convtr.', 'convtr.convtr.')\n k = k.replace('quantizer.layers.', 'quantizer.vq.layers.')\n k = k.replace('.codebook.', '._codebook.')\n new_state[k] = v\n state = new_state\n elif isinstance(model, models.EncodecModel):\n state = model.state_dict()\n else:\n raise RuntimeError(f\"Cannot fine tune model type {type(model)}.\")\n return {\n 'best_state': {'model': state}\n }\n\n @staticmethod\n def model_from_checkpoint(checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a CompressionModel from a given checkpoint path or dora sig.\n This method is a convenient endpoint to load a CompressionModel to use in other solvers.\n\n Args:\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n This also supports pre-trained models by using a path of the form //pretrained/NAME.\n See `model_from_pretrained` for a list of supported pretrained models.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n checkpoint_path = str(checkpoint_path)\n if checkpoint_path.startswith('//pretrained/'):\n name = checkpoint_path.split('/', 3)[-1]\n return models.CompressionModel.get_pretrained(name, device)\n logger = logging.getLogger(__name__)\n logger.info(f\"Loading compression model from checkpoint: {checkpoint_path}\")\n _checkpoint_path = checkpoint.resolve_checkpoint_path(checkpoint_path, use_fsdp=False)\n assert _checkpoint_path is not None, f\"Could not resolve compression model checkpoint path: {checkpoint_path}\"\n state = checkpoint.load_checkpoint(_checkpoint_path)\n assert state is not None and 'xp.cfg' in state, f\"Could not load compression model from ckpt: {checkpoint_path}\"\n cfg = state['xp.cfg']\n cfg.device = device\n compression_model = models.builders.get_compression_model(cfg).to(device)\n assert compression_model.sample_rate == cfg.sample_rate, \"Compression model sample rate should match\"\n\n assert 'best_state' in state and state['best_state'] != {}\n assert 'exported' not in state, \"When loading an exported checkpoint, use the //pretrained/ prefix.\"\n compression_model.load_state_dict(state['best_state']['model'])\n compression_model.eval()\n logger.info(\"Compression model loaded!\")\n return compression_model\n\n @staticmethod\n def wrapped_model_from_checkpoint(cfg: omegaconf.DictConfig,\n checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a wrapped CompressionModel from a given checkpoint path or dora sig.\n\n Args:\n cfg (omegaconf.DictConfig): Configuration to read from for wrapped mode.\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n compression_model = CompressionSolver.model_from_checkpoint(checkpoint_path, device)\n compression_model = models.builders.get_wrapped_compression_model(compression_model, cfg)\n return compression_model" }, { "identifier": "MultiBandDiffusion", "path": "audiocraft/models/multibanddiffusion.py", "snippet": "class MultiBandDiffusion:\n \"\"\"Sample from multiple diffusion models.\n\n Args:\n DPs (list of DiffusionProcess): Diffusion processes.\n codec_model (CompressionModel): Underlying compression model used to obtain discrete tokens.\n \"\"\"\n def __init__(self, DPs: tp.List[DiffusionProcess], codec_model: CompressionModel) -> None:\n self.DPs = DPs\n self.codec_model = codec_model\n self.device = next(self.codec_model.parameters()).device\n\n @property\n def sample_rate(self) -> int:\n return self.codec_model.sample_rate\n\n @staticmethod\n def get_mbd_musicgen(device=None):\n \"\"\"Load our diffusion models trained for MusicGen.\"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n path = 'facebook/multiband-diffusion'\n filename = 'mbd_musicgen_32khz.th'\n name = 'facebook/musicgen-small'\n codec_model = load_compression_model(name, device=device)\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n @staticmethod\n def get_mbd_24khz(bw: float = 3.0, pretrained: bool = True,\n device: tp.Optional[tp.Union[torch.device, str]] = None,\n n_q: tp.Optional[int] = None):\n \"\"\"Get the pretrained Models for MultibandDiffusion.\n\n Args:\n bw (float): Bandwidth of the compression model.\n pretrained (bool): Whether to use / download if necessary the models.\n device (torch.device or str, optional): Device on which the models are loaded.\n n_q (int, optional): Number of quantizers to use within the compression model.\n \"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n assert bw in [1.5, 3.0, 6.0], f\"bandwidth {bw} not available\"\n if n_q is not None:\n assert n_q in [2, 4, 8]\n assert {1.5: 2, 3.0: 4, 6.0: 8}[bw] == n_q, \\\n f\"bandwidth and number of codebooks missmatch to use n_q = {n_q} bw should be {n_q * (1.5 / 2)}\"\n n_q = {1.5: 2, 3.0: 4, 6.0: 8}[bw]\n codec_model = CompressionSolver.model_from_checkpoint(\n '//pretrained/facebook/encodec_24khz', device=device)\n codec_model.set_num_codebooks(n_q)\n codec_model = codec_model.to(device)\n path = 'facebook/multiband-diffusion'\n filename = f'mbd_comp_{n_q}.pt'\n models, processors, cfgs = load_diffusion_models(path, filename=filename, device=device)\n DPs = []\n for i in range(len(models)):\n schedule = NoiseSchedule(**cfgs[i].schedule, sample_processor=processors[i], device=device)\n DPs.append(DiffusionProcess(model=models[i], noise_schedule=schedule))\n return MultiBandDiffusion(DPs=DPs, codec_model=codec_model)\n\n return MultiBandDiffusion(DPs, codec_model)\n\n @torch.no_grad()\n def get_condition(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor:\n \"\"\"Get the conditioning (i.e. latent reprentatios of the compression model) from a waveform.\n Args:\n wav (torch.Tensor): The audio that we want to extract the conditioning from\n sample_rate (int): sample rate of the audio\"\"\"\n if sample_rate != self.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.sample_rate)\n codes, scale = self.codec_model.encode(wav)\n assert scale is None, \"Scaled compression models not supported.\"\n emb = self.get_emb(codes)\n return emb\n\n @torch.no_grad()\n def get_emb(self, codes: torch.Tensor):\n \"\"\"Get latent representation from the discrete codes\n Argrs:\n codes (torch.Tensor): discrete tokens\"\"\"\n emb = self.codec_model.decode_latent(codes)\n return emb\n\n def generate(self, emb: torch.Tensor, size: tp.Optional[torch.Size] = None,\n step_list: tp.Optional[tp.List[int]] = None):\n \"\"\"Generate Wavform audio from the latent embeddings of the compression model\n Args:\n emb (torch.Tensor): Conditioning embeddinds\n size (none torch.Size): size of the output\n if None this is computed from the typical upsampling of the model\n step_list (optional list[int]): list of Markov chain steps, defaults to 50 linearly spaced step.\n \"\"\"\n if size is None:\n upsampling = int(self.codec_model.sample_rate / self.codec_model.frame_rate)\n size = torch.Size([emb.size(0), self.codec_model.channels, emb.size(-1) * upsampling])\n assert size[0] == emb.size(0)\n out = torch.zeros(size).to(self.device)\n for DP in self.DPs:\n out += DP.generate(condition=emb, step_list=step_list, initial_noise=torch.randn_like(out))\n return out\n\n def re_eq(self, wav: torch.Tensor, ref: torch.Tensor, n_bands: int = 32, strictness: float = 1):\n \"\"\"match the eq to the encodec output by matching the standard deviation of some frequency bands\n Args:\n wav (torch.Tensor): audio to equalize\n ref (torch.Tensor):refenrence audio from which we match the spectrogram.\n n_bands (int): number of bands of the eq\n strictness (float): how strict the the matching. 0 is no matching, 1 is exact matching.\n \"\"\"\n split = julius.SplitBands(n_bands=n_bands, sample_rate=self.codec_model.sample_rate).to(wav.device)\n bands = split(wav)\n bands_ref = split(ref)\n out = torch.zeros_like(ref)\n for i in range(n_bands):\n out += bands[i] * (bands_ref[i].std() / bands[i].std()) ** strictness\n return out\n\n def regenerate(self, wav: torch.Tensor, sample_rate: int):\n \"\"\"Regenerate a wavform through compression and diffusion regeneration.\n Args:\n wav (torch.Tensor): Original 'ground truth' audio\n sample_rate (int): sample rate of the input (and output) wav\n \"\"\"\n if sample_rate != self.codec_model.sample_rate:\n wav = julius.resample_frac(wav, sample_rate, self.codec_model.sample_rate)\n emb = self.get_condition(wav, sample_rate=self.codec_model.sample_rate)\n size = wav.size()\n out = self.generate(emb, size=size)\n if sample_rate != self.codec_model.sample_rate:\n out = julius.resample_frac(out, self.codec_model.sample_rate, sample_rate)\n return out\n\n def tokens_to_wav(self, tokens: torch.Tensor, n_bands: int = 32):\n \"\"\"Generate Waveform audio with diffusion from the discrete codes.\n Args:\n tokens (torch.Tensor): discrete codes\n n_bands (int): bands for the eq matching.\n \"\"\"\n wav_encodec = self.codec_model.decode(tokens)\n condition = self.get_emb(tokens)\n wav_diffusion = self.generate(emb=condition, size=wav_encodec.size())\n return self.re_eq(wav=wav_diffusion, ref=wav_encodec, n_bands=n_bands)" }, { "identifier": "MusicGen", "path": "audiocraft/models/musicgen.py", "snippet": "class MusicGen:\n \"\"\"MusicGen main model with convenient generation API.\n\n Args:\n name (str): name of the model.\n compression_model (CompressionModel): Compression model\n used to map audio to invertible discrete representations.\n lm (LMModel): Language model over discrete representations.\n max_duration (float, optional): maximum duration the model can produce,\n otherwise, inferred from the training params.\n \"\"\"\n def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel,\n max_duration: tp.Optional[float] = None):\n self.name = name\n self.compression_model = compression_model\n self.lm = lm\n self.cfg: tp.Optional[omegaconf.DictConfig] = None\n # Just to be safe, let's put everything in eval mode.\n self.compression_model.eval()\n self.lm.eval()\n\n if hasattr(lm, 'cfg'):\n cfg = lm.cfg\n assert isinstance(cfg, omegaconf.DictConfig)\n self.cfg = cfg\n\n if self.cfg is not None:\n self.compression_model = get_wrapped_compression_model(self.compression_model, self.cfg)\n\n if max_duration is None:\n if self.cfg is not None:\n max_duration = lm.cfg.dataset.segment_duration # type: ignore\n else:\n raise ValueError(\"You must provide max_duration when building directly MusicGen\")\n assert max_duration is not None\n self.max_duration: float = max_duration\n self.device = next(iter(lm.parameters())).device\n\n self.generation_params: dict = {}\n self.set_generation_params(duration=15) # 15 seconds by default\n self._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None\n if self.device.type == 'cpu':\n self.autocast = TorchAutocast(enabled=False)\n else:\n self.autocast = TorchAutocast(\n enabled=True, device_type=self.device.type, dtype=torch.float16)\n\n @property\n def frame_rate(self) -> float:\n \"\"\"Roughly the number of AR steps per seconds.\"\"\"\n return self.compression_model.frame_rate\n\n @property\n def sample_rate(self) -> int:\n \"\"\"Sample rate of the generated audio.\"\"\"\n return self.compression_model.sample_rate\n\n @property\n def audio_channels(self) -> int:\n \"\"\"Audio channels of the generated audio.\"\"\"\n return self.compression_model.channels\n\n @staticmethod\n def get_pretrained(name: str = 'facebook/musicgen-melody', device=None):\n \"\"\"Return pretrained model, we provide four models:\n - facebook/musicgen-small (300M), text to music,\n # see: https://huggingface.co/facebook/musicgen-small\n - facebook/musicgen-medium (1.5B), text to music,\n # see: https://huggingface.co/facebook/musicgen-medium\n - facebook/musicgen-melody (1.5B) text to music and text+melody to music,\n # see: https://huggingface.co/facebook/musicgen-melody\n - facebook/musicgen-large (3.3B), text to music,\n # see: https://huggingface.co/facebook/musicgen-large\n \"\"\"\n if device is None:\n if torch.cuda.device_count():\n device = 'cuda'\n else:\n device = 'cpu'\n\n if name == 'debug':\n # used only for unit tests\n compression_model = get_debug_compression_model(device)\n lm = get_debug_lm_model(device)\n return MusicGen(name, compression_model, lm, max_duration=30)\n\n if name in _HF_MODEL_CHECKPOINTS_MAP:\n warnings.warn(\n \"MusicGen pretrained model relying on deprecated checkpoint mapping. \" +\n f\"Please use full pre-trained id instead: facebook/musicgen-{name}\")\n name = _HF_MODEL_CHECKPOINTS_MAP[name]\n\n lm = load_lm_model(name, device=device)\n compression_model = load_compression_model(name, device=device)\n if 'self_wav' in lm.condition_provider.conditioners:\n lm.condition_provider.conditioners['self_wav'].match_len_on_eval = True\n lm.condition_provider.conditioners['self_wav']._use_masking = False\n\n return MusicGen(name, compression_model, lm)\n\n def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,\n top_p: float = 0.0, temperature: float = 1.0,\n duration: float = 30.0, cfg_coef: float = 3.0,\n two_step_cfg: bool = False, extend_stride: float = 18):\n \"\"\"Set the generation parameters for MusicGen.\n\n Args:\n use_sampling (bool, optional): Use sampling if True, else do argmax decoding. Defaults to True.\n top_k (int, optional): top_k used for sampling. Defaults to 250.\n top_p (float, optional): top_p used for sampling, when set to 0 top_k is used. Defaults to 0.0.\n temperature (float, optional): Softmax temperature parameter. Defaults to 1.0.\n duration (float, optional): Duration of the generated waveform. Defaults to 30.0.\n cfg_coef (float, optional): Coefficient used for classifier free guidance. Defaults to 3.0.\n two_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,\n instead of batching together the two. This has some impact on how things\n are padded but seems to have little impact in practice.\n extend_stride: when doing extended generation (i.e. more than 30 seconds), by how much\n should we extend the audio each time. Larger values will mean less context is\n preserved, and shorter value will require extra computations.\n \"\"\"\n assert extend_stride < self.max_duration, \"Cannot stride by more than max generation duration.\"\n self.extend_stride = extend_stride\n self.duration = duration\n self.generation_params = {\n 'use_sampling': use_sampling,\n 'temp': temperature,\n 'top_k': top_k,\n 'top_p': top_p,\n 'cfg_coef': cfg_coef,\n 'two_step_cfg': two_step_cfg,\n }\n\n def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):\n \"\"\"Override the default progress callback.\"\"\"\n self._progress_callback = progress_callback\n\n def generate_unconditional(self, num_samples: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples in an unconditional manner.\n\n Args:\n num_samples (int): Number of samples to be generated.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n descriptions: tp.List[tp.Optional[str]] = [None] * num_samples\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate(self, descriptions: tp.List[str], progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_with_chroma(self, descriptions: tp.List[str], melody_wavs: MelodyType,\n melody_sample_rate: int, progress: bool = False,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=melody_wavs)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation(self, prompt: torch.Tensor, prompt_sample_rate: int,\n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, prompt)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_continuation_with_audio_token(self, prompt, \n descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions, None)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt, melody_wavs=melody_wavs)\n assert prompt_tokens is not None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_audio_chroma(self, prompt, melody_wavs: MelodyType,\n melody_sample_rate: int, descriptions: tp.Optional[tp.List[tp.Optional[str]]] = None,\n progress: bool = False, return_tokens: bool = False) \\\n -> tp.Union[torch.Tensor, tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on audio prompts.\n\n Args:\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n Prompt should be [B, C, T], or [C, T] if only one sample is generated.\n prompt_sample_rate (int): Sampling rate of the given audio waveforms.\n descriptions (list of str, optional): A list of strings used as text conditioning. Defaults to None.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(melody_wavs, torch.Tensor):\n if melody_wavs.dim() == 2:\n melody_wavs = melody_wavs[None]\n if melody_wavs.dim() != 3:\n raise ValueError(\"Melody wavs should have a shape [B, C, T].\")\n melody_wavs = list(melody_wavs)\n else:\n for melody in melody_wavs:\n if melody is not None:\n assert melody.dim() == 2, \"One melody in the list has the wrong number of dims.\"\n\n melody_wavs = [\n convert_audio(wav, melody_sample_rate, self.sample_rate, self.audio_channels)\n if wav is not None else None\n for wav in melody_wavs]\n \n if descriptions is None:\n descriptions = [None] * len(prompt)\n \n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None, melody_wavs=melody_wavs)\n assert prompt_tokens is None\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_text_chroma(self, prompt: torch.Tensor, prompt_sample_rate: int, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if prompt.dim() == 2:\n prompt = prompt[None]\n if prompt.dim() != 3:\n raise ValueError(\"prompt should have 3 dimensions: [B, C, T] (C = 1).\")\n prompt = convert_audio(prompt, prompt_sample_rate, self.sample_rate, self.audio_channels)\n\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=prompt,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n\n def generate_continuation_with_audio_tokens_and_text_chroma(self, prompt, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n \n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n prompt_tokens = prompt\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n def generate_with_text_chroma(self, descriptions: tp.List[str], chord_texts: tp.Union[tp.List[str],str],\n progress: bool = False, bpm: tp.Union[float,int,tp.List[float],tp.List[int]] = 120, meter: tp.Optional[tp.Union[int,tp.List[int]]] = 4,\n return_tokens: bool = False) -> tp.Union[torch.Tensor,\n tp.Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"Generate samples conditioned on text and melody.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n melody_wavs: (torch.Tensor or list of Tensor): A batch of waveforms used as\n melody conditioning. Should have shape [B, C, T] with B matching the description length,\n C=1 or 2. It can be [C, T] if there is a single description. It can also be\n a list of [C, T] tensors.\n melody_sample_rate: (int): Sample rate of the melody waveforms.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n \"\"\"\n if isinstance(chord_texts, str):\n chord_texts = [chord_texts]\n\n attributes, prompt_tokens = self._prepare_tokens_and_attributes(descriptions=descriptions, prompt=None,\n melody_wavs=chord_texts, bpm=bpm, meter=meter)\n assert prompt_tokens is None\n tokens = self._generate_tokens(attributes, prompt_tokens, progress)\n if return_tokens:\n return self.generate_audio(tokens), tokens\n return self.generate_audio(tokens)\n \n @torch.no_grad()\n def _prepare_tokens_and_attributes(\n self,\n descriptions: tp.Sequence[tp.Optional[str]],\n prompt: tp.Optional[torch.Tensor],\n melody_wavs: tp.Optional[tp.Union[MelodyList,tp.List[str]]] = None, bpm: tp.Optional[tp.Union[float,int,tp.List[float],tp.List[int]]] = None, meter:tp.Optional[tp.Union[int,tp.List[int]]] = None\n ) -> tp.Tuple[tp.List[ConditioningAttributes], tp.Optional[torch.Tensor]]:\n \"\"\"Prepare model inputs.\n\n Args:\n descriptions (list of str): A list of strings used as text conditioning.\n prompt (torch.Tensor): A batch of waveforms used for continuation.\n melody_wavs (torch.Tensor, optional): A batch of waveforms\n used as melody conditioning. Defaults to None.\n \"\"\"\n attributes = [\n ConditioningAttributes(text={'description': description})\n for description in descriptions]\n\n if melody_wavs is None:\n for attr in attributes:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n else:\n if 'self_wav' not in self.lm.condition_provider.conditioners:\n raise RuntimeError(\"This model doesn't support melody conditioning. \"\n \"Use the `melody` model.\")\n assert len(melody_wavs) == len(descriptions), \\\n f\"number of melody wavs must match number of descriptions! \" \\\n f\"got melody len={len(melody_wavs)}, and descriptions len={len(descriptions)}\"\n\n if bpm is not None and (isinstance(bpm, int) or isinstance(bpm, float)):\n bpm = [bpm for i in range(len(melody_wavs))]\n elif bpm is not None and isinstance(bpm, tp.List):\n assert len(melody_wavs) == len(bpm)\n\n if meter is not None and (isinstance(meter, int) or isinstance(meter, float)):\n meter = [meter for i in range(len(melody_wavs))]\n elif meter is not None and isinstance(meter, tp.List):\n assert len(melody_wavs) == len(meter)\n\n for attr, melody, i in zip(attributes, melody_wavs, range(len(melody_wavs))):\n if melody is None:\n attr.wav['self_wav'] = WavCondition(\n torch.zeros((1, 1, 1), device=self.device),\n torch.tensor([0], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None])\n elif isinstance(melody, torch.Tensor):\n attr.wav['self_wav'] = WavCondition(\n melody[None].to(device=self.device),\n torch.tensor([melody.shape[-1]], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n )\n else :\n attr.wav['self_wav'] = WavChordTextCondition(\n [melody],\n torch.tensor([self.duration*self.sample_rate], device=self.device),\n sample_rate=[self.sample_rate],\n path=[None],\n bpm = [bpm[i]],\n meter = [meter[i]]\n )\n\n if prompt is not None:\n if descriptions is not None:\n assert len(descriptions) == len(prompt), \"Prompt and nb. descriptions doesn't match\"\n prompt = prompt.to(self.device)\n prompt_tokens, scale = self.compression_model.encode(prompt)\n assert scale is None\n else:\n prompt_tokens = None\n return attributes, prompt_tokens\n\n def _generate_tokens(self, attributes: tp.List[ConditioningAttributes],\n prompt_tokens: tp.Optional[torch.Tensor], progress: bool = False) -> torch.Tensor:\n \"\"\"Generate discrete audio tokens given audio prompt and/or conditions.\n\n Args:\n attributes (list of ConditioningAttributes): Conditions used for generation (text/melody).\n prompt_tokens (torch.Tensor, optional): Audio prompt used for continuation.\n progress (bool, optional): Flag to display progress of the generation process. Defaults to False.\n Returns:\n torch.Tensor: Generated audio, of shape [B, C, T], T is defined by the generation params.\n \"\"\"\n total_gen_len = int(self.duration * self.frame_rate)\n max_prompt_len = int(min(self.duration, self.max_duration) * self.frame_rate)\n current_gen_offset: int = 0\n\n def _progress_callback(generated_tokens: int, tokens_to_generate: int):\n generated_tokens += current_gen_offset\n if self._progress_callback is not None:\n # Note that total_gen_len might be quite wrong depending on the\n # codebook pattern used, but with delay it is almost accurate.\n self._progress_callback(generated_tokens, total_gen_len)\n else:\n print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\\r')\n\n if prompt_tokens is not None:\n assert max_prompt_len >= prompt_tokens.shape[-1], \\\n \"Prompt is longer than audio to generate\"\n\n callback = None\n if progress:\n callback = _progress_callback\n\n if self.duration <= self.max_duration:\n # generate by sampling from LM, simple case.\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=total_gen_len, **self.generation_params)\n\n else:\n # now this gets a bit messier, we need to handle prompts,\n # melody conditioning etc.\n ref_wavs = [attr.wav['self_wav'] for attr in attributes]\n all_tokens = []\n if prompt_tokens is None:\n prompt_length = 0\n else:\n all_tokens.append(prompt_tokens)\n prompt_length = prompt_tokens.shape[-1]\n\n stride_tokens = int(self.frame_rate * self.extend_stride)\n step = 0\n\n while current_gen_offset + prompt_length < total_gen_len:\n self.lm.condition_provider.conditioners['self_wav'].set_continuation_count(self.extend_stride/self.max_duration, step) #For text based chord conditioning\n time_offset = current_gen_offset / self.frame_rate\n chunk_duration = min(self.duration - time_offset, self.max_duration)\n max_gen_len = int(chunk_duration * self.frame_rate)\n for attr, ref_wav in zip(attributes, ref_wavs):\n if isinstance(ref_wav, WavCondition):\n wav_length = ref_wav.length.item()\n if wav_length == 0:\n continue\n # We will extend the wav periodically if it not long enough.\n # we have to do it here rather than in conditioners.py as otherwise\n # we wouldn't have the full wav.\n initial_position = int(time_offset * self.sample_rate)\n wav_target_length = int(self.max_duration * self.sample_rate)\n positions = torch.arange(initial_position,\n initial_position + wav_target_length, device=self.device)\n attr.wav['self_wav'] = WavCondition(\n ref_wav[0][..., positions % wav_length],\n torch.full_like(ref_wav[1], wav_target_length),\n [self.sample_rate] * ref_wav[0].size(0),\n [None], [0.])\n with self.autocast:\n gen_tokens = self.lm.generate(\n prompt_tokens, attributes,\n callback=callback, max_gen_len=max_gen_len, **self.generation_params)\n if prompt_tokens is None:\n all_tokens.append(gen_tokens)\n else:\n all_tokens.append(gen_tokens[:, :, prompt_tokens.shape[-1]:])\n prompt_tokens = gen_tokens[:, :, stride_tokens:]\n prompt_length = prompt_tokens.shape[-1]\n current_gen_offset += stride_tokens\n step = step + 1\n\n gen_tokens = torch.cat(all_tokens, dim=-1)\n return gen_tokens\n\n def generate_audio(self, gen_tokens: torch.Tensor):\n \"\"\"Generate Audio from tokens\"\"\"\n assert gen_tokens.dim() == 3\n with torch.no_grad():\n gen_audio = self.compression_model.decode(gen_tokens, None)\n return gen_audio" }, { "identifier": "CompressionSolver", "path": "audiocraft/solvers/compression.py", "snippet": "class CompressionSolver(base.StandardSolver):\n \"\"\"Solver for compression task.\n\n The compression task combines a set of perceptual and objective losses\n to train an EncodecModel (composed of an encoder-decoder and a quantizer)\n to perform high fidelity audio reconstruction.\n \"\"\"\n def __init__(self, cfg: omegaconf.DictConfig):\n super().__init__(cfg)\n self.rng: torch.Generator # set at each epoch\n self.adv_losses = builders.get_adversarial_losses(self.cfg)\n self.aux_losses = nn.ModuleDict()\n self.info_losses = nn.ModuleDict()\n assert not cfg.fsdp.use, \"FSDP not supported by CompressionSolver.\"\n loss_weights = dict()\n for loss_name, weight in self.cfg.losses.items():\n if loss_name in ['adv', 'feat']:\n for adv_name, _ in self.adv_losses.items():\n loss_weights[f'{loss_name}_{adv_name}'] = weight\n elif weight > 0:\n self.aux_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n loss_weights[loss_name] = weight\n else:\n self.info_losses[loss_name] = builders.get_loss(loss_name, self.cfg)\n self.balancer = builders.get_balancer(loss_weights, self.cfg.balancer)\n self.register_stateful('adv_losses')\n\n @property\n def best_metric_name(self) -> tp.Optional[str]:\n # best model is the last for the compression model\n return None\n\n def build_model(self):\n \"\"\"Instantiate model and optimizer.\"\"\"\n # Model and optimizer\n self.model = models.builders.get_compression_model(self.cfg).to(self.device)\n self.optimizer = builders.get_optimizer(self.model.parameters(), self.cfg.optim)\n self.register_stateful('model', 'optimizer')\n self.register_best_state('model')\n self.register_ema('model')\n\n def build_dataloaders(self):\n \"\"\"Instantiate audio dataloaders for each stage.\"\"\"\n self.dataloaders = builders.get_audio_datasets(self.cfg)\n\n def show(self):\n \"\"\"Show the compression model and employed adversarial loss.\"\"\"\n self.logger.info(f\"Compression model with {self.model.quantizer.total_codebooks} codebooks:\")\n self.log_model_summary(self.model)\n self.logger.info(\"Adversarial loss:\")\n self.log_model_summary(self.adv_losses)\n self.logger.info(\"Auxiliary losses:\")\n self.logger.info(self.aux_losses)\n self.logger.info(\"Info losses:\")\n self.logger.info(self.info_losses)\n\n def run_step(self, idx: int, batch: torch.Tensor, metrics: dict):\n \"\"\"Perform one training or valid step on a given batch.\"\"\"\n x = batch.to(self.device)\n y = x.clone()\n\n qres = self.model(x)\n assert isinstance(qres, quantization.QuantizedResult)\n y_pred = qres.x\n # Log bandwidth in kb/s\n metrics['bandwidth'] = qres.bandwidth.mean()\n\n if self.is_training:\n d_losses: dict = {}\n if len(self.adv_losses) > 0 and torch.rand(1, generator=self.rng).item() <= 1 / self.cfg.adversarial.every:\n for adv_name, adversary in self.adv_losses.items():\n disc_loss = adversary.train_adv(y_pred, y)\n d_losses[f'd_{adv_name}'] = disc_loss\n metrics['d_loss'] = torch.sum(torch.stack(list(d_losses.values())))\n metrics.update(d_losses)\n\n balanced_losses: dict = {}\n other_losses: dict = {}\n\n # penalty from quantization\n if qres.penalty is not None and qres.penalty.requires_grad:\n other_losses['penalty'] = qres.penalty # penalty term from the quantizer\n\n # adversarial losses\n for adv_name, adversary in self.adv_losses.items():\n adv_loss, feat_loss = adversary(y_pred, y)\n balanced_losses[f'adv_{adv_name}'] = adv_loss\n balanced_losses[f'feat_{adv_name}'] = feat_loss\n\n # auxiliary losses\n for loss_name, criterion in self.aux_losses.items():\n loss = criterion(y_pred, y)\n balanced_losses[loss_name] = loss\n\n # weighted losses\n metrics.update(balanced_losses)\n metrics.update(other_losses)\n metrics.update(qres.metrics)\n\n if self.is_training:\n # backprop losses that are not handled by balancer\n other_loss = torch.tensor(0., device=self.device)\n if 'penalty' in other_losses:\n other_loss += other_losses['penalty']\n if other_loss.requires_grad:\n other_loss.backward(retain_graph=True)\n ratio1 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio1, torch.Tensor)\n metrics['ratio1'] = ratio1.sqrt()\n\n # balancer losses backward, returns effective training loss\n # with effective weights at the current batch.\n metrics['g_loss'] = self.balancer.backward(balanced_losses, y_pred)\n # add metrics corresponding to weight ratios\n metrics.update(self.balancer.metrics)\n ratio2 = sum(p.grad.data.norm(p=2).pow(2)\n for p in self.model.parameters() if p.grad is not None)\n assert isinstance(ratio2, torch.Tensor)\n metrics['ratio2'] = ratio2.sqrt()\n\n # optim\n flashy.distrib.sync_model(self.model)\n if self.cfg.optim.max_norm:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.cfg.optim.max_norm\n )\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n # informative losses only\n info_losses: dict = {}\n with torch.no_grad():\n for loss_name, criterion in self.info_losses.items():\n loss = criterion(y_pred, y)\n info_losses[loss_name] = loss\n\n metrics.update(info_losses)\n\n # aggregated GAN losses: this is useful to report adv and feat across different adversarial loss setups\n adv_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('adv')]\n if len(adv_losses) > 0:\n metrics['adv'] = torch.sum(torch.stack(adv_losses))\n feat_losses = [loss for loss_name, loss in metrics.items() if loss_name.startswith('feat')]\n if len(feat_losses) > 0:\n metrics['feat'] = torch.sum(torch.stack(feat_losses))\n\n return metrics\n\n def run_epoch(self):\n # reset random seed at the beginning of the epoch\n self.rng = torch.Generator()\n self.rng.manual_seed(1234 + self.epoch)\n # run epoch\n super().run_epoch()\n\n def evaluate(self):\n \"\"\"Evaluate stage. Runs audio reconstruction evaluation.\"\"\"\n self.model.eval()\n evaluate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['evaluate']\n updates = len(loader)\n lp = self.log_progress(f'{evaluate_stage_name} inference', loader, total=updates, updates=self.log_updates)\n average = flashy.averager()\n\n pendings = []\n ctx = multiprocessing.get_context('spawn')\n with get_pool_executor(self.cfg.evaluate.num_workers, mp_context=ctx) as pool:\n for idx, batch in enumerate(lp):\n x = batch.to(self.device)\n with torch.no_grad():\n qres = self.model(x)\n\n y_pred = qres.x.cpu()\n y = batch.cpu() # should already be on CPU but just in case\n pendings.append(pool.submit(evaluate_audio_reconstruction, y_pred, y, self.cfg))\n\n metrics_lp = self.log_progress(f'{evaluate_stage_name} metrics', pendings, updates=self.log_updates)\n for pending in metrics_lp:\n metrics = pending.result()\n metrics = average(metrics)\n\n metrics = flashy.distrib.average_metrics(metrics, len(loader))\n return metrics\n\n def generate(self):\n \"\"\"Generate stage.\"\"\"\n self.model.eval()\n sample_manager = SampleManager(self.xp, map_reference_to_sample_id=True)\n generate_stage_name = str(self.current_stage)\n\n loader = self.dataloaders['generate']\n updates = len(loader)\n lp = self.log_progress(generate_stage_name, loader, total=updates, updates=self.log_updates)\n\n for batch in lp:\n reference, _ = batch\n reference = reference.to(self.device)\n with torch.no_grad():\n qres = self.model(reference)\n assert isinstance(qres, quantization.QuantizedResult)\n\n reference = reference.cpu()\n estimate = qres.x.cpu()\n sample_manager.add_samples(estimate, self.epoch, ground_truth_wavs=reference)\n\n flashy.distrib.barrier()\n\n def load_from_pretrained(self, name: str) -> dict:\n model = models.CompressionModel.get_pretrained(name)\n if isinstance(model, models.DAC):\n raise RuntimeError(\"Cannot fine tune a DAC model.\")\n elif isinstance(model, models.HFEncodecCompressionModel):\n self.logger.warning('Trying to automatically convert a HuggingFace model '\n 'to AudioCraft, this might fail!')\n state = model.model.state_dict()\n new_state = {}\n for k, v in state.items():\n if k.startswith('decoder.layers') and '.conv.' in k and '.block.' not in k:\n # We need to determine if this a convtr or a regular conv.\n layer = int(k.split('.')[2])\n if isinstance(model.model.decoder.layers[layer].conv, torch.nn.ConvTranspose1d):\n\n k = k.replace('.conv.', '.convtr.')\n k = k.replace('encoder.layers.', 'encoder.model.')\n k = k.replace('decoder.layers.', 'decoder.model.')\n k = k.replace('conv.', 'conv.conv.')\n k = k.replace('convtr.', 'convtr.convtr.')\n k = k.replace('quantizer.layers.', 'quantizer.vq.layers.')\n k = k.replace('.codebook.', '._codebook.')\n new_state[k] = v\n state = new_state\n elif isinstance(model, models.EncodecModel):\n state = model.state_dict()\n else:\n raise RuntimeError(f\"Cannot fine tune model type {type(model)}.\")\n return {\n 'best_state': {'model': state}\n }\n\n @staticmethod\n def model_from_checkpoint(checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a CompressionModel from a given checkpoint path or dora sig.\n This method is a convenient endpoint to load a CompressionModel to use in other solvers.\n\n Args:\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n This also supports pre-trained models by using a path of the form //pretrained/NAME.\n See `model_from_pretrained` for a list of supported pretrained models.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n checkpoint_path = str(checkpoint_path)\n if checkpoint_path.startswith('//pretrained/'):\n name = checkpoint_path.split('/', 3)[-1]\n return models.CompressionModel.get_pretrained(name, device)\n logger = logging.getLogger(__name__)\n logger.info(f\"Loading compression model from checkpoint: {checkpoint_path}\")\n _checkpoint_path = checkpoint.resolve_checkpoint_path(checkpoint_path, use_fsdp=False)\n assert _checkpoint_path is not None, f\"Could not resolve compression model checkpoint path: {checkpoint_path}\"\n state = checkpoint.load_checkpoint(_checkpoint_path)\n assert state is not None and 'xp.cfg' in state, f\"Could not load compression model from ckpt: {checkpoint_path}\"\n cfg = state['xp.cfg']\n cfg.device = device\n compression_model = models.builders.get_compression_model(cfg).to(device)\n assert compression_model.sample_rate == cfg.sample_rate, \"Compression model sample rate should match\"\n\n assert 'best_state' in state and state['best_state'] != {}\n assert 'exported' not in state, \"When loading an exported checkpoint, use the //pretrained/ prefix.\"\n compression_model.load_state_dict(state['best_state']['model'])\n compression_model.eval()\n logger.info(\"Compression model loaded!\")\n return compression_model\n\n @staticmethod\n def wrapped_model_from_checkpoint(cfg: omegaconf.DictConfig,\n checkpoint_path: tp.Union[Path, str],\n device: tp.Union[torch.device, str] = 'cpu') -> models.CompressionModel:\n \"\"\"Instantiate a wrapped CompressionModel from a given checkpoint path or dora sig.\n\n Args:\n cfg (omegaconf.DictConfig): Configuration to read from for wrapped mode.\n checkpoint_path (Path or str): Path to checkpoint or dora sig from where the checkpoint is resolved.\n use_ema (bool): Use EMA variant of the model instead of the actual model.\n device (torch.device or str): Device on which the model is loaded.\n \"\"\"\n compression_model = CompressionSolver.model_from_checkpoint(checkpoint_path, device)\n compression_model = models.builders.get_wrapped_compression_model(compression_model, cfg)\n return compression_model" }, { "identifier": "load_compression_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_compression_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_compression_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n if 'pretrained' in pkg:\n return CompressionModel.get_pretrained(pkg['pretrained'], device=device)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n model = builders.get_compression_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n return model" }, { "identifier": "load_lm_model", "path": "audiocraft/models/loaders.py", "snippet": "def load_lm_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):\n pkg = load_lm_model_ckpt(file_or_url_or_id, cache_dir=cache_dir)\n cfg = OmegaConf.create(pkg['xp.cfg'])\n cfg.device = str(device)\n if cfg.device == 'cpu':\n cfg.dtype = 'float32'\n else:\n cfg.dtype = 'float16'\n _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path')\n _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path')\n _delete_param(cfg, 'conditioners.args.merge_text_conditions_p')\n _delete_param(cfg, 'conditioners.args.drop_desc_p')\n model = builders.get_lm_model(cfg)\n model.load_state_dict(pkg['best_state'])\n model.eval()\n model.cfg = cfg\n return model" }, { "identifier": "audio_write", "path": "audiocraft/data/audio.py", "snippet": "def audio_write(stem_name: tp.Union[str, Path],\n wav: torch.Tensor, sample_rate: int,\n format: str = 'wav', mp3_rate: int = 320, ogg_rate: tp.Optional[int] = None,\n normalize: bool = True, strategy: str = 'peak', peak_clip_headroom_db: float = 1,\n rms_headroom_db: float = 18, loudness_headroom_db: float = 14,\n loudness_compressor: bool = False,\n log_clipping: bool = True, make_parent_dir: bool = True,\n add_suffix: bool = True) -> Path:\n \"\"\"Convenience function for saving audio to disk. Returns the filename the audio was written to.\n\n Args:\n stem_name (str or Path): Filename without extension which will be added automatically.\n wav (torch.Tensor): Audio data to save.\n sample_rate (int): Sample rate of audio data.\n format (str): Either \"wav\", \"mp3\", \"ogg\", or \"flac\".\n mp3_rate (int): kbps when using mp3s.\n ogg_rate (int): kbps when using ogg/vorbis. If not provided, let ffmpeg decide for itself.\n normalize (bool): if `True` (default), normalizes according to the prescribed\n strategy (see after). If `False`, the strategy is only used in case clipping\n would happen.\n strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak',\n i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square\n with extra headroom to avoid clipping. 'clip' just clips.\n peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy.\n rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger\n than the `peak_clip` one to avoid further clipping.\n loudness_headroom_db (float): Target loudness for loudness normalization.\n loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'.\n when strategy is 'loudness' log_clipping (bool): If True, basic logging on stderr when clipping still\n occurs despite strategy (only for 'rms').\n make_parent_dir (bool): Make parent directory if it doesn't exist.\n Returns:\n Path: Path of the saved audio.\n \"\"\"\n assert wav.dtype.is_floating_point, \"wav is not floating point\"\n if wav.dim() == 1:\n wav = wav[None]\n elif wav.dim() > 2:\n raise ValueError(\"Input wav should be at most 2 dimension.\")\n assert wav.isfinite().all()\n wav = normalize_audio(wav, normalize, strategy, peak_clip_headroom_db,\n rms_headroom_db, loudness_headroom_db, loudness_compressor,\n log_clipping=log_clipping, sample_rate=sample_rate,\n stem_name=str(stem_name))\n if format == 'mp3':\n suffix = '.mp3'\n flags = ['-f', 'mp3', '-c:a', 'libmp3lame', '-b:a', f'{mp3_rate}k']\n elif format == 'wav':\n suffix = '.wav'\n flags = ['-f', 'wav', '-c:a', 'pcm_s16le']\n elif format == 'ogg':\n suffix = '.ogg'\n flags = ['-f', 'ogg', '-c:a', 'libvorbis']\n if ogg_rate is not None:\n flags += ['-b:a', f'{ogg_rate}k']\n elif format == 'flac':\n suffix = '.flac'\n flags = ['-f', 'flac']\n else:\n raise RuntimeError(f\"Invalid format {format}. Only wav or mp3 are supported.\")\n if not add_suffix:\n suffix = ''\n path = Path(str(stem_name) + suffix)\n if make_parent_dir:\n path.parent.mkdir(exist_ok=True, parents=True)\n try:\n _piping_to_ffmpeg(path, wav, sample_rate, flags)\n except Exception:\n if path.exists():\n # we do not want to leave half written files around.\n path.unlink()\n raise\n return path" }, { "identifier": "get_lm_model", "path": "audiocraft/models/builders.py", "snippet": "def get_lm_model(cfg: omegaconf.DictConfig) -> LMModel:\n \"\"\"Instantiate a transformer LM.\"\"\"\n if cfg.lm_model == 'transformer_lm':\n kwargs = dict_from_config(getattr(cfg, 'transformer_lm'))\n n_q = kwargs['n_q']\n q_modeling = kwargs.pop('q_modeling', None)\n codebooks_pattern_cfg = getattr(cfg, 'codebooks_pattern')\n attribute_dropout = dict_from_config(getattr(cfg, 'attribute_dropout'))\n cls_free_guidance = dict_from_config(getattr(cfg, 'classifier_free_guidance'))\n cfg_prob, cfg_coef = cls_free_guidance['training_dropout'], cls_free_guidance['inference_coef']\n fuser = get_condition_fuser(cfg)\n condition_provider = get_conditioner_provider(kwargs[\"dim\"], cfg).to(cfg.device)\n if len(fuser.fuse2cond['cross']) > 0: # enforce cross-att programmatically\n kwargs['cross_attention'] = True\n if codebooks_pattern_cfg.modeling is None:\n assert q_modeling is not None, \\\n \"LM model should either have a codebook pattern defined or transformer_lm.q_modeling\"\n codebooks_pattern_cfg = omegaconf.OmegaConf.create(\n {'modeling': q_modeling, 'delay': {'delays': list(range(n_q))}}\n )\n pattern_provider = get_codebooks_pattern_provider(n_q, codebooks_pattern_cfg)\n return LMModel(\n pattern_provider=pattern_provider,\n condition_provider=condition_provider,\n fuser=fuser,\n cfg_dropout=cfg_prob,\n cfg_coef=cfg_coef,\n attribute_dropout=attribute_dropout,\n dtype=getattr(torch, cfg.dtype),\n device=cfg.device,\n **kwargs\n ).to(cfg.device)\n else:\n raise KeyError(f\"Unexpected LM model {cfg.lm_model}\")" } ]
import os import random import torchaudio import typing as tp import numpy as np import torch import subprocess from typing import Optional from cog import BasePredictor, Input, Path from audiocraft.solvers.compression import CompressionSolver from audiocraft.models import MusicGen, MultiBandDiffusion from audiocraft.solvers.compression import CompressionSolver from audiocraft.models.loaders import ( load_compression_model, load_lm_model, ) from audiocraft.data.audio import audio_write from audiocraft.models.builders import get_lm_model from omegaconf import OmegaConf
17,716
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p') lm = get_lm_model(loaded['xp.cfg']) lm.load_state_dict(loaded['model']) lm.eval() lm.cfg = cfg compression_model = CompressionSolver.model_from_checkpoint(cfg.compression_model_checkpoint, device=device)
# Prediction interface for Cog ⚙️ # https://github.com/replicate/cog/blob/main/docs/python.md # We need to set `TRANSFORMERS_CACHE` before any imports, which is why this is up here. MODEL_PATH = "/src/models/" os.environ["TRANSFORMERS_CACHE"] = MODEL_PATH os.environ["TORCH_HOME"] = MODEL_PATH # Model specific imports def _delete_param(cfg, full_name: str): parts = full_name.split('.') for part in parts[:-1]: if part in cfg: cfg = cfg[part] else: return OmegaConf.set_struct(cfg, False) if parts[-1] in cfg: del cfg[parts[-1]] OmegaConf.set_struct(cfg, True) def load_ckpt(path, device, url=False): if url: loaded = torch.hub.load_state_dict_from_url(str(path)) else: loaded = torch.load(str(path)) cfg = OmegaConf.create(loaded['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.dtype = 'float32' else: cfg.dtype = 'float16' _delete_param(cfg, 'conditioners.self_wav.chroma_chord.cache_path') _delete_param(cfg, 'conditioners.self_wav.chroma_stem.cache_path') _delete_param(cfg, 'conditioners.args.merge_text_conditions_p') _delete_param(cfg, 'conditioners.args.drop_desc_p') lm = get_lm_model(loaded['xp.cfg']) lm.load_state_dict(loaded['model']) lm.eval() lm.cfg = cfg compression_model = CompressionSolver.model_from_checkpoint(cfg.compression_model_checkpoint, device=device)
return MusicGen(f"{os.getenv('COG_USERNAME')}/musicgen-chord", compression_model, lm)
2
2023-10-09 09:52:24+00:00
24k
zhijie-group/LOVECon
test_lovecon.py
[ { "identifier": "UNetPseudo3DConditionModel", "path": "video_diffusion/models/unet_3d_condition.py", "snippet": "class UNetPseudo3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in_channels: int = 4,\n out_channels: int = 4,\n center_input_sample: bool = False,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"DownBlockPseudo3D\",\n ),\n mid_block_type: str = \"UNetMidBlockPseudo3DCrossAttn\",\n up_block_types: Tuple[str] = (\n \"UpBlockPseudo3D\",\n \"CrossAttnUpBlockPseudo3D\",\n \"CrossAttnUpBlockPseudo3D\",\n \"CrossAttnUpBlockPseudo3D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: int = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n dual_cross_attention: bool = False,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n **kwargs\n ):\n super().__init__()\n\n self.sample_size = sample_size\n time_embed_dim = block_out_channels[0] * 4\n if 'temporal_downsample' in kwargs and kwargs['temporal_downsample'] is True:\n kwargs['temporal_downsample_time'] = 3\n self.temporal_downsample_time = kwargs.get('temporal_downsample_time', 0)\n \n # input\n self.conv_in = PseudoConv3d(in_channels, block_out_channels[0], \n kernel_size=3, padding=(1, 1), model_config=kwargs)\n\n # time\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n self.down_blocks = nn.ModuleList([])\n self.mid_block = None\n self.up_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n kwargs_copy=copy.deepcopy(kwargs)\n temporal_downsample_i = ((i >= (len(down_block_types)-self.temporal_downsample_time))\n and (not is_final_block))\n kwargs_copy.update({'temporal_downsample': temporal_downsample_i} )\n # kwargs_copy.update({'SparseCausalAttention_index': temporal_downsample_i} )\n if temporal_downsample_i:\n print(f'Initialize model temporal downsample at layer {i}')\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n model_config=kwargs_copy\n )\n self.down_blocks.append(down_block)\n # mid\n if mid_block_type == \"UNetMidBlockPseudo3DCrossAttn\":\n self.mid_block = UNetMidBlockPseudo3DCrossAttn(\n in_channels=block_out_channels[-1],\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n model_config=kwargs\n )\n else:\n raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n\n # count how many layers upsample the images\n self.num_upsamplers = 0\n\n # up\n reversed_block_out_channels = list(reversed(block_out_channels))\n reversed_attention_head_dim = list(reversed(attention_head_dim))\n only_cross_attention = list(reversed(only_cross_attention))\n output_channel = reversed_block_out_channels[0]\n for i, up_block_type in enumerate(up_block_types):\n is_final_block = i == len(block_out_channels) - 1\n\n prev_output_channel = output_channel\n output_channel = reversed_block_out_channels[i]\n input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n # add upsample block for all BUT final layer\n if not is_final_block:\n add_upsample = True\n self.num_upsamplers += 1\n else:\n add_upsample = False\n \n kwargs_copy=copy.deepcopy(kwargs)\n kwargs_copy.update({'temporal_downsample': \n i < (self.temporal_downsample_time-1)})\n if i < (self.temporal_downsample_time-1):\n print(f'Initialize model temporal updample at layer {i}')\n\n up_block = get_up_block(\n up_block_type,\n num_layers=layers_per_block + 1,\n in_channels=input_channel,\n out_channels=output_channel,\n prev_output_channel=prev_output_channel,\n temb_channels=time_embed_dim,\n add_upsample=add_upsample,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=reversed_attention_head_dim[i],\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n model_config=kwargs_copy\n )\n self.up_blocks.append(up_block)\n prev_output_channel = output_channel\n\n # out\n self.conv_norm_out = nn.GroupNorm(\n num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps\n )\n self.conv_act = nn.SiLU()\n self.conv_out = PseudoConv3d(block_out_channels[0], out_channels, \n kernel_size=3, padding=1, model_config=kwargs)\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = (\n num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n )\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(\n module,\n (CrossAttnDownBlockPseudo3D, DownBlockPseudo3D, CrossAttnUpBlockPseudo3D, UpBlockPseudo3D),\n ):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n class_labels: Optional[torch.Tensor] = None, # None\n attention_mask: Optional[torch.Tensor] = None, # None\n down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n mid_block_additional_residual: Optional[torch.Tensor] = None,\n return_dict: bool = True,\n ) -> Union[UNetPseudo3DConditionOutput, Tuple]:\n # By default samples have to be AT least a multiple of the overall upsampling factor.\n # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).\n # However, the upsampling interpolation output size can be forced to fit any upsampling size\n # on the fly if necessary.\n default_overall_up_factor = 2**self.num_upsamplers\n\n # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n forward_upsample_size = False\n upsample_size = None\n\n if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):\n logger.info(\"Forward upsample size to force interpolation output size.\")\n forward_upsample_size = True\n\n # prepare attention_mask\n if attention_mask is not None: # None\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 0. center input if necessary\n if self.config.center_input_sample: # False\n sample = 2 * sample - 1.0\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n emb = self.time_embedding(t_emb)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n if down_block_additional_residuals is not None:\n new_down_block_res_samples = ()\n\n for down_block_res_sample, down_block_additional_residual in zip(\n down_block_res_samples, down_block_additional_residuals\n ):\n new_down_block_res_samples += (down_block_res_sample + down_block_additional_residual,)\n\n down_block_res_samples = new_down_block_res_samples\n\n # 4. mid\n sample = self.mid_block(\n sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n # for i in down_block_res_samples: print(i.shape) \n # torch.Size([1, 320, 16, 64, 64])\n # torch.Size([1, 320, 16, 64, 64])\n # torch.Size([1, 320, 16, 64, 64])\n # torch.Size([1, 320, 8, 32, 32])\n # torch.Size([1, 640, 8, 32, 32])\n # torch.Size([1, 640, 8, 32, 32])\n # torch.Size([1, 640, 4, 16, 16])\n # torch.Size([1, 1280, 4, 16, 16])\n # torch.Size([1, 1280, 4, 16, 16])\n # torch.Size([1, 1280, 2, 8, 8])\n # torch.Size([1, 1280, 2, 8, 8])\n # torch.Size([1, 1280, 2, 8, 8])\n if mid_block_additional_residual is not None:\n sample = sample + mid_block_additional_residual\n \n # 5. up\n for i, upsample_block in enumerate(self.up_blocks):\n is_final_block = i == len(self.up_blocks) - 1\n\n res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n # if we have not reached the final block and need to forward the\n # upsample size, we do it here\n if not is_final_block and forward_upsample_size:\n upsample_size = down_block_res_samples[-1].shape[2:]\n\n if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n encoder_hidden_states=encoder_hidden_states,\n upsample_size=upsample_size,\n attention_mask=attention_mask,\n )\n else:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n upsample_size=upsample_size,\n )\n # 6. post-process\n sample = self.conv_norm_out(sample)\n sample = self.conv_act(sample)\n sample = self.conv_out(sample)\n\n if not return_dict:\n return (sample,)\n\n return UNetPseudo3DConditionOutput(sample=sample)\n\n @classmethod\n def from_2d_model(cls, model_path, model_config):\n config_path = os.path.join(model_path, \"config.json\")\n if not os.path.isfile(config_path):\n raise RuntimeError(f\"{config_path} does not exist\")\n with open(config_path, \"r\") as f:\n config = json.load(f)\n\n config.pop(\"_class_name\")\n config.pop(\"_diffusers_version\")\n\n block_replacer = {\n \"CrossAttnDownBlock2D\": \"CrossAttnDownBlockPseudo3D\",\n \"DownBlock2D\": \"DownBlockPseudo3D\",\n \"UpBlock2D\": \"UpBlockPseudo3D\",\n \"CrossAttnUpBlock2D\": \"CrossAttnUpBlockPseudo3D\",\n }\n\n def convert_2d_to_3d_block(block):\n return block_replacer[block] if block in block_replacer else block\n\n config[\"down_block_types\"] = [\n convert_2d_to_3d_block(block) for block in config[\"down_block_types\"]\n ]\n config[\"up_block_types\"] = [convert_2d_to_3d_block(block) for block in config[\"up_block_types\"]]\n if model_config is not None:\n config.update(model_config)\n\n model = cls(**config)\n\n state_dict_path_condidates = glob.glob(os.path.join(model_path, \"*.bin\"))\n if state_dict_path_condidates:\n state_dict = torch.load(state_dict_path_condidates[0], map_location=\"cpu\")\n model.load_2d_state_dict(state_dict=state_dict)\n\n return model\n\n def load_2d_state_dict(self, state_dict, **kwargs):\n state_dict_3d = self.state_dict()\n\n for k, v in state_dict.items():\n if k not in state_dict_3d:\n raise KeyError(f\"2d state_dict key {k} does not exist in 3d model\")\n elif v.shape != state_dict_3d[k].shape:\n raise ValueError(f\"state_dict shape mismatch, 2d {v.shape}, 3d {state_dict_3d[k].shape}\")\n\n for k, v in state_dict_3d.items():\n if \"_temporal\" in k:\n continue\n if k not in state_dict:\n raise KeyError(f\"3d state_dict key {k} does not exist in 2d model\")\n\n state_dict_3d.update(state_dict)\n self.load_state_dict(state_dict_3d, **kwargs)" }, { "identifier": "ControlNetPseudo3DModel", "path": "video_diffusion/models/controlnet_3d_condition.py", "snippet": "class ControlNetPseudo3DModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n in_channels: int = 4,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"DownBlockPseudo3D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: Optional[int] = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n projection_class_embeddings_input_dim: Optional[int] = None,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n **kwargs\n ):\n super().__init__()\n\n if 'temporal_downsample' in kwargs and kwargs['temporal_downsample'] is True:\n kwargs['temporal_downsample_time'] = 3\n self.temporal_downsample_time = kwargs.get('temporal_downsample_time', 0)\n\n # Check inputs\n if len(block_out_channels) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n )\n\n # input\n conv_in_kernel = 3\n conv_in_padding = (conv_in_kernel - 1) // 2\n # self.conv_in = PseudoConv3d(\n # in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n # )\n self.conv_in = InflatedConv3d(\n in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n # time\n time_embed_dim = block_out_channels[0] * 4\n\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(\n timestep_input_dim,\n time_embed_dim,\n act_fn=act_fn,\n )\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n elif class_embed_type == \"projection\":\n if projection_class_embeddings_input_dim is None:\n raise ValueError(\n \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n )\n # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n # 2. it projects from an arbitrary input dimension.\n #\n # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n # control net conditioning embedding\n self.controlnet_cond_embedding = ControlNetPseudo3DConditioningEmbedding(\n conditioning_embedding_channels=block_out_channels[0],\n block_out_channels=conditioning_embedding_out_channels,\n )\n\n self.down_blocks = nn.ModuleList([])\n self.controlnet_down_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n\n # controlnet_block = PseudoConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(output_channel, output_channel, kernel_size=1)\n\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n #non temperal \n # kwargs_copy=copy.deepcopy(kwargs)\n # temporal_downsample_i = ((i >= (len(down_block_types)-self.temporal_downsample_time))\n # and (not is_final_block))\n # kwargs_copy.update({'temporal_downsample': temporal_downsample_i} )\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n # model_config=kwargs_copy\n )\n self.down_blocks.append(down_block)\n\n for _ in range(layers_per_block):\n # controlnet_block = PseudoConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n if not is_final_block:\n # controlnet_block = PseudoConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n # mid\n mid_block_channel = block_out_channels[-1]\n\n # controlnet_block = PseudoConv3d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = InflatedConv3d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_mid_block = controlnet_block\n\n self.mid_block = UNetMidBlockPseudo3DCrossAttn(\n in_channels=mid_block_channel,\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n # model_config=kwargs\n )\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlockPseudo3D, DownBlockPseudo3D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n controlnet_cond: torch.FloatTensor,\n class_labels: Optional[torch.Tensor] = None,\n timestep_cond: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n return_dict: bool = True,\n ) -> Union[ControlNetPseudo3DOutput, Tuple]:\n # check channel order\n channel_order = self.config.controlnet_conditioning_channel_order\n if channel_order == \"rgb\":\n # in rgb order by default\n ...\n elif channel_order == \"bgr\":\n controlnet_cond = torch.flip(controlnet_cond, dims=[1])\n else:\n raise ValueError(f\"unknown `controlnet_conditioning_channel_order`: {channel_order}\")\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n \n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n\n emb = self.time_embedding(t_emb)\n\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)\n # print(sample.shape,controlnet_cond.shape)\n sample += controlnet_cond\n \n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n # 4. mid\n if self.mid_block is not None:\n sample = self.mid_block(\n sample,\n emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n\n # 5. Control net blocks\n\n controlnet_down_block_res_samples = ()\n\n for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):\n down_block_res_sample = controlnet_block(down_block_res_sample)\n controlnet_down_block_res_samples += (down_block_res_sample,)\n\n down_block_res_samples = controlnet_down_block_res_samples\n\n mid_block_res_sample = self.controlnet_mid_block(sample)\n\n if not return_dict:\n return (down_block_res_samples, mid_block_res_sample)\n\n return ControlNetPseudo3DOutput(\n down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample\n )\n\n @classmethod\n def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, control_temporal_idx=None, control_mid_temporal=None):\n if subfolder is not None:\n pretrained_model_path = os.path.join(pretrained_model_path, subfolder)\n\n config_file = os.path.join(pretrained_model_path, 'config.json')\n if not os.path.isfile(config_file):\n raise RuntimeError(f\"{config_file} does not exist\")\n with open(config_file, \"r\") as f:\n config = json.load(f)\n config[\"_class_name\"] = cls.__name__\n config[\"down_block_types\"] = [\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"CrossAttnDownBlockPseudo3D\",\n \"DownBlockPseudo3D\"\n ]\n # config[\"control_temporal_idx\"] = control_temporal_idx\n # config[\"control_mid_temporal\"] = control_mid_temporal\n\n from diffusers.utils import WEIGHTS_NAME\n model = cls.from_config(config)\n model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)\n if not os.path.isfile(model_file):\n raise RuntimeError(f\"{model_file} does not exist\")\n\n state_dict = torch.load(model_file, map_location=\"cpu\")\n for k, v in model.state_dict().items():\n if '_temp.' in k:\n if 'conv' in k:\n state_dict.update({k: v})\n else:\n copyk = k\n copyk = copyk.replace('_temp.', '1.')\n state_dict.update({k: state_dict[copyk]})\n model.load_state_dict(state_dict)\n\n return model\n\n\n @classmethod\n def from_2d_model(cls, model_path, model_config):\n config_path = os.path.join(model_path, \"config.json\")\n if not os.path.isfile(config_path):\n raise RuntimeError(f\"{config_path} does not exist\")\n with open(config_path, \"r\") as f:\n config = json.load(f)\n\n config.pop(\"_class_name\")\n config.pop(\"_diffusers_version\")\n\n block_replacer = {\n \"CrossAttnDownBlock2D\": \"CrossAttnDownBlockPseudo3D\",\n \"DownBlock2D\": \"DownBlockPseudo3D\",\n \"UpBlock2D\": \"UpBlockPseudo3D\",\n \"CrossAttnUpBlock2D\": \"CrossAttnUpBlockPseudo3D\",\n }\n\n def convert_2d_to_3d_block(block):\n return block_replacer[block] if block in block_replacer else block\n\n config[\"down_block_types\"] = [\n convert_2d_to_3d_block(block) for block in config[\"down_block_types\"]\n ]\n \n if model_config is not None:\n config.update(model_config)\n\n model = cls(**config)\n\n state_dict_path_condidates = glob.glob(os.path.join(model_path, \"*.bin\"))\n if state_dict_path_condidates:\n state_dict = torch.load(state_dict_path_condidates[0], map_location=\"cpu\")\n model.load_2d_state_dict(state_dict=state_dict)\n\n return model\n\n def load_2d_state_dict(self, state_dict, **kwargs):\n state_dict_3d = self.state_dict()\n\n for k, v in state_dict.items():\n if k not in state_dict_3d:\n raise KeyError(f\"2d state_dict key {k} does not exist in 3d model\")\n elif v.shape != state_dict_3d[k].shape:\n raise ValueError(f\"state_dict shape mismatch, 2d {v.shape}, 3d {state_dict_3d[k].shape}\")\n\n for k, v in state_dict_3d.items():\n if \"_temporal\" in k:\n continue\n if k not in state_dict:\n raise KeyError(f\"3d state_dict key {k} does not exist in 2d model\")\n\n state_dict_3d.update(state_dict)\n self.load_state_dict(state_dict_3d, **kwargs)" }, { "identifier": "ImageSequenceDataset", "path": "video_diffusion/data/dataset.py", "snippet": "class ImageSequenceDataset(Dataset):\n def __init__(\n self,\n path: str,\n prompt_ids: torch.Tensor,\n prompt: str,\n start_sample_frame: int=0,\n n_sample_frame: int = 8,\n sampling_rate: int = 1,\n stride: int = -1, # only used during tuning to sample a long video\n image_mode: str = \"RGB\",\n image_size: int = 512,\n crop: str = \"center\",\n \n class_data_root: str = None,\n class_prompt_ids: torch.Tensor = None,\n \n offset: dict = {\n \"left\": 0,\n \"right\": 0,\n \"top\": 0,\n \"bottom\": 0\n },\n **args\n \n ):\n self.path = path\n self.images = self.get_image_list(path)\n self.n_images = len(self.images)\n self.offset = offset\n self.start_sample_frame = start_sample_frame\n if n_sample_frame < 0:\n n_sample_frame = len(self.images) \n self.n_sample_frame = n_sample_frame\n # local sampling rate from the video\n self.sampling_rate = sampling_rate\n\n self.sequence_length = (n_sample_frame - 1) * sampling_rate + 1\n if self.n_images < self.sequence_length:\n raise ValueError(f\"self.n_images {self.n_images } < self.sequence_length {self.sequence_length}: Required number of frames {self.sequence_length} larger than total frames in the dataset {self.n_images }\")\n \n # During tuning if video is too long, we sample the long video every self.stride globally\n self.stride = stride if stride > 0 else (self.n_images+1)\n self.video_len = (self.n_images - self.sequence_length) // self.stride + 1\n\n self.image_mode = image_mode\n self.image_size = image_size\n crop_methods = {\n \"center\": center_crop,\n \"random\": random_crop,\n }\n if crop not in crop_methods:\n raise ValueError\n self.crop = crop_methods[crop]\n\n self.prompt = prompt\n self.prompt_ids = prompt_ids\n # Negative prompt for regularization to avoid overfitting during one-shot tuning\n if class_data_root is not None:\n self.class_data_root = Path(class_data_root)\n self.class_images_path = sorted(list(self.class_data_root.iterdir()))\n self.num_class_images = len(self.class_images_path)\n self.class_prompt_ids = class_prompt_ids\n \n \n def __len__(self):\n max_len = (self.n_images - self.sequence_length) // self.stride + 1\n \n if hasattr(self, 'num_class_images'):\n max_len = max(max_len, self.num_class_images)\n \n return max_len\n\n def __getitem__(self, index):\n return_batch = {}\n frame_indices = self.get_frame_indices(index%self.video_len)\n frames = [self.load_frame(i) for i in frame_indices]\n frames = self.transform(frames)\n\n return_batch.update(\n {\n \"images\": frames,\n \"prompt_ids\": self.prompt_ids,\n }\n )\n\n if hasattr(self, 'class_data_root'):\n class_index = index % (self.num_class_images - self.n_sample_frame)\n class_indices = self.get_class_indices(class_index) \n frames = [self.load_class_frame(i) for i in class_indices]\n return_batch[\"class_images\"] = self.tensorize_frames(frames)\n return_batch[\"class_prompt_ids\"] = self.class_prompt_ids\n return return_batch\n \n def transform(self, frames):\n frames = self.tensorize_frames(frames)\n frames = offset_crop(frames, **self.offset)\n frames = short_size_scale(frames, size=self.image_size)\n frames = self.crop(frames, height=self.image_size, width=self.image_size)\n return frames\n\n @staticmethod\n def tensorize_frames(frames):\n frames = rearrange(np.stack(frames), \"f h w c -> c f h w\")\n return torch.from_numpy(frames).div(255) * 2 - 1\n\n def load_frame(self, index):\n image_path = os.path.join(self.path, self.images[index])\n return Image.open(image_path).convert(self.image_mode)\n\n def load_class_frame(self, index):\n image_path = self.class_images_path[index]\n return Image.open(image_path).convert(self.image_mode)\n\n def get_frame_indices(self, index):\n if self.start_sample_frame is not None:\n frame_start = self.start_sample_frame + self.stride * index\n else:\n frame_start = self.stride * index\n return (frame_start + i * self.sampling_rate for i in range(self.n_sample_frame))\n\n def get_class_indices(self, index):\n frame_start = index\n return (frame_start + i for i in range(self.n_sample_frame))\n\n @staticmethod\n def get_image_list(path):\n images = []\n for file in sorted(os.listdir(path)):\n if file.endswith(IMAGE_EXTENSION):\n images.append(file)\n return images" }, { "identifier": "get_time_string", "path": "video_diffusion/common/util.py", "snippet": "def get_time_string() -> str:\n x = datetime.datetime.now()\n return f\"{(x.year - 2000):02d}{x.month:02d}{x.day:02d}-{x.hour:02d}{x.minute:02d}{x.second:02d}\"" }, { "identifier": "get_function_args", "path": "video_diffusion/common/util.py", "snippet": "def get_function_args() -> Dict:\n frame = sys._getframe(1)\n args, _, _, values = inspect.getargvalues(frame)\n args_dict = copy.deepcopy({arg: values[arg] for arg in args})\n\n return args_dict" }, { "identifier": "get_logger_config_path", "path": "video_diffusion/common/logger.py", "snippet": "def get_logger_config_path(logdir):\n # accelerate handles the logger in multiprocessing\n logger = get_logger(__name__)\n logging.basicConfig(\n level=logging.INFO, \n format='%(asctime)s:%(levelname)s : %(message)s', \n datefmt='%a, %d %b %Y %H:%M:%S', \n filename=os.path.join(logdir, 'log.log'),\n filemode='w')\n chlr = logging.StreamHandler()\n chlr.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s : %(message)s'))\n logger.logger.addHandler(chlr)\n return logger" }, { "identifier": "log_train_samples", "path": "video_diffusion/common/image_util.py", "snippet": "def log_train_samples(\n train_dataloader,\n save_path,\n num_batch: int = 4,\n):\n train_samples = []\n for idx, batch in enumerate(train_dataloader):\n if idx >= num_batch:\n break\n train_samples.append(batch[\"images\"])\n\n train_samples = torch.cat(train_samples).numpy()\n train_samples = rearrange(train_samples, \"b c f h w -> b f h w c\")\n train_samples = (train_samples * 0.5 + 0.5).clip(0, 1)\n train_samples = numpy_batch_seq_to_pil(train_samples)\n train_samples = [make_grid(images, cols=int(np.ceil(np.sqrt(len(train_samples))))) for images in zip(*train_samples)]\n # save_images_as_gif(train_samples, save_path)\n save_gif_mp4_folder_type(train_samples, save_path)" }, { "identifier": "instantiate_from_config", "path": "video_diffusion/common/instantiate_from_config.py", "snippet": "def instantiate_from_config(config:dict, **args_from_code):\n \"\"\"Util funciton to decompose differenct modules using config\n\n Args:\n config (dict): with key of \"target\" and \"params\", better from yaml\n static \n args_from_code: additional con\n\n\n Returns:\n a validation/training pipeline, a module\n \"\"\"\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()), **args_from_code)" }, { "identifier": "P2pSampleLogger", "path": "video_diffusion/pipelines/p2p_validation_loop_controlnet.py", "snippet": "class P2pSampleLogger:\n def __init__(\n self,\n editing_prompts: List[str],\n clip_length: int,\n logdir: str,\n subdir: str = \"sample\",\n num_samples_per_prompt: int = 1,\n sample_seeds: List[int] = None,\n num_inference_steps: int = 20,\n guidance_scale: float = 7,\n strength: float = None,\n annotate: bool = False,\n annotate_size: int = 15,\n use_make_grid: bool = True,\n grid_column_size: int = 2,\n prompt2prompt_edit: bool=False,\n p2p_config: dict = None,\n use_inversion_attention: bool = True,\n source_prompt: str = None,\n traverse_p2p_config: bool = False,\n **args\n ) -> None:\n self.editing_prompts = editing_prompts\n self.clip_length = clip_length\n self.guidance_scale = guidance_scale\n self.num_inference_steps = num_inference_steps\n self.strength = strength\n\n if sample_seeds is None:\n max_num_samples_per_prompt = int(1e5)\n if num_samples_per_prompt > max_num_samples_per_prompt:\n raise ValueError\n sample_seeds = torch.randint(0, max_num_samples_per_prompt, (num_samples_per_prompt,))\n sample_seeds = sorted(sample_seeds.numpy().tolist())\n self.sample_seeds = sample_seeds\n\n self.logdir = os.path.join(logdir, subdir)\n os.makedirs(self.logdir)\n\n self.annotate = annotate\n self.annotate_size = annotate_size\n self.make_grid = use_make_grid\n self.grid_column_size = grid_column_size\n self.prompt2prompt_edit = prompt2prompt_edit\n self.p2p_config = p2p_config\n self.use_inversion_attention = use_inversion_attention\n self.source_prompt = source_prompt\n self.traverse_p2p_config =traverse_p2p_config\n\n def log_sample_images(\n self, pipeline: DiffusionPipeline,\n device: torch.device, step: int,\n image: Union[torch.FloatTensor, PIL.Image.Image] = None,\n control_image: torch.FloatTensor = None,\n latents: torch.FloatTensor = None,\n mask:torch.FloatTensor = None,\n editing_type:str = \"attribute\",\n uncond_embeddings_list: List[torch.FloatTensor] = None,\n save_dir = None,\n duration = 100,\n fps = 10,\n use_interpolater = True\n ):\n torch.cuda.empty_cache()\n samples_all = []\n attention_all = []\n # handle input image\n if image is not None:\n input_pil_images = pipeline.numpy_to_pil(tensor_to_numpy(image))[0]\n if self.annotate :\n samples_all.append([\n annotate_image(image, \"input sequence\", font_size=self.annotate_size) for image in input_pil_images\n ])\n else:\n samples_all.append(input_pil_images)\n if isinstance(self.editing_prompts,str):\n self.editing_prompts = [self.editing_prompts]\n for idx, prompt in enumerate(tqdm(self.editing_prompts, desc=\"Generating sample images\")):\n # if self.prompt2prompt_edit:\n # if self.traverse_p2p_config:\n # p2p_config_now = copy.deepcopy(self.p2p_config[idx])\n # else:\n # p2p_config_now = copy.deepcopy(self.p2p_config[idx])\n\n # if idx == 0 and not self.use_inversion_attention:\n # edit_type = 'save'\n # p2p_config_now.update({'save_self_attention': True})\n # print('Reflash the attention map in pipeline')\n\n # else:\n # edit_type = 'swap'\n # p2p_config_now.update({'save_self_attention': False})\n\n # p2p_config_now.update({'use_inversion_attention': self.use_inversion_attention})\n # else:\n # edit_type = None\n\n input_prompt = prompt\n\n # generator = torch.Generator(device=device)\n # generator.manual_seed(seed)\n generator = None\n sequence = []\n window = 8\n window = min(window,self.clip_length)\n start_frame = 0\n end_frame = window\n patch_index = 0\n while start_frame < self.clip_length:\n torch.cuda.empty_cache()\n if patch_index == 0:\n sequence_return = pipeline(\n prompt=input_prompt,\n source_prompt = self.editing_prompts[0] if self.source_prompt is None else self.source_prompt,\n # edit_type = edit_type,\n image=image[[0] + [0] + list(range(start_frame,min(self.clip_length,end_frame))),], # torch.Size([8, 3, 512, 512])\n strength=self.strength,\n generator=generator,\n # window = 1,\n num_inference_steps=self.num_inference_steps,\n guidance_scale=self.guidance_scale,\n num_images_per_prompt=1,\n # used in null inversion\n editing_type = editing_type,\n latents = [timestep_latent[:, :,[0] + [0] + list(range(start_frame,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n mask = mask[:,:, [0] + [0] + list(range(start_frame, min(self.clip_length,end_frame))),] if mask is not None else None,\n # latents = [timestep_latent[:, :,list(range(start_frame,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n # mask = mask[:,:, list(range(start_frame, min(self.clip_length,end_frame))),] if mask is not None else None,\n uncond_embeddings_list = uncond_embeddings_list,\n save_path = save_dir,\n # **p2p_config_now,\n )\n else:\n sequence_return = pipeline(\n prompt=input_prompt,\n reference_global_latents = reference_global_latents,\n reference_latents = reference_latents,\n source_prompt = self.editing_prompts[0] if self.source_prompt is None else self.source_prompt,\n # edit_type = edit_type,\n image=image[[0] + list(range(start_frame - 1,min(self.clip_length,end_frame))),], # torch.Size([8, 3, 512, 512])\n strength=self.strength,\n generator=generator,\n # window = window,\n num_inference_steps=self.num_inference_steps,\n guidance_scale=self.guidance_scale,\n num_images_per_prompt=1,\n # used in null inversion\n editing_type = editing_type,\n latents = [timestep_latent[:, :,[0] + list(range(start_frame-1,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n mask = mask[:,:, [0] + list(range(start_frame-1, min(self.clip_length,end_frame))),] if mask is not None else None,\n # latents = [timestep_latent[:, :,list(range(start_frame,min(self.clip_length,end_frame))), :, :] for timestep_latent in latents],\n # mask = mask[:,:, list(range(start_frame, min(self.clip_length,end_frame))),] if mask is not None else None,\n uncond_embeddings_list = uncond_embeddings_list,\n save_path = save_dir,\n # **p2p_config_now,\n )\n start_frame = end_frame\n end_frame = end_frame + window\n if patch_index == 0:\n reference_global_latents = sequence_return['reference_global_latents']\n reference_latents = sequence_return['reference_latents']\n patch_index = patch_index + 1\n # if self.prompt2prompt_edit:\n # sequence_temp = sequence_return['sdimage_output'].images[0]\n # # attention_output = sequence_return['attention_output']\n # else:\n # sequence_temp = sequence_return.images[0]\n sequence_temp = sequence_return['sdimage_output'].images[0]\n sequence = sequence + sequence_temp\n torch.cuda.empty_cache()\n # sequence = torch.cat(sequence,dim = 2)\n\n if self.annotate:\n images = [\n annotate_image(image, prompt, font_size=self.annotate_size) for image in sequence\n ]\n else:\n images = sequence\n control_images = []\n for i in range(control_image.shape[2]):\n control_images.append(Image.fromarray((control_image[0,:,i]*255).cpu().numpy().transpose(1,2,0).astype(np.uint8)))\n #smoother start\n if use_interpolater:\n for i in range(len(images)):\n images[i] = np.array(images[i]).transpose(2,0,1)[None:]/255\n frames = torch.from_numpy(np.stack(images, axis= 0)).cuda()\n f, C, H, W = frames.shape\n ph = ((H - 1) // 32 + 1) * 32\n pw = ((W - 1) // 32 + 1) * 32\n padding = (0, pw - W, 0, ph - H)\n frames = F.pad(frames,padding)\n smoother = Model()\n smoother.load_model('RIFEModel', -1)\n print('using smoother')\n with torch.no_grad():\n for i in range(f - 2):\n img0 = frames[i:i+1].float()\n img1 = frames[i+2:i+3].float()\n mid = smoother.inference(img0,img1)\n mid_padded = F.pad(mid,padding)\n frames[i+1:i+2,] = (frames[i+1:i+2,] + mid_padded[None:])/2\n torch.cuda.empty_cache()\n images = []\n for i in range(len(frames)):\n images.append(Image.fromarray((frames[i] * 255).cpu().numpy().astype(np.uint8).transpose(1,2,0)))\n # smoother end\n if self.make_grid:\n samples_all.append(control_images)\n samples_all.append(images)\n # if self.prompt2prompt_edit:\n # if attention_output is not None:\n # attention_all.append(attention_output)\n\n save_path = os.path.join(self.logdir, f\"step_{step}_{idx}.gif\")\n save_gif_mp4_folder_type(images, save_path,duration = duration,fps = fps)\n\n # if self.prompt2prompt_edit:\n\n # if attention_output is not None:\n # save_gif_mp4_folder_type(attention_output, save_path.replace('.gif', 'atten.gif'),duration = duration,fps = fps)\n\n if self.make_grid:\n samples_all = [make_grid(images, cols=int(len(samples_all))) for images in zip(*samples_all)]\n save_path = os.path.join(self.logdir, f\"step_{step}.gif\")\n save_gif_mp4_folder_type(samples_all, save_path,duration = duration,fps = fps)\n if self.prompt2prompt_edit:\n if len(attention_all) > 0 :\n attention_all = [make_grid(images, cols=1) for images in zip(*attention_all)]\n if len(attention_all) > 0:\n save_gif_mp4_folder_type(attention_all, save_path.replace('.gif', 'atten.gif'),duration = duration,fps = fps)\n return samples_all" }, { "identifier": "get_control", "path": "annotator/util.py", "snippet": "def get_control(type):\n if type == 'canny':\n from .canny import CannyDetector\n apply_control = CannyDetector()\n elif type == 'openpose':\n from .openpose import OpenposeDetector\n apply_control = OpenposeDetector()\n elif type == 'depth' or type == 'normal':\n from .midas import MidasDetector\n apply_control = MidasDetector()\n elif type == 'hed':\n from .hed import HEDdetector\n apply_control = HEDdetector()\n elif type == 'scribble':\n apply_control = None\n elif type == 'seg':\n from .uniformer import UniformerDetector\n apply_control = UniformerDetector()\n elif type == 'mlsd':\n from .mlsd import MLSDdetector\n apply_control = MLSDdetector()\n else:\n raise TypeError(type)\n return apply_control" }, { "identifier": "DDIMInterpolationScheduler", "path": "video_diffusion/pipelines/DDIMInterpolationScheduler.py", "snippet": "class DDIMInterpolationScheduler(DDIMScheduler):\n \"\"\"\n Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising\n diffusion probabilistic models (DDPMs) with non-Markovian guidance.\n\n [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`\n function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.\n [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and\n [`~SchedulerMixin.from_pretrained`] functions.\n\n For more details, see the original paper: https://arxiv.org/abs/2010.02502\n\n Args:\n num_train_timesteps (`int`): number of diffusion steps used to train the model.\n beta_start (`float`): the starting `beta` value of inference.\n beta_end (`float`): the final `beta` value.\n beta_schedule (`str`):\n the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from\n `linear`, `scaled_linear`, or `squaredcos_cap_v2`.\n trained_betas (`np.ndarray`, optional):\n option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.\n clip_sample (`bool`, default `True`):\n option to clip predicted sample between -1 and 1 for numerical stability.\n set_alpha_to_one (`bool`, default `True`):\n each diffusion step uses the value of alphas product at that step and at the previous one. For the final\n step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,\n otherwise it uses the value of alpha at step 0.\n steps_offset (`int`, default `0`):\n an offset added to the inference steps. You can use a combination of `offset=1` and\n `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in\n stable diffusion.\n prediction_type (`str`, default `epsilon`, optional):\n prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion\n process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4\n https://imagen.research.google/video/paper.pdf)\n \"\"\"\n\n _compatibles = _COMPATIBLE_STABLE_DIFFUSION_SCHEDULERS.copy()\n _deprecated_kwargs = [\"predict_epsilon\"]\n order = 1\n\n def set_model(self,vae,interpolater):\n self.interpolater = interpolater\n self.vae = vae\n \n \n def decode_latents(self, latents):\n is_video = (latents.dim() == 5)\n b = latents.shape[0]\n latents = 1 / 0.18215 * latents\n \n if is_video:\n latents = rearrange(latents, \"b c f h w -> (b f) c h w\") # torch.Size([70, 4, 64, 64])\n\n latents_split = torch.split(latents, 16, dim=0)\n image = torch.cat([self.vae.decode(l).sample for l in latents_split], dim=0)\n \n # image_full = self.vae.decode(latents).sample\n # RuntimeError: upsample_nearest_nhwc only supports output tensors with less than INT_MAX elements\n # Pytorch upsample alogrithm not work for batch size 32 -> 64 \n image = (image / 2 + 0.5).clamp(0, 1)\n # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16\n\n # image = image.cpu().float().numpy()\n # if is_video:\n # image = rearrange(image, \"(b f) c h w -> b f h w c\", b=b)\n # else:\n # image = rearrange(image, \"b c h w -> b h w c\", b=b)\n return image\n def encode_latents(self,images,generator = None):\n if len(images.shape) == 4:\n images = images[None:]\n images = ((images - 0.5) * 2 ) \n latents = self.vae.encode(images).latent_dist.sample(generator)\n latents = latents * 0.18215\n return latents\n\n def step(\n self,\n model_output: torch.FloatTensor,\n timestep: int,\n sample: torch.FloatTensor,\n eta: float = 0.0,\n use_clipped_model_output: bool = False,\n generator=None,\n variance_noise: Optional[torch.FloatTensor] = None,\n return_dict: bool = True,\n ) -> Union[DDIMSchedulerOutput, Tuple]:\n \"\"\"\n Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion\n process from the learned model outputs (most often the predicted noise).\n\n Args:\n model_output (`torch.FloatTensor`): direct output from learned diffusion model.\n timestep (`int`): current discrete timestep in the diffusion chain.\n sample (`torch.FloatTensor`):\n current instance of sample being created by diffusion process.\n eta (`float`): weight of noise for added noise in diffusion step.\n use_clipped_model_output (`bool`): if `True`, compute \"corrected\" `model_output` from the clipped\n predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when\n `self.config.clip_sample` is `True`. If no clipping has happened, \"corrected\" `model_output` would\n coincide with the one provided as input and `use_clipped_model_output` will have not effect.\n generator: random number generator.\n variance_noise (`torch.FloatTensor`): instead of generating noise for the variance using `generator`, we\n can directly provide the noise for the variance itself. This is useful for methods such as\n CycleDiffusion. (https://arxiv.org/abs/2210.05559)\n return_dict (`bool`): option for returning tuple rather than DDIMSchedulerOutput class\n\n Returns:\n [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] or `tuple`:\n [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When\n returning a tuple, the first element is the sample tensor.\n\n \"\"\"\n if self.num_inference_steps is None:\n raise ValueError(\n \"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler\"\n )\n\n # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf\n # Ideally, read DDIM paper in-detail understanding\n\n # Notation (<variable name> -> <name in paper>\n # - pred_noise_t -> e_theta(x_t, t)\n # - pred_original_sample -> f_theta(x_t, t) or x_0\n # - std_dev_t -> sigma_t\n # - eta -> η\n # - pred_sample_direction -> \"direction pointing to x_t\"\n # - pred_prev_sample -> \"x_t-1\"\n\n # 1. get previous step value (=t-1)\n prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps\n\n # 2. compute alphas, betas\n alpha_prod_t = self.alphas_cumprod[timestep]\n alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod\n\n beta_prod_t = 1 - alpha_prod_t\n\n # 3. compute predicted original sample from predicted noise also called\n # \"predicted x_0\" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf\n if self.config.prediction_type == \"epsilon\":\n pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)\n elif self.config.prediction_type == \"sample\":\n pred_original_sample = model_output\n elif self.config.prediction_type == \"v_prediction\":\n pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output\n # predict V\n model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample\n else:\n raise ValueError(\n f\"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or\"\n \" `v_prediction`\"\n )\n\n # # add a interpolater\n images = self.decode_latents(pred_original_sample)\n\n f , C, H, W = images.shape\n # images = torch.from_numpy(images).cuda()\n ph = ((H - 1) // 32 + 1) * 32\n pw = ((W - 1) // 32 + 1) * 32\n padding = (0, pw - W, 0, ph - H)\n images= F.pad(images,padding).float()\n for i in range(1,f-2):\n img0 = images[i:i+1]\n img1 = images[i+2:i+3] \n inference_img = self.interpolater.inference(img0,img1)\n images[i+1:i+2] = inference_img\n pred_original_sample = self.encode_latents(images.to(self.vae.dtype),generator)\n pred_original_sample = rearrange(pred_original_sample[None], 'b f c h w -> b c f h w') \n\n \n # 4. Clip \"predicted x_0\"\n if self.config.clip_sample:\n pred_original_sample = torch.clamp(pred_original_sample, -1, 1)\n\n # 5. compute variance: \"sigma_t(η)\" -> see formula (16)\n # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)\n variance = self._get_variance(timestep, prev_timestep)\n std_dev_t = eta * variance ** (0.5)\n\n if use_clipped_model_output:\n # the model_output is always re-derived from the clipped x_0 in Glide\n model_output = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)\n\n # 6. compute \"direction pointing to x_t\" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf\n pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output\n\n # 7. compute x_t without \"random noise\" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf\n prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction\n\n if eta > 0:\n # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072\n device = model_output.device\n if variance_noise is not None and generator is not None:\n raise ValueError(\n \"Cannot pass both generator and variance_noise. Please make sure that either `generator` or\"\n \" `variance_noise` stays `None`.\"\n )\n\n if variance_noise is None:\n if device.type == \"mps\":\n # randn does not work reproducibly on mps\n variance_noise = torch.randn(model_output.shape, dtype=model_output.dtype, generator=generator)\n variance_noise = variance_noise.to(device)\n else:\n variance_noise = torch.randn(\n model_output.shape, generator=generator, device=device, dtype=model_output.dtype\n )\n variance = self._get_variance(timestep, prev_timestep) ** (0.5) * eta * variance_noise\n\n prev_sample = prev_sample + variance\n\n if not return_dict:\n return (prev_sample,)\n\n return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)" }, { "identifier": "Model", "path": "RIFEModel/RIFE_HDv3.py", "snippet": "class Model:\n def __init__(self, local_rank=-1):\n self.flownet = IFNet()\n self.device()\n self.optimG = AdamW(self.flownet.parameters(), lr=1e-6, weight_decay=1e-4)\n self.epe = EPE()\n # self.vgg = VGGPerceptualLoss().to(device)\n self.sobel = SOBEL()\n if local_rank != -1:\n self.flownet = DDP(self.flownet, device_ids=[local_rank], output_device=local_rank)\n\n def train(self):\n self.flownet.train()\n\n def eval(self):\n self.flownet.eval()\n\n def device(self):\n self.flownet.to(device)\n\n def load_model(self, path, rank=0):\n def convert(param):\n if rank == -1:\n return {\n k.replace(\"module.\", \"\"): v\n for k, v in param.items()\n if \"module.\" in k\n }\n else:\n return param\n if rank <= 0:\n if torch.cuda.is_available():\n self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path))))\n else:\n self.flownet.load_state_dict(convert(torch.load('{}/flownet.pkl'.format(path), map_location ='cpu')))\n \n def save_model(self, path, rank=0):\n if rank == 0:\n torch.save(self.flownet.state_dict(),'{}/flownet.pkl'.format(path))\n\n def inference(self, img0, img1, scale=1.0):\n imgs = torch.cat((img0, img1), 1)\n scale_list = [4/scale, 2/scale, 1/scale]\n flow, mask, merged = self.flownet(imgs, scale_list)\n return merged[2]\n \n def update(self, imgs, gt, learning_rate=0, mul=1, training=True, flow_gt=None):\n for param_group in self.optimG.param_groups:\n param_group['lr'] = learning_rate\n img0 = imgs[:, :3]\n img1 = imgs[:, 3:]\n if training:\n self.train()\n else:\n self.eval()\n scale = [4, 2, 1]\n flow, mask, merged = self.flownet(torch.cat((imgs, gt), 1), scale=scale, training=training)\n loss_l1 = (merged[2] - gt).abs().mean()\n loss_smooth = self.sobel(flow[2], flow[2]*0).mean()\n # loss_vgg = self.vgg(merged[2], gt)\n if training:\n self.optimG.zero_grad()\n loss_G = loss_cons + loss_smooth * 0.1\n loss_G.backward()\n self.optimG.step()\n else:\n flow_teacher = flow[2]\n return merged[2], {\n 'mask': mask,\n 'flow': flow[2][:, :2],\n 'loss_l1': loss_l1,\n 'loss_cons': loss_cons,\n 'loss_smooth': loss_smooth,\n }" } ]
import os import copy import click import re import numpy as np import torch import torch.utils.data import torch.utils.checkpoint import decord import shutil from glob import glob from typing import Optional,Dict from tqdm.auto import tqdm from omegaconf import OmegaConf from PIL import Image from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed from diffusers import ( AutoencoderKL, DDIMScheduler, ) from diffusers.utils.import_utils import is_xformers_available from transformers import AutoTokenizer, CLIPTextModel from einops import rearrange from video_diffusion.models.unet_3d_condition import UNetPseudo3DConditionModel from video_diffusion.models.controlnet_3d_condition import ControlNetPseudo3DModel from video_diffusion.data.dataset import ImageSequenceDataset from video_diffusion.common.util import get_time_string, get_function_args from video_diffusion.common.logger import get_logger_config_path from video_diffusion.common.image_util import log_train_samples from video_diffusion.common.instantiate_from_config import instantiate_from_config from video_diffusion.pipelines.p2p_validation_loop_controlnet import P2pSampleLogger from annotator.util import get_control from video_diffusion.pipelines.DDIMInterpolationScheduler import DDIMInterpolationScheduler from RIFEModel.RIFE_HDv3 import Model
19,930
"images": torch.stack([example["images"] for example in examples]), } return batch def test( config: str, pretrained_model_path: str, control_type:str, pretrained_controlnet_model_path :str, dataset_config: Dict, logdir: str = None, editing_config: Optional[Dict] = None, test_pipeline_config: Optional[Dict] = None, gradient_accumulation_steps: int = 1, seed: Optional[int] = None, mixed_precision: Optional[str] = "fp16", batch_size: int = 1, model_config: dict={}, verbose: bool=True, **kwargs ): args = get_function_args() vr = decord.VideoReader(dataset_config.video_path) fps = vr.get_avg_fps() duration = len(vr) / fps print("There are {} frames in the video but we take {} frames".format(len(vr), dataset_config.n_sample_frame)) if dataset_config.n_sample_frame <= 50: duration = 100 fps = 10 sample_index = list(range(0,len(vr), 1))[:dataset_config.n_sample_frame] video = vr.get_batch(sample_index) video_name_match = re.search(r"(.*)/(.*).mp4", dataset_config.video_path) video_name = video_name_match.group(2) video_frame_folder = os.path.join('data',video_name) if os.path.exists(video_frame_folder): shutil.rmtree(video_frame_folder) os.makedirs(video_frame_folder,exist_ok=True) for i in range(video.shape[0]): frame = video[i] frame_path = os.path.join(video_frame_folder,f'frame-{i:04}.jpg') frame = Image.fromarray(frame.numpy().astype(np.uint8)) frame.save(frame_path) dataset_config.update({'path': video_frame_folder} ) time_string = get_time_string() if logdir is None: logdir = config.replace('config', 'result').replace('.yml', '').replace('.yaml', '') logdir += f"_{time_string}" accelerator = Accelerator( gradient_accumulation_steps=gradient_accumulation_steps, mixed_precision=mixed_precision, ) if accelerator.is_main_process: os.makedirs(logdir, exist_ok=True) OmegaConf.save(args, os.path.join(logdir, "config.yml")) logger = get_logger_config_path(logdir) if seed is not None: set_seed(seed) # Load the tokenizer tokenizer = AutoTokenizer.from_pretrained( pretrained_model_path, subfolder="tokenizer", use_fast=False, ) # Load models and create wrapper for stable diffusion text_encoder = CLIPTextModel.from_pretrained( pretrained_model_path, subfolder="text_encoder", ) vae = AutoencoderKL.from_pretrained( pretrained_model_path, subfolder="vae", ) #加载unet报错 unet = UNetPseudo3DConditionModel.from_2d_model( os.path.join(pretrained_model_path, "unet"), model_config=model_config ) controlnet = ControlNetPseudo3DModel.from_2d_model( pretrained_controlnet_model_path, model_config=model_config ) if 'target' not in test_pipeline_config: test_pipeline_config['target'] = 'video_diffusion.pipelines.stable_diffusion.SpatioTemporalStableDiffusionControlPipeline' scheduler = DDIMScheduler.from_pretrained( pretrained_model_path, subfolder="scheduler", ) pipeline = instantiate_from_config( test_pipeline_config, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, controlnet=controlnet, scheduler=scheduler, control_type = control_type, editing_type = editing_config.editing_type, dilation_kernel = editing_config.dilation_kernel, disk_store=kwargs.get('disk_store', False) ) pipeline.scheduler.set_timesteps(editing_config['num_inference_steps']) if editing_config.use_interpolater: new_scheduler = DDIMInterpolationScheduler.from_pretrained( pretrained_model_path, subfolder="scheduler", )
decord.bridge.set_bridge('torch') # from video_diffusion.pipelines.p2p_validation_loop_controlnet_ablation import P2pSampleLogger # logger = get_logger(__name__) def collate_fn(examples): """Concat a batch of sampled image in dataloader """ batch = { "prompt_ids": torch.cat([example["prompt_ids"] for example in examples], dim=0), "images": torch.stack([example["images"] for example in examples]), } return batch def test( config: str, pretrained_model_path: str, control_type:str, pretrained_controlnet_model_path :str, dataset_config: Dict, logdir: str = None, editing_config: Optional[Dict] = None, test_pipeline_config: Optional[Dict] = None, gradient_accumulation_steps: int = 1, seed: Optional[int] = None, mixed_precision: Optional[str] = "fp16", batch_size: int = 1, model_config: dict={}, verbose: bool=True, **kwargs ): args = get_function_args() vr = decord.VideoReader(dataset_config.video_path) fps = vr.get_avg_fps() duration = len(vr) / fps print("There are {} frames in the video but we take {} frames".format(len(vr), dataset_config.n_sample_frame)) if dataset_config.n_sample_frame <= 50: duration = 100 fps = 10 sample_index = list(range(0,len(vr), 1))[:dataset_config.n_sample_frame] video = vr.get_batch(sample_index) video_name_match = re.search(r"(.*)/(.*).mp4", dataset_config.video_path) video_name = video_name_match.group(2) video_frame_folder = os.path.join('data',video_name) if os.path.exists(video_frame_folder): shutil.rmtree(video_frame_folder) os.makedirs(video_frame_folder,exist_ok=True) for i in range(video.shape[0]): frame = video[i] frame_path = os.path.join(video_frame_folder,f'frame-{i:04}.jpg') frame = Image.fromarray(frame.numpy().astype(np.uint8)) frame.save(frame_path) dataset_config.update({'path': video_frame_folder} ) time_string = get_time_string() if logdir is None: logdir = config.replace('config', 'result').replace('.yml', '').replace('.yaml', '') logdir += f"_{time_string}" accelerator = Accelerator( gradient_accumulation_steps=gradient_accumulation_steps, mixed_precision=mixed_precision, ) if accelerator.is_main_process: os.makedirs(logdir, exist_ok=True) OmegaConf.save(args, os.path.join(logdir, "config.yml")) logger = get_logger_config_path(logdir) if seed is not None: set_seed(seed) # Load the tokenizer tokenizer = AutoTokenizer.from_pretrained( pretrained_model_path, subfolder="tokenizer", use_fast=False, ) # Load models and create wrapper for stable diffusion text_encoder = CLIPTextModel.from_pretrained( pretrained_model_path, subfolder="text_encoder", ) vae = AutoencoderKL.from_pretrained( pretrained_model_path, subfolder="vae", ) #加载unet报错 unet = UNetPseudo3DConditionModel.from_2d_model( os.path.join(pretrained_model_path, "unet"), model_config=model_config ) controlnet = ControlNetPseudo3DModel.from_2d_model( pretrained_controlnet_model_path, model_config=model_config ) if 'target' not in test_pipeline_config: test_pipeline_config['target'] = 'video_diffusion.pipelines.stable_diffusion.SpatioTemporalStableDiffusionControlPipeline' scheduler = DDIMScheduler.from_pretrained( pretrained_model_path, subfolder="scheduler", ) pipeline = instantiate_from_config( test_pipeline_config, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, controlnet=controlnet, scheduler=scheduler, control_type = control_type, editing_type = editing_config.editing_type, dilation_kernel = editing_config.dilation_kernel, disk_store=kwargs.get('disk_store', False) ) pipeline.scheduler.set_timesteps(editing_config['num_inference_steps']) if editing_config.use_interpolater: new_scheduler = DDIMInterpolationScheduler.from_pretrained( pretrained_model_path, subfolder="scheduler", )
interpolater = Model()
11
2023-10-09 14:38:28+00:00
24k
LiYunfengLYF/LightFC
lib/train/data/base_functions.py
[ { "identifier": "sampler", "path": "lib/train/data/sampler.py", "snippet": "def no_processing(data):\r\n def __init__(self, datasets, p_datasets, samples_per_epoch, max_gap,\r\n num_search_frames, num_template_frames=1, processing=no_processing, frame_sample_mode='causal',\r\n train_cls=False, pos_prob=0.5):\r\n def __len__(self):\r\n def _sample_visible_ids(self, visible, num_ids=1, min_id=None, max_id=None,\r\n allow_invisible=False, force_invisible=False):\r\n def __getitem__(self, index):\r\n def getitem(self):\r\n def getitem_cls(self):\r\n def get_center_box(self, H, W, ratio=1 / 8):\r\n def sample_seq_from_dataset(self, dataset, is_video_dataset):\r\n def get_one_search(self):\r\n def get_frame_ids_trident(self, visible):\r\n def get_frame_ids_stark(self, visible, valid):\r\nclass TrackingSampler(torch.utils.data.Dataset):\r\n H, W, _ = template_frames[0].shape\r\n H, W, _ = template_frames[0].shape\r\n H, W, _ = search_frames[0].shape\r" }, { "identifier": "processing", "path": "lib/train/data/processing.py", "snippet": "def stack_tensors(x):\r\n def __init__(self, transform=transforms.ToTensor(), template_transform=None, search_transform=None,\r\n joint_transform=None):\r\n def __call__(self, data: TensorDict):\r\n def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor,\r\n mode='pair', settings=None, *args, **kwargs):\r\n def _get_jittered_box(self, box, mode):\r\n def __call__(self, data: TensorDict):\r\nclass BaseProcessing:\r\nclass STARKProcessing(BaseProcessing):\r" }, { "identifier": "LTRLoader", "path": "lib/train/data/loader.py", "snippet": "class LTRLoader(torch.utils.data.dataloader.DataLoader):\r\n \"\"\"\r\n Data loader. Combines a dataset and a sampler, and provides\r\n single- or multi-process iterators over the dataset.\r\n\r\n Note: The only difference with default pytorch DataLoader is that an additional option stack_dim is available to\r\n select along which dimension the data should be stacked to form a batch.\r\n\r\n Arguments:\r\n dataset (Dataset): dataset from which to load the data.\r\n batch_size (int, optional): how many samples per batch to load\r\n (default: 1).\r\n shuffle (bool, optional): set to ``True`` to have the data reshuffled\r\n at every epoch (default: False).\r\n sampler (Sampler, optional): defines the strategy to draw samples from\r\n the dataset. If specified, ``shuffle`` must be False.\r\n batch_sampler (Sampler, optional): like sampler, but returns a batch of\r\n indices at a time. Mutually exclusive with batch_size, shuffle,\r\n sampler, and drop_last.\r\n num_workers (int, optional): how many subprocesses to use for data\r\n loading. 0 means that the data will be loaded in the main process.\r\n (default: 0)\r\n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\r\n stack_dim (int): Dimension along which to stack to form the batch. (default: 0)\r\n pin_memory (bool, optional): If ``True``, the data loader will copy tensors\r\n into CUDA pinned memory before returning them.\r\n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,\r\n if the dataset size is not divisible by the batch size. If ``False`` and\r\n the size of dataset is not divisible by the batch size, then the last batch\r\n will be smaller. (default: False)\r\n timeout (numeric, optional): if positive, the timeout value for collecting a batch\r\n from workers. Should always be non-negative. (default: 0)\r\n worker_init_fn (callable, optional): If not None, this will be called on each\r\n worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as\r\n input, after seeding and before data loading. (default: None)\r\n\r\n .. note:: By default, each worker will have its PyTorch seed set to\r\n ``base_seed + worker_id``, where ``base_seed`` is a long generated\r\n by main process using its RNG. However, seeds for other libraries\r\n may be duplicated upon initializing workers (w.g., NumPy), causing\r\n each worker to return identical random numbers. (See\r\n :ref:`dataloader-workers-random-seed` section in FAQ.) You may\r\n use ``torch.initial_seed()`` to access the PyTorch seed for each\r\n worker in :attr:`worker_init_fn`, and use it to set other seeds\r\n before data loading.\r\n\r\n .. warning:: If ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an\r\n unpicklable object, e.g., a lambda function.\r\n \"\"\"\r\n\r\n __initialized = False\r\n\r\n def __init__(self, name, dataset, training=True, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,\r\n num_workers=0, epoch_interval=1, collate_fn=None, stack_dim=0, pin_memory=False, drop_last=False,\r\n timeout=0, worker_init_fn=None):\r\n if collate_fn is None:\r\n if stack_dim == 0:\r\n collate_fn = ltr_collate\r\n elif stack_dim == 1:\r\n collate_fn = ltr_collate_stack1\r\n else:\r\n raise ValueError('Stack dim no supported. Must be 0 or 1.')\r\n\r\n super(LTRLoader, self).__init__(dataset, batch_size, shuffle, sampler, batch_sampler,\r\n num_workers, collate_fn, pin_memory, drop_last,\r\n timeout, worker_init_fn)\r\n\r\n self.name = name\r\n self.training = training\r\n self.epoch_interval = epoch_interval\r\n self.stack_dim = stack_dim\r" }, { "identifier": "opencv_loader", "path": "lib/train/data/image_loader.py", "snippet": "def opencv_loader(path):\r\n \"\"\" Read image using opencv's imread function and returns it in rgb format\"\"\"\r\n try:\r\n im = cv.imread(path, cv.IMREAD_COLOR)\r\n\r\n # convert to rgb and return\r\n return cv.cvtColor(im, cv.COLOR_BGR2RGB)\r\n except Exception as e:\r\n print('ERROR: Could not read image \"{}\"'.format(path))\r\n print(e)\r\n return None\r" }, { "identifier": "Lasot", "path": "lib/train/dataset/lasot.py", "snippet": "class Lasot(BaseVideoDataset):\r\n \"\"\" LaSOT dataset.\r\n\r\n Publication:\r\n LaSOT: A High-quality Benchmark for Large-scale Single Object Tracking\r\n Heng Fan, Liting Lin, Fan Yang, Peng Chu, Ge Deng, Sijia Yu, Hexin Bai, Yong Xu, Chunyuan Liao and Haibin Ling\r\n CVPR, 2019\r\n https://arxiv.org/pdf/1809.07845.pdf\r\n\r\n Download the dataset from https://cis.temple.edu/lasot/download.html\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the lasot dataset.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\r\n videos with subscripts -1, -3, and -5 from each class will be used for training.\r\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\r\n vid_ids or split option can be used at a time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).lasot_dir if root is None else root\r\n super().__init__('LaSOT', root, image_loader)\r\n\r\n # Keep a list of all classes\r\n self.class_list = [f for f in os.listdir(self.root)]\r\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\r\n\r\n self.sequence_list = self._build_sequence_list(vid_ids, split)\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_per_class = self._build_class_list()\r\n\r\n def _build_sequence_list(self, vid_ids=None, split=None):\r\n if split is not None:\r\n if vid_ids is not None:\r\n raise ValueError('Cannot set both split_name and vid_ids.')\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n # sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\r\n sequence_list = pandas.read_csv(file_path, header=None).squeeze(\"columns\").values.tolist()\r\n elif vid_ids is not None:\r\n sequence_list = [c + '-' + str(v) for c in self.class_list for v in vid_ids]\r\n else:\r\n raise ValueError('Set either split_name or vid_ids.')\r\n\r\n return sequence_list\r\n\r\n def _build_class_list(self):\r\n seq_per_class = {}\r\n for seq_id, seq_name in enumerate(self.sequence_list):\r\n class_name = seq_name.split('-')[0]\r\n if class_name in seq_per_class:\r\n seq_per_class[class_name].append(seq_id)\r\n else:\r\n seq_per_class[class_name] = [seq_id]\r\n\r\n return seq_per_class\r\n\r\n def get_name(self):\r\n return 'lasot'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\r\n low_memory=False).values\r\n return torch.tensor(gt)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # Read full occlusion and out_of_view\r\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\r\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\r\n\r\n with open(occlusion_file, 'r', newline='') as f:\r\n occlusion = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\r\n with open(out_of_view_file, 'r') as f:\r\n out_of_view = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\r\n\r\n target_visible = ~occlusion & ~out_of_view\r\n\r\n return target_visible\r\n\r\n def _get_sequence_path(self, seq_id):\r\n seq_name = self.sequence_list[seq_id]\r\n class_name = seq_name.split('-')[0]\r\n vid_id = seq_name.split('-')[1]\r\n\r\n return os.path.join(self.root, class_name, class_name + '-' + vid_id)\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = self._read_target_visible(seq_path) & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\r\n\r\n def _get_class(self, seq_path):\r\n raw_class = seq_path.split('/')[-2]\r\n return raw_class\r\n\r\n def get_class_name(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_class = self._get_class(seq_path)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n\r\n obj_class = self._get_class(seq_path)\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "Got10k", "path": "lib/train/dataset/got10k.py", "snippet": "class Got10k(BaseVideoDataset):\r\n \"\"\" GOT-10k dataset.\r\n\r\n Publication:\r\n GOT-10k: A Large High-Diversity Benchmark for Generic Object Tracking in the Wild\r\n Lianghua Huang, Xin Zhao, and Kaiqi Huang\r\n arXiv:1810.11981, 2018\r\n https://arxiv.org/pdf/1810.11981.pdf\r\n\r\n Download dataset from http://got-10k.aitestunion.com/downloads\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\r\n not NOT the official got-10k validation split. To use the official validation split, provide that as\r\n the root folder instead.\r\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\r\n options can be used at the same time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).got10k_dir if root is None else root\r\n super().__init__('GOT10k', root, image_loader)\r\n\r\n # all folders inside the root\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n # seq_id is the index of the folder inside the got10k root path\r\n if split is not None:\r\n if seq_ids is not None:\r\n raise ValueError('Cannot set both split_name and seq_ids.')\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_split.txt')\r\n elif split == 'val':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_val_split.txt')\r\n elif split == 'train_full':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_full_split.txt')\r\n elif split == 'vottrain':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_train_split.txt')\r\n elif split == 'votval':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_val_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n # seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\r\n seq_ids = pandas.read_csv(file_path, header=None, dtype=np.int64).squeeze(\"columns\").values.tolist()\r\n elif seq_ids is None:\r\n seq_ids = list(range(0, len(self.sequence_list)))\r\n\r\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.sequence_meta_info = self._load_meta_info()\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def get_name(self):\r\n return 'got10k'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def _load_meta_info(self):\r\n sequence_meta_info = {s: self._read_meta(os.path.join(self.root, s)) for s in self.sequence_list}\r\n return sequence_meta_info\r\n\r\n def _read_meta(self, seq_path):\r\n try:\r\n with open(os.path.join(seq_path, 'meta_info.ini')) as f:\r\n meta_info = f.readlines()\r\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1][:-1],\r\n 'motion_class': meta_info[6].split(': ')[-1][:-1],\r\n 'major_class': meta_info[7].split(': ')[-1][:-1],\r\n 'root_class': meta_info[8].split(': ')[-1][:-1],\r\n 'motion_adverb': meta_info[9].split(': ')[-1][:-1]})\r\n except:\r\n object_meta = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return object_meta\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n\r\n for i, s in enumerate(self.sequence_list):\r\n object_class = self.sequence_meta_info[s]['object_class_name']\r\n if object_class in seq_per_class:\r\n seq_per_class[object_class].append(i)\r\n else:\r\n seq_per_class[object_class] = [i]\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _get_sequence_list(self):\r\n with open(os.path.join(self.root, 'list.txt')) as f:\r\n dir_list = list(csv.reader(f))\r\n dir_list = [dir_name[0] for dir_name in dir_list]\r\n return dir_list\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\r\n low_memory=False).values\r\n return torch.tensor(gt)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # Read full occlusion and out_of_view\r\n occlusion_file = os.path.join(seq_path, \"absence.label\")\r\n cover_file = os.path.join(seq_path, \"cover.label\")\r\n\r\n with open(occlusion_file, 'r', newline='') as f:\r\n occlusion = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\r\n with open(cover_file, 'r', newline='') as f:\r\n cover = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\r\n\r\n target_visible = ~occlusion & (cover > 0).byte()\r\n\r\n visible_ratio = cover.float() / 8\r\n return target_visible, visible_ratio\r\n\r\n def _get_sequence_path(self, seq_id):\r\n return os.path.join(self.root, self.sequence_list[seq_id])\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible, visible_ratio = self._read_target_visible(seq_path)\r\n visible = visible & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\r\n\r\n def get_class_name(self, seq_id):\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n return obj_meta['object_class_name']\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n return frame_list, anno_frames, obj_meta\r" }, { "identifier": "TrackingNet", "path": "lib/train/dataset/tracking_net.py", "snippet": "class TrackingNet(BaseVideoDataset):\r\n \"\"\" TrackingNet dataset.\r\n\r\n Publication:\r\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\r\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\r\n ECCV, 2018\r\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\r\n\r\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None, env_num=None):\r\n \"\"\"\r\n args:\r\n root - The path to the TrackingNet folder, containing the training sets.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\r\n sets (0 - 11) will be used.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).trackingnet_dir if root is None else root\r\n super().__init__('TrackingNet', root, image_loader)\r\n\r\n if set_ids is None:\r\n set_ids = [i for i in range(12)]\r\n\r\n self.set_ids = set_ids\r\n\r\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\r\n # video_name for each sequence\r\n self.sequence_list = list_sequences(self.root, self.set_ids)\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\r\n\r\n # we do not have the class_lists for the tracking net\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def _load_class_info(self):\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\r\n\r\n with open(class_map_path, 'r') as f:\r\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\r\n\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_to_class_map, seq_per_class\r\n\r\n def get_name(self):\r\n return 'trackingnet'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n bb_anno_file = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"anno\", vid_name + \".txt\")\r\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\r\n low_memory=False).values\r\n return torch.tensor(gt)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bbox = self._read_bb_anno(seq_id)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = valid.clone().byte()\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, seq_id, frame_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n frame_path = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"frames\", vid_name, str(frame_id) + \".jpg\")\r\n return self.image_loader(frame_path)\r\n\r\n def _get_class(self, seq_id):\r\n seq_name = self.sequence_list[seq_id][1]\r\n return self.seq_to_class_map[seq_name]\r\n\r\n def get_class_name(self, seq_id):\r\n obj_class = self._get_class(seq_id)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n obj_class = self._get_class(seq_id)\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "ImagenetVID", "path": "lib/train/dataset/imagenetvid.py", "snippet": "class ImagenetVID(BaseVideoDataset):\r\n \"\"\" Imagenet VID dataset.\r\n\r\n Publication:\r\n ImageNet Large Scale Visual Recognition Challenge\r\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\r\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\r\n IJCV, 2015\r\n https://arxiv.org/pdf/1409.0575.pdf\r\n\r\n Download the dataset from http://image-net.org/\r\n \"\"\"\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1,env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the imagenet vid dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n min_length - Minimum allowed sequence length.\r\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\r\n which cover complete image.\r\n \"\"\"\r\n root = env_settings(env_num).imagenet_dir if root is None else root\r\n super().__init__(\"imagenetvid\", root, image_loader)\r\n\r\n cache_file = os.path.join(root, 'cache.json')\r\n if os.path.isfile(cache_file):\r\n # If available, load the pre-processed cache file containing meta-info for each sequence\r\n with open(cache_file, 'r') as f:\r\n sequence_list_dict = json.load(f)\r\n\r\n self.sequence_list = sequence_list_dict\r\n else:\r\n # Else process the imagenet annotations and generate the cache file\r\n self.sequence_list = self._process_anno(root)\r\n\r\n with open(cache_file, 'w') as f:\r\n json.dump(self.sequence_list, f)\r\n\r\n # Filter the sequences based on min_length and max_target_area in the first frame\r\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\r\n get_target_to_image_ratio(x) < max_target_area]\r\n\r\n def get_name(self):\r\n return 'imagenetvid'\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\r\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\r\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\r\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, sequence, frame_id):\r\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\r\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\r\n frame_number = frame_id + sequence['start_frame']\r\n frame_path = os.path.join(self.root, 'Data', 'VID', 'train', set_name, vid_name,\r\n '{:06d}.JPEG'.format(frame_number))\r\n return self.image_loader(frame_path)\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n sequence = self.sequence_list[seq_id]\r\n\r\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n # Create anno dict\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n # added the class info to the meta info\r\n object_meta = OrderedDict({'object_class': sequence['class_name'],\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r\n\r\n def _process_anno(self, root):\r\n # Builds individual tracklets\r\n base_vid_anno_path = os.path.join(root, 'Annotations', 'VID', 'train')\r\n\r\n all_sequences = []\r\n for set in sorted(os.listdir(base_vid_anno_path)):\r\n set_id = int(set.split('_')[-1])\r\n for vid in sorted(os.listdir(os.path.join(base_vid_anno_path, set))):\r\n\r\n vid_id = int(vid.split('_')[-1])\r\n anno_files = sorted(os.listdir(os.path.join(base_vid_anno_path, set, vid)))\r\n\r\n frame1_anno = ET.parse(os.path.join(base_vid_anno_path, set, vid, anno_files[0]))\r\n image_size = [int(frame1_anno.find('size/width').text), int(frame1_anno.find('size/height').text)]\r\n\r\n objects = [ET.ElementTree(file=os.path.join(base_vid_anno_path, set, vid, f)).findall('object')\r\n for f in anno_files]\r\n\r\n tracklets = {}\r\n\r\n # Find all tracklets along with start frame\r\n for f_id, all_targets in enumerate(objects):\r\n for target in all_targets:\r\n tracklet_id = target.find('trackid').text\r\n if tracklet_id not in tracklets:\r\n tracklets[tracklet_id] = f_id\r\n\r\n for tracklet_id, tracklet_start in tracklets.items():\r\n tracklet_anno = []\r\n target_visible = []\r\n class_name_id = None\r\n\r\n for f_id in range(tracklet_start, len(objects)):\r\n found = False\r\n for target in objects[f_id]:\r\n if target.find('trackid').text == tracklet_id:\r\n if not class_name_id:\r\n class_name_id = target.find('name').text\r\n x1 = int(target.find('bndbox/xmin').text)\r\n y1 = int(target.find('bndbox/ymin').text)\r\n x2 = int(target.find('bndbox/xmax').text)\r\n y2 = int(target.find('bndbox/ymax').text)\r\n\r\n tracklet_anno.append([x1, y1, x2 - x1, y2 - y1])\r\n target_visible.append(target.find('occluded').text == '0')\r\n\r\n found = True\r\n break\r\n if not found:\r\n break\r\n\r\n new_sequence = {'set_id': set_id, 'vid_id': vid_id, 'class_name': class_name_id,\r\n 'start_frame': tracklet_start, 'anno': tracklet_anno,\r\n 'target_visible': target_visible, 'image_size': image_size}\r\n all_sequences.append(new_sequence)\r\n\r\n return all_sequences\r" }, { "identifier": "MSCOCOSeq", "path": "lib/train/dataset/coco_seq.py", "snippet": "class MSCOCOSeq(BaseVideoDataset):\r\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\r\n\r\n Publication:\r\n Microsoft COCO: Common Objects in Context.\r\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\r\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\r\n ECCV, 2014\r\n https://arxiv.org/pdf/1405.0312.pdf\r\n\r\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\r\n organized as follows.\r\n - coco_root\r\n - annotations\r\n - instances_train2014.json\r\n - instances_train2017.json\r\n - images\r\n - train2014\r\n - train2017\r\n\r\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\",env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the coco dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\r\n images will be used\r\n split - 'train' or 'val'.\r\n version - version of coco dataset (2014 or 2017)\r\n \"\"\"\r\n root = env_settings(env_num).coco_dir if root is None else root\r\n super().__init__('COCO', root, image_loader)\r\n\r\n self.img_pth = os.path.join(root, 'images/{}{}/'.format(split, version))\r\n self.anno_path = os.path.join(root, 'annotations/instances_{}{}.json'.format(split, version))\r\n\r\n # Load the COCO set.\r\n self.coco_set = COCO(self.anno_path)\r\n\r\n self.cats = self.coco_set.cats\r\n\r\n self.class_list = self.get_class_list()\r\n\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n def _get_sequence_list(self):\r\n ann_list = list(self.coco_set.anns.keys())\r\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\r\n\r\n return seq_list\r\n\r\n def is_video_sequence(self):\r\n return False\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_name(self):\r\n return 'coco'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_class_list(self):\r\n class_list = []\r\n for cat_id in self.cats.keys():\r\n class_list.append(self.cats[cat_id]['name'])\r\n return class_list\r\n\r\n def has_segmentation_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def get_sequence_info(self, seq_id):\r\n anno = self._get_anno(seq_id)\r\n\r\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\r\n\r\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\r\n\r\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\r\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\r\n\r\n visible = valid.clone().byte()\r\n\r\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\r\n\r\n def _get_anno(self, seq_id):\r\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\r\n\r\n return anno\r\n\r\n def _get_frames(self, seq_id):\r\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\r\n img = self.image_loader(os.path.join(self.img_pth, path))\r\n return img\r\n\r\n def get_meta_info(self, seq_id):\r\n try:\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\r\n 'motion_class': None,\r\n 'major_class': cat_dict_current['supercategory'],\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n except:\r\n object_meta = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return object_meta\r\n\r\n\r\n def get_class_name(self, seq_id):\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n return cat_dict_current['name']\r\n\r\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\r\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\r\n # list containing these replicated images.\r\n frame = self._get_frames(seq_id)\r\n\r\n frame_list = [frame.copy() for _ in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\r\n\r\n object_meta = self.get_meta_info(seq_id)\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "Got10k_lmdb", "path": "lib/train/dataset/got10k_lmdb.py", "snippet": "class Got10k_lmdb(BaseVideoDataset):\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\r\n not NOT the official got-10k validation split. To use the official validation split, provide that as\r\n the root folder instead.\r\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\r\n options can be used at the same time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n use_lmdb - whether the dataset is stored in lmdb format\r\n \"\"\"\r\n root = env_settings(env_num).got10k_lmdb_dir if root is None else root\r\n super().__init__('GOT10k_lmdb', root, image_loader)\r\n\r\n # all folders inside the root\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n # seq_id is the index of the folder inside the got10k root path\r\n if split is not None:\r\n if seq_ids is not None:\r\n raise ValueError('Cannot set both split_name and seq_ids.')\r\n train_lib_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_split.txt')\r\n elif split == 'val':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_val_split.txt')\r\n elif split == 'train_full':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_full_split.txt')\r\n elif split == 'vottrain':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_train_split.txt')\r\n elif split == 'votval':\r\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_val_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\r\n elif seq_ids is None:\r\n seq_ids = list(range(0, len(self.sequence_list)))\r\n\r\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.sequence_meta_info = self._load_meta_info()\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def get_name(self):\r\n return 'got10k_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def _load_meta_info(self):\r\n def _read_meta(meta_info):\r\n\r\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1],\r\n 'motion_class': meta_info[6].split(': ')[-1],\r\n 'major_class': meta_info[7].split(': ')[-1],\r\n 'root_class': meta_info[8].split(': ')[-1],\r\n 'motion_adverb': meta_info[9].split(': ')[-1]})\r\n\r\n return object_meta\r\n\r\n sequence_meta_info = {}\r\n for s in self.sequence_list:\r\n try:\r\n meta_str = decode_str(self.root, \"train/%s/meta_info.ini\" % s)\r\n sequence_meta_info[s] = _read_meta(meta_str.split('\\n'))\r\n except:\r\n sequence_meta_info[s] = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return sequence_meta_info\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n\r\n for i, s in enumerate(self.sequence_list):\r\n object_class = self.sequence_meta_info[s]['object_class_name']\r\n if object_class in seq_per_class:\r\n seq_per_class[object_class].append(i)\r\n else:\r\n seq_per_class[object_class] = [i]\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _get_sequence_list(self):\r\n dir_str = decode_str(self.root, 'train/list.txt')\r\n dir_list = dir_str.split('\\n')\r\n return dir_list\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line in got10k is empty\r\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\r\n gt_arr = np.array(gt_list).astype(np.float32)\r\n\r\n return torch.tensor(gt_arr)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # full occlusion and out_of_view files\r\n occlusion_file = os.path.join(seq_path, \"absence.label\")\r\n cover_file = os.path.join(seq_path, \"cover.label\")\r\n # Read these files\r\n occ_list = list(\r\n map(int, decode_str(self.root, occlusion_file).split('\\n')[:-1])) # the last line in got10k is empty\r\n occlusion = torch.ByteTensor(occ_list)\r\n cover_list = list(\r\n map(int, decode_str(self.root, cover_file).split('\\n')[:-1])) # the last line in got10k is empty\r\n cover = torch.ByteTensor(cover_list)\r\n\r\n target_visible = ~occlusion & (cover > 0).byte()\r\n\r\n visible_ratio = cover.float() / 8\r\n return target_visible, visible_ratio\r\n\r\n def _get_sequence_path(self, seq_id):\r\n return os.path.join(\"train\", self.sequence_list[seq_id])\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible, visible_ratio = self._read_target_visible(seq_path)\r\n visible = visible & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\r\n\r\n def get_class_name(self, seq_id):\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n return obj_meta['object_class_name']\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\r\n\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n return frame_list, anno_frames, obj_meta\r" }, { "identifier": "Lasot_lmdb", "path": "lib/train/dataset/lasot_lmdb.py", "snippet": "class Lasot_lmdb(BaseVideoDataset):\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None,\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the lasot dataset.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\r\n videos with subscripts -1, -3, and -5 from each class will be used for training.\r\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\r\n vid_ids or split option can be used at a time.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).lasot_lmdb_dir if root is None else root\r\n super().__init__('LaSOT_lmdb', root, image_loader)\r\n\r\n self.sequence_list = self._build_sequence_list(vid_ids, split)\r\n class_list = [seq_name.split('-')[0] for seq_name in self.sequence_list]\r\n self.class_list = []\r\n for ele in class_list:\r\n if ele not in self.class_list:\r\n self.class_list.append(ele)\r\n # Keep a list of all classes\r\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_per_class = self._build_class_list()\r\n\r\n def _build_sequence_list(self, vid_ids=None, split=None):\r\n if split is not None:\r\n if vid_ids is not None:\r\n raise ValueError('Cannot set both split_name and vid_ids.')\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n if split == 'train':\r\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\r\n else:\r\n raise ValueError('Unknown split name.')\r\n sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\r\n elif vid_ids is not None:\r\n sequence_list = [c + '-' + str(v) for c in self.class_list for v in vid_ids]\r\n else:\r\n raise ValueError('Set either split_name or vid_ids.')\r\n\r\n return sequence_list\r\n\r\n def _build_class_list(self):\r\n seq_per_class = {}\r\n for seq_id, seq_name in enumerate(self.sequence_list):\r\n class_name = seq_name.split('-')[0]\r\n if class_name in seq_per_class:\r\n seq_per_class[class_name].append(seq_id)\r\n else:\r\n seq_per_class[class_name] = [seq_id]\r\n\r\n return seq_per_class\r\n\r\n def get_name(self):\r\n return 'lasot_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def has_occlusion_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_path):\r\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\r\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line is empty\r\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\r\n gt_arr = np.array(gt_list).astype(np.float32)\r\n return torch.tensor(gt_arr)\r\n\r\n def _read_target_visible(self, seq_path):\r\n # Read full occlusion and out_of_view\r\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\r\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\r\n\r\n occ_list = list(map(int, decode_str(self.root, occlusion_file).split(',')))\r\n occlusion = torch.ByteTensor(occ_list)\r\n out_view_list = list(map(int, decode_str(self.root, out_of_view_file).split(',')))\r\n out_of_view = torch.ByteTensor(out_view_list)\r\n\r\n target_visible = ~occlusion & ~out_of_view\r\n\r\n return target_visible\r\n\r\n def _get_sequence_path(self, seq_id):\r\n seq_name = self.sequence_list[seq_id]\r\n class_name = seq_name.split('-')[0]\r\n vid_id = seq_name.split('-')[1]\r\n\r\n return os.path.join(class_name, class_name + '-' + vid_id)\r\n\r\n def get_sequence_info(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n bbox = self._read_bb_anno(seq_path)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = self._read_target_visible(seq_path) & valid.byte()\r\n\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame_path(self, seq_path, frame_id):\r\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id + 1)) # frames start from 1\r\n\r\n def _get_frame(self, seq_path, frame_id):\r\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\r\n\r\n def _get_class(self, seq_path):\r\n raw_class = seq_path.split('/')[-2]\r\n return raw_class\r\n\r\n def get_class_name(self, seq_id):\r\n seq_path = self._get_sequence_path(seq_id)\r\n obj_class = self._get_class(seq_path)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n seq_path = self._get_sequence_path(seq_id)\r\n\r\n obj_class = self._get_class(seq_path)\r\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "ImagenetVID_lmdb", "path": "lib/train/dataset/imagenetvid_lmdb.py", "snippet": "class ImagenetVID_lmdb(BaseVideoDataset):\r\n \"\"\" Imagenet VID dataset.\r\n\r\n Publication:\r\n ImageNet Large Scale Visual Recognition Challenge\r\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\r\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\r\n IJCV, 2015\r\n https://arxiv.org/pdf/1409.0575.pdf\r\n\r\n Download the dataset from http://image-net.org/\r\n \"\"\"\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1,env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the imagenet vid dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n min_length - Minimum allowed sequence length.\r\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\r\n which cover complete image.\r\n \"\"\"\r\n root = env_settings(env_num).imagenet_dir if root is None else root\r\n super().__init__(\"imagenetvid_lmdb\", root, image_loader)\r\n\r\n sequence_list_dict = decode_json(root, \"cache.json\")\r\n self.sequence_list = sequence_list_dict\r\n\r\n # Filter the sequences based on min_length and max_target_area in the first frame\r\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\r\n get_target_to_image_ratio(x) < max_target_area]\r\n\r\n def get_name(self):\r\n return 'imagenetvid_lmdb'\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\r\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\r\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\r\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, sequence, frame_id):\r\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\r\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\r\n frame_number = frame_id + sequence['start_frame']\r\n frame_path = os.path.join('Data', 'VID', 'train', set_name, vid_name,\r\n '{:06d}.JPEG'.format(frame_number))\r\n return decode_img(self.root, frame_path)\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n sequence = self.sequence_list[seq_id]\r\n\r\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n # Create anno dict\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n # added the class info to the meta info\r\n object_meta = OrderedDict({'object_class': sequence['class_name'],\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "MSCOCOSeq_lmdb", "path": "lib/train/dataset/coco_seq_lmdb.py", "snippet": "class MSCOCOSeq_lmdb(BaseVideoDataset):\r\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\r\n\r\n Publication:\r\n Microsoft COCO: Common Objects in Context.\r\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\r\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\r\n ECCV, 2014\r\n https://arxiv.org/pdf/1405.0312.pdf\r\n\r\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\r\n organized as follows.\r\n - coco_root\r\n - annotations\r\n - instances_train2014.json\r\n - instances_train2017.json\r\n - images\r\n - train2014\r\n - train2017\r\n\r\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\r\n \"\"\"\r\n\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\",\r\n env_num=None):\r\n \"\"\"\r\n args:\r\n root - path to the coco dataset.\r\n image_loader (default_image_loader) - The function to read the images. If installed,\r\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\r\n opencv's imread is used.\r\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\r\n images will be used\r\n split - 'train' or 'val'.\r\n version - version of coco dataset (2014 or 2017)\r\n \"\"\"\r\n root = env_settings(env_num).coco_dir if root is None else root\r\n super().__init__('COCO_lmdb', root, image_loader)\r\n self.root = root\r\n self.img_pth = 'images/{}{}/'.format(split, version)\r\n self.anno_path = 'annotations/instances_{}{}.json'.format(split, version)\r\n\r\n # Load the COCO set.\r\n print('loading annotations into memory...')\r\n tic = time.time()\r\n coco_json = decode_json(root, self.anno_path)\r\n print('Done (t={:0.2f}s)'.format(time.time() - tic))\r\n\r\n self.coco_set = COCO(coco_json)\r\n\r\n self.cats = self.coco_set.cats\r\n\r\n self.class_list = self.get_class_list()\r\n\r\n self.sequence_list = self._get_sequence_list()\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n self.seq_per_class = self._build_seq_per_class()\r\n\r\n def _get_sequence_list(self):\r\n ann_list = list(self.coco_set.anns.keys())\r\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\r\n\r\n return seq_list\r\n\r\n def is_video_sequence(self):\r\n return False\r\n\r\n def get_num_classes(self):\r\n return len(self.class_list)\r\n\r\n def get_name(self):\r\n return 'coco_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_class_list(self):\r\n class_list = []\r\n for cat_id in self.cats.keys():\r\n class_list.append(self.cats[cat_id]['name'])\r\n return class_list\r\n\r\n def has_segmentation_info(self):\r\n return True\r\n\r\n def get_num_sequences(self):\r\n return len(self.sequence_list)\r\n\r\n def _build_seq_per_class(self):\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_per_class\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def get_sequence_info(self, seq_id):\r\n anno = self._get_anno(seq_id)\r\n\r\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\r\n\r\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\r\n\r\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\r\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\r\n\r\n visible = valid.clone().byte()\r\n\r\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\r\n\r\n def _get_anno(self, seq_id):\r\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\r\n\r\n return anno\r\n\r\n def _get_frames(self, seq_id):\r\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\r\n # img = self.image_loader(os.path.join(self.img_pth, path))\r\n img = decode_img(self.root, os.path.join(self.img_pth, path))\r\n return img\r\n\r\n def get_meta_info(self, seq_id):\r\n try:\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\r\n 'motion_class': None,\r\n 'major_class': cat_dict_current['supercategory'],\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n except:\r\n object_meta = OrderedDict({'object_class_name': None,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n return object_meta\r\n\r\n def get_class_name(self, seq_id):\r\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\r\n return cat_dict_current['name']\r\n\r\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\r\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\r\n # list containing these replicated images.\r\n frame = self._get_frames(seq_id)\r\n\r\n frame_list = [frame.copy() for _ in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\r\n\r\n object_meta = self.get_meta_info(seq_id)\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "TrackingNet_lmdb", "path": "lib/train/dataset/tracking_net_lmdb.py", "snippet": "class TrackingNet_lmdb(BaseVideoDataset):\r\n \"\"\" TrackingNet dataset.\r\n\r\n Publication:\r\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\r\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\r\n ECCV, 2018\r\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\r\n\r\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\r\n \"\"\"\r\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None,env_num=None):\r\n \"\"\"\r\n args:\r\n root - The path to the TrackingNet folder, containing the training sets.\r\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\r\n is used by default.\r\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\r\n sets (0 - 11) will be used.\r\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\r\n \"\"\"\r\n root = env_settings(env_num).trackingnet_lmdb_dir if root is None else root\r\n super().__init__('TrackingNet_lmdb', root, image_loader)\r\n\r\n if set_ids is None:\r\n set_ids = [i for i in range(12)]\r\n\r\n self.set_ids = set_ids\r\n\r\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\r\n # video_name for each sequence\r\n self.sequence_list = list_sequences(self.root)\r\n\r\n if data_fraction is not None:\r\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\r\n\r\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\r\n\r\n # we do not have the class_lists for the tracking net\r\n self.class_list = list(self.seq_per_class.keys())\r\n self.class_list.sort()\r\n\r\n def _load_class_info(self):\r\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\r\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\r\n\r\n with open(class_map_path, 'r') as f:\r\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\r\n\r\n seq_per_class = {}\r\n for i, seq in enumerate(self.sequence_list):\r\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\r\n if class_name not in seq_per_class:\r\n seq_per_class[class_name] = [i]\r\n else:\r\n seq_per_class[class_name].append(i)\r\n\r\n return seq_to_class_map, seq_per_class\r\n\r\n def get_name(self):\r\n return 'trackingnet_lmdb'\r\n\r\n def has_class_info(self):\r\n return True\r\n\r\n def get_sequences_in_class(self, class_name):\r\n return self.seq_per_class[class_name]\r\n\r\n def _read_bb_anno(self, seq_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n gt_str_list = decode_str(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\r\n os.path.join(\"anno\", vid_name + \".txt\")).split('\\n')[:-1]\r\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\r\n gt_arr = np.array(gt_list).astype(np.float32)\r\n return torch.tensor(gt_arr)\r\n\r\n def get_sequence_info(self, seq_id):\r\n bbox = self._read_bb_anno(seq_id)\r\n\r\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\r\n visible = valid.clone().byte()\r\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\r\n\r\n def _get_frame(self, seq_id, frame_id):\r\n set_id = self.sequence_list[seq_id][0]\r\n vid_name = self.sequence_list[seq_id][1]\r\n return decode_img(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\r\n os.path.join(\"frames\", vid_name, str(frame_id) + \".jpg\"))\r\n\r\n def _get_class(self, seq_id):\r\n seq_name = self.sequence_list[seq_id][1]\r\n return self.seq_to_class_map[seq_name]\r\n\r\n def get_class_name(self, seq_id):\r\n obj_class = self._get_class(seq_id)\r\n\r\n return obj_class\r\n\r\n def get_frames(self, seq_id, frame_ids, anno=None):\r\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\r\n\r\n if anno is None:\r\n anno = self.get_sequence_info(seq_id)\r\n\r\n anno_frames = {}\r\n for key, value in anno.items():\r\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\r\n\r\n obj_class = self._get_class(seq_id)\r\n\r\n object_meta = OrderedDict({'object_class_name': obj_class,\r\n 'motion_class': None,\r\n 'major_class': None,\r\n 'root_class': None,\r\n 'motion_adverb': None})\r\n\r\n return frame_list, anno_frames, object_meta\r" }, { "identifier": "Adan", "path": "lib/train/optimizer/anan.py", "snippet": "class Adan(Optimizer):\r\n \"\"\"\r\n Implements a pytorch variant of Adan\r\n Adan was proposed in\r\n Adan: Adaptive Nesterov Momentum Algorithm for\r\n Faster Optimizing Deep Models[J].arXiv preprint arXiv:2208.06677, 2022.\r\n https://arxiv.org/abs/2208.06677\r\n Arguments:\r\n params (iterable): iterable of parameters to optimize or\r\n dicts defining parameter groups.\r\n lr (float, optional): learning rate. (default: 1e-3)\r\n betas (Tuple[float, float, flot], optional): coefficients used for\r\n first- and second-order moments. (default: (0.98, 0.92, 0.99))\r\n eps (float, optional): term added to the denominator to improve\r\n numerical stability. (default: 1e-8)\r\n weight_decay (float, optional): decoupled weight decay\r\n (L2 penalty) (default: 0)\r\n max_grad_norm (float, optional): value used to clip\r\n global grad norm (default: 0.0 no clip)\r\n no_prox (bool): how to perform the decoupled weight decay\r\n (default: False)\r\n foreach (bool): if True would use torch._foreach implementation.\r\n It's faster but uses slightly more memory. (default: True)\r\n fused (bool, optional): whether fused implementation is used.\r\n (default: False)\r\n\r\n VIT:\r\n 150\r\n lr 0.015\r\n betas (0.98, 0.92, 0.99)\r\n eps 1.0e-08\r\n weight_decay 0.02\r\n max_grad_norm 5.0\r\n no_prox\r\n foreach\r\n fused\r\n 300\r\n lr 0.015\r\n betas (0.98, 0.92, 0.99)\r\n eps 1.0e-08\r\n weight_decay 0.02\r\n max_grad_norm 5.0\r\n no_prox\r\n foreach\r\n fused\r\n \"\"\"\r\n def __init__(self,\r\n params,\r\n lr=1e-3,\r\n betas=(0.98, 0.92, 0.99),\r\n eps=1e-8,\r\n weight_decay=0.0,\r\n max_grad_norm=0.0,\r\n no_prox=False,\r\n foreach: bool = True,\r\n fused: bool = False):\r\n if not 0.0 <= max_grad_norm:\r\n raise ValueError('Invalid Max grad norm: {}'.format(max_grad_norm))\r\n if not 0.0 <= lr:\r\n raise ValueError('Invalid learning rate: {}'.format(lr))\r\n if not 0.0 <= eps:\r\n raise ValueError('Invalid epsilon value: {}'.format(eps))\r\n if not 0.0 <= betas[0] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 0: {}'.format(\r\n betas[0]))\r\n if not 0.0 <= betas[1] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 1: {}'.format(\r\n betas[1]))\r\n if not 0.0 <= betas[2] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 2: {}'.format(\r\n betas[2]))\r\n defaults = dict(lr=lr,\r\n betas=betas,\r\n eps=eps,\r\n weight_decay=weight_decay,\r\n max_grad_norm=max_grad_norm,\r\n no_prox=no_prox,\r\n foreach=foreach,\r\n fused=fused)\r\n super().__init__(params, defaults)\r\n\r\n def __setstate__(self, state):\r\n super(Adan, self).__setstate__(state)\r\n for group in self.param_groups:\r\n group.setdefault('no_prox', False)\r\n\r\n @torch.no_grad()\r\n def restart_opt(self):\r\n for group in self.param_groups:\r\n group['step'] = 0\r\n for p in group['params']:\r\n if p.requires_grad:\r\n state = self.state[p]\r\n # State initialization\r\n\r\n # Exponential moving average of gradient values\r\n state['exp_avg'] = torch.zeros_like(p)\r\n # Exponential moving average of squared gradient values\r\n state['exp_avg_sq'] = torch.zeros_like(p)\r\n # Exponential moving average of gradient difference\r\n state['exp_avg_diff'] = torch.zeros_like(p)\r\n\r\n @torch.no_grad()\r\n def step(self, closure=None):\r\n \"\"\"Performs a single optimization step.\"\"\"\r\n\r\n loss = None\r\n if closure is not None:\r\n with torch.enable_grad():\r\n loss = closure()\r\n\r\n if self.defaults['max_grad_norm'] > 0:\r\n device = self.param_groups[0]['params'][0].device\r\n global_grad_norm = torch.zeros(1, device=device)\r\n\r\n max_grad_norm = torch.tensor(self.defaults['max_grad_norm'],\r\n device=device)\r\n for group in self.param_groups:\r\n\r\n for p in group['params']:\r\n if p.grad is not None:\r\n grad = p.grad\r\n global_grad_norm.add_(grad.pow(2).sum())\r\n\r\n global_grad_norm = torch.sqrt(global_grad_norm)\r\n\r\n clip_global_grad_norm = torch.clamp(\r\n max_grad_norm / (global_grad_norm + group['eps']),\r\n max=1.0).item()\r\n else:\r\n clip_global_grad_norm = 1.0\r\n\r\n for group in self.param_groups:\r\n params_with_grad = []\r\n grads = []\r\n exp_avgs = []\r\n exp_avg_sqs = []\r\n exp_avg_diffs = []\r\n neg_pre_grads = []\r\n\r\n beta1, beta2, beta3 = group['betas']\r\n # assume same step across group now to simplify things\r\n # per parameter step can be easily support\r\n # by making it tensor, or pass list into kernel\r\n if 'step' in group:\r\n group['step'] += 1\r\n else:\r\n group['step'] = 1\r\n\r\n bias_correction1 = 1.0 - beta1**group['step']\r\n bias_correction2 = 1.0 - beta2**group['step']\r\n bias_correction3 = 1.0 - beta3**group['step']\r\n\r\n for p in group['params']:\r\n if p.grad is None:\r\n continue\r\n params_with_grad.append(p)\r\n grads.append(p.grad)\r\n\r\n state = self.state[p]\r\n if len(state) == 0:\r\n state['exp_avg'] = torch.zeros_like(p)\r\n state['exp_avg_sq'] = torch.zeros_like(p)\r\n state['exp_avg_diff'] = torch.zeros_like(p)\r\n\r\n if 'neg_pre_grad' not in state or group['step'] == 1:\r\n state['neg_pre_grad'] = p.grad.clone().mul_(\r\n -clip_global_grad_norm)\r\n\r\n exp_avgs.append(state['exp_avg'])\r\n exp_avg_sqs.append(state['exp_avg_sq'])\r\n exp_avg_diffs.append(state['exp_avg_diff'])\r\n neg_pre_grads.append(state['neg_pre_grad'])\r\n\r\n kwargs = dict(\r\n params=params_with_grad,\r\n grads=grads,\r\n exp_avgs=exp_avgs,\r\n exp_avg_sqs=exp_avg_sqs,\r\n exp_avg_diffs=exp_avg_diffs,\r\n neg_pre_grads=neg_pre_grads,\r\n beta1=beta1,\r\n beta2=beta2,\r\n beta3=beta3,\r\n bias_correction1=bias_correction1,\r\n bias_correction2=bias_correction2,\r\n bias_correction3_sqrt=math.sqrt(bias_correction3),\r\n lr=group['lr'],\r\n weight_decay=group['weight_decay'],\r\n eps=group['eps'],\r\n no_prox=group['no_prox'],\r\n clip_global_grad_norm=clip_global_grad_norm,\r\n )\r\n\r\n if group['foreach']:\r\n if group['fused']:\r\n if torch.cuda.is_available():\r\n _fused_adan_multi_tensor(**kwargs)\r\n else:\r\n raise ValueError('Fused Adan does not support CPU')\r\n else:\r\n _multi_tensor_adan(**kwargs)\r\n elif group['fused']:\r\n if torch.cuda.is_available():\r\n _fused_adan_single_tensor(**kwargs)\r\n else:\r\n raise ValueError('Fused Adan does not support CPU')\r\n else:\r\n _single_tensor_adan(**kwargs)\r\n\r\n return loss\r" }, { "identifier": "Lion", "path": "lib/train/optimizer/lion.py", "snippet": "class Lion(Optimizer):\r\n r\"\"\"Implements Lion algorithm.\"\"\"\r\n\r\n def __init__(self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0):\r\n \"\"\"Initialize the hyperparameters.\r\n\r\n Args:\r\n params (iterable): iterable of parameters to optimize or dicts defining\r\n parameter groups\r\n lr (float, optional): learning rate (default: 1e-4)\r\n betas (Tuple[float, float], optional): coefficients used for computing\r\n running averages of gradient and its square (default: (0.9, 0.99))\r\n weight_decay (float, optional): weight decay coefficient (default: 0)\r\n \"\"\"\r\n\r\n if not 0.0 <= lr:\r\n raise ValueError('Invalid learning rate: {}'.format(lr))\r\n if not 0.0 <= betas[0] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 0: {}'.format(betas[0]))\r\n if not 0.0 <= betas[1] < 1.0:\r\n raise ValueError('Invalid beta parameter at index 1: {}'.format(betas[1]))\r\n defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay)\r\n super().__init__(params, defaults)\r\n\r\n @torch.no_grad()\r\n def step(self, closure=None):\r\n \"\"\"Performs a single optimization step.\r\n\r\n Args:\r\n closure (callable, optional): A closure that reevaluates the model\r\n and returns the loss.\r\n\r\n Returns:\r\n the loss.\r\n \"\"\"\r\n loss = None\r\n if closure is not None:\r\n with torch.enable_grad():\r\n loss = closure()\r\n\r\n for group in self.param_groups:\r\n for p in group['params']:\r\n if p.grad is None:\r\n continue\r\n\r\n # Perform stepweight decay\r\n p.data.mul_(1 - group['lr'] * group['weight_decay'])\r\n\r\n grad = p.grad\r\n state = self.state[p]\r\n # State initialization\r\n if len(state) == 0:\r\n # Exponential moving average of gradient values\r\n state['exp_avg'] = torch.zeros_like(p)\r\n\r\n exp_avg = state['exp_avg']\r\n beta1, beta2 = group['betas']\r\n\r\n # Weight update\r\n update = exp_avg * beta1 + grad * (1 - beta1)\r\n p.add_(torch.sign(update), alpha=-group['lr'])\r\n # Decay the momentum running average coefficient\r\n exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2)\r\n\r\n return loss" }, { "identifier": "is_main_process", "path": "lib/utils/misc.py", "snippet": "def is_main_process():\r\n return get_rank() == 0\r" } ]
import torch import lib.train.data.transforms as tfm from torch.utils.data.distributed import DistributedSampler from lib.train.data import sampler, opencv_loader, processing, LTRLoader from lib.train.dataset import Lasot, Got10k, MSCOCOSeq, ImagenetVID, TrackingNet from lib.train.dataset import Lasot_lmdb, Got10k_lmdb, MSCOCOSeq_lmdb, ImagenetVID_lmdb, TrackingNet_lmdb from lib.train.optimizer.anan import Adan from lib.train.optimizer.lion import Lion from lib.utils.misc import is_main_process
20,508
# datasets related def update_settings(settings, cfg): settings.print_interval = cfg.TRAIN.PRINT_INTERVAL settings.search_area_factor = {'template': cfg.DATA.TEMPLATE.FACTOR, 'search': cfg.DATA.SEARCH.FACTOR} settings.output_sz = {'template': cfg.DATA.TEMPLATE.SIZE, 'search': cfg.DATA.SEARCH.SIZE} settings.center_jitter_factor = {'template': cfg.DATA.TEMPLATE.CENTER_JITTER, 'search': cfg.DATA.SEARCH.CENTER_JITTER} settings.scale_jitter_factor = {'template': cfg.DATA.TEMPLATE.SCALE_JITTER, 'search': cfg.DATA.SEARCH.SCALE_JITTER} settings.grad_clip_norm = cfg.TRAIN.GRAD_CLIP_NORM settings.print_stats = None settings.batchsize = cfg.TRAIN.BATCH_SIZE settings.scheduler_type = cfg.TRAIN.SCHEDULER.TYPE settings.save_interval = cfg.TRAIN.SAVE_INTERVAL def names2datasets(name_list: list, settings, image_loader): assert isinstance(name_list, list) datasets = [] for name in name_list: # assert name in ["LASOT", "GOT10K_vottrain", "GOT10K_votval", "GOT10K_train_full", "GOT10K_official_val", # "COCO17", "VID", "TRACKINGNET"] if name == "LASOT": if settings.use_lmdb: print("Building lasot dataset from lmdb") datasets.append(Lasot_lmdb(settings.env.lasot_lmdb_dir, split='train', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(
# datasets related def update_settings(settings, cfg): settings.print_interval = cfg.TRAIN.PRINT_INTERVAL settings.search_area_factor = {'template': cfg.DATA.TEMPLATE.FACTOR, 'search': cfg.DATA.SEARCH.FACTOR} settings.output_sz = {'template': cfg.DATA.TEMPLATE.SIZE, 'search': cfg.DATA.SEARCH.SIZE} settings.center_jitter_factor = {'template': cfg.DATA.TEMPLATE.CENTER_JITTER, 'search': cfg.DATA.SEARCH.CENTER_JITTER} settings.scale_jitter_factor = {'template': cfg.DATA.TEMPLATE.SCALE_JITTER, 'search': cfg.DATA.SEARCH.SCALE_JITTER} settings.grad_clip_norm = cfg.TRAIN.GRAD_CLIP_NORM settings.print_stats = None settings.batchsize = cfg.TRAIN.BATCH_SIZE settings.scheduler_type = cfg.TRAIN.SCHEDULER.TYPE settings.save_interval = cfg.TRAIN.SAVE_INTERVAL def names2datasets(name_list: list, settings, image_loader): assert isinstance(name_list, list) datasets = [] for name in name_list: # assert name in ["LASOT", "GOT10K_vottrain", "GOT10K_votval", "GOT10K_train_full", "GOT10K_official_val", # "COCO17", "VID", "TRACKINGNET"] if name == "LASOT": if settings.use_lmdb: print("Building lasot dataset from lmdb") datasets.append(Lasot_lmdb(settings.env.lasot_lmdb_dir, split='train', image_loader=image_loader, env_num=settings.env_num)) else: datasets.append(
Lasot(settings.env.lasot_dir, split='train', image_loader=image_loader, env_num=settings.env_num))
4
2023-10-08 11:44:32+00:00
24k
LiyaoTang/ERDA
main.py
[ { "identifier": "load_config", "path": "config/utils.py", "snippet": "def load_config(cfg_path=None, dataset_name=None, cfg_name=None, cfg_group=None, reload=True):\n # cfg from path\n if cfg_path is not None:\n update = None\n if os.path.isfile(cfg_path):\n # update on the default cfg\n from config.base import Base, Config\n update = Base(cfg_path)\n cfg_path = [update.dataset.lower(), 'default']\n else:\n # directly specified cfg\n cfg_path = cfg_path.replace('/', '.').split('.')\n cfg_path = cfg_path if cfg_path[0] == 'config' else ['config'] + cfg_path\n cfg_module = cfg_path[1]\n cfg_class = '.'.join(cfg_path[2:])\n mod = _import_module(cfg_module)\n if hasattr(mod, cfg_class):\n cfg = getattr(mod, cfg_class)\n else:\n cfg = load_config(dataset_name=cfg_path[1], cfg_name=cfg_class, reload=reload)\n\n if update is not None:\n cfg = Config(cfg) # avoid overriding\n cfg.update(update, exclude=[]) # full override with no exclude\n return cfg\n\n # setup dict\n cfg_name_dict = load_config.cfg_name_dict # dataset_name -> {cfg.name -> cfg.idx_name}\n cfg_module_dict = load_config.cfg_module_dict # dataset_name -> cfg_module\n\n if dataset_name is not None and dataset_name not in cfg_module_dict or reload:\n mod = _import_module(dataset_name)\n cfg_module_dict[dataset_name] = mod\n cfg_name_dict[dataset_name] = {}\n for i in dir(mod):\n if not is_config(i, mod=mod): # use the 'base' class imported in 'mod'\n continue\n cfg = getattr(mod, i)\n if cfg.name:\n cfg_name_dict[dataset_name][cfg.name] = cfg.idx_name\n\n # module/cfg from dataset/cfg name\n mod = cfg_module_dict[dataset_name]\n if cfg_name is not None:\n if cfg_name not in cfg_name_dict[dataset_name]:\n raise KeyError(f'no cfg_name = {cfg_name} in module {dataset_name}')\n idx_name = cfg_name_dict[dataset_name][cfg_name]\n return getattr(mod, idx_name)\n elif cfg_group is not None:\n if not hasattr(mod, cfg_group):\n raise KeyError(f'no cfg_group = {cfg_group} in module {dataset_name}')\n cfg_g = getattr(mod, cfg_group)\n if isinstance(cfg_g, type(mod.Base)) and cfg_g._store_dict:\n cfg_g = cfg_g._store_dict\n if not isinstance(cfg_g, (tuple, list, dict, set)):\n raise ValueError(f'cfg_group = {cfg_group} appears to be {cfg_g}, not of type (tuple, list, dict, set)')\n return cfg_g\n return mod" }, { "identifier": "log_config", "path": "config/utils.py", "snippet": "def log_config(config, title='', f_out=None, prefix='', base=None):\n if f_out is None:\n f_out = sys.stdout\n if base is None:\n root = os.path.join(os.getcwd(), os.path.dirname(__file__), '../')\n sys.path += [] if root in sys.path or os.path.realpath(root) in sys.path else [root]\n from config.base import Base as base\n\n print(f'\\n{prefix}<<< ======= {config._cls} ======= {title if title else config.name}', file=f_out)\n max_len = max([len(k) for k in dir(config) if not k.startswith('_')] + [0])\n for k in config.keys(): # dir would sort\n # if k.startswith('_') or _is_method(getattr(config, k)):\n # continue\n cur_attr = getattr(config, k)\n if isinstance(cur_attr, list) and len(str(cur_attr)) > 200: # overlong list\n cur_attr = '[' + f'\\n{prefix}\\t\\t'.join([''] + [str(s) for s in cur_attr]) + f'\\n{prefix}\\t]'\n\n print('\\t%s%s\\t= %s' % (prefix + k, ' ' * (max_len-len(k)), str(cur_attr)), file=f_out)\n if is_config(cur_attr, base=base):\n log_config(cur_attr, f_out=f_out, prefix=prefix+'\\t', base=base)\n print('\\n', file=f_out, flush=True)" }, { "identifier": "print_mem", "path": "utils/logger.py", "snippet": "def print_mem(prefix, gpu=True, check_time=False, check_sys=False, **kwargs):\n sep = '\\n\\t' if any([gpu, check_time]) else ' '\n lines = [prefix, 'Mem Comsumption: %.2f GB' % (print_mem.process.memory_info()[0] / float(2**30))]\n if check_sys:\n sysmem = psutil.virtual_memory()\n lines += [f'Mem in sys: avail {sysmem.available / 2**30:.2f} / total {sysmem.total / 2**30:.2f}']\n if gpu:\n try:\n gpu_mem = get_gpu_mem()\n lines += [f'Availabel Mem of each GPU: {gpu_mem}']\n except FileNotFoundError:\n pass\n except sp.CalledProcessError:\n pass\n if check_time:\n cur_t = time.time()\n if not hasattr(print_mem, 't_start'):\n print_mem.t_start = cur_t\n print_mem.t = cur_t\n else:\n gap = int(cur_t-print_mem.t)\n cum = int(cur_t-print_mem.t_start)\n lines += [f'time used [gap/cum] : {gap // 60}min {gap % 60}s / {cum // 60}min {cum % 60}s']\n print_mem.t = cur_t\n print(sep.join(lines), **kwargs)" }, { "identifier": "redirect_io", "path": "utils/logger.py", "snippet": "class redirect_io(object):\n def __init__(self, log_file, debug):\n self.log_file = log_file\n self.debug = debug\n def __enter__(self):\n if self.debug or not self.log_file:\n return\n self.log_file = open(self.log_file, 'w') if isinstance(self.log_file, str) else self.log_file\n self.stdout, self.stderr = sys.stdout, sys.stderr\n sys.stdout = sys.stderr = self.log_file\n \n def __exit__(self, exc_type, exc_value, tb):\n if self.debug or not self.log_file:\n return\n if sys.exc_info() != (None, None, None):\n traceback.print_exc()\n self.log_file.close()\n sys.stdout, sys.stderr = self.stdout, self.stderr" }, { "identifier": "get_snap", "path": "config/utils.py", "snippet": "def get_snap(saving_path, step='last', snap_prefix='snap'):\n # get the best of running val (done in training)\n snap_path = os.path.join(saving_path, 'snapshots') if not saving_path.endswith('snapshots') else saving_path\n snap_steps = [f.split('.')[0].split('-')[-1] for f in os.listdir(snap_path) if f.startswith(snap_prefix)]\n if step == 'last':\n snap_steps = sorted([int(s) for s in snap_steps if s.isdigit()]) + sorted([s for s in snap_steps if not s.isdigit()])\n chosen_step = snap_steps[-1] # last saved snap (best val estimation)\n chosen_snap = os.path.join(snap_path, f'snap-{chosen_step}')\n else:\n assert isinstance(step, int) or step.isdigit() or step == 'best', f'not supported step = {step}'\n step = str(step)\n chosen_snap = None\n if step in snap_steps:\n chosen_snap = os.path.join(snap_path, f'snap-{step}')\n else:\n raise ValueError(f'step={step} not in {snap_steps} (path={snap_path})')\n return chosen_snap" }, { "identifier": "ModelTester", "path": "utils/tester.py", "snippet": "class ModelTester:\n\n # Initiation methods\n # ------------------------------------------------------------------------------------------------------------------\n\n def __init__(self, config, verbose=True):\n self.config = config\n self.verbose = verbose\n\n self.save_extra = {} # for saving with extra ops\n\n if config.dataset in ['S3DIS', 'ScanNet', 'SensatUrban']:\n self.val_running_vote = self.val_running_vote_seg\n self.val_vote = self.val_vote_seg\n self.test_vote = self.test_vote_seg\n else:\n raise NotImplementedError(f'not supported dataset: {config.dataset}')\n\n def init_pointcloud_log(self, dataset, split, d, dtype=np.float32, init_fn=np.zeros):\n shape = lambda l: [l, d] if d else [l] # d - size of last dimension => each point d-dim [N, d] (d = None to have [N])\n log = [init_fn(shape=shape(t.data.shape[0]), dtype=dtype) for t in dataset.input_trees[split]]\n return log\n\n def initialize(self, ops, dataset, model, split):\n # initialize cum_dict & ops\n config = self.config\n ncls = config.num_classes\n\n run_ops = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # assumes per-gpu rst - support multi-gpu\n cum_dict = {\n 'prob': self.init_pointcloud_log(dataset, split, ncls)\n }\n\n extra_ops = [k for k in config.extra_ops.split('-') if k]\n extra_ops_solved = extra_ops.copy()\n for k in extra_ops:\n if k in ['prob', 'conf']:\n continue\n else:\n raise ValueError(f'not supported extra ops k = {k} from {config.extra_ops}')\n\n return run_ops, cum_dict, extra_ops_solved\n\n # Val methods\n # ------------------------------------------------------------------------------------------------------------------\n\n def val_running_vote_seg(self, sess, ops, dataset, model, validation_probs, epoch=1):\n \"\"\"\n One epoch validating - running voting used during training, main task results only\n \"\"\"\n\n val_smooth = 0.95 # Choose validation smoothing parameter (0 for no smothing, 0.99 for big smoothing)\n\n result_dict = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # result dict for seg\n val_ops = {'loss_dict': ops['loss_dict'], 'result_dict': result_dict}\n feed_dict = {ops['is_training']: False}\n\n # Initialise iterator\n sess.run(ops['val_init_op'])\n\n ep = 0\n loss_meter = {k: AverageMeter() for k in val_ops['loss_dict']} if 'loss_dict' in val_ops else{}\n cum_dict = {\n 'conf': 0, # conf from current validation\n 'prob': validation_probs, # accumulating probs\n }\n while ep < epoch:\n try:\n rst = sess.run(val_ops, feed_dict=feed_dict)\n\n loss_dict = rst['loss_dict'] if 'loss_dict' in rst else {}\n cur_rst = rst['result_dict'] # per-gpu result\n\n for k, v in loss_dict.items():\n loss_meter[k].update(v)\n\n # Stack all validation predictions for each class separately - iterate over each gpu & cloud\n self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=val_smooth)\n\n except tf.errors.OutOfRangeError:\n ep += 1\n pass\n\n if loss_meter:\n print(f'val loss avg:', ' '.join([f'{loss_n} = {meter.avg:.3f}' for loss_n, meter in loss_meter.items()]))\n\n label_to_idx = dataset.label_to_idx\n proportions = dataset.val_proportions\n cur_m = metrics_from_confusions(cum_dict['conf'], proportions=proportions) # use sampled pred-label of current epoch\n vote_m = metrics_from_result(validation_probs, dataset.input_labels['validation'], dataset.num_classes, label_to_idx=label_to_idx, proportions=proportions) # use the accumulated per-point voting\n\n print(f'metrics - current {cur_m}\\n'\n f' - accumulated {vote_m}', flush=True)\n return cur_m\n\n\n def val_vote_seg(self, sess, ops, dataset, model, num_votes=20):\n \"\"\"\n Voting validating\n \"\"\"\n\n feed_dict = {ops['is_training']: False}\n\n # Smoothing parameter for votes\n val_smooth = 0.95\n\n # Initialise iterator with val data\n sess.run(ops['val_init_op'])\n\n # Initiate global prediction over val clouds\n label_to_idx = dataset.label_to_idx\n proportions = dataset.val_proportions\n val_ops, cum_dict, extra_ops = self.initialize(ops, dataset, model, 'validation')\n val_probs = cum_dict['prob']\n\n vote_ind = 0\n last_min = -0.5\n if self.config.debug:\n print_dict(val_ops, head='val_vote_seg - val_ops')\n while last_min < num_votes:\n try:\n cur_rst = sess.run(val_ops, feed_dict=feed_dict)\n # Stack all validation predictions for each class separately - iterate over each gpu & cloud\n self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=val_smooth)\n\n except tf.errors.OutOfRangeError:\n new_min = np.min(dataset.min_potentials['validation'])\n if self.verbose:\n print(f'Step {vote_ind:3d}, end. Min potential = {new_min:.1f}', flush=True)\n if last_min + 1 < new_min:\n # Update last_min\n last_min += 1\n\n if self.verbose > 1:\n # Show vote results on subcloud (match original label to valid) => not the good values here\n vote_m = metrics_from_result(val_probs, dataset.input_labels['validation'], dataset.num_classes, label_to_idx=label_to_idx, proportions=proportions)\n print('==> Confusion on sub clouds: ', vote_m.scalar_str)\n\n if self.verbose > 1 and int(np.ceil(new_min)) % 2 == 0:\n # Project predictions\n vote_m = metrics_from_result(val_probs, dataset.validation_labels, dataset.num_classes, label_to_idx=label_to_idx, projections=dataset.validation_proj)\n print('==> Confusion on full clouds:', vote_m)\n\n sess.run(ops['val_init_op'])\n vote_ind += 1\n\n vote_m = metrics_from_result(val_probs, dataset.input_labels['validation'], dataset.num_classes, label_to_idx=label_to_idx, proportions=proportions)\n print('==> Confusion on sub clouds - final: ', vote_m.scalar_str)\n\n # Project predictions\n print('==> Confusion on full clouds - final:')\n vote_m = metrics_from_result(val_probs, dataset.validation_labels, dataset.num_classes, label_to_idx=label_to_idx, projections=dataset.validation_proj)\n vote_m.print()\n print('\\nfinished\\n', flush=True)\n\n return\n\n\n # Test methods\n # ------------------------------------------------------------------------------------------------------------------\n\n def test_classification(self, model, dataset, num_votes=100):\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n # Number of classes predicted by the model\n nc_model = config.num_classes\n\n # Initiate votes\n average_probs = np.zeros((len(dataset.input_labels['test']), nc_model))\n average_counts = np.zeros((len(dataset.input_labels['test']), nc_model))\n\n mean_dt = np.zeros(2)\n last_display = time.time()\n while np.min(average_counts) < num_votes:\n\n # Run model on all test examples\n # ******************************\n\n # Initiate result containers\n probs = []\n targets = []\n obj_inds = []\n count = 0\n\n while True:\n try:\n\n # Run one step of the model\n t = [time.time()]\n ops = (self.prob_logits, model.labels, model.inputs['object_inds'])\n prob, labels, inds = self.sess.run(ops, {model.dropout_prob: 1.0})\n t += [time.time()]\n\n # Get probs and labels\n probs += [prob]\n targets += [labels]\n obj_inds += [inds]\n count += prob.shape[0]\n\n # Average timing\n t += [time.time()]\n mean_dt = 0.95 * mean_dt + 0.05 * (np.array(t[1:]) - np.array(t[:-1]))\n\n # Display\n if (t[-1] - last_display) > self.gap_display:\n last_display = t[-1]\n message = 'Vote {:.0f} : {:.1f}% (timings : {:4.2f} {:4.2f})'\n print(message.format(np.min(average_counts),\n 100 * count / dataset.num_test,\n 1000 * (mean_dt[0]),\n 1000 * (mean_dt[1])))\n\n except tf.errors.OutOfRangeError:\n break\n\n # Average votes\n # *************\n\n # Stack all validation predictions\n probs = np.vstack(probs)\n targets = np.hstack(targets)\n obj_inds = np.hstack(obj_inds)\n\n if np.any(dataset.input_labels['test'][obj_inds] != targets):\n raise ValueError('wrong object indices')\n\n # Compute incremental average (predictions are always ordered)\n average_counts[obj_inds] += 1\n average_probs[obj_inds] += (probs - average_probs[obj_inds]) / (average_counts[obj_inds])\n\n # Save/Display temporary results\n # ******************************\n\n test_labels = np.array(dataset.label_values)\n\n # Compute classification results\n C1 = confusion_matrix(dataset.input_labels['test'],\n np.argmax(average_probs, axis=1),\n test_labels)\n\n ACC = 100 * np.sum(np.diag(C1)) / (np.sum(C1) + 1e-6)\n print('Test Accuracy = {:.1f}%'.format(ACC))\n\n s = ''\n for cc in C1:\n for c in cc:\n s += '{:d} '.format(c)\n s += '\\n'\n print(s)\n\n\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n return\n\n def test_multi_segmentation(self, model, dataset, num_votes=100, num_saves=10):\n\n ##################\n # Pre-computations\n ##################\n\n print('Preparing test structures')\n t1 = time.time()\n\n # Collect original test file names\n original_path = join(dataset.path, 'test_ply')\n test_names = [f[:-4] for f in listdir(original_path) if f[-4:] == '.ply']\n test_names = np.sort(test_names)\n\n original_labels = []\n original_points = []\n projection_inds = []\n for i, cloud_name in enumerate(test_names):\n\n # Read data in ply file\n data = read_ply(join(original_path, cloud_name + '.ply'))\n points = np.vstack((data['x'], -data['z'], data['y'])).T\n original_labels += [data['label'] - 1]\n original_points += [points]\n\n # Create tree structure to compute neighbors\n tree = KDTree(dataset.input_points['test'][i])\n projection_inds += [np.squeeze(tree.query(points, return_distance=False))]\n\n t2 = time.time()\n print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n ##########\n # Initiate\n ##########\n\n # Test saving path\n if config.save_test:\n test_path = join(model.saving_path, 'test')\n if not exists(test_path):\n makedirs(test_path)\n else:\n test_path = None\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n # Initiate result containers\n average_predictions = [np.zeros((1, 1), dtype=np.float32) for _ in test_names]\n\n #####################\n # Network predictions\n #####################\n\n mean_dt = np.zeros(2)\n last_display = time.time()\n for v in range(num_votes):\n\n # Run model on all test examples\n # ******************************\n\n # Initiate result containers\n all_predictions = []\n all_obj_inds = []\n\n while True:\n try:\n\n # Run one step of the model\n t = [time.time()]\n ops = (self.prob_logits,\n model.labels,\n model.inputs['super_labels'],\n model.inputs['object_inds'],\n model.inputs['in_batches'])\n preds, labels, obj_labels, o_inds, batches = self.sess.run(ops, {model.dropout_prob: 1.0})\n t += [time.time()]\n\n # Stack all predictions for each class separately\n max_ind = np.max(batches)\n for b_i, b in enumerate(batches):\n\n # Eliminate shadow indices\n b = b[b < max_ind - 0.5]\n\n # Get prediction (only for the concerned parts)\n obj = obj_labels[b[0]]\n predictions = preds[b][:, :config.num_classes[obj]]\n\n # Stack all results\n all_predictions += [predictions]\n all_obj_inds += [o_inds[b_i]]\n\n # Average timing\n t += [time.time()]\n mean_dt = 0.95 * mean_dt + 0.05 * (np.array(t[1:]) - np.array(t[:-1]))\n\n # Display\n if (t[-1] - last_display) > self.gap_display:\n last_display = t[-1]\n message = 'Vote {:d} : {:.1f}% (timings : {:4.2f} {:4.2f})'\n print(message.format(v,\n 100 * len(all_predictions) / dataset.num_test,\n 1000 * (mean_dt[0]),\n 1000 * (mean_dt[1])))\n\n except tf.errors.OutOfRangeError:\n break\n\n # Project predictions on original point clouds\n # ********************************************\n\n print('\\nGetting test confusions')\n t1 = time.time()\n\n for i, probs in enumerate(all_predictions):\n\n # Interpolate prediction from current positions to original points\n obj_i = all_obj_inds[i]\n proj_predictions = probs[projection_inds[obj_i]]\n\n # Average prediction across votes\n average_predictions[obj_i] = average_predictions[obj_i] + \\\n (proj_predictions - average_predictions[obj_i]) / (v + 1)\n\n Confs = []\n for obj_i, avg_probs in enumerate(average_predictions):\n\n # Compute confusion matrices\n parts = [j for j in range(avg_probs.shape[1])]\n Confs += [confusion_matrix(original_labels[obj_i], np.argmax(avg_probs, axis=1), parts)]\n\n\n t2 = time.time()\n print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n # Save the best/worst segmentations per class\n # *******************************************\n\n print('Saving test examples')\n t1 = time.time()\n\n # Regroup confusions per object class\n Confs = np.array(Confs)\n obj_mIoUs = []\n for l in dataset.label_values:\n\n # Get confusions for this object\n obj_inds = np.where(dataset.input_labels['test'] == l)[0]\n obj_confs = np.stack(Confs[obj_inds])\n\n # Get IoU\n obj_IoUs = IoU_from_confusions(obj_confs)\n obj_mIoUs += [np.mean(obj_IoUs, axis=-1)]\n\n # Get X best and worst prediction\n order = np.argsort(obj_mIoUs[-1])\n worst_inds = obj_inds[order[:num_saves]]\n best_inds = obj_inds[order[:-num_saves-1:-1]]\n worst_IoUs = obj_IoUs[order[:num_saves]]\n best_IoUs = obj_IoUs[order[:-num_saves-1:-1]]\n\n # Save the names in a file\n if config.save_test:\n obj_path = join(test_path, dataset.label_to_names[l])\n if not exists(obj_path):\n makedirs(obj_path)\n worst_file = join(obj_path, 'worst_inds.txt')\n best_file = join(obj_path, 'best_inds.txt')\n with open(worst_file, \"w\") as text_file:\n for w_i, w_IoUs in zip(worst_inds, worst_IoUs):\n text_file.write('{:d} {:s} :'.format(w_i, test_names[w_i]))\n for IoU in w_IoUs:\n text_file.write(' {:.1f}'.format(100*IoU))\n text_file.write('\\n')\n\n with open(best_file, \"w\") as text_file:\n for b_i, b_IoUs in zip(best_inds, best_IoUs):\n text_file.write('{:d} {:s} :'.format(b_i, test_names[b_i]))\n for IoU in b_IoUs:\n text_file.write(' {:.1f}'.format(100*IoU))\n text_file.write('\\n')\n\n # Save the clouds\n for i, w_i in enumerate(worst_inds):\n filename = join(obj_path, 'worst_{:02d}.ply'.format(i+1))\n preds = np.argmax(average_predictions[w_i], axis=1).astype(np.int32)\n write_ply(filename,\n [original_points[w_i], original_labels[w_i], preds],\n ['x', 'y', 'z', 'gt', 'pre'])\n\n for i, b_i in enumerate(best_inds):\n filename = join(obj_path, 'best_{:02d}.ply'.format(i+1))\n preds = np.argmax(average_predictions[b_i], axis=1).astype(np.int32)\n write_ply(filename,\n [original_points[b_i], original_labels[b_i], preds],\n ['x', 'y', 'z', 'gt', 'pre'])\n\n t2 = time.time()\n print('Done in {:.1f} s\\n'.format(t2 - t1))\n\n # Display results\n # ***************\n\n objs_average = [np.mean(mIoUs) for mIoUs in obj_mIoUs]\n instance_average = np.mean(np.hstack(obj_mIoUs))\n class_average = np.mean(objs_average)\n\n print('Objs | Inst | Air Bag Cap Car Cha Ear Gui Kni Lam Lap Mot Mug Pis Roc Ska Tab')\n print('-----|------|--------------------------------------------------------------------------------')\n\n s = '{:4.1f} | {:4.1f} | '.format(100 * class_average, 100 * instance_average)\n for AmIoU in objs_average:\n s += '{:4.1f} '.format(100 * AmIoU)\n print(s + '\\n')\n\n # Initialise iterator with test data\n self.sess.run(dataset.test_init_op)\n\n return\n\n def test_vote_seg(self, sess, ops, dataset, model, num_votes=20, test_path=None, make_zip=True):\n\n config = self.config\n assert os.path.isdir(config.saving_path), f'not a dir: {config.saving_path}'\n if test_path is None:\n test_path = os.path.join(config.saving_path, 'test')\n os.makedirs(test_path, exist_ok=True)\n\n options = None # tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = None # tf.RunMetadata()\n feed_dict = {ops['is_training']: False}\n\n # Smoothing parameter for votes\n test_smooth = 0.98\n\n # Initialise iterator with test data\n sess.run(ops['test_init_op'])\n\n # Initiate global prediction over val clouds\n test_ops, cum_dict, extra_ops = self.initialize(ops, dataset, model, 'test')\n test_probs = cum_dict['prob']\n\n vote_ind = 0\n last_min = -0.5 \n if config.num_votes:\n num_votes = config.num_votes\n while last_min < num_votes:\n try:\n cur_rst = sess.run(test_ops, feed_dict=feed_dict, options=options, run_metadata=run_metadata)\n # Stack all test predictions for each class separately - iterate over each gpu & cloud\n self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=test_smooth)\n\n except tf.errors.OutOfRangeError:\n # NOTE: need to check\n new_min = np.min(dataset.min_potentials['test'])\n if self.verbose:\n print(f'Step {vote_ind:3d}, end. Min potential = {new_min:.1f}', flush=True)\n\n if last_min + 1 < new_min:\n # Update last_min\n last_min += 1\n\n # if int(last_min) > 0 and int(last_min) // 5 == 0: # periodic test results\n # self.project_test_predictions(dataset, test_path)\n\n sess.run(ops['test_init_op'])\n vote_ind += 1\n\n if self.verbose:\n new_min = np.min(dataset.min_potentials['test'])\n print(f'Step {vote_ind:3d}, end. Min potential = {new_min:.1f}', flush=True)\n\n self.project_test_predictions(dataset, test_probs, test_path)\n print('\\nfinished\\n', flush=True)\n\n if make_zip:\n zip_name = test_path.split(os.sep) # cfg name / Log_* / test_*\n zip_name = '_'.join([i for i in ['test', *zip_name[-3:-1], zip_name[-1][len('test'):].strip('_')] if i])\n # include test_* dir (except Semantic3D, ScanNet)\n j = 'j' if config.dataset in ['ScanNet', 'Semantic3D', 'SensatUrban'] else ''\n os.system(f'cd {os.path.dirname(test_path)}; zip -rmTq{j} {zip_name}.zip {test_path.split(os.sep)[-1]}/*') # -m to move, -j junk file, -T test integrity, -q quiet\n os.system(f'rm -r {test_path}')\n return\n\n def project_test_predictions(self, dataset, test_probs, test_path):\n\n # Project predictions\n t1 = time.time()\n files = dataset.test_files\n ignored_inds = None\n if hasattr(dataset, 'ignored_labels_test'):\n ignored_inds = dataset.label_to_idx[[l for l in dataset.ignored_labels_test if l not in dataset.ignored_labels]].astype(int)\n\n config = self.config\n if config.save_test:\n pred_path = os.sep.join([*test_path.split(os.sep)[:-1], test_path.split(os.sep)[-1].replace('test', 'predictions')]) # model pred\n os.makedirs(pred_path, exist_ok=True)\n\n for i_test, file_path in enumerate(files):\n\n # Reproject probs\n probs = test_probs[i_test][dataset.test_proj[i_test], :]\n\n # Remove invalid classes in test\n if ignored_inds is not None:\n probs[:, ignored_inds] = 0\n\n # Get the predicted labels\n preds = dataset.idx_to_label[np.argmax(probs, axis=-1)]\n\n # Save plys - predictions & probs\n cloud_name = file_path.split('/')[-1]\n if config.save_test:\n points = dataset.load_evaluation_points(file_path) # test original points\n pots = dataset.potentials['test'][i_test][dataset.test_proj[i_test]] # project potentials on original points\n test_name = os.path.join(pred_path, cloud_name)\n prob_names = ['_'.join(dataset.label_to_names[label].split()) for label in dataset.label_values if label not in dataset.ignored_labels]\n write_ply(test_name,\n [points, preds, pots, probs],\n ['x', 'y', 'z', 'preds', 'pots'] + prob_names)\n\n # Save ascii preds - submission files\n if config.dataset == 'Semantic3D':\n ascii_name = os.path.join(test_path, dataset.ascii_files[cloud_name])\n np.savetxt(ascii_name, preds, fmt='%d')\n elif config.dataset == 'SensatUrban':\n ascii_name = os.path.join(test_path, f'{cloud_name[:-4]}.label')\n preds.astype(np.uint8).tofile(ascii_name)\n else:\n ascii_name = os.path.join(test_path, cloud_name[:-4] + '.txt')\n np.savetxt(ascii_name, preds, fmt='%d')\n\n t2 = time.time()\n if self.verbose:\n print('\\nReproject Vote in {:.1f}s\\n'.format(t2-t1))\n\n\n # Utilities\n # ------------------------------------------------------------------------------------------------------------------\n\n def cumulate_probs(self, dataset, model, rst, cum_dict, task, smooth):\n # cum_dict - {cum_dict name : {args : rst_dict}}\n\n # iterate over gpu\n for gpu_i, cloud_inds in enumerate(rst['inputs']['cloud_inds']):\n point_inds = rst['inputs']['point_inds'][gpu_i]\n\n b_start = 0\n # iterate over clouds\n for b_i, c_i in enumerate(cloud_inds): # [B]\n if 'batches_len' in rst['inputs']: # [BxN] - stacked\n b_len = rst['inputs']['batches_len'][gpu_i][0][b_i] # npoints in cloud\n b_i = np.arange(b_start, b_start + b_len)\n b_start += b_len\n else: # [B, N] - batched\n pass\n inds = point_inds[b_i] # input point inds\n\n probs = rst[task]['probs'][gpu_i][b_i]\n labels = rst[task]['labels'][gpu_i][b_i]\n if np.all(labels == -1):\n # c_pts = np.array(dataset.input_trees['validation'][c_i].data, copy=False)[inds].mean(axis=0)\n # unique_l_cnt = np.unique(dataset.input_labels['validation'][c_i][inds], return_counts=True)\n # raise ValueError(f'all invalid labels found in cumulate_prob: cloud_inds={c_i}, center_pts={c_pts}'\n # f'input_labels & counts - {unique_l_cnt}')\n continue\n if 'conf' in cum_dict:\n cur_conf = confusion_matrix(labels, np.argmax(probs, axis=-1).astype(np.int), labels=np.arange(dataset.num_classes))\n cum_dict['conf'] += cur_conf\n if 'prob' in cum_dict:\n cum_dict['prob'][c_i][inds] = smooth * cum_dict['prob'][c_i][inds] + (1 - smooth) * probs\n if 'feature' in cum_dict:\n cum_dict['feature'][c_i][inds] = smooth * cum_dict['feature'][c_i][inds] + (1 - smooth) * rst[task]['latent'][gpu_i][b_i]\n\n def _search_func(self, k_r, cloud_idx, split, dataset, neighbor_dict, verbose=True): # create tf_ops of generating neighbor_idx & get result\n if cloud_idx in neighbor_dict[k_r]:\n return neighbor_dict[k_r][cloud_idx]\n\n config = self.config\n points = np.array(dataset.input_trees[split][cloud_idx].data, copy=False) # [N, 3]\n\n from ops import get_tf_func\n func = get_tf_func(config.search, verbose=verbose)\n\n if config.search in ['knn']:\n tf_ops = tf.squeeze(func(points[None, ...], points[None, ...], k_r), axis=0)\n elif config.search in ['radius']:\n tf_ops = func(points, points, [len(points)], [len(points)], k_r)\n # if hasattr(dataset, 'neighborhood_limits'):\n # print('neighborhood_limits', dataset.neighborhood_limits[0])\n # tf_ops = tf_ops[..., :dataset.neighborhood_limits[0]]\n else:\n raise\n\n if verbose:\n print_mem(f'k = {k_r} - start', check_time=True, check_sys=True, flush=True)\n with tf.Session(config=tf.ConfigProto(device_count={'GPU': 0}, allow_soft_placement=True)) as s:\n neighbor_idx = s.run(tf_ops)\n if verbose:\n print_mem(f'neighbor_idx {neighbor_idx.shape}', check_time=True, check_sys=True, flush=True)\n\n neighbor_dict[k_r][cloud_idx] = neighbor_idx # neighbor idx - np arr\n return neighbor_idx" }, { "identifier": "ModelTrainer", "path": "utils/trainer.py", "snippet": "class ModelTrainer:\n \"\"\"\n get & train the model (potential multi-gpu training)\n \"\"\"\n\n def __init__(self, config, verbose=True):\n self.config = config\n self.verbose = verbose\n self.tester = ModelTester(config, verbose=False)\n\n def add_summary(self, model):\n with tf.variable_scope('summary'):\n summary = model.summary\n log_content = self.config.log_content\n\n if 'var' in log_content:\n summary['per_log'] += [tf.summary.histogram(v.name, v) for g, v in gvs]\n if 'gard' in log_content:\n summary['per_log'] += [tf.summary.histogram(f'{v.name}_grad', g) for g, v in gvs]\n\n sum_levels = ['per_step', 'per_log', 'per_epoch']\n assert all([k in sum_levels for k in summary.keys()]), f'undesired keys in summary dict: {str(summary.keys())}'\n for i in range(len(sum_levels)):\n summary[lv] = tf.summary.merge(summary[lv]) if summary[lv] else [tf.no_op]\n self.summary = summary\n return\n\n # Training main method\n # ------------------------------------------------------------------------------------------------------------------\n\n def train(self):\n config = self.config\n with tf.Graph().as_default(): # use one graph\n\n # prepare compute graph\n g = GraphBuilder(config, verbose=self.verbose)\n ops, sess, grads, saver = g.ops, g.sess, g.grads, g.saver\n model, dataset = g.model, g.dataset\n self.model = model\n\n # printing model parameters\n if self.verbose:\n print('\\n --------- printing grads {')\n re_list = ['.*bias:.*', '.*batch_normalization.*'] # skipping\n print_table([(v.name, g) for g, v in grads if not any([bool(re.fullmatch(expr, v.name)) for expr in re_list])], prefix='\\t')\n print('} --------- printing grads')\n # all ops in graph\n print('\\n --------- all ops {')\n re_list = ['optimizer.*', 'gpu_.*', 'gradients.*', 'save.*'] # '.*/batch_normalization/.*', '.*/bias:.*' # skipping\n for n in tf.get_default_graph().as_graph_def().node:\n if any([bool(re.fullmatch(expr, n.name)) for expr in re_list]): continue\n print('\\t', n.name)\n print('} --------- all ops')\n # model params\n all_params_size = sum([np.prod(v.shape) for _, v in grads])\n # all_params_size = tf.reduce_sum([tf.reduce_prod(v.shape) for _, v in grads])\n # all_params_size = sess.run(all_params_size)\n print(f'==> Model have {all_params_size} total Params', flush=True)\n\n # init sess\n sess.run(tf.global_variables_initializer())\n if self.config.model_path:\n except_list = [f'.*{n}.*' for n in self.config.exclude_vars] + ['optimizer.*'] if not self.config.continue_training else []\n g.restore(sess, self.config.model_path, except_list=except_list)\n print(f'Model restored -- {self.config.model_path}')\n\n # running voting - used throughout the training process (accumulated voting)\n validation_probs = self.tester.init_pointcloud_log(dataset, 'validation', config.num_classes)\n\n # train func\n if config.debug_nan:\n self.train_one_epoch = self.train_one_epoch_debug\n\n # train\n metric_best = None\n # save_snap = [i for i in range(1, config.max_epoch + 1) if i % config.save_freq == 0]\n lr_scheduler = LrScheduler(config)\n snap_path = os.path.join(config.saving_path, config.snap_dir, config.snap_prefix)\n for epoch in range(1, config.max_epoch + 1):\n print(f'\\n****EPOCH {epoch}****')\n lr = lr_scheduler.learning_rate\n\n tic1 = time.time()\n step = self.train_one_epoch(sess, ops, epoch, lr, g=g)\n tic2 = time.time()\n print(f'total time: {(tic2 - tic1)/60:.1f}min, learning rate = {lr:.7f}', flush=True)\n\n if epoch % config.val_freq == 0:\n metric = self.tester.val_running_vote(sess, ops, dataset, model, validation_probs) # running voting\n if metric_best is None or metric > metric_best: # keep the best val\n metric_best = metric\n saver.save(sess, snap_path + '-best')\n print('best saved')\n # if config.save_best:\n # saver.save(sess, snap_path + '-best')\n # if config.save_best == 'center':\n # epoch_start = max(epoch // config.save_freq - config.max_to_keep // 2, 1)\n # save_snap = [i * config.save_freq for i in range(epoch_start, epoch_start + config.max_to_keep + 1)]\n # save_snap = [i for i in save_snap if i != epoch]\n # if epoch in save_snap:\n if config.save_freq and epoch % config.save_freq == 0:\n saver.save(sess, snap_path, global_step=epoch)\n lr_scheduler.step(epoch=1, step=step)\n\n # val & save last model if missed\n if epoch % config.val_freq != 0:\n self.tester.val_running_vote(sess, ops, dataset, model, validation_probs)\n if config.save_freq and epoch % config.save_freq != 0:\n saver.save(sess, snap_path, global_step=epoch)\n print('\\nfinished\\n', flush=True)\n return\n\n def train_one_epoch(self, sess, ops, epoch, lr, g=None):\n \"\"\"\n One epoch training\n \"\"\"\n config = self.config\n\n is_training = True\n batch_time = AverageMeter()\n loss_meter = {k: AverageMeter() for k in ops['loss_dict']}\n\n train_ops = {'train_op': ops['train_op'], 'loss_dict': ops['loss_dict']}\n feed_dict = {ops['is_training']: is_training, ops['learning_rate']: lr}\n sess.run(ops['train_init_op'])\n\n batch_idx = 0\n end = time.time()\n while True:\n try:\n rst = sess.run(train_ops, feed_dict=feed_dict)\n\n if (batch_idx + 1) % config.update_freq == 0:\n for k, v in rst['loss_dict'].items():\n loss_meter[k].update(v)\n batch_time.update(time.time() - end)\n end = time.time()\n\n if (batch_idx + 1) % config.print_freq == 0:\n loss_str = ' '.join([f'{n}={meter.avg:<6.2f}' for n, meter in loss_meter.items()])\n print(f'Step {batch_idx+1:08d} ' + loss_str + f' ---{batch_time.avg:5.3f} s/batch', flush=True)\n\n batch_idx += 1\n except tf.errors.OutOfRangeError:\n break\n return batch_idx\n\n # Debug methods\n # ------------------------------------------------------------------------------------------------------------------\n\n def show_memory_usage(self, batch_to_feed):\n\n for l in range(self.config.num_layers):\n neighb_size = list(batch_to_feed[self.in_neighbors_f32[l]].shape)\n dist_size = neighb_size + [self.config.num_kernel_points, 3]\n dist_memory = np.prod(dist_size) * 4 * 1e-9\n in_feature_size = neighb_size + [self.config.first_features_dim * 2**l]\n in_feature_memory = np.prod(in_feature_size) * 4 * 1e-9\n out_feature_size = [neighb_size[0], self.config.num_kernel_points, self.config.first_features_dim * 2**(l+1)]\n out_feature_memory = np.prod(out_feature_size) * 4 * 1e-9\n\n print('Layer {:d} => {:.1f}GB {:.1f}GB {:.1f}GB'.format(l,\n dist_memory,\n in_feature_memory,\n out_feature_memory))\n print('************************************')\n\n def train_one_epoch_debug(self, sess, ops, epoch, lr, g=None):\n \"\"\"\n One epoch training\n \"\"\"\n config = self.config\n\n is_training = True\n batch_time = AverageMeter()\n loss_meter = {k: AverageMeter() for k in ops['loss_dict']}\n\n inputs = self.model.inputs\n inputs_flat = {k: v for k, v in inputs.items() if not isinstance(v, (list, dict))}\n train_ops = {'train_op': ops['train_op'], 'loss_dict': ops['loss_dict'], 'inputs': inputs_flat, 'result_dict': ops['result_dict']}\n assert_ops = inputs['assert_ops'] if 'assert_ops' in inputs and len(inputs['assert_ops']) > 0 else []\n feed_dict = {ops['is_training']: is_training, ops['learning_rate']: lr}\n sess.run(ops['train_init_op'])\n\n if config.debug_grads:\n assert g is not None # [(g, v), ...]\n train_ops['grads'] = g.grads\n\n batch_idx = 0\n end = time.time()\n while True:\n try:\n with tf.control_dependencies(assert_ops):\n rst = sess.run(train_ops, feed_dict=feed_dict)\n\n # NaN appears\n if config.debug_grads:\n self.debug_grads_nan(sess, inputs, train_ops, rst)\n\n if any([np.isnan(v) for v in rst['loss_dict'].values()]):\n self.debug_nan(sess, rst['inputs'], rst['result_dict'], rst['loss_dict'])\n raise ArithmeticError(f'NaN encountered !!!')\n\n if (batch_idx + 1) % config.update_freq == 0:\n for k, v in rst['loss_dict'].items():\n loss_meter[k].update(v)\n batch_time.update(time.time() - end)\n end = time.time()\n\n if (batch_idx + 1) % config.print_freq == 0:\n loss_str = ' '.join([f'{n}={meter.avg:<6.2f}' for n, meter in loss_meter.items()])\n print(f'Step {batch_idx+1:08d} ' + loss_str + f' ---{batch_time.avg:5.3f} s/batch', flush=True)\n\n batch_idx += 1\n except tf.errors.OutOfRangeError:\n break\n return batch_idx\n\n def debug_grads_nan(self, sess, inputs, ops, rst):\n grads = ops['grads']\n grads_v = rst['grads']\n\n nan_grads = [(g, v, g_val, v_val) for (g, v), (g_val, v_val) in zip(grads, grads_v) if np.isnan(g_val).any() or np.isnan(v_val).any()]\n if not nan_grads:\n return\n\n lines = []\n for g, v, g_val, v_val in nan_grads:\n g_nan = 100 * np.sum(np.isnan(g_val)) / np.prod(g_val.shape)\n v_nan = 100 * np.sum(np.isnan(v_val)) / np.prod(v_val.shape)\n lines.append([v.name, g, '-', v_val.shape, f'/ {v_nan:.1f}', 'val nan', g_val.shape, f'/ {g_nan:.1f}', 'grad nan'])\n print_table(lines)\n\n self.debug_nan(sess, rst['inputs'], rst['result_dict'], rst['loss_dict'])\n raise ArithmeticError(f'NaN encountered in grads checking !!!')\n return\n\n def debug_nan(self, sess, inputs, result_dict, loss_dict):\n \"\"\"\n NaN happened, find where\n \"\"\"\n\n print('\\n\\n------------------------ NaN DEBUG ------------------------\\n')\n\n print('loss_dict :')\n print('*******************\\n')\n print_dict(loss_dict)\n\n # Then print a list of the trainable variables and if they have nan\n print('List of variables :')\n print('*******************\\n')\n all_vars = sess.run(tf.global_variables())\n for v, value in zip(tf.global_variables(), all_vars):\n nan_percentage = 100 * np.sum(np.isnan(value)) / np.prod(value.shape)\n line = v.name + (f'\\t => {nan_percentage:.1f}% of values are NaN' if np.isnan(value).any() else '')\n print(line)\n\n print('Inputs :')\n print('********')\n\n #Print inputs\n for layer in range(self.config.num_layers):\n\n print(f'Layer : {layer}')\n\n points = inputs['points'][layer]\n neighbors = inputs['neighbors'][layer]\n pools = inputs['pools'][layer]\n upsamples = inputs['upsamples'][layer]\n\n nan_percentage = 100 * np.sum(np.isnan(points)) / np.prod(points.shape)\n print('Points =>', points.shape, '{:.1f}% NaN'.format(nan_percentage))\n nan_percentage = 100 * np.sum(np.isnan(neighbors)) / np.prod(neighbors.shape)\n print('neighbors =>', neighbors.shape, '{:.1f}% NaN'.format(nan_percentage))\n nan_percentage = 100 * np.sum(np.isnan(pools)) / np.prod(pools.shape)\n print('pools =>', pools.shape, '{:.1f}% NaN'.format(nan_percentage))\n nan_percentage = 100 * np.sum(np.isnan(upsamples)) / np.prod(upsamples.shape)\n print('upsamples =>', upsamples.shape, '{:.1f}% NaN'.format(nan_percentage))\n\n features = inputs['features']\n nan_percentage = 100 * np.sum(np.isnan(features)) / np.prod(features.shape)\n print('features =>', features.shape, '{:.1f}% NaN'.format(nan_percentage))\n batch_weights = inputs['batch_weights']\n in_batches = inputs['in_batches']\n max_b = np.max(in_batches)\n print(in_batches.shape)\n in_b_sizes = np.sum(in_batches < max_b - 0.5, axis=-1)\n print('in_batch_sizes =>', in_b_sizes)\n out_batches = inputs['out_batches']\n max_b = np.max(out_batches)\n print(out_batches.shape)\n out_b_sizes = np.sum(out_batches < max_b - 0.5, axis=-1)\n print('out_batch_sizes =>', out_b_sizes)\n point_labels = inputs['point_labels']\n if self.config.dataset.startswith('ShapeNetPart_multi'):\n object_labels = inputs['object_labels']\n nan_percentage = 100 * np.sum(np.isnan(object_labels)) / np.prod(object_labels.shape)\n print('object_labels =>', object_labels.shape, '{:.1f}% NaN'.format(nan_percentage))\n augment_scales = inputs['augment_scales']\n augment_rotations = inputs['augment_rotations']\n\n print('\\npoolings and upsamples nums :\\n')\n\n #Print inputs\n for layer in range(self.config.num_layers):\n\n print(f'\\nLayer : {layer}')\n\n neighbors = inputs['neighbors'][layer]\n pools = inputs['pools'][layer]\n upsamples = inputs['upsamples'][layer]\n\n max_n = np.max(neighbors)\n nums = np.sum(neighbors < max_n - 0.5, axis=-1)\n print('min neighbors =>', np.min(nums))\n\n max_n = np.max(pools)\n nums = np.sum(pools < max_n - 0.5, axis=-1)\n print('min pools =>', np.min(nums))\n\n max_n = np.max(upsamples)\n nums = np.sum(upsamples < max_n - 0.5, axis=-1)\n print('min upsamples =>', np.min(nums))\n\n\n print('\\n--- NaN Debug Print End ---\\n\\n', flush=True)\n\n # # save everything to reproduce error - inputs/logits\n # file1 = os.path.join(self.config.saving_path, 'all_debug_inputs.pkl')\n # with open(file1, 'wb') as f1:\n # pickle.dump(inputs, f1)\n # file1 = os.path.join(self.config.saving_path, 'all_debug_logits.pkl')\n # with open(file1, 'wb') as f1:\n # pickle.dump(logits, f1)\n\n\n time.sleep(0.5)" }, { "identifier": "GraphBuilder", "path": "utils/tf_graph_builder.py", "snippet": "class GraphBuilder(object):\n\n def __init__(self, config, graph=None, verbose=True):\n \"\"\"\n get the full compute graph including dataset, model inference, loss, optimizer, lr scheduler and required ops\n \"\"\"\n\n if graph is not None: # if graph specified\n with graph.as_default():\n return self.__init__(config, None, verbose)\n\n if isinstance(config.rand_seed, int): # set seed\n tf.set_random_seed(config.rand_seed)\n np.random.seed(config.rand_seed)\n if verbose:\n print(f'==> np random seed = {np.random.get_state()[1][0]}')\n\n # model & dataset fn\n self.get_dataset = getattr(datasets, f'{config.dataset}Dataset') # datasets.[name]Dataset\n self.get_model = models.get_model\n # if config.distribute == 'tf_device': # full compute graph (handle devices & platforms)\n # self.build = self.build_devices\n # else:\n # raise NotImplementedError(f'not supported type of distributing graphs: config.distribute={config.distribute}')\n\n # Get dataset\n if verbose:\n print('==> Preparing datasets...')\n dataset = self.get_dataset(config, verbose)\n dataset.initialize(verbose)\n if verbose:\n print('==> setting dataset info:')\n print_dict(dataset.info, prefix='\\t')\n print_mem('>>> dataset built')\n config.update(dataset.info)\n\n # placeholder\n is_training = tf.placeholder(tf.bool, shape=())\n learning_rate = tf.placeholder(tf.float32, shape=(), name='learning_rate')\n # learning_rate = tf.get_variable('learning_rate', [], initializer=tf.constant_initializer(float('nan')), trainable=False)\n\n # # build model\n # grads, total_loss_dict, total_result_dict, model = self.build(dataset, is_training, config, verbose=verbose)\n\n # -------------------------------------------\n # Get model and loss on multiple GPU devices\n # -------------------------------------------\n # Allocating variables on CPU first will greatly accelerate multi-gpu training.\n # Ref: https://github.com/kuza55/keras-extras/issues/21\n flat_inputs = dataset.flat_inputs\n if config.cpu_variables:\n self.get_model(flat_inputs[0], is_training, config=config, verbose=verbose)\n tower_grads = []\n total_losses = []\n total_result = []\n for igpu in range(config.gpu_num):\n with tf.variable_scope(tf.get_variable_scope(), reuse=True if config.cpu_variables else tf.AUTO_REUSE):\n name_scope = f'gpu_{igpu}' if config.cpu_variables or igpu > 0 else ''\n verbose = not bool(name_scope)\n with tf.device(f'/gpu:{igpu}'), tf.name_scope(name_scope) as scope:\n flat_inputs_i = flat_inputs[igpu]\n model = self.get_model(flat_inputs_i, is_training, config=config, scope=scope, verbose=verbose) # inference model\n\n # collect per-gpu info\n result_dict = model.get_result() # inference result\n total_result.append(result_dict)\n\n loss_dict = model.get_loss() # loss\n total_losses.append(loss_dict)\n\n var_list = tf.trainable_variables() # vars & grads\n var_list = self.collect_vars(var_list, include_k=config.vars_train, except_k=config.vars_freeze)\n grads = tf.gradients(loss_dict['loss'], var_list, colocate_gradients_with_ops=config.colocate_gradients_with_ops) # normally, should NOT co-locate\n grads = list(zip(grads, var_list))\n tower_grads.append(grads)\n total_inputs = dict_list(flat_inputs)\n total_result = dict_list(total_result)\n total_losses = dict_list(total_losses)\n\n # average losses from multiple GPUs\n with tf.variable_scope('losses'):\n total_losses = {k: tf.reduce_mean(v, name=k) if len(v) > 1 else v[0] for k, v in total_losses.items()}\n\n # average grad\n with tf.variable_scope('gradients'):\n # [(gradient, variable), ...] - gradient averaged over gpu towers (if >1)\n grads = average_gradients(tower_grads, grad_norm=config.grad_norm, raise_on_none=config.grad_raise_none, grad_reduce=config.grad_reduce)\n\n # setup optimizer\n with tf.variable_scope('optimizer'):\n if config.optimizer == 'sgd':\n optimizer = tf.train.MomentumOptimizer(learning_rate, momentum=config.momentum)\n elif config.optimizer == 'adam':\n optimizer = tf.train.AdamOptimizer(learning_rate)\n elif config.optimizer == 'adamW':\n from utils.AdamWOptimizer import AdamWeightDecayOptimizer\n optimizer = AdamWeightDecayOptimizer(learning_rate=learning_rate, weight_decay_rate=config.weight_decay, exclude_from_weight_decay=[\"bias\"])\n\n # if config.mixed_precision:\n # optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(optimizer)\n\n # momentume as update ops\n update_ops = self.get_momentum_update(model, config, total_inputs, total_result)\n for ops in update_ops: # add to collection\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, ops)\n\n # train op\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.apply_gradients(grads)\n # train_op = optimizer.apply_gradients(grads)\n # train_op = tf.group([train_op, update_ops])\n\n # saver\n save_vars = None\n if config.save_compact:\n save_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='model')\n if isinstance(config.save_compact, bool):\n pass\n elif isinstance(config.save_compact, str) and config.save_compact == 'trained':\n vars_grads = {v: g for g, v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='model')}\n save_vars = [v for v in save_vars if v in vars_grads and vars_grads[v] is not None] # save only trained\n else:\n raise ValueError(f'not support save_compact={config.save_compact}')\n saver = tf.train.Saver(save_vars, max_to_keep=int(config.max_to_keep))\n\n # summary\n with tf.variable_scope('summary'):\n if config.summary and isinstance(config.summary, str):\n inputs = model.inputs\n if 'summary' not in inputs:\n inputs['summary'] = defaultdict(lambda: [])\n if config.summary == 'loss':\n inputs['summary']['per_step'] += [tf.summary.scalar(k, v) for k, v in total_losses.items()]\n # log grads - debug use\n # inputs = model.inputs\n # inputs['summary'] = defaultdict(lambda: [])\n # from models.utils import tf_Print\n # for i, (g, v) in enumerate(grads):\n # if config.summary:\n # inputs['summary']['per_step'] += [tf.summary.histogram(f'{v.name}/v', v)]\n # inputs['summary']['per_step'] += [tf.summary.histogram(f'{v.name}/g', g)]\n # if v.name in [\n # 'model/resnet_scene_segmentation_head/up_conv3/weights:0',\n # 'model/resnet_scene_segmentation_head/segmentation_head/weights:0',\n # ]:\n # print(f'print grad - {v.name}')\n # g = tf_Print(g, [f'grads - {v.name}', g])\n # grads[i] = (g, v)\n # input('\\nprint above grads')\n # summary - merge\n summary_dict = {} # {level : merged op}\n if config.summary:\n sum_levels = ['per_step', 'per_log', 'per_epoch']\n summary_ops = model.inputs['summary'] if 'summary' in model.inputs else {k: [] for k in sum_levels}\n assert all([k in sum_levels for k in summary_ops]), f'undesired keys in summary ops: {summary_ops.keys()}'\n for i in range(len(sum_levels)):\n lv = sum_levels[-i - 1]\n ops = sum([summary_ops[k] for k in sum_levels[:len(sum_levels)-i]], [])\n summary_dict[lv] = tf.summary.merge(ops) if len(ops) > 0 else tf.no_op()\n\n # Create a session\n cProto = tf.ConfigProto()\n if config.gpu_allow_growth:\n cProto.gpu_options.allow_growth = True\n if config.debug_single:\n cProto.device_count['CPU'] = 1\n # config.intra_op_parallelism_threads = config.inter_op_parallelism_threads = psutil.cpu_count(logical=False) # set to num of physical (default to logical) cpu cores\n cProto.allow_soft_placement = bool(config.allow_soft_placement) or not bool(config.gpu_devices) # if specified or cpu-only\n cProto.log_device_placement = False\n sess = tf.Session(config=cProto)\n\n ops = {\n 'train_init_op': dataset.train_init_op,\n 'val_init_op': dataset.val_init_op,\n 'test_init_op': dataset.test_init_op,\n\n 'train_op': train_op,\n 'is_training': is_training,\n 'learning_rate': learning_rate,\n\n 'inputs': dict(total_inputs),\n 'loss_dict': dict(total_losses),\n 'result_dict': dict(total_result),\n 'summary_dict': dict(summary_dict),\n }\n if verbose:\n print_mem('>>> model built')\n print('\\n -------- inputs {')\n print_dict(model.inputs, prefix='\\t')\n print('} --------- inputs')\n print('\\n -------- loss_dict {')\n print_dict(total_losses, prefix='\\t')\n print('} --------- loss_dict')\n print('\\n -------- result_dict {')\n print_dict(total_result, prefix='\\t')\n print('} --------- result_dict')\n\n self.ops = ops\n self.sess = sess\n self.grads = grads\n self.saver = saver\n\n self.model = model\n self.dataset = dataset\n\n # -------------------------------------------\n # Other utils & interfaces\n # -------------------------------------------\n\n def collect_vars(self, var_list, include_k=[], except_k=[], match='search'):\n # collect specified vars - default to all vars\n var_collect = []\n match_func = getattr(re, match)\n include_k = [include_k] if include_k and isinstance(include_k, str) else include_k\n except_k = [include_k] if except_k and isinstance(except_k, str) else except_k\n for v in var_list:\n if include_k and not any(match_func(k, v.name) for k in include_k):\n continue\n if except_k and any(match_func(k, v.name) for k in except_k):\n continue\n var_collect.append(v)\n return var_collect\n\n def get_momentum_update(self, model, config, total_inputs, total_result):\n # collect update ops for momentum update\n update_ops = []\n\n # update ops - momentum dict\n # NOTE - can be done in per-head fashion\n # => check only sepcial 'momentum_update_stage'\n for head_n, head_d in total_result.items():\n if 'momentum_dict' not in head_d or 'momentum_dict' not in total_inputs: continue\n if head_n not in total_inputs['momentum_dict']:\n raise KeyError(f'building momentum cycle for head {head_n}: missing tensor for momentum dict')\n head_cfg = model.head_dict['config'][head_n]\n\n # per-device input/output\n mom_in = total_inputs['momentum_dict'][head_n] # {k : [v = tensor]}, with inputs['momentum_dict'] = {head_n: {k : placeholder/vars}}\n mom_out = head_d['momentum_dict'] # {k: [v = tensor]}\n for k, v_out in mom_out.items():\n v_in = mom_in[k]\n\n # collect for update\n mom_avg = head_cfg.momentum_update\n mom_avg = float(mom_avg) if isinstance(mom_avg, (str, int)) else mom_avg # can be variable\n with tf.variable_scope(f'mom_dict_update/{head_n}/{k}'):\n if head_cfg.momentum_update_stage == 'glb_avg':\n # average over devices\n v_out = tf.reduce_mean(tf.stack(v_out, axis=0), axis=0)\n v_out = [v_in[i] * mom_avg + v_out * (1 - mom_avg) for i in range(config.gpu_num)]\n\n elif head_cfg.momentum_update_stage == 'glb_sum':\n # sum over devices\n v_out = tf.reduce_sum(tf.stack(v_out, axis=0), axis=0)\n v_out = [v_in[i] * mom_avg + v_out * (1 - mom_avg) for i in range(config.gpu_num)]\n\n # create update ops\n for igpu in range(config.gpu_num): # assign to each device input\n with tf.variable_scope(f'gpu_{igpu}/mom_dict_update/{head_n}/{k}', reuse=True):\n update_ops += [tf.assign(v_in[igpu], v_out[igpu])]\n\n return update_ops\n\n\n\n def restore(self, *args, **kwargs):\n argspec = inspect.getfullargspec(restore)\n kwargs.update(zip(argspec.args, args))\n kw_self = {'session': self.sess} # , 'saver': self.saver\n for k, v in kw_self.items():\n if k not in kwargs:\n kwargs[k] = v\n return restore(**kwargs)\n\n def close(self):\n self.sess.close()\n tf.reset_default_graph()" } ]
import numpy as np import multiprocessing as mp import os, sys, time, glob, pickle, psutil, argparse, importlib import tensorflow as tf import models, datasets import utils.memory_saving_gradients from config import load_config, log_config from utils.logger import print_mem, redirect_io from config.utils import get_snap from utils.tester import ModelTester from utils.trainer import ModelTrainer from utils.tf_graph_builder import GraphBuilder
17,100
# Common libs sys.path.insert(0, f'{os.getcwd()}') # Custom libs def get_last_train(cfg): saving_path = sorted(glob.glob(f'results/{cfg.dataset.lower()}/{cfg.name}/*')) return saving_path[-1] if saving_path else None parser = argparse.ArgumentParser() parser.add_argument('-c', '--cfg_path', type=str, help='config path') parser.add_argument('--gpus', type=str, default=None, help='the number/ID of GPU(s) to use [default: 1], 0 to use cpu only') parser.add_argument('--mode', type=str, default=None, help='options: train, val, test') parser.add_argument('--seed', type=int, default=None, dest='rand_seed', help='random seed for use') parser.add_argument('--data_path', type=str, default=None, help='path to dataset dir = data_path/dataset_name') parser.add_argument('--model_path', type=str, default=None, help='pretrained model path') parser.add_argument('--saving_path', type=str, default=None, help='specified saving path') parser.add_argument('--num_votes', type=float, default=None, help='least num of votes of each point (default to 30)') parser.add_argument('--num_threads', type=lambda n: mp.cpu_count() if n == 'a' else int(n) if n else None, default=None, help='the number of cpu to use for data loading') parser.add_argument('--set', type=str, help='external source to set the config - str of dict / yaml file') parser.add_argument('--debug', action='store_true', help='debug mode') FLAGS = parser.parse_args() # sys.argv = sys.argv[:1] # clean extra argv # ---------------------------------------------------------------------------- # # solve env & cfg # ---------------------------------------------------------------------------- # assert FLAGS.cfg_path is not None # load config - config path: config(dir).dataset_name(py).config_name(py_class) cfg = load_config(cfg_path=FLAGS.cfg_path) # update config for arg in ['data_path', 'model_path', 'saving_path', 'mode', 'gpus', 'rand_seed', 'num_threads', 'num_votes', 'debug']: if getattr(FLAGS, arg) is not None: setattr(cfg, arg, getattr(FLAGS, arg)) if FLAGS.set: for arg in FLAGS.set.split(';'): cfg.update(arg) # env setting: visible gpu, tf warnings (level = '0'/'3') os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES'] = cfg.gpu_devices os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0' if cfg.mixed_precision: os.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1' if tf.__version__.split('.')[0] == '2': tf = tf.compat.v1 tf.disable_v2_behavior() # solve config if cfg.dataset in ['S3DIS']: cfg.mode = cfg.mode.replace('test', 'validation') if cfg.model_path and os.path.isdir(cfg.model_path): cfg.model_path = get_snap(cfg.model_path, step='last') if cfg.save_memory: # use gradient-checkpointing to save memory tf.__dict__['gradients'] = utils.memory_saving_gradients.gradients_memory # one from the: gradients_speed, gradients_memory, gradients_collection if isinstance(cfg.rand_seed, int): # manual set seed tf.set_random_seed(cfg.rand_seed) np.random.seed(cfg.rand_seed) if cfg.debug: # debug mode cfg.saving_path = 'test' cfg.log_file = sys.stdout # ---------------------------------------------------------------------------- # # training # ---------------------------------------------------------------------------- # if 'train' in cfg.mode: # result dir: results/dataset_name/config_name/Log_time/... if not cfg.saving_path: time.sleep(np.random.randint(1, 10)) # random sleep (avoid same log dir) # dataset_name = '_'.join([i for i in [cfg.dataset.lower(), cfg.version, cfg.validation_split] if i]) # default version / validation_split specified in dataset class cfg.saving_path = f'results/{cfg.dataset.lower()}/{cfg.name}/' + time.strftime('Log_%Y-%m-%d_%H-%M-%S', time.gmtime()) os.makedirs(cfg.saving_path, exist_ok=True) if not cfg.log_file: cfg.log_file = os.path.join(cfg.saving_path, 'log_train.txt') if isinstance(cfg.log_file, str): cfg.log_file = open(cfg.log_file, 'w') log_config(cfg) log_config(cfg, f_out=cfg.log_file) # actual training print_mem('>>> start training', check_time=True)
# Common libs sys.path.insert(0, f'{os.getcwd()}') # Custom libs def get_last_train(cfg): saving_path = sorted(glob.glob(f'results/{cfg.dataset.lower()}/{cfg.name}/*')) return saving_path[-1] if saving_path else None parser = argparse.ArgumentParser() parser.add_argument('-c', '--cfg_path', type=str, help='config path') parser.add_argument('--gpus', type=str, default=None, help='the number/ID of GPU(s) to use [default: 1], 0 to use cpu only') parser.add_argument('--mode', type=str, default=None, help='options: train, val, test') parser.add_argument('--seed', type=int, default=None, dest='rand_seed', help='random seed for use') parser.add_argument('--data_path', type=str, default=None, help='path to dataset dir = data_path/dataset_name') parser.add_argument('--model_path', type=str, default=None, help='pretrained model path') parser.add_argument('--saving_path', type=str, default=None, help='specified saving path') parser.add_argument('--num_votes', type=float, default=None, help='least num of votes of each point (default to 30)') parser.add_argument('--num_threads', type=lambda n: mp.cpu_count() if n == 'a' else int(n) if n else None, default=None, help='the number of cpu to use for data loading') parser.add_argument('--set', type=str, help='external source to set the config - str of dict / yaml file') parser.add_argument('--debug', action='store_true', help='debug mode') FLAGS = parser.parse_args() # sys.argv = sys.argv[:1] # clean extra argv # ---------------------------------------------------------------------------- # # solve env & cfg # ---------------------------------------------------------------------------- # assert FLAGS.cfg_path is not None # load config - config path: config(dir).dataset_name(py).config_name(py_class) cfg = load_config(cfg_path=FLAGS.cfg_path) # update config for arg in ['data_path', 'model_path', 'saving_path', 'mode', 'gpus', 'rand_seed', 'num_threads', 'num_votes', 'debug']: if getattr(FLAGS, arg) is not None: setattr(cfg, arg, getattr(FLAGS, arg)) if FLAGS.set: for arg in FLAGS.set.split(';'): cfg.update(arg) # env setting: visible gpu, tf warnings (level = '0'/'3') os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES'] = cfg.gpu_devices os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0' if cfg.mixed_precision: os.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1' if tf.__version__.split('.')[0] == '2': tf = tf.compat.v1 tf.disable_v2_behavior() # solve config if cfg.dataset in ['S3DIS']: cfg.mode = cfg.mode.replace('test', 'validation') if cfg.model_path and os.path.isdir(cfg.model_path): cfg.model_path = get_snap(cfg.model_path, step='last') if cfg.save_memory: # use gradient-checkpointing to save memory tf.__dict__['gradients'] = utils.memory_saving_gradients.gradients_memory # one from the: gradients_speed, gradients_memory, gradients_collection if isinstance(cfg.rand_seed, int): # manual set seed tf.set_random_seed(cfg.rand_seed) np.random.seed(cfg.rand_seed) if cfg.debug: # debug mode cfg.saving_path = 'test' cfg.log_file = sys.stdout # ---------------------------------------------------------------------------- # # training # ---------------------------------------------------------------------------- # if 'train' in cfg.mode: # result dir: results/dataset_name/config_name/Log_time/... if not cfg.saving_path: time.sleep(np.random.randint(1, 10)) # random sleep (avoid same log dir) # dataset_name = '_'.join([i for i in [cfg.dataset.lower(), cfg.version, cfg.validation_split] if i]) # default version / validation_split specified in dataset class cfg.saving_path = f'results/{cfg.dataset.lower()}/{cfg.name}/' + time.strftime('Log_%Y-%m-%d_%H-%M-%S', time.gmtime()) os.makedirs(cfg.saving_path, exist_ok=True) if not cfg.log_file: cfg.log_file = os.path.join(cfg.saving_path, 'log_train.txt') if isinstance(cfg.log_file, str): cfg.log_file = open(cfg.log_file, 'w') log_config(cfg) log_config(cfg, f_out=cfg.log_file) # actual training print_mem('>>> start training', check_time=True)
with redirect_io(cfg.log_file, cfg.debug):
3
2023-10-13 08:03:07+00:00
24k
bilibini/Lovely_Image_Downloader
py/Python38/site-packages/urllib3/poolmanager.py
[ { "identifier": "HTTPHeaderDict", "path": "py/Python38/site-packages/urllib3/_collections.py", "snippet": "class HTTPHeaderDict(typing.MutableMapping[str, str]):\n \"\"\"\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-insensitively.\n\n :param kwargs:\n Additional field-value pairs to pass in to ``dict.update``.\n\n A ``dict`` like container for storing HTTP Headers.\n\n Field names are stored and compared case-insensitively in compliance with\n RFC 7230. Iteration provides the first case-sensitive key seen for each\n case-insensitive pair.\n\n Using ``__setitem__`` syntax overwrites fields that compare equal\n case-insensitively in order to maintain ``dict``'s api. For fields that\n compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n in a loop.\n\n If multiple fields that are equal case-insensitively are passed to the\n constructor or ``.update``, the behavior is undefined and some will be\n lost.\n\n >>> headers = HTTPHeaderDict()\n >>> headers.add('Set-Cookie', 'foo=bar')\n >>> headers.add('set-cookie', 'baz=quxx')\n >>> headers['content-length'] = '7'\n >>> headers['SET-cookie']\n 'foo=bar, baz=quxx'\n >>> headers['Content-Length']\n '7'\n \"\"\"\n\n _container: typing.MutableMapping[str, list[str]]\n\n def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str):\n super().__init__()\n self._container = {} # 'dict' is insert-ordered in Python 3.7+\n if headers is not None:\n if isinstance(headers, HTTPHeaderDict):\n self._copy_from(headers)\n else:\n self.extend(headers)\n if kwargs:\n self.extend(kwargs)\n\n def __setitem__(self, key: str, val: str) -> None:\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n self._container[key.lower()] = [key, val]\n\n def __getitem__(self, key: str) -> str:\n val = self._container[key.lower()]\n return \", \".join(val[1:])\n\n def __delitem__(self, key: str) -> None:\n del self._container[key.lower()]\n\n def __contains__(self, key: object) -> bool:\n if isinstance(key, str):\n return key.lower() in self._container\n return False\n\n def setdefault(self, key: str, default: str = \"\") -> str:\n return super().setdefault(key, default)\n\n def __eq__(self, other: object) -> bool:\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return False\n else:\n other_as_http_header_dict = type(self)(maybe_constructable)\n\n return {k.lower(): v for k, v in self.itermerged()} == {\n k.lower(): v for k, v in other_as_http_header_dict.itermerged()\n }\n\n def __ne__(self, other: object) -> bool:\n return not self.__eq__(other)\n\n def __len__(self) -> int:\n return len(self._container)\n\n def __iter__(self) -> typing.Iterator[str]:\n # Only provide the originally cased names\n for vals in self._container.values():\n yield vals[0]\n\n def discard(self, key: str) -> None:\n try:\n del self[key]\n except KeyError:\n pass\n\n def add(self, key: str, val: str, *, combine: bool = False) -> None:\n \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n If this is called with combine=True, instead of adding a new header value\n as a distinct item during iteration, this will instead append the value to\n any existing header value with a comma. If no existing header value exists\n for the key, then the value will simply be added, ignoring the combine parameter.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n >>> list(headers.items())\n [('foo', 'bar'), ('foo', 'baz')]\n >>> headers.add('foo', 'quz', combine=True)\n >>> list(headers.items())\n [('foo', 'bar, baz, quz')]\n \"\"\"\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n key_lower = key.lower()\n new_vals = [key, val]\n # Keep the common case aka no item present as fast as possible\n vals = self._container.setdefault(key_lower, new_vals)\n if new_vals is not vals:\n # if there are values here, then there is at least the initial\n # key/value pair\n assert len(vals) >= 2\n if combine:\n vals[-1] = vals[-1] + \", \" + val\n else:\n vals.append(val)\n\n def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None:\n \"\"\"Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n \"\"\"\n if len(args) > 1:\n raise TypeError(\n f\"extend() takes at most 1 positional arguments ({len(args)} given)\"\n )\n other = args[0] if len(args) >= 1 else ()\n\n if isinstance(other, HTTPHeaderDict):\n for key, val in other.iteritems():\n self.add(key, val)\n elif isinstance(other, typing.Mapping):\n for key, val in other.items():\n self.add(key, val)\n elif isinstance(other, typing.Iterable):\n other = typing.cast(typing.Iterable[typing.Tuple[str, str]], other)\n for key, value in other:\n self.add(key, value)\n elif hasattr(other, \"keys\") and hasattr(other, \"__getitem__\"):\n # THIS IS NOT A TYPESAFE BRANCH\n # In this branch, the object has a `keys` attr but is not a Mapping or any of\n # the other types indicated in the method signature. We do some stuff with\n # it as though it partially implements the Mapping interface, but we're not\n # doing that stuff safely AT ALL.\n for key in other.keys():\n self.add(key, other[key])\n\n for key, value in kwargs.items():\n self.add(key, value)\n\n @typing.overload\n def getlist(self, key: str) -> list[str]:\n ...\n\n @typing.overload\n def getlist(self, key: str, default: _DT) -> list[str] | _DT:\n ...\n\n def getlist(\n self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed\n ) -> list[str] | _DT:\n \"\"\"Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist.\"\"\"\n try:\n vals = self._container[key.lower()]\n except KeyError:\n if default is _Sentinel.not_passed:\n # _DT is unbound; empty list is instance of List[str]\n return []\n # _DT is bound; default is instance of _DT\n return default\n else:\n # _DT may or may not be bound; vals[1:] is instance of List[str], which\n # meets our external interface requirement of `Union[List[str], _DT]`.\n return vals[1:]\n\n def _prepare_for_method_change(self) -> Self:\n \"\"\"\n Remove content-specific header fields before changing the request\n method to GET or HEAD according to RFC 9110, Section 15.4.\n \"\"\"\n content_specific_headers = [\n \"Content-Encoding\",\n \"Content-Language\",\n \"Content-Location\",\n \"Content-Type\",\n \"Content-Length\",\n \"Digest\",\n \"Last-Modified\",\n ]\n for header in content_specific_headers:\n self.discard(header)\n return self\n\n # Backwards compatibility for httplib\n getheaders = getlist\n getallmatchingheaders = getlist\n iget = getlist\n\n # Backwards compatibility for http.cookiejar\n get_all = getlist\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({dict(self.itermerged())})\"\n\n def _copy_from(self, other: HTTPHeaderDict) -> None:\n for key in other:\n val = other.getlist(key)\n self._container[key.lower()] = [key, *val]\n\n def copy(self) -> HTTPHeaderDict:\n clone = type(self)()\n clone._copy_from(self)\n return clone\n\n def iteritems(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n for key in self:\n vals = self._container[key.lower()]\n for val in vals[1:]:\n yield vals[0], val\n\n def itermerged(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n for key in self:\n val = self._container[key.lower()]\n yield val[0], \", \".join(val[1:])\n\n def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]\n return HTTPHeaderDictItemView(self)\n\n def _has_value_for_header(self, header_name: str, potential_value: str) -> bool:\n if header_name in self:\n return potential_value in self._container[header_name.lower()][1:]\n return False\n\n def __ior__(self, other: object) -> HTTPHeaderDict:\n # Supports extending a header dict in-place using operator |=\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n self.extend(maybe_constructable)\n return self\n\n def __or__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator |\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = self.copy()\n result.extend(maybe_constructable)\n return result\n\n def __ror__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator | when other is on left side\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = type(self)(maybe_constructable)\n result.extend(self)\n return result" }, { "identifier": "RecentlyUsedContainer", "path": "py/Python38/site-packages/urllib3/_collections.py", "snippet": "class RecentlyUsedContainer(typing.Generic[_KT, _VT], typing.MutableMapping[_KT, _VT]):\n \"\"\"\n Provides a thread-safe dict-like container which maintains up to\n ``maxsize`` keys while throwing away the least-recently-used keys beyond\n ``maxsize``.\n\n :param maxsize:\n Maximum number of recent elements to retain.\n\n :param dispose_func:\n Every time an item is evicted from the container,\n ``dispose_func(value)`` is called. Callback which will get called\n \"\"\"\n\n _container: typing.OrderedDict[_KT, _VT]\n _maxsize: int\n dispose_func: typing.Callable[[_VT], None] | None\n lock: RLock\n\n def __init__(\n self,\n maxsize: int = 10,\n dispose_func: typing.Callable[[_VT], None] | None = None,\n ) -> None:\n super().__init__()\n self._maxsize = maxsize\n self.dispose_func = dispose_func\n self._container = OrderedDict()\n self.lock = RLock()\n\n def __getitem__(self, key: _KT) -> _VT:\n # Re-insert the item, moving it to the end of the eviction line.\n with self.lock:\n item = self._container.pop(key)\n self._container[key] = item\n return item\n\n def __setitem__(self, key: _KT, value: _VT) -> None:\n evicted_item = None\n with self.lock:\n # Possibly evict the existing value of 'key'\n try:\n # If the key exists, we'll overwrite it, which won't change the\n # size of the pool. Because accessing a key should move it to\n # the end of the eviction line, we pop it out first.\n evicted_item = key, self._container.pop(key)\n self._container[key] = value\n except KeyError:\n # When the key does not exist, we insert the value first so that\n # evicting works in all cases, including when self._maxsize is 0\n self._container[key] = value\n if len(self._container) > self._maxsize:\n # If we didn't evict an existing value, and we've hit our maximum\n # size, then we have to evict the least recently used item from\n # the beginning of the container.\n evicted_item = self._container.popitem(last=False)\n\n # After releasing the lock on the pool, dispose of any evicted value.\n if evicted_item is not None and self.dispose_func:\n _, evicted_value = evicted_item\n self.dispose_func(evicted_value)\n\n def __delitem__(self, key: _KT) -> None:\n with self.lock:\n value = self._container.pop(key)\n\n if self.dispose_func:\n self.dispose_func(value)\n\n def __len__(self) -> int:\n with self.lock:\n return len(self._container)\n\n def __iter__(self) -> typing.NoReturn:\n raise NotImplementedError(\n \"Iteration over this class is unlikely to be threadsafe.\"\n )\n\n def clear(self) -> None:\n with self.lock:\n # Copy pointers to all values, then wipe the mapping\n values = list(self._container.values())\n self._container.clear()\n\n if self.dispose_func:\n for value in values:\n self.dispose_func(value)\n\n def keys(self) -> set[_KT]: # type: ignore[override]\n with self.lock:\n return set(self._container.keys())" }, { "identifier": "RequestMethods", "path": "py/Python38/site-packages/urllib3/_request_methods.py", "snippet": "class RequestMethods:\n \"\"\"\n Convenience mixin for classes who implement a :meth:`urlopen` method, such\n as :class:`urllib3.HTTPConnectionPool` and\n :class:`urllib3.PoolManager`.\n\n Provides behavior for making common types of HTTP request methods and\n decides which type of request field encoding to use.\n\n Specifically,\n\n :meth:`.request_encode_url` is for sending requests whose fields are\n encoded in the URL (such as GET, HEAD, DELETE).\n\n :meth:`.request_encode_body` is for sending requests whose fields are\n encoded in the *body* of the request using multipart or www-form-urlencoded\n (such as for POST, PUT, PATCH).\n\n :meth:`.request` is for making any kind of request, it will look up the\n appropriate encoding format and use one of the above two methods to make\n the request.\n\n Initializer parameters:\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n \"\"\"\n\n _encode_url_methods = {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\"}\n\n def __init__(self, headers: typing.Mapping[str, str] | None = None) -> None:\n self.headers = headers or {}\n\n def urlopen(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n encode_multipart: bool = True,\n multipart_boundary: str | None = None,\n **kw: typing.Any,\n ) -> BaseHTTPResponse: # Abstract\n raise NotImplementedError(\n \"Classes extending RequestMethods must implement \"\n \"their own ``urlopen`` method.\"\n )\n\n def request(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n fields: _TYPE_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n json: typing.Any | None = None,\n **urlopen_kw: typing.Any,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the appropriate encoding of\n ``fields`` based on the ``method`` used.\n\n This is a convenience method that requires the least amount of manual\n effort. It can be used in most situations, while still having the\n option to drop down to more specific methods when necessary, such as\n :meth:`request_encode_url`, :meth:`request_encode_body`,\n or even the lowest level :meth:`urlopen`.\n \"\"\"\n method = method.upper()\n\n if json is not None and body is not None:\n raise TypeError(\n \"request got values for both 'body' and 'json' parameters which are mutually exclusive\"\n )\n\n if json is not None:\n if headers is None:\n headers = self.headers.copy() # type: ignore\n if not (\"content-type\" in map(str.lower, headers.keys())):\n headers[\"Content-Type\"] = \"application/json\" # type: ignore\n\n body = _json.dumps(json, separators=(\",\", \":\"), ensure_ascii=False).encode(\n \"utf-8\"\n )\n\n if body is not None:\n urlopen_kw[\"body\"] = body\n\n if method in self._encode_url_methods:\n return self.request_encode_url(\n method,\n url,\n fields=fields, # type: ignore[arg-type]\n headers=headers,\n **urlopen_kw,\n )\n else:\n return self.request_encode_body(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n\n def request_encode_url(\n self,\n method: str,\n url: str,\n fields: _TYPE_ENCODE_URL_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n **urlopen_kw: str,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw: dict[str, typing.Any] = {\"headers\": headers}\n extra_kw.update(urlopen_kw)\n\n if fields:\n url += \"?\" + urlencode(fields)\n\n return self.urlopen(method, url, **extra_kw)\n\n def request_encode_body(\n self,\n method: str,\n url: str,\n fields: _TYPE_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n encode_multipart: bool = True,\n multipart_boundary: str | None = None,\n **urlopen_kw: str,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :func:`urllib3.encode_multipart_formdata` is used to encode\n the payload with the appropriate content type. Otherwise\n :func:`urllib.parse.urlencode` is used with the\n 'application/x-www-form-urlencoded' content type.\n\n Multipart encoding must be used when posting files, and it's reasonably\n safe to use it in other times too. However, it may break request\n signing, such as with OAuth.\n\n Supports an optional ``fields`` parameter of key/value strings AND\n key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n the MIME type is optional. For example::\n\n fields = {\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(),\n 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n }\n\n When uploading a file, providing a filename (the first parameter of the\n tuple) is optional but recommended to best mimic behavior of browsers.\n\n Note that if ``headers`` are supplied, the 'Content-Type' header will\n be overwritten because it depends on the dynamic random boundary string\n which is used to compose the body of the request. The random boundary\n string can be explicitly set with the ``multipart_boundary`` parameter.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw: dict[str, typing.Any] = {\"headers\": HTTPHeaderDict(headers)}\n body: bytes | str\n\n if fields:\n if \"body\" in urlopen_kw:\n raise TypeError(\n \"request got values for both 'fields' and 'body', can only specify one.\"\n )\n\n if encode_multipart:\n body, content_type = encode_multipart_formdata(\n fields, boundary=multipart_boundary\n )\n else:\n body, content_type = (\n urlencode(fields), # type: ignore[arg-type]\n \"application/x-www-form-urlencoded\",\n )\n\n extra_kw[\"body\"] = body\n extra_kw[\"headers\"].setdefault(\"Content-Type\", content_type)\n\n extra_kw.update(urlopen_kw)\n\n return self.urlopen(method, url, **extra_kw)" }, { "identifier": "ProxyConfig", "path": "py/Python38/site-packages/urllib3/connection.py", "snippet": " class BaseSSLError(BaseException): # type: ignore[no-redef]\nclass HTTPConnection(_HTTPConnection):\nclass HTTPSConnection(HTTPConnection):\nclass _WrappedAndVerifiedSocket(typing.NamedTuple):\nclass DummyConnection:\nRECENT_DATE = datetime.date(2022, 1, 1)\n_CONTAINS_CONTROL_CHAR_RE = re.compile(r\"[^-!#$%&'*+.^_`|~0-9a-zA-Z]\")\n_HAS_SYS_AUDIT = hasattr(sys, \"audit\")\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n ) -> None:\n def host(self) -> str:\n def host(self, value: str) -> None:\n def _new_conn(self) -> socket.socket:\n def set_tunnel(\n self,\n host: str,\n port: int | None = None,\n headers: typing.Mapping[str, str] | None = None,\n scheme: str = \"http\",\n ) -> None:\n def connect(self) -> None:\n def is_closed(self) -> bool:\n def is_connected(self) -> bool:\n def has_connected_to_proxy(self) -> bool:\n def close(self) -> None:\n def putrequest(\n self,\n method: str,\n url: str,\n skip_host: bool = False,\n skip_accept_encoding: bool = False,\n ) -> None:\n def putheader(self, header: str, *values: str) -> None:\n def request( # type: ignore[override]\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n *,\n chunked: bool = False,\n preload_content: bool = True,\n decode_content: bool = True,\n enforce_content_length: bool = True,\n ) -> None:\n def request_chunked(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n ) -> None:\n def getresponse( # type: ignore[override]\n self,\n ) -> HTTPResponse:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = HTTPConnection.default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n cert_reqs: int | str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n server_hostname: str | None = None,\n ssl_context: ssl.SSLContext | None = None,\n ca_certs: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ssl_minimum_version: int | None = None,\n ssl_maximum_version: int | None = None,\n ssl_version: int | str | None = None, # Deprecated\n cert_file: str | None = None,\n key_file: str | None = None,\n key_password: str | None = None,\n ) -> None:\n def set_cert(\n self,\n key_file: str | None = None,\n cert_file: str | None = None,\n cert_reqs: int | str | None = None,\n key_password: str | None = None,\n ca_certs: str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ) -> None:\n def connect(self) -> None:\n def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket:\ndef _ssl_wrap_socket_and_match_hostname(\n sock: socket.socket,\n *,\n cert_reqs: None | str | int,\n ssl_version: None | str | int,\n ssl_minimum_version: int | None,\n ssl_maximum_version: int | None,\n cert_file: str | None,\n key_file: str | None,\n key_password: str | None,\n ca_certs: str | None,\n ca_cert_dir: str | None,\n ca_cert_data: None | str | bytes,\n assert_hostname: None | str | Literal[False],\n assert_fingerprint: str | None,\n server_hostname: str | None,\n ssl_context: ssl.SSLContext | None,\n tls_in_tls: bool = False,\n) -> _WrappedAndVerifiedSocket:\ndef _match_hostname(\n cert: _TYPE_PEER_CERT_RET_DICT | None,\n asserted_hostname: str,\n hostname_checks_common_name: bool = False,\n) -> None:\ndef _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError:\ndef _get_default_user_agent() -> str:\ndef _url_from_connection(\n conn: HTTPConnection | HTTPSConnection, path: str | None = None\n) -> str:" }, { "identifier": "HTTPConnectionPool", "path": "py/Python38/site-packages/urllib3/connectionpool.py", "snippet": "_TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None]\nclass ConnectionPool:\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\nclass HTTPSConnectionPool(HTTPConnectionPool):\n def __init__(self, host: str, port: int | None = None) -> None:\n def __str__(self) -> str:\n def __enter__(self: _SelfT) -> _SelfT:\n def __exit__(\n self,\n exc_type: type[BaseException] | None,\n exc_val: BaseException | None,\n exc_tb: TracebackType | None,\n ) -> Literal[False]:\n def close(self) -> None:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,\n maxsize: int = 1,\n block: bool = False,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | bool | int | None = None,\n _proxy: Url | None = None,\n _proxy_headers: typing.Mapping[str, str] | None = None,\n _proxy_config: ProxyConfig | None = None,\n **conn_kw: typing.Any,\n ):\n def _new_conn(self) -> BaseHTTPConnection:\n def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:\n def _put_conn(self, conn: BaseHTTPConnection | None) -> None:\n def _validate_conn(self, conn: BaseHTTPConnection) -> None:\n def _prepare_proxy(self, conn: BaseHTTPConnection) -> None:\n def _get_timeout(self, timeout: _TYPE_TIMEOUT) -> Timeout:\n def _raise_timeout(\n self,\n err: BaseSSLError | OSError | SocketTimeout,\n url: str,\n timeout_value: _TYPE_TIMEOUT | None,\n ) -> None:\n def _make_request(\n self,\n conn: BaseHTTPConnection,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | None = None,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n chunked: bool = False,\n response_conn: BaseHTTPConnection | None = None,\n preload_content: bool = True,\n decode_content: bool = True,\n enforce_content_length: bool = True,\n ) -> BaseHTTPResponse:\n def close(self) -> None:\n def is_same_host(self, url: str) -> bool:\n def urlopen( # type: ignore[override]\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | bool | int | None = None,\n redirect: bool = True,\n assert_same_host: bool = True,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n pool_timeout: int | None = None,\n release_conn: bool | None = None,\n chunked: bool = False,\n body_pos: _TYPE_BODY_POSITION | None = None,\n preload_content: bool = True,\n decode_content: bool = True,\n **response_kw: typing.Any,\n ) -> BaseHTTPResponse:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,\n maxsize: int = 1,\n block: bool = False,\n headers: typing.Mapping[str, str] | None = None,\n retries: Retry | bool | int | None = None,\n _proxy: Url | None = None,\n _proxy_headers: typing.Mapping[str, str] | None = None,\n key_file: str | None = None,\n cert_file: str | None = None,\n cert_reqs: int | str | None = None,\n key_password: str | None = None,\n ca_certs: str | None = None,\n ssl_version: int | str | None = None,\n ssl_minimum_version: ssl.TLSVersion | None = None,\n ssl_maximum_version: ssl.TLSVersion | None = None,\n assert_hostname: str | Literal[False] | None = None,\n assert_fingerprint: str | None = None,\n ca_cert_dir: str | None = None,\n **conn_kw: typing.Any,\n ) -> None:\n def _prepare_proxy(self, conn: HTTPSConnection) -> None: # type: ignore[override]\n def _new_conn(self) -> BaseHTTPSConnection:\n def _validate_conn(self, conn: BaseHTTPConnection) -> None:\ndef connection_from_url(url: str, **kw: typing.Any) -> HTTPConnectionPool:\ndef _normalize_host(host: None, scheme: str | None) -> None:\ndef _normalize_host(host: str, scheme: str | None) -> str:\ndef _normalize_host(host: str | None, scheme: str | None) -> str | None:\ndef _url_from_pool(\n pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None\n) -> str:\ndef _close_pool_connections(pool: queue.LifoQueue[typing.Any]) -> None:" }, { "identifier": "LocationValueError", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class LocationValueError(ValueError, HTTPError):\n \"\"\"Raised when there is something wrong with a given URL input.\"\"\"" }, { "identifier": "MaxRetryError", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class MaxRetryError(RequestError):\n \"\"\"Raised when the maximum number of retries is exceeded.\n\n :param pool: The connection pool\n :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n :param str url: The requested Url\n :param reason: The underlying error\n :type reason: :class:`Exception`\n\n \"\"\"\n\n def __init__(\n self, pool: ConnectionPool, url: str, reason: Exception | None = None\n ) -> None:\n self.reason = reason\n\n message = f\"Max retries exceeded with url: {url} (Caused by {reason!r})\"\n\n super().__init__(pool, url, message)" }, { "identifier": "ProxySchemeUnknown", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):\n \"\"\"ProxyManager does not support the supplied scheme\"\"\"\n\n # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.\n\n def __init__(self, scheme: str | None) -> None:\n # 'localhost' is here because our URL parser parses\n # localhost:8080 -> scheme=localhost, remove if we fix this.\n if scheme == \"localhost\":\n scheme = None\n if scheme is None:\n message = \"Proxy URL had no scheme, should start with http:// or https://\"\n else:\n message = f\"Proxy URL had unsupported scheme {scheme}, should use http:// or https://\"\n super().__init__(message)" }, { "identifier": "URLSchemeUnknown", "path": "py/Python38/site-packages/urllib3/exceptions.py", "snippet": "class URLSchemeUnknown(LocationValueError):\n \"\"\"Raised when a URL input has an unsupported scheme.\"\"\"\n\n def __init__(self, scheme: str):\n message = f\"Not supported URL scheme {scheme}\"\n super().__init__(message)\n\n self.scheme = scheme" }, { "identifier": "BaseHTTPResponse", "path": "py/Python38/site-packages/urllib3/response.py", "snippet": "class BaseHTTPResponse(io.IOBase):\n CONTENT_DECODERS = [\"gzip\", \"deflate\"]\n if brotli is not None:\n CONTENT_DECODERS += [\"br\"]\n if zstd is not None:\n CONTENT_DECODERS += [\"zstd\"]\n REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (IOError, zlib.error)\n if brotli is not None:\n DECODER_ERROR_CLASSES += (brotli.error,)\n\n if zstd is not None:\n DECODER_ERROR_CLASSES += (zstd.ZstdError,)\n\n def __init__(\n self,\n *,\n headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None,\n status: int,\n version: int,\n reason: str | None,\n decode_content: bool,\n request_url: str | None,\n retries: Retry | None = None,\n ) -> None:\n if isinstance(headers, HTTPHeaderDict):\n self.headers = headers\n else:\n self.headers = HTTPHeaderDict(headers) # type: ignore[arg-type]\n self.status = status\n self.version = version\n self.reason = reason\n self.decode_content = decode_content\n self._has_decoded_content = False\n self._request_url: str | None = request_url\n self.retries = retries\n\n self.chunked = False\n tr_enc = self.headers.get(\"transfer-encoding\", \"\").lower()\n # Don't incur the penalty of creating a list and then discarding it\n encodings = (enc.strip() for enc in tr_enc.split(\",\"))\n if \"chunked\" in encodings:\n self.chunked = True\n\n self._decoder: ContentDecoder | None = None\n\n def get_redirect_location(self) -> str | None | Literal[False]:\n \"\"\"\n Should we redirect and where to?\n\n :returns: Truthy redirect location string if we got a redirect status\n code and valid location. ``None`` if redirect status and no\n location. ``False`` if not a redirect status code.\n \"\"\"\n if self.status in self.REDIRECT_STATUSES:\n return self.headers.get(\"location\")\n return False\n\n @property\n def data(self) -> bytes:\n raise NotImplementedError()\n\n def json(self) -> typing.Any:\n \"\"\"\n Parses the body of the HTTP response as JSON.\n\n To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to the decoder.\n\n This method can raise either `UnicodeDecodeError` or `json.JSONDecodeError`.\n\n Read more :ref:`here <json>`.\n \"\"\"\n data = self.data.decode(\"utf-8\")\n return _json.loads(data)\n\n @property\n def url(self) -> str | None:\n raise NotImplementedError()\n\n @url.setter\n def url(self, url: str | None) -> None:\n raise NotImplementedError()\n\n @property\n def connection(self) -> HTTPConnection | None:\n raise NotImplementedError()\n\n @property\n def retries(self) -> Retry | None:\n return self._retries\n\n @retries.setter\n def retries(self, retries: Retry | None) -> None:\n # Override the request_url if retries has a redirect location.\n if retries is not None and retries.history:\n self.url = retries.history[-1].redirect_location\n self._retries = retries\n\n def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()\n\n def read(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n cache_content: bool = False,\n ) -> bytes:\n raise NotImplementedError()\n\n def read_chunked(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()\n\n def release_conn(self) -> None:\n raise NotImplementedError()\n\n def drain_conn(self) -> None:\n raise NotImplementedError()\n\n def close(self) -> None:\n raise NotImplementedError()\n\n def _init_decoder(self) -> None:\n \"\"\"\n Set-up the _decoder attribute if necessary.\n \"\"\"\n # Note: content-encoding value should be case-insensitive, per RFC 7230\n # Section 3.2\n content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n if self._decoder is None:\n if content_encoding in self.CONTENT_DECODERS:\n self._decoder = _get_decoder(content_encoding)\n elif \",\" in content_encoding:\n encodings = [\n e.strip()\n for e in content_encoding.split(\",\")\n if e.strip() in self.CONTENT_DECODERS\n ]\n if encodings:\n self._decoder = _get_decoder(content_encoding)\n\n def _decode(\n self, data: bytes, decode_content: bool | None, flush_decoder: bool\n ) -> bytes:\n \"\"\"\n Decode the data passed in and potentially flush the decoder.\n \"\"\"\n if not decode_content:\n if self._has_decoded_content:\n raise RuntimeError(\n \"Calling read(decode_content=False) is not supported after \"\n \"read(decode_content=True) was called.\"\n )\n return data\n\n try:\n if self._decoder:\n data = self._decoder.decompress(data)\n self._has_decoded_content = True\n except self.DECODER_ERROR_CLASSES as e:\n content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n raise DecodeError(\n \"Received response with content-encoding: %s, but \"\n \"failed to decode it.\" % content_encoding,\n e,\n ) from e\n if flush_decoder:\n data += self._flush_decoder()\n\n return data\n\n def _flush_decoder(self) -> bytes:\n \"\"\"\n Flushes the decoder. Should only be called if the decoder is actually\n being used.\n \"\"\"\n if self._decoder:\n return self._decoder.decompress(b\"\") + self._decoder.flush()\n return b\"\"\n\n # Compatibility methods for `io` module\n def readinto(self, b: bytearray) -> int:\n temp = self.read(len(b))\n if len(temp) == 0:\n return 0\n else:\n b[: len(temp)] = temp\n return len(temp)\n\n # Compatibility methods for http.client.HTTPResponse\n def getheaders(self) -> HTTPHeaderDict:\n warnings.warn(\n \"HTTPResponse.getheaders() is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers\n\n def getheader(self, name: str, default: str | None = None) -> str | None:\n warnings.warn(\n \"HTTPResponse.getheader() is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Instead use HTTPResponse.headers.get(name, default).\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers.get(name, default)\n\n # Compatibility method for http.cookiejar\n def info(self) -> HTTPHeaderDict:\n return self.headers\n\n def geturl(self) -> str | None:\n return self.url" }, { "identifier": "_TYPE_SOCKET_OPTIONS", "path": "py/Python38/site-packages/urllib3/util/connection.py", "snippet": "_TYPE_SOCKET_OPTIONS = typing.Sequence[typing.Tuple[int, int, typing.Union[int, bytes]]]" }, { "identifier": "connection_requires_http_tunnel", "path": "py/Python38/site-packages/urllib3/util/proxy.py", "snippet": "def connection_requires_http_tunnel(\n proxy_url: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n destination_scheme: str | None = None,\n) -> bool:\n \"\"\"\n Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n :param URL proxy_url:\n URL of the proxy.\n :param ProxyConfig proxy_config:\n Proxy configuration from poolmanager.py\n :param str destination_scheme:\n The scheme of the destination. (i.e https, http, etc)\n \"\"\"\n # If we're not using a proxy, no way to use a tunnel.\n if proxy_url is None:\n return False\n\n # HTTP destinations never require tunneling, we always forward.\n if destination_scheme == \"http\":\n return False\n\n # Support for forwarding with HTTPS proxies and HTTPS destinations.\n if (\n proxy_url.scheme == \"https\"\n and proxy_config\n and proxy_config.use_forwarding_for_https\n ):\n return False\n\n # Otherwise always use a tunnel.\n return True" }, { "identifier": "Retry", "path": "py/Python38/site-packages/urllib3/util/retry.py", "snippet": "class Retry:\n \"\"\"Retry configuration.\n\n Each retry attempt will create a new Retry object with updated values, so\n they can be safely reused.\n\n Retries can be defined as a default for a pool:\n\n .. code-block:: python\n\n retries = Retry(connect=5, read=2, redirect=5)\n http = PoolManager(retries=retries)\n response = http.request(\"GET\", \"https://example.com/\")\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", retries=Retry(10))\n\n Retries can be disabled by passing ``False``:\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", retries=False)\n\n Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n retries are disabled, in which case the causing exception will be raised.\n\n :param int total:\n Total number of retries to allow. Takes precedence over other counts.\n\n Set to ``None`` to remove this constraint and fall back on other\n counts.\n\n Set to ``0`` to fail on the first retry.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int connect:\n How many connection-related errors to retry on.\n\n These are errors raised before the request is sent to the remote server,\n which we assume has not triggered the server to process the request.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int read:\n How many times to retry on read errors.\n\n These errors are raised after the request was sent to the server, so the\n request may have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int redirect:\n How many redirects to perform. Limit this to avoid infinite redirect\n loops.\n\n A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n 308.\n\n Set to ``0`` to fail on the first retry of this type.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int status:\n How many times to retry on bad status codes.\n\n These are retries made on responses, where status code matches\n ``status_forcelist``.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int other:\n How many times to retry on other errors.\n\n Other errors are errors that are not connect, read, redirect or status errors.\n These errors might be raised after the request was sent to the server, so the\n request might have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n If ``total`` is not set, it's a good idea to set this to 0 to account\n for unexpected edge cases and avoid infinite retry loops.\n\n :param Collection allowed_methods:\n Set of uppercased HTTP method verbs that we should retry on.\n\n By default, we only retry on methods which are considered to be\n idempotent (multiple requests with the same parameters end with the\n same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n Set to a ``None`` value to retry on any verb.\n\n :param Collection status_forcelist:\n A set of integer HTTP status codes that we should force a retry on.\n A retry is initiated if the request method is in ``allowed_methods``\n and the response status code is in ``status_forcelist``.\n\n By default, this is disabled with ``None``.\n\n :param float backoff_factor:\n A backoff factor to apply between attempts after the second try\n (most errors are resolved immediately by a second try without a\n delay). urllib3 will sleep for::\n\n {backoff factor} * (2 ** ({number of previous retries}))\n\n seconds. If `backoff_jitter` is non-zero, this sleep is extended by::\n\n random.uniform(0, {backoff jitter})\n\n seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will\n sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever\n be longer than `backoff_max`.\n\n By default, backoff is disabled (factor set to 0).\n\n :param bool raise_on_redirect: Whether, if the number of redirects is\n exhausted, to raise a MaxRetryError, or to return a response with a\n response code in the 3xx range.\n\n :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n whether we should raise an exception, or return a response,\n if status falls in ``status_forcelist`` range and retries have\n been exhausted.\n\n :param tuple history: The history of the request encountered during\n each call to :meth:`~Retry.increment`. The list is in the order\n the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n :param bool respect_retry_after_header:\n Whether to respect Retry-After header on status codes defined as\n :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n :param Collection remove_headers_on_redirect:\n Sequence of headers to remove from the request when a response\n indicating a redirect is returned before firing off the redirected\n request.\n \"\"\"\n\n #: Default methods to be used for ``allowed_methods``\n DEFAULT_ALLOWED_METHODS = frozenset(\n [\"HEAD\", \"GET\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"]\n )\n\n #: Default status codes to be used for ``status_forcelist``\n RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n #: Default headers to be used for ``remove_headers_on_redirect``\n DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset([\"Cookie\", \"Authorization\"])\n\n #: Default maximum backoff time.\n DEFAULT_BACKOFF_MAX = 120\n\n # Backward compatibility; assigned outside of the class.\n DEFAULT: typing.ClassVar[Retry]\n\n def __init__(\n self,\n total: bool | int | None = 10,\n connect: int | None = None,\n read: int | None = None,\n redirect: bool | int | None = None,\n status: int | None = None,\n other: int | None = None,\n allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS,\n status_forcelist: typing.Collection[int] | None = None,\n backoff_factor: float = 0,\n backoff_max: float = DEFAULT_BACKOFF_MAX,\n raise_on_redirect: bool = True,\n raise_on_status: bool = True,\n history: tuple[RequestHistory, ...] | None = None,\n respect_retry_after_header: bool = True,\n remove_headers_on_redirect: typing.Collection[\n str\n ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT,\n backoff_jitter: float = 0.0,\n ) -> None:\n self.total = total\n self.connect = connect\n self.read = read\n self.status = status\n self.other = other\n\n if redirect is False or total is False:\n redirect = 0\n raise_on_redirect = False\n\n self.redirect = redirect\n self.status_forcelist = status_forcelist or set()\n self.allowed_methods = allowed_methods\n self.backoff_factor = backoff_factor\n self.backoff_max = backoff_max\n self.raise_on_redirect = raise_on_redirect\n self.raise_on_status = raise_on_status\n self.history = history or ()\n self.respect_retry_after_header = respect_retry_after_header\n self.remove_headers_on_redirect = frozenset(\n h.lower() for h in remove_headers_on_redirect\n )\n self.backoff_jitter = backoff_jitter\n\n def new(self, **kw: typing.Any) -> Retry:\n params = dict(\n total=self.total,\n connect=self.connect,\n read=self.read,\n redirect=self.redirect,\n status=self.status,\n other=self.other,\n allowed_methods=self.allowed_methods,\n status_forcelist=self.status_forcelist,\n backoff_factor=self.backoff_factor,\n backoff_max=self.backoff_max,\n raise_on_redirect=self.raise_on_redirect,\n raise_on_status=self.raise_on_status,\n history=self.history,\n remove_headers_on_redirect=self.remove_headers_on_redirect,\n respect_retry_after_header=self.respect_retry_after_header,\n backoff_jitter=self.backoff_jitter,\n )\n\n params.update(kw)\n return type(self)(**params) # type: ignore[arg-type]\n\n @classmethod\n def from_int(\n cls,\n retries: Retry | bool | int | None,\n redirect: bool | int | None = True,\n default: Retry | bool | int | None = None,\n ) -> Retry:\n \"\"\"Backwards-compatibility for the old retries format.\"\"\"\n if retries is None:\n retries = default if default is not None else cls.DEFAULT\n\n if isinstance(retries, Retry):\n return retries\n\n redirect = bool(redirect) and None\n new_retries = cls(retries, redirect=redirect)\n log.debug(\"Converted retries value: %r -> %r\", retries, new_retries)\n return new_retries\n\n def get_backoff_time(self) -> float:\n \"\"\"Formula for computing the current backoff\n\n :rtype: float\n \"\"\"\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n if self.backoff_jitter != 0.0:\n backoff_value += random.random() * self.backoff_jitter\n return float(max(0, min(self.backoff_max, backoff_value)))\n\n def parse_retry_after(self, retry_after: str) -> float:\n seconds: float\n # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n if re.match(r\"^\\s*[0-9]+\\s*$\", retry_after):\n seconds = int(retry_after)\n else:\n retry_date_tuple = email.utils.parsedate_tz(retry_after)\n if retry_date_tuple is None:\n raise InvalidHeader(f\"Invalid Retry-After header: {retry_after}\")\n\n retry_date = email.utils.mktime_tz(retry_date_tuple)\n seconds = retry_date - time.time()\n\n seconds = max(seconds, 0)\n\n return seconds\n\n def get_retry_after(self, response: BaseHTTPResponse) -> float | None:\n \"\"\"Get the value of Retry-After in seconds.\"\"\"\n\n retry_after = response.headers.get(\"Retry-After\")\n\n if retry_after is None:\n return None\n\n return self.parse_retry_after(retry_after)\n\n def sleep_for_retry(self, response: BaseHTTPResponse) -> bool:\n retry_after = self.get_retry_after(response)\n if retry_after:\n time.sleep(retry_after)\n return True\n\n return False\n\n def _sleep_backoff(self) -> None:\n backoff = self.get_backoff_time()\n if backoff <= 0:\n return\n time.sleep(backoff)\n\n def sleep(self, response: BaseHTTPResponse | None = None) -> None:\n \"\"\"Sleep between retry attempts.\n\n This method will respect a server's ``Retry-After`` response header\n and sleep the duration of the time requested. If that is not present, it\n will use an exponential backoff. By default, the backoff factor is 0 and\n this method will return immediately.\n \"\"\"\n\n if self.respect_retry_after_header and response:\n slept = self.sleep_for_retry(response)\n if slept:\n return\n\n self._sleep_backoff()\n\n def _is_connection_error(self, err: Exception) -> bool:\n \"\"\"Errors when we're fairly sure that the server did not receive the\n request, so it should be safe to retry.\n \"\"\"\n if isinstance(err, ProxyError):\n err = err.original_error\n return isinstance(err, ConnectTimeoutError)\n\n def _is_read_error(self, err: Exception) -> bool:\n \"\"\"Errors that occur after the request has been started, so we should\n assume that the server began processing it.\n \"\"\"\n return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n def _is_method_retryable(self, method: str) -> bool:\n \"\"\"Checks if a given HTTP method should be retried upon, depending if\n it is included in the allowed_methods\n \"\"\"\n if self.allowed_methods and method.upper() not in self.allowed_methods:\n return False\n return True\n\n def is_retry(\n self, method: str, status_code: int, has_retry_after: bool = False\n ) -> bool:\n \"\"\"Is this method/status code retryable? (Based on allowlists and control\n variables such as the number of total retries to allow, whether to\n respect the Retry-After header, whether this header is present, and\n whether the returned status code is on the list of status codes to\n be retried upon on the presence of the aforementioned header)\n \"\"\"\n if not self._is_method_retryable(method):\n return False\n\n if self.status_forcelist and status_code in self.status_forcelist:\n return True\n\n return bool(\n self.total\n and self.respect_retry_after_header\n and has_retry_after\n and (status_code in self.RETRY_AFTER_STATUS_CODES)\n )\n\n def is_exhausted(self) -> bool:\n \"\"\"Are we out of retries?\"\"\"\n retry_counts = [\n x\n for x in (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n if x\n ]\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0\n\n def increment(\n self,\n method: str | None = None,\n url: str | None = None,\n response: BaseHTTPResponse | None = None,\n error: Exception | None = None,\n _pool: ConnectionPool | None = None,\n _stacktrace: TracebackType | None = None,\n ) -> Retry:\n \"\"\"Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.BaseHTTPResponse`\n :param Exception error: An error encountered during the request, or\n None if the response was received successfully.\n\n :return: A new ``Retry`` object.\n \"\"\"\n if self.total is False and error:\n # Disabled, indicate to re-raise the error.\n raise reraise(type(error), error, _stacktrace)\n\n total = self.total\n if total is not None:\n total -= 1\n\n connect = self.connect\n read = self.read\n redirect = self.redirect\n status_count = self.status\n other = self.other\n cause = \"unknown\"\n status = None\n redirect_location = None\n\n if error and self._is_connection_error(error):\n # Connect retry?\n if connect is False:\n raise reraise(type(error), error, _stacktrace)\n elif connect is not None:\n connect -= 1\n\n elif error and self._is_read_error(error):\n # Read retry?\n if read is False or method is None or not self._is_method_retryable(method):\n raise reraise(type(error), error, _stacktrace)\n elif read is not None:\n read -= 1\n\n elif error:\n # Other retry?\n if other is not None:\n other -= 1\n\n elif response and response.get_redirect_location():\n # Redirect retry?\n if redirect is not None:\n redirect -= 1\n cause = \"too many redirects\"\n response_redirect_location = response.get_redirect_location()\n if response_redirect_location:\n redirect_location = response_redirect_location\n status = response.status\n\n else:\n # Incrementing because of a server error like a 500 in\n # status_forcelist and the given method is in the allowed_methods\n cause = ResponseError.GENERIC_ERROR\n if response and response.status:\n if status_count is not None:\n status_count -= 1\n cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n status = response.status\n\n history = self.history + (\n RequestHistory(method, url, error, status, redirect_location),\n )\n\n new_retry = self.new(\n total=total,\n connect=connect,\n read=read,\n redirect=redirect,\n status=status_count,\n other=other,\n history=history,\n )\n\n if new_retry.is_exhausted():\n reason = error or ResponseError(cause)\n raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]\n\n log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n return new_retry\n\n def __repr__(self) -> str:\n return (\n f\"{type(self).__name__}(total={self.total}, connect={self.connect}, \"\n f\"read={self.read}, redirect={self.redirect}, status={self.status})\"\n )" }, { "identifier": "Timeout", "path": "py/Python38/site-packages/urllib3/util/timeout.py", "snippet": "class Timeout:\n \"\"\"Timeout configuration.\n\n Timeouts can be defined as a default for a pool:\n\n .. code-block:: python\n\n import urllib3\n\n timeout = urllib3.util.Timeout(connect=2.0, read=7.0)\n\n http = urllib3.PoolManager(timeout=timeout)\n\n resp = http.request(\"GET\", \"https://example.com/\")\n\n print(resp.status)\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", timeout=Timeout(10))\n\n Timeouts can be disabled by setting all the parameters to ``None``:\n\n .. code-block:: python\n\n no_timeout = Timeout(connect=None, read=None)\n response = http.request(\"GET\", \"https://example.com/\", timeout=no_timeout)\n\n\n :param total:\n This combines the connect and read timeouts into one; the read timeout\n will be set to the time leftover from the connect attempt. In the\n event that both a connect timeout and a total are specified, or a read\n timeout and a total are specified, the shorter timeout will be applied.\n\n Defaults to None.\n\n :type total: int, float, or None\n\n :param connect:\n The maximum amount of time (in seconds) to wait for a connection\n attempt to a server to succeed. Omitting the parameter will default the\n connect timeout to the system default, probably `the global default\n timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout for connection attempts.\n\n :type connect: int, float, or None\n\n :param read:\n The maximum amount of time (in seconds) to wait between consecutive\n read operations for a response from the server. Omitting the parameter\n will default the read timeout to the system default, probably `the\n global default timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout.\n\n :type read: int, float, or None\n\n .. note::\n\n Many factors can affect the total amount of time for urllib3 to return\n an HTTP response.\n\n For example, Python's DNS resolver does not obey the timeout specified\n on the socket. Other factors that can affect total request time include\n high CPU load, high swap, the program running at a low priority level,\n or other behaviors.\n\n In addition, the read and total timeouts only measure the time between\n read operations on the socket connecting the client and the server,\n not the total amount of time for the request to return a complete\n response. For most requests, the timeout is raised because the server\n has not sent the first byte in the specified time. This is not always\n the case; if a server streams one byte every fifteen seconds, a timeout\n of 20 seconds will not trigger, even though the request will take\n several minutes to complete.\n\n If your goal is to cut off any request after a set amount of wall clock\n time, consider having a second \"watcher\" thread to cut off a slow\n request.\n \"\"\"\n\n #: A sentinel object representing the default timeout value\n DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT\n\n def __init__(\n self,\n total: _TYPE_TIMEOUT = None,\n connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n ) -> None:\n self._connect = self._validate_timeout(connect, \"connect\")\n self._read = self._validate_timeout(read, \"read\")\n self.total = self._validate_timeout(total, \"total\")\n self._start_connect: float | None = None\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})\"\n\n # __str__ provided for backwards compatibility\n __str__ = __repr__\n\n @staticmethod\n def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None:\n return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout\n\n @classmethod\n def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT:\n \"\"\"Check that a timeout attribute is valid.\n\n :param value: The timeout value to validate\n :param name: The name of the timeout attribute to validate. This is\n used to specify in error messages.\n :return: The validated and casted version of the given value.\n :raises ValueError: If it is a numeric value less than or equal to\n zero, or the type is not an integer, float, or None.\n \"\"\"\n if value is None or value is _DEFAULT_TIMEOUT:\n return value\n\n if isinstance(value, bool):\n raise ValueError(\n \"Timeout cannot be a boolean value. It must \"\n \"be an int, float or None.\"\n )\n try:\n float(value)\n except (TypeError, ValueError):\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n try:\n if value <= 0:\n raise ValueError(\n \"Attempted to set %s timeout to %s, but the \"\n \"timeout cannot be set to a value less \"\n \"than or equal to 0.\" % (name, value)\n )\n except TypeError:\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n return value\n\n @classmethod\n def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout:\n \"\"\"Create a new Timeout from a legacy timeout value.\n\n The timeout value used by httplib.py sets the same timeout on the\n connect(), and recv() socket requests. This creates a :class:`Timeout`\n object that sets the individual timeouts to the ``timeout`` value\n passed to this function.\n\n :param timeout: The legacy timeout value.\n :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None\n :return: Timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n return Timeout(read=timeout, connect=timeout)\n\n def clone(self) -> Timeout:\n \"\"\"Create a copy of the timeout object\n\n Timeout properties are stored per-pool but each request needs a fresh\n Timeout object to ensure each one has its own start/stop configured.\n\n :return: a copy of the timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n # We can't use copy.deepcopy because that will also create a new object\n # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to\n # detect the user default.\n return Timeout(connect=self._connect, read=self._read, total=self.total)\n\n def start_connect(self) -> float:\n \"\"\"Start the timeout clock, used during a connect() attempt\n\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to start a timer that has been started already.\n \"\"\"\n if self._start_connect is not None:\n raise TimeoutStateError(\"Timeout timer has already been started.\")\n self._start_connect = time.monotonic()\n return self._start_connect\n\n def get_connect_duration(self) -> float:\n \"\"\"Gets the time elapsed since the call to :meth:`start_connect`.\n\n :return: Elapsed time in seconds.\n :rtype: float\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to get duration for a timer that hasn't been started.\n \"\"\"\n if self._start_connect is None:\n raise TimeoutStateError(\n \"Can't get connect duration for timer that has not started.\"\n )\n return time.monotonic() - self._start_connect\n\n @property\n def connect_timeout(self) -> _TYPE_TIMEOUT:\n \"\"\"Get the value to use when setting a connection timeout.\n\n This will be a positive float or integer, the value None\n (never timeout), or the default system timeout.\n\n :return: Connect timeout.\n :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n \"\"\"\n if self.total is None:\n return self._connect\n\n if self._connect is None or self._connect is _DEFAULT_TIMEOUT:\n return self.total\n\n return min(self._connect, self.total) # type: ignore[type-var]\n\n @property\n def read_timeout(self) -> float | None:\n \"\"\"Get the value for the read timeout.\n\n This assumes some time has elapsed in the connection timeout and\n computes the read timeout appropriately.\n\n If self.total is set, the read timeout is dependent on the amount of\n time taken by the connect timeout. If the connection time has not been\n established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be\n raised.\n\n :return: Value to use for the read timeout.\n :rtype: int, float or None\n :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`\n has not yet been called on this object.\n \"\"\"\n if (\n self.total is not None\n and self.total is not _DEFAULT_TIMEOUT\n and self._read is not None\n and self._read is not _DEFAULT_TIMEOUT\n ):\n # In case the connect timeout has not yet been established.\n if self._start_connect is None:\n return self._read\n return max(0, min(self.total - self.get_connect_duration(), self._read))\n elif self.total is not None and self.total is not _DEFAULT_TIMEOUT:\n return max(0, self.total - self.get_connect_duration())\n else:\n return self.resolve_default_timeout(self._read)" }, { "identifier": "Url", "path": "py/Python38/site-packages/urllib3/util/url.py", "snippet": "class Url(\n typing.NamedTuple(\n \"Url\",\n [\n (\"scheme\", typing.Optional[str]),\n (\"auth\", typing.Optional[str]),\n (\"host\", typing.Optional[str]),\n (\"port\", typing.Optional[int]),\n (\"path\", typing.Optional[str]),\n (\"query\", typing.Optional[str]),\n (\"fragment\", typing.Optional[str]),\n ],\n )\n):\n \"\"\"\n Data structure for representing an HTTP URL. Used as a return value for\n :func:`parse_url`. Both the scheme and host are normalized as they are\n both case-insensitive according to RFC 3986.\n \"\"\"\n\n def __new__( # type: ignore[no-untyped-def]\n cls,\n scheme: str | None = None,\n auth: str | None = None,\n host: str | None = None,\n port: int | None = None,\n path: str | None = None,\n query: str | None = None,\n fragment: str | None = None,\n ):\n if path and not path.startswith(\"/\"):\n path = \"/\" + path\n if scheme is not None:\n scheme = scheme.lower()\n return super().__new__(cls, scheme, auth, host, port, path, query, fragment)\n\n @property\n def hostname(self) -> str | None:\n \"\"\"For backwards-compatibility with urlparse. We're nice like that.\"\"\"\n return self.host\n\n @property\n def request_uri(self) -> str:\n \"\"\"Absolute path including the query string.\"\"\"\n uri = self.path or \"/\"\n\n if self.query is not None:\n uri += \"?\" + self.query\n\n return uri\n\n @property\n def authority(self) -> str | None:\n \"\"\"\n Authority component as defined in RFC 3986 3.2.\n This includes userinfo (auth), host and port.\n\n i.e.\n userinfo@host:port\n \"\"\"\n userinfo = self.auth\n netloc = self.netloc\n if netloc is None or userinfo is None:\n return netloc\n else:\n return f\"{userinfo}@{netloc}\"\n\n @property\n def netloc(self) -> str | None:\n \"\"\"\n Network location including host and port.\n\n If you need the equivalent of urllib.parse's ``netloc``,\n use the ``authority`` property instead.\n \"\"\"\n if self.host is None:\n return None\n if self.port:\n return f\"{self.host}:{self.port}\"\n return self.host\n\n @property\n def url(self) -> str:\n \"\"\"\n Convert self into a url\n\n This function should more or less round-trip with :func:`.parse_url`. The\n returned url may not be exactly the same as the url inputted to\n :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n with a blank port will have : removed).\n\n Example:\n\n .. code-block:: python\n\n import urllib3\n\n U = urllib3.util.parse_url(\"https://google.com/mail/\")\n\n print(U.url)\n # \"https://google.com/mail/\"\n\n print( urllib3.util.Url(\"https\", \"username:password\",\n \"host.com\", 80, \"/path\", \"query\", \"fragment\"\n ).url\n )\n # \"https://username:[email protected]:80/path?query#fragment\"\n \"\"\"\n scheme, auth, host, port, path, query, fragment = self\n url = \"\"\n\n # We use \"is not None\" we want things to happen with empty strings (or 0 port)\n if scheme is not None:\n url += scheme + \"://\"\n if auth is not None:\n url += auth + \"@\"\n if host is not None:\n url += host\n if port is not None:\n url += \":\" + str(port)\n if path is not None:\n url += path\n if query is not None:\n url += \"?\" + query\n if fragment is not None:\n url += \"#\" + fragment\n\n return url\n\n def __str__(self) -> str:\n return self.url" }, { "identifier": "parse_url", "path": "py/Python38/site-packages/urllib3/util/url.py", "snippet": "def parse_url(url: str) -> Url:\n \"\"\"\n Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n performed to parse incomplete urls. Fields not provided will be None.\n This parser is RFC 3986 and RFC 6874 compliant.\n\n The parser logic and helper functions are based heavily on\n work done in the ``rfc3986`` module.\n\n :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n Partly backwards-compatible with :mod:`urllib.parse`.\n\n Example:\n\n .. code-block:: python\n\n import urllib3\n\n print( urllib3.util.parse_url('http://google.com/mail/'))\n # Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n\n print( urllib3.util.parse_url('google.com:80'))\n # Url(scheme=None, host='google.com', port=80, path=None, ...)\n\n print( urllib3.util.parse_url('/foo?bar'))\n # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n \"\"\"\n if not url:\n # Empty\n return Url()\n\n source_url = url\n if not _SCHEME_RE.search(url):\n url = \"//\" + url\n\n scheme: str | None\n authority: str | None\n auth: str | None\n host: str | None\n port: str | None\n port_int: int | None\n path: str | None\n query: str | None\n fragment: str | None\n\n try:\n scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr]\n normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES\n\n if scheme:\n scheme = scheme.lower()\n\n if authority:\n auth, _, host_port = authority.rpartition(\"@\")\n auth = auth or None\n host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr]\n if auth and normalize_uri:\n auth = _encode_invalid_chars(auth, _USERINFO_CHARS)\n if port == \"\":\n port = None\n else:\n auth, host, port = None, None, None\n\n if port is not None:\n port_int = int(port)\n if not (0 <= port_int <= 65535):\n raise LocationParseError(url)\n else:\n port_int = None\n\n host = _normalize_host(host, scheme)\n\n if normalize_uri and path:\n path = _remove_path_dot_segments(path)\n path = _encode_invalid_chars(path, _PATH_CHARS)\n if normalize_uri and query:\n query = _encode_invalid_chars(query, _QUERY_CHARS)\n if normalize_uri and fragment:\n fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS)\n\n except (ValueError, AttributeError) as e:\n raise LocationParseError(source_url) from e\n\n # For the sake of backwards compatibility we put empty\n # string values for path if there are any defined values\n # beyond the path in the URL.\n # TODO: Remove this when we break backwards compatibility.\n if not path:\n if query is not None or fragment is not None:\n path = \"\"\n else:\n path = None\n\n return Url(\n scheme=scheme,\n auth=auth,\n host=host,\n port=port_int,\n path=path,\n query=query,\n fragment=fragment,\n )" } ]
import functools import logging import typing import warnings import ssl from types import TracebackType from urllib.parse import urljoin from ._collections import HTTPHeaderDict, RecentlyUsedContainer from ._request_methods import RequestMethods from .connection import ProxyConfig from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, URLSchemeUnknown, ) from .response import BaseHTTPResponse from .util.connection import _TYPE_SOCKET_OPTIONS from .util.proxy import connection_requires_http_tunnel from .util.retry import Retry from .util.timeout import Timeout from .util.url import Url, parse_url from typing_extensions import Literal
20,115
from __future__ import annotations if typing.TYPE_CHECKING: __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ssl_minimum_version", "ssl_maximum_version", "ca_cert_dir", "ssl_context", "key_password", "server_hostname", ) # Default value for `blocksize` - a new parameter introduced to # http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7 _DEFAULT_BLOCKSIZE = 16384 _SelfT = typing.TypeVar("_SelfT") class PoolKey(typing.NamedTuple): """ All known keyword arguments that could be provided to the pool manager, its pools, or the underlying connections. All custom key schemes should include the fields in this key at a minimum. """ key_scheme: str key_host: str key_port: int | None key_timeout: Timeout | float | int | None key_retries: Retry | bool | int | None key_block: bool | None key_source_address: tuple[str, int] | None key_key_file: str | None key_key_password: str | None key_cert_file: str | None key_cert_reqs: str | None key_ca_certs: str | None key_ssl_version: int | str | None key_ssl_minimum_version: ssl.TLSVersion | None key_ssl_maximum_version: ssl.TLSVersion | None key_ca_cert_dir: str | None key_ssl_context: ssl.SSLContext | None key_maxsize: int | None key_headers: frozenset[tuple[str, str]] | None
from __future__ import annotations if typing.TYPE_CHECKING: __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ssl_minimum_version", "ssl_maximum_version", "ca_cert_dir", "ssl_context", "key_password", "server_hostname", ) # Default value for `blocksize` - a new parameter introduced to # http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7 _DEFAULT_BLOCKSIZE = 16384 _SelfT = typing.TypeVar("_SelfT") class PoolKey(typing.NamedTuple): """ All known keyword arguments that could be provided to the pool manager, its pools, or the underlying connections. All custom key schemes should include the fields in this key at a minimum. """ key_scheme: str key_host: str key_port: int | None key_timeout: Timeout | float | int | None key_retries: Retry | bool | int | None key_block: bool | None key_source_address: tuple[str, int] | None key_key_file: str | None key_key_password: str | None key_cert_file: str | None key_cert_reqs: str | None key_ca_certs: str | None key_ssl_version: int | str | None key_ssl_minimum_version: ssl.TLSVersion | None key_ssl_maximum_version: ssl.TLSVersion | None key_ca_cert_dir: str | None key_ssl_context: ssl.SSLContext | None key_maxsize: int | None key_headers: frozenset[tuple[str, str]] | None
key__proxy: Url | None
14
2023-10-11 09:08:57+00:00
24k
MTgeophysics/mtpy-v2
mtpy/modeling/modem/convariance.py
[ { "identifier": "CovarianceError", "path": "mtpy/modeling/modem/exception.py", "snippet": "class CovarianceError(ModEMError):\n \"\"\" Raise for Covariance class specific exceptions\"\"\"\n\n pass" }, { "identifier": "Model", "path": "mtpy/modeling/modem/model.py", "snippet": "class Model:\n \"\"\"\n make and read a FE mesh grid\n\n The mesh assumes the coordinate system where:\n x == North\n y == East\n z == + down\n\n All dimensions are in meters.\n\n The mesh is created by first making a regular grid around the station area,\n then padding cells are added that exponentially increase to the given\n extensions. Depth cell increase on a log10 scale to the desired depth,\n then padding cells are added that increase exponentially.\n\n Arguments\n -------------\n **station_object** : mtpy.modeling.modem.Stations object\n .. seealso:: mtpy.modeling.modem.Stations\n\n Examples\n -------------\n\n :Example 1 --> create mesh first then data file: ::\n\n >>> import mtpy.modeling.modem as modem\n >>> import os\n >>> # 1) make a list of all .edi files that will be inverted for\n >>> edi_path = r\"/home/EDI_Files\"\n >>> edi_list = [os.path.join(edi_path, edi)\n for edi in os.listdir(edi_path)\n >>> ... if edi.find('.edi') > 0]\n >>> # 2) Make a Stations object\n >>> stations_obj = modem.Stations()\n >>> stations_obj.get_station_locations_from_edi(edi_list)\n >>> # 3) make a grid from the stations themselves with 200m cell spacing\n >>> mmesh = modem.Model(station_obj)\n >>> # change cell sizes\n >>> mmesh.cell_size_east = 200,\n >>> mmesh.cell_size_north = 200\n >>> mmesh.ns_ext = 300000 # north-south extension\n >>> mmesh.ew_ext = 200000 # east-west extension of model\n >>> mmesh.make_mesh()\n >>> # check to see if the mesh is what you think it should be\n >>> msmesh.plot_mesh()\n >>> # all is good write the mesh file\n >>> msmesh.write_model_file(save_path=r\"/home/modem/Inv1\")\n >>> # create data file\n >>> md = modem.Data(edi_list, station_locations=mmesh.station_locations)\n >>> md.write_data_file(save_path=r\"/home/modem/Inv1\")\n\n :Example 2 --> Rotate Mesh: ::\n\n >>> mmesh.mesh_rotation_angle = 60\n >>> mmesh.make_mesh()\n\n .. note:: ModEM assumes all coordinates are relative to North and East, and\n does not accommodate mesh rotations, therefore, here the rotation\n is of the stations, which essentially does the same thing. You\n will need to rotate you data to align with the 'new' coordinate\n system.\n\n ==================== ======================================================\n Attributes Description\n ==================== ======================================================\n _logger python logging object that put messages in logging\n format defined in logging configure file, see MtPyLog\n more information\n cell_number_ew optional for user to specify the total number of sells\n on the east-west direction. *default* is None\n cell_number_ns optional for user to specify the total number of sells\n on the north-south direction. *default* is None\n cell_size_east mesh block width in east direction\n *default* is 500\n cell_size_north mesh block width in north direction\n *default* is 500\n grid_center center of the mesh grid\n grid_east overall distance of grid nodes in east direction\n grid_north overall distance of grid nodes in north direction\n grid_z overall distance of grid nodes in z direction\n model_fn full path to initial file name\n model_fn_basename default name for the model file name\n n_air_layers number of air layers in the model. *default* is 0\n n_layers total number of vertical layers in model\n nodes_east relative distance between nodes in east direction\n nodes_north relative distance between nodes in north direction\n nodes_z relative distance between nodes in east direction\n pad_east number of cells for padding on E and W sides\n *default* is 7\n pad_north number of cells for padding on S and N sides\n *default* is 7\n pad_num number of cells with cell_size with outside of\n station area. *default* is 3\n pad_method method to use to create padding:\n extent1, extent2 - calculate based on ew_ext and\n ns_ext\n stretch - calculate based on pad_stretch factors\n pad_stretch_h multiplicative number for padding in horizontal\n direction.\n pad_stretch_v padding cells N & S will be pad_root_north**(x)\n pad_z number of cells for padding at bottom\n *default* is 4\n ew_ext E-W extension of model in meters\n ns_ext N-S extension of model in meters\n res_scale scaling method of res, supports\n 'loge' - for log e format\n 'log' or 'log10' - for log with base 10\n 'linear' - linear scale\n *default* is 'loge'\n res_list list of resistivity values for starting model\n res_model starting resistivity model\n res_initial_value resistivity initial value for the resistivity model\n *default* is 100\n mesh_rotation_angle Angle to rotate the grid to. Angle is measured\n positve clockwise assuming North is 0 and east is 90.\n *default* is None\n save_path path to save file to\n sea_level sea level in grid_z coordinates. *default* is 0\n station_locations location of stations\n title title in initial file\n z1_layer first layer thickness\n z_bottom absolute bottom of the model *default* is 300,000\n z_target_depth Depth of deepest target, *default* is 50,000\n ==================== ======================================================\n\n\n \"\"\"\n\n def __init__(self, station_locations=None, center_point=None, **kwargs):\n self._logger = logger\n\n self.station_locations = None\n self.center_point = MTLocation()\n\n if station_locations is not None:\n self.station_locations = station_locations\n\n if center_point is not None:\n self.center_point = center_point\n self.model_epsg = self.center_point.utm_epsg\n\n # size of cells within station area in meters\n self.cell_size_east = 500\n self.cell_size_north = 500\n\n # FZ: added this for user input number of cells in the horizontal mesh\n self.cell_number_ew = None\n self.cell_number_ns = None\n\n # padding cells on either side\n self.pad_east = 7\n self.pad_north = 7\n self.pad_z = 4\n\n self.pad_num = 3\n\n self.ew_ext = 100000\n self.ns_ext = 100000\n\n # root of padding cells\n self.pad_stretch_h = 1.2\n self.pad_stretch_v = 1.2\n\n self.z1_layer = 10\n self.z_layer_rounding = 0\n self.z_target_depth = 50000\n self.z_bottom = 300000\n\n # number of vertical layers\n self.n_layers = 30\n\n # number of air layers\n self.n_air_layers = 0\n # sea level in grid_z coordinates. Auto adjusts when topography read in?\n self.sea_level = 0.0\n\n # strike angle to rotate grid to\n self.mesh_rotation_angle = 0\n\n # --> attributes to be calculated\n # grid nodes\n self._nodes_east = None\n self._nodes_north = None\n self._nodes_z = None\n\n # grid locations\n self.grid_east = None\n self.grid_north = None\n self.grid_z = kwargs.pop(\"grid_z\", None)\n if self.grid_z is not None:\n self.n_layers = len(self.grid_z)\n self.z_mesh_method = \"custom\"\n else:\n self.z_mesh_method = \"new\"\n if \"z_mesh_method\" in list(kwargs.keys()):\n self.z_mesh_method = kwargs[\"z_mesh_method\"]\n\n # method to use to create padding\n self.pad_method = \"extent1\"\n\n self.grid_center = None\n self.surface_dict = {}\n\n # resistivity model\n self.res_initial_value = 100.0\n self.res_model = None\n\n # initial file stuff\n self.save_path = Path().cwd()\n self.model_fn_basename = \"ModEM_Model_File.rho\"\n\n self.title = \"Model File written by MTpy.modeling.modem\"\n self.res_scale = \"loge\"\n\n for key, value in kwargs.items():\n if hasattr(self, key):\n setattr(self, key, value)\n else:\n self._logger.warning(\n f\"Argument {key}={value} is not supportted thus not been set.\"\n )\n\n def __str__(self):\n lines = [\"ModEM Model Object:\", \"-\" * 20]\n # --> print out useful information\n try:\n lines.append(\n f\"\\tNumber of stations = {len(self.station_locations.station)}\"\n )\n except AttributeError:\n lines.append(\"\\tNumber of stations = unknown\")\n\n lines.append(\"\\tMesh Parameter: \")\n lines.append(f\"\\t\\tcell_size_east: {self.cell_size_east}\")\n lines.append(f\"\\t\\tcell_size_north: {self.cell_size_north}\")\n lines.append(f\"\\t\\tpad_east: {self.pad_east}\")\n lines.append(f\"\\t\\tpad_north: {self.pad_north}\")\n lines.append(f\"\\t\\tpad_num: {self.pad_num}\")\n lines.append(f\"\\t\\tz1_layer: {self.z1_layer}\")\n lines.append(f\"\\t\\tz_target_depth: {self.z_target_depth}\")\n lines.append(f\"\\t\\tn_layers: {self.n_layers}\")\n lines.append(f\"\\t\\tres_initial_value: {self.res_initial_value}\")\n lines.append(\"\\tDimensions: \")\n lines.append(f\"\\t\\te-w: {self.grid_east.size}\")\n lines.append(f\"\\t\\tn-s: {self.grid_north.size}\")\n lines.append(f\"\\t\\tz: {self.grid_z.size} (without 7 air layers)\")\n lines.append(\"\\tExtensions: \")\n lines.append(f\"\\t\\te-w: {self.nodes_east.__abs__().sum():.1f} (m)\")\n lines.append(f\"\\t\\tn-s: {self.nodes_north.__abs__().sum():.1f} (m)\")\n lines.append(f\"\\t\\t0-z: {self.nodes_z.__abs__().sum():.1f} (m)\")\n if self.mesh_rotation_angle != 0:\n lines.append(\n f\"\\tStations rotated by: {self.mesh_rotation_angle:.1f} deg clockwise positive from N\"\n )\n\n lines.append(\n \" ** Note ModEM does not accommodate mesh rotations, it assumes\"\n )\n lines.append(\" all coordinates are aligned to geographic N, E\")\n lines.append(\n \" therefore rotating the stations will have a similar effect\"\n )\n lines.append(\" as rotating the mesh.\")\n lines.append(\"-\" * 20)\n return \"\\n\".join(lines)\n\n def __repr__(self):\n return self.__str__()\n\n @property\n def save_path(self):\n return self._save_path\n\n @save_path.setter\n def save_path(self, save_path):\n if save_path is None:\n self._save_path = Path().cwd()\n else:\n self._save_path = Path(save_path)\n\n if not self._save_path.exists():\n self._save_path.mkdir()\n\n @property\n def model_fn(self):\n return self.save_path.joinpath(self.model_fn_basename)\n\n @model_fn.setter\n def model_fn(self, filename):\n if filename is not None:\n filename = Path(filename)\n self.save_path = filename.parent\n self.model_fn_basename = filename.name\n\n @property\n def model_epsg(self):\n return self.center_point.utm_epsg\n\n @model_epsg.setter\n def model_epsg(self, value):\n self.center_point.utm_epsg = value\n\n # --> make nodes and grid symbiotic so if you set one the other one\n # gets set as well\n # Nodes East\n @property\n def nodes_east(self):\n if self.grid_east is not None:\n self._nodes_east = np.array(\n [\n abs(self.grid_east[ii + 1] - self.grid_east[ii])\n for ii in range(self.grid_east.size - 1)\n ]\n )\n return self._nodes_east\n\n @nodes_east.setter\n def nodes_east(self, nodes):\n nodes = np.array(nodes)\n self._nodes_east = nodes\n self.grid_east = np.array(\n [\n nodes[0:ii].sum() for ii in range(nodes.size + 1)\n ] # -nodes.sum() / 2 +\n ) # + [shift])#[nodes.sum() / 2]\n\n # Nodes North\n @property\n def nodes_north(self):\n if self.grid_north is not None:\n self._nodes_north = np.array(\n [\n abs(self.grid_north[ii + 1] - self.grid_north[ii])\n for ii in range(self.grid_north.size - 1)\n ]\n )\n return self._nodes_north\n\n @nodes_north.setter\n def nodes_north(self, nodes):\n nodes = np.array(nodes)\n self._nodes_north = nodes\n self.grid_north = np.array(\n [\n nodes[0:ii].sum() for ii in range(nodes.size + 1)\n ] # -nodes.sum() / 2 +\n ) # + [shift])#[nodes.sum() / 2]\n\n @property\n def nodes_z(self):\n if self.grid_z is not None:\n self._nodes_z = np.array(\n [\n abs(self.grid_z[ii + 1] - self.grid_z[ii])\n for ii in range(self.grid_z.size - 1)\n ]\n )\n\n return self._nodes_z\n\n @nodes_z.setter\n def nodes_z(self, nodes):\n nodes = np.array(nodes)\n self._nodes_z = nodes\n self.grid_z = np.array(\n [nodes[0:ii].sum() for ii in range(nodes.size)] + [nodes.sum()]\n )\n\n # need some arrays for plotting that are the same length as the\n # resistivity model\n @property\n def plot_east(self):\n plot_east = np.array(\n [self.nodes_east[0:ii].sum() for ii in range(self.nodes_east.size)]\n )\n return plot_east - plot_east[-1] / 2.0\n\n @property\n def plot_north(self):\n plot_north = np.array(\n [\n self.nodes_north[0:ii].sum()\n for ii in range(self.nodes_north.size)\n ]\n )\n return plot_north - plot_north[-1] / 2.0\n\n @property\n def plot_z(self):\n return np.array(\n [self.nodes_z[0:ii].sum() for ii in range(self.nodes_z.size)]\n )\n\n def make_mesh(self, verbose=True):\n \"\"\"\n create finite element mesh according to user-input parameters.\n\n The mesh is built by:\n 1. Making a regular grid within the station area.\n 2. Adding pad_num of cell_width cells outside of station area\n 3. Adding padding cells to given extension and number of padding\n cells.\n 4. Making vertical cells starting with z1_layer increasing\n logarithmically (base 10) to z_target_depth and num_layers.\n 5. Add vertical padding cells to desired extension.\n 6. Check to make sure none of the stations lie on a node.\n If they do then move the node by .02*cell_width\n\n \"\"\"\n\n # --> find the edges of the grid\n # calculate the extra width of padding cells\n # multiply by 1.5 because this is only for 1 side\n pad_width_east = self.pad_num * 1.5 * self.cell_size_east\n pad_width_north = self.pad_num * 1.5 * self.cell_size_north\n\n # get the extremities\n west = self.station_locations.model_east.min() - pad_width_east\n east = self.station_locations.model_east.max() + pad_width_east\n south = self.station_locations.model_north.min() - pad_width_north\n north = self.station_locations.model_north.max() + pad_width_north\n\n # round the numbers so they are easier to read\n west = np.round(west, -2)\n east = np.round(east, -2)\n south = np.round(south, -2)\n north = np.round(north, -2)\n\n # -------make a grid around the stations from the parameters above------\n\n # adjust the edges so we have a whole number of cells\n add_ew = ((east - west) % self.cell_size_east) / 2.0\n add_ns = ((north - south) % self.cell_size_north) / 2.0\n\n # --> make the inner grid first\n inner_east = np.arange(\n west + add_ew - self.cell_size_east,\n east - add_ew + 2 * self.cell_size_east,\n self.cell_size_east,\n )\n inner_north = np.arange(\n south + add_ns + self.cell_size_north,\n north - add_ns + 2 * self.cell_size_north,\n self.cell_size_north,\n )\n\n # compute padding cells\n # first validate ew_ext and ns_ext to ensure it is large enough\n if \"extent\" in self.pad_method:\n self._validate_extent(\n inner_east.min(),\n inner_east.max(),\n inner_north.min(),\n inner_north.max(),\n )\n\n if self.pad_method == \"extent1\":\n padding_east = mtmesh.get_padding_cells(\n self.cell_size_east,\n self.ew_ext / 2 - east,\n self.pad_east,\n self.pad_stretch_h,\n )\n padding_north = mtmesh.get_padding_cells(\n self.cell_size_north,\n self.ns_ext / 2 - north,\n self.pad_north,\n self.pad_stretch_h,\n )\n elif self.pad_method == \"extent2\":\n padding_east = mtmesh.get_padding_cells2(\n self.cell_size_east,\n inner_east[-1],\n self.ew_ext / 2.0,\n self.pad_east,\n )\n padding_north = mtmesh.get_padding_cells2(\n self.cell_size_north,\n inner_north[-1],\n self.ns_ext / 2.0,\n self.pad_north,\n )\n elif self.pad_method == \"stretch\":\n padding_east = mtmesh.get_padding_from_stretch(\n self.cell_size_east, self.pad_stretch_h, self.pad_east\n )\n padding_north = mtmesh.get_padding_from_stretch(\n self.cell_size_north, self.pad_stretch_h, self.pad_north\n )\n else:\n raise NameError(\n 'Padding method \"{}\" is not supported'.format(self.pad_method)\n )\n\n # make the horizontal grid\n self.grid_east = np.append(\n np.append(-1 * padding_east[::-1] + inner_east.min(), inner_east),\n padding_east + inner_east.max(),\n )\n self.grid_north = np.append(\n np.append(\n -1 * padding_north[::-1] + inner_north.min(), inner_north\n ),\n padding_north + inner_north.max(),\n )\n\n # --> need to make sure none of the stations lie on the nodes\n for s_east in sorted(self.station_locations.model_east):\n try:\n node_index = np.where(\n abs(s_east - self.grid_east) < 0.02 * self.cell_size_east\n )[0][0]\n if s_east - self.grid_east[node_index] > 0:\n self.grid_east[node_index] -= 0.02 * self.cell_size_east\n elif s_east - self.grid_east[node_index] < 0:\n self.grid_east[node_index] += 0.02 * self.cell_size_east\n except IndexError:\n continue\n\n # --> need to make sure none of the stations lie on the nodes\n for s_north in sorted(self.station_locations.model_north):\n try:\n node_index = np.where(\n abs(s_north - self.grid_north)\n < 0.02 * self.cell_size_north\n )[0][0]\n if s_north - self.grid_north[node_index] > 0:\n self.grid_north[node_index] -= 0.02 * self.cell_size_north\n elif s_north - self.grid_north[node_index] < 0:\n self.grid_north[node_index] += 0.02 * self.cell_size_north\n except IndexError:\n continue\n\n if self.z_mesh_method == \"custom\":\n if self.grid_z is None:\n self.z_mesh_method = \"new\"\n self._logger.warn(\n \"No grid_z provided, creating new z mesh using default method\"\n )\n\n if self.z_mesh_method == \"custom\":\n self.nodes_z, z_grid = (\n self.grid_z[1:] - self.grid_z[:-1],\n self.grid_z,\n )\n elif self.z_mesh_method == \"new\":\n self.nodes_z, z_grid = self.make_z_mesh()\n else:\n raise NameError(\n 'Z mesh method \"{}\" is not supported'.format(\n self.z_mesh_method\n )\n )\n\n # compute grid center\n center_east = np.round(\n self.grid_east.min() - self.grid_east.mean(), -1\n )\n center_north = np.round(\n self.grid_north.min() - self.grid_north.mean(), -1\n )\n center_z = 0\n\n # this is the value to the lower left corner from the center.\n self.grid_center = np.array([center_north, center_east, center_z])\n\n # make the resistivity array\n self.res_model = np.zeros(\n (self.nodes_north.size, self.nodes_east.size, self.nodes_z.size)\n )\n self.res_model[:, :, :] = self.res_initial_value\n\n # --> print out useful information\n if verbose:\n print(self.__str__())\n\n def make_z_mesh(self, n_layers=None):\n \"\"\"\n new version of make_z_mesh. make_z_mesh and M\n \"\"\"\n n_layers = self.n_layers if n_layers is None else n_layers\n\n # --> make depth grid\n # if n_airlayers < 0; set to 0\n log_z = mtcc.make_log_increasing_array(\n self.z1_layer, self.z_target_depth, n_layers - self.pad_z\n )\n\n if self.z_layer_rounding is not None:\n z_nodes = np.around(log_z, decimals=self.z_layer_rounding)\n else:\n # round any values less than 100 to the same s.f. as z1_layer\n z_nodes = np.around(\n log_z[log_z < 100],\n decimals=-int(np.floor(np.log10(self.z1_layer))),\n )\n # round any values greater than or equal to 100 to the nearest 100\n z_nodes = np.append(\n z_nodes, np.around(log_z[log_z >= 100], decimals=-2)\n )\n\n # index of top of padding\n # itp = len(z_nodes) - 1\n\n # padding cells in the vertical direction\n z_0 = float(z_nodes[-1])\n for ii in range(1, self.pad_z + 1):\n pad_d = np.round(z_0 * self.pad_stretch_v**ii, -2)\n z_nodes = np.append(z_nodes, pad_d)\n # add air layers and define ground surface level.\n # initial layer thickness is same as z1_layer\n # z_nodes = np.hstack([[z1_layer] * n_air, z_nodes])\n\n # make an array of absolute values\n z_grid = np.array(\n [z_nodes[:ii].sum() for ii in range(z_nodes.shape[0] + 1)]\n )\n\n return z_nodes, z_grid\n\n def add_layers_to_mesh(\n self, n_add_layers=None, layer_thickness=None, where=\"top\"\n ):\n \"\"\"\n Function to add constant thickness layers to the top or bottom of mesh.\n Note: It is assumed these layers are added before the topography. If\n you want to add topography layers, use function add_topography_to_model\n\n :param n_add_layers: integer, number of layers to add\n :param layer_thickness: real value or list/array. Thickness of layers,\n defaults to z1 layer. Can provide a single value\n or a list/array containing multiple layer\n thicknesses.\n :param where: where to add, top or bottom\n\n\n \"\"\"\n # create array containing layers to add\n if layer_thickness is None:\n layer_thickness = self.z1_layer\n if np.iterable(layer_thickness):\n add_layers = np.insert(np.cumsum(layer_thickness), 0, 0)[:-1]\n layer_thickness = layer_thickness[-1]\n\n if n_add_layers != len(add_layers):\n self._logger.warn(\n \"Updating number of layers to reflect the length of the layer thickness array\"\n )\n n_add_layers = len(add_layers)\n else:\n add_layers = np.arange(\n 0, n_add_layers * layer_thickness, layer_thickness\n )\n\n # create a new z grid\n self.grid_z = np.hstack(\n [add_layers, self.grid_z + add_layers[-1] + layer_thickness]\n )\n\n # update the number of layers\n self.n_layers = len(self.grid_z) - 1\n\n # add the extra layer to the res model\n self.res_model = np.vstack(\n [self.res_model[:, :, :n_add_layers].T, self.res_model.T]\n ).T\n\n def assign_resistivity_from_surface_data(\n self, top_surface, bottom_surface, resistivity_value\n ):\n \"\"\"\n assign resistivity value to all points above or below a surface\n requires the surface_dict attribute to exist and contain data for\n surface key (can get this information from ascii file using\n project_surface)\n\n **inputs**\n surface_name = name of surface (must correspond to key in surface_dict)\n resistivity_value = value to assign\n where = 'above' or 'below' - assign resistivity above or below the\n surface\n \"\"\"\n\n # FZ: should ref-define the self.res_model if its shape has changed after topo air layer are added\n\n gcz = np.mean([self.grid_z[:-1], self.grid_z[1:]], axis=0)\n\n self._logger.debug(\n \"gcz is the cells centre coordinates: %s, %s\" % (len(gcz), gcz)\n )\n\n # assign resistivity value\n for j in range(len(self.res_model)):\n for i in range(len(self.res_model[j])):\n ii = np.where(\n (gcz > top_surface[j, i]) & (gcz <= bottom_surface[j, i])\n )[0]\n self.res_model[j, i, ii] = resistivity_value\n\n def write_model_file(self, **kwargs):\n \"\"\"\n will write an initial file for ModEM.\n\n Note that x is assumed to be S --> N, y is assumed to be W --> E and\n z is positive downwards. This means that index [0, 0, 0] is the\n southwest corner of the first layer. Therefore if you build a model\n by hand the layer block will look as it should in map view.\n\n Also, the xgrid, ygrid and zgrid are assumed to be the relative\n distance between neighboring nodes. This is needed because wsinv3d\n builds the model from the bottom SW corner assuming the cell width\n from the init file.\n\n Key Word Arguments:\n ----------------------\n\n **nodes_north** : np.array(nx)\n block dimensions (m) in the N-S direction.\n **Note** that the code reads the grid assuming that\n index=0 is the southern most point.\n\n **nodes_east** : np.array(ny)\n block dimensions (m) in the E-W direction.\n **Note** that the code reads in the grid assuming that\n index=0 is the western most point.\n\n **nodes_z** : np.array(nz)\n block dimensions (m) in the vertical direction.\n This is positive downwards.\n\n **save_path** : string\n Path to where the initial file will be saved\n to save_path/model_fn_basename\n\n **model_fn_basename** : string\n basename to save file to\n *default* is ModEM_Model.ws\n file is saved at save_path/model_fn_basename\n\n **title** : string\n Title that goes into the first line\n *default* is Model File written by MTpy.modeling.modem\n\n **res_model** : np.array((nx,ny,nz))\n Prior resistivity model.\n\n .. note:: again that the modeling code\n assumes that the first row it reads in is the southern\n most row and the first column it reads in is the\n western most column. Similarly, the first plane it\n reads in is the Earth's surface.\n\n **res_starting_value** : float\n starting model resistivity value,\n assumes a half space in Ohm-m\n *default* is 100 Ohm-m\n\n **res_scale** : [ 'loge' | 'log' | 'log10' | 'linear' ]\n scale of resistivity. In the ModEM code it\n converts everything to Loge,\n *default* is 'loge'\n\n \"\"\"\n for key in list(kwargs.keys()):\n setattr(self, key, kwargs[key])\n\n # get resistivity model\n if self.res_model is None:\n self.res_model = np.zeros(\n (\n self.nodes_north.size,\n self.nodes_east.size,\n self.nodes_z.size,\n )\n )\n self.res_model[:, :, :] = self.res_initial_value\n\n elif type(self.res_model) in [float, int]:\n self.res_initial_value = self.res_model\n self.res_model = np.zeros(\n (\n self.nodes_north.size,\n self.nodes_east.size,\n self.nodes_z.size,\n )\n )\n self.res_model[:, :, :] = self.res_initial_value\n\n # --> write file\n with open(self.model_fn, \"w\") as ifid:\n ifid.write(\"# {0}\\n\".format(self.title.upper()))\n ifid.write(\n \"{0:>5}{1:>5}{2:>5}{3:>5} {4}\\n\".format(\n self.nodes_north.size,\n self.nodes_east.size,\n self.nodes_z.size,\n 0,\n self.res_scale.upper(),\n )\n )\n\n # write S --> N node block\n for ii, nnode in enumerate(self.nodes_north):\n ifid.write(\"{0:>12.3f}\".format(abs(nnode)))\n\n ifid.write(\"\\n\")\n\n # write W --> E node block\n for jj, enode in enumerate(self.nodes_east):\n ifid.write(\"{0:>12.3f}\".format(abs(enode)))\n ifid.write(\"\\n\")\n\n # write top --> bottom node block\n for kk, zz in enumerate(self.nodes_z):\n ifid.write(\"{0:>12.3f}\".format(abs(zz)))\n ifid.write(\"\\n\")\n\n # write the resistivity in log e format\n if self.res_scale.lower() == \"loge\":\n write_res_model = np.log(self.res_model[::-1, :, :])\n elif (\n self.res_scale.lower() == \"log\"\n or self.res_scale.lower() == \"log10\"\n ):\n write_res_model = np.log10(self.res_model[::-1, :, :])\n elif self.res_scale.lower() == \"linear\":\n write_res_model = self.res_model[::-1, :, :]\n else:\n raise ModelError(\n 'resistivity scale \"{}\" is not supported.'.format(\n self.res_scale\n )\n )\n\n # write out the layers from resmodel\n for zz in range(self.nodes_z.size):\n ifid.write(\"\\n\")\n for ee in range(self.nodes_east.size):\n for nn in range(self.nodes_north.size):\n ifid.write(\n \"{0:>13.5E}\".format(write_res_model[nn, ee, zz])\n )\n ifid.write(\"\\n\")\n\n if self.grid_center is None:\n # compute grid center\n center_east = -self.nodes_east.__abs__().sum() / 2\n center_north = -self.nodes_north.__abs__().sum() / 2\n center_z = 0\n self.grid_center = np.array(\n [center_north, center_east, center_z]\n )\n\n ifid.write(\n \"\\n{0:>16.3f}{1:>16.3f}{2:>16.3f}\\n\".format(\n self.grid_center[0],\n self.grid_center[1],\n self.grid_center[2],\n )\n )\n\n if self.mesh_rotation_angle is None:\n ifid.write(\"{0:>9.3f}\\n\".format(0))\n else:\n ifid.write(\"{0:>9.3f}\\n\".format(self.mesh_rotation_angle))\n\n # not needed ifid.close()\n\n self._logger.info(\"Wrote file to: {0}\".format(self.model_fn))\n\n def read_model_file(self, model_fn=None):\n \"\"\"\n read an initial file and return the pertinent information including\n grid positions in coordinates relative to the center point (0,0) and\n starting model.\n\n Note that the way the model file is output, it seems is that the\n blocks are setup as\n\n ModEM: WS:\n ---------- -----\n 0-----> N_north 0-------->N_east\n | |\n | |\n V V\n N_east N_north\n\n\n Arguments:\n ----------\n\n **model_fn** : full path to initializing file.\n\n Outputs:\n --------\n\n **nodes_north** : np.array(nx)\n array of nodes in S --> N direction\n\n **nodes_east** : np.array(ny)\n array of nodes in the W --> E direction\n\n **nodes_z** : np.array(nz)\n array of nodes in vertical direction positive downwards\n\n **res_model** : dictionary\n dictionary of the starting model with keys as layers\n\n **res_list** : list\n list of resistivity values in the model\n\n **title** : string\n title string\n\n \"\"\"\n\n if model_fn is not None:\n self.model_fn = model_fn\n\n if self.model_fn is None:\n raise ModelError(\"model_fn is None, input a model file name\")\n\n if not self.model_fn.exists():\n raise ModelError(f\"Cannot find {self.model_fn}, check path\")\n\n with open(self.model_fn, \"r\") as ifid:\n ilines = ifid.readlines()\n\n self.title = ilines[0].strip()\n\n # get size of dimensions, remembering that x is N-S, y is E-W, z is + down\n nsize = ilines[1].strip().split()\n n_north = int(nsize[0])\n n_east = int(nsize[1])\n n_z = int(nsize[2])\n log_yn = nsize[4]\n\n # get nodes\n self.nodes_north = np.array(\n [float(nn) for nn in ilines[2].strip().split()]\n )\n self.nodes_east = np.array(\n [float(nn) for nn in ilines[3].strip().split()]\n )\n self.nodes_z = np.array(\n [float(nn) for nn in ilines[4].strip().split()]\n )\n\n self.res_model = np.zeros((n_north, n_east, n_z))\n\n # get model\n count_z = 0\n line_index = 6\n count_e = 0\n while count_z < n_z:\n iline = ilines[line_index].strip().split()\n # blank lines spit the depth blocks, use those as a marker to\n # set the layer number and start a new block\n if len(iline) == 0:\n count_z += 1\n count_e = 0\n line_index += 1\n # 3D grid model files don't have a space at the end\n # additional condition to account for this.\n elif (len(iline) == 3) & (count_z == n_z - 1):\n count_z += 1\n count_e = 0\n line_index += 1\n # each line in the block is a line of N-->S values for an east value\n else:\n north_line = np.array([float(nres) for nres in iline])\n\n # Need to be sure that the resistivity array matches\n # with the grids, such that the first index is the\n # furthest south\n self.res_model[:, count_e, count_z] = north_line[::-1]\n\n count_e += 1\n line_index += 1\n\n # --> get grid center and rotation angle\n if len(ilines) > line_index:\n for iline in ilines[line_index:]:\n ilist = iline.strip().split()\n # grid center\n if len(ilist) == 3:\n self.grid_center = np.array(ilist, dtype=float)\n # rotation angle\n elif len(ilist) == 1:\n self.mesh_rotation_angle = float(ilist[0])\n else:\n pass\n\n # --> make sure the resistivity units are in linear Ohm-m\n if log_yn.lower() == \"loge\":\n self.res_model = np.e**self.res_model\n elif log_yn.lower() == \"log\" or log_yn.lower() == \"log10\":\n self.res_model = 10**self.res_model\n\n # center the grids\n if self.grid_center is None:\n self.grid_center = np.array(\n [-self.nodes_north.sum() / 2, -self.nodes_east.sum() / 2, 0.0]\n )\n\n # need to shift the grid if the center is not symmetric\n # use the grid centre from the model file\n shift_north = self.grid_center[0] # + self.nodes_north.sum() / 2\n shift_east = self.grid_center[1] # + self.nodes_east.sum() / 2\n shift_z = self.grid_center[2]\n\n # shift the grid. if shift is + then that means the center is\n self.grid_north += shift_north\n self.grid_east += shift_east\n self.grid_z += shift_z\n\n # get cell size\n self.cell_size_east = stats.mode(self.nodes_east)[0][0]\n self.cell_size_north = stats.mode(self.nodes_north)[0][0]\n\n # get number of padding cells\n self.pad_east = np.where(\n self.nodes_east[0 : int(self.nodes_east.size / 2)]\n != self.cell_size_east\n )[0].size\n self.pad_north = np.where(\n self.nodes_north[0 : int(self.nodes_north.size / 2)]\n != self.cell_size_north\n )[0].size\n\n def plot_mesh(self, **kwargs):\n \"\"\"\n Plot model mesh\n\n :param plot_topography: DESCRIPTION, defaults to False\n :type plot_topography: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n if \"topography\" in self.surface_dict.keys():\n kwargs[\"plot_topography\"] = True\n return PlotMesh(self, **kwargs)\n\n @property\n def model_parameters(self):\n \"\"\"\n get important model parameters to write to a file for documentation\n later.\n\n\n \"\"\"\n\n parameter_list = [\n \"cell_size_east\",\n \"cell_size_north\",\n \"ew_ext\",\n \"ns_ext\",\n \"pad_east\",\n \"pad_north\",\n \"pad_z\",\n \"pad_num\",\n \"z1_layer\",\n \"z_target_depth\",\n \"z_bottom\",\n \"mesh_rotation_angle\",\n \"res_initial_value\",\n \"save_path\",\n ]\n\n parameter_dict = {}\n for parameter in parameter_list:\n key = \"model.{0}\".format(parameter)\n parameter_dict[key] = getattr(self, parameter)\n\n parameter_dict[\"model.size\"] = self.res_model.shape\n\n return parameter_dict\n\n def write_gocad_sgrid_file(\n self, fn=None, origin=[0, 0, 0], clip=0, no_data_value=-99999\n ):\n \"\"\"\n write a model to gocad sgrid\n\n optional inputs:\n\n fn = filename to save to. File extension ('.sg') will be appended.\n default is the model name with extension removed\n origin = real world [x,y,z] location of zero point in model grid\n clip = how much padding to clip off the edge of the model for export,\n provide one integer value or list of 3 integers for x,y,z directions\n no_data_value = no data value to put in sgrid\n\n \"\"\"\n if not np.iterable(clip):\n clip = [clip, clip, clip]\n\n # determine save path\n if fn is not None:\n fn = Path(fn)\n # if fn is a full path, convert to a file name\n fndir = fn.parent\n if fndir.is_dir():\n sg_basename = fn.name\n else:\n sg_basename = fn\n else:\n # create a basename if fn is None\n sg_basename = self.model_fn.stem\n\n self.save_path, fn, sg_basename = mtfh.validate_save_file(\n save_path=self.save_path, savefile=fn, basename=sg_basename\n )\n\n # number of cells in the ModEM model\n nyin, nxin, nzin = np.array(self.res_model.shape) + 1\n\n gx, gy = mtmesh.rotate_mesh(\n self.grid_east[clip[0] : nxin - clip[0]],\n self.grid_north[clip[1] : nyin - clip[1]],\n origin[:2],\n self.mesh_rotation_angle,\n )\n\n gz = -1.0 * self.grid_z[: nzin - clip[2]] - origin[2]\n\n gxm, gzm = np.meshgrid(gx, gz)\n gym, gzm = np.meshgrid(gy, gz)\n\n gxm = gxm.reshape(len(gz), len(gy), len(gx[0])).transpose(1, 2, 0)\n gym = gym.reshape(len(gz), len(gy), len(gx[0])).transpose(1, 2, 0)\n gzm = gzm.reshape(len(gz), len(gy), len(gx[0])).transpose(1, 2, 0)\n\n gridedges = (gxm, gym, gzm)\n\n # resistivity values, clipped to one smaller than grid edges\n resvals = self.res_model[\n clip[1] : nyin - clip[1] - 1,\n clip[0] : nxin - clip[0] - 1,\n : nzin - clip[2] - 1,\n ]\n\n sg_obj = mtgocad.Sgrid(\n resistivity=resvals,\n grid_xyz=gridedges,\n fn=sg_basename,\n workdir=self.save_path,\n )\n sg_obj.write_sgrid_file()\n\n def read_gocad_sgrid_file(\n self,\n sgrid_header_file,\n air_resistivity=1e39,\n sea_resistivity=0.3,\n sgrid_positive_up=True,\n ):\n \"\"\"\n read a gocad sgrid file and put this info into a ModEM file.\n Note: can only deal with grids oriented N-S or E-W at this stage,\n with orthogonal coordinates\n\n \"\"\"\n # read sgrid file\n sg_obj = mtgocad.Sgrid()\n sg_obj.read_sgrid_file(sgrid_header_file)\n self.sg_obj = sg_obj\n\n # get resistivity model values\n self.res_model = sg_obj.resistivity\n\n # get nodes and grid locations\n grideast, gridnorth, gridz = [\n np.unique(sg_obj.grid_xyz[i]) for i in range(3)\n ]\n # check if sgrid is positive up and convert to positive down if it is\n # (ModEM grid is positive down)\n if sgrid_positive_up:\n gridz = -gridz\n\n gridz.sort()\n\n if np.all(\n np.array([len(gridnorth), len(grideast), len(gridz)]) - 1\n == np.array(self.res_model.shape)\n ):\n self.grid_east, self.grid_north, self.grid_z = (\n grideast,\n gridnorth,\n gridz,\n )\n else:\n print(\n \"Cannot read sgrid, can't deal with non-orthogonal grids or grids not aligned N-S or E-W\"\n )\n return\n\n # check if we have a data object and if we do, is there a centre position\n # if not then assume it is the centre of the grid\n calculate_centre = True\n if self.data_obj is not None:\n if hasattr(self.data_obj, \"center_point\"):\n if self.data_obj.center_point is not None:\n centre = np.zeros(3)\n centre[0] = self.data_obj.center_point[\"east\"]\n centre[1] = self.data_obj.center_point[\"north\"]\n calculate_centre = False\n # get relative grid locations\n if calculate_centre:\n print(\"Calculating center position\")\n centre = np.zeros(3)\n centre[0] = (self.grid_east.max() + self.grid_east.min()) / 2.0\n centre[1] = (self.grid_north.max() + self.grid_north.min()) / 2.0\n centre[2] = self.grid_z[0]\n\n self.grid_east -= centre[0]\n self.grid_north -= centre[1]\n\n self.grid_center = np.array(\n [self.grid_north[0], self.grid_east[0], self.grid_z[0]]\n )\n\n self.z1_layer = self.nodes_z[0]\n # self.z_target_depth = None\n self.z_bottom = self.nodes_z[-1]\n\n # number of vertical layers\n self.n_layers = len(self.grid_z) - 1\n\n # number of air layers\n self.n_airlayers = sum(\n np.amax(self.res_model, axis=(0, 1)) > 0.9 * air_resistivity\n )\n\n # sea level in grid_z coordinates, calculate and adjust centre\n self.sea_level = self.grid_z[self.n_airlayers]\n\n def interpolate_elevation(\n self,\n surface_file=None,\n surface=None,\n get_surface_name=False,\n method=\"nearest\",\n fast=True,\n shift_north=0,\n shift_east=0,\n ):\n \"\"\"\n project a surface to the model grid and add resulting elevation data\n to a dictionary called surface_dict. Assumes the surface is in lat/long\n coordinates (wgs84)\n\n **returns**\n nothing returned, but surface data are added to surface_dict under\n the key given by surface_name.\n\n **inputs**\n choose to provide either surface_file (path to file) or surface (tuple).\n If both are provided then surface tuple takes priority.\n\n surface elevations are positive up, and relative to sea level.\n surface file format is:\n\n ncols 3601\n nrows 3601\n xllcorner -119.00013888889 (longitude of lower left)\n yllcorner 36.999861111111 (latitude of lower left)\n cellsize 0.00027777777777778\n NODATA_value -9999\n elevation data W --> E\n N\n |\n V\n S\n\n Alternatively, provide a tuple with:\n (lon,lat,elevation)\n where elevation is a 2D array (shape (ny,nx)) containing elevation\n points (order S -> N, W -> E)\n and lon, lat are either 1D arrays containing list of longitudes and\n latitudes (in the case of a regular grid) or 2D arrays with same shape\n as elevation array containing longitude and latitude of each point.\n\n other inputs:\n surface_epsg = epsg number of input surface, default is 4326 for lat/lon(wgs84)\n method = interpolation method. Default is 'nearest', if model grid is\n dense compared to surface points then choose 'linear' or 'cubic'\n\n \"\"\"\n # initialise a dictionary to contain the surfaces\n if not hasattr(self, \"surface_dict\"):\n self.surface_dict = {}\n\n # get centre position of model grid in real world coordinates\n x0, y0 = (\n self.center_point.east + shift_east,\n self.center_point.north + shift_north,\n )\n\n if self.mesh_rotation_angle is None:\n self.mesh_rotation_angle = 0\n\n xg, yg = mtmesh.rotate_mesh(\n self.grid_east,\n self.grid_north,\n [x0, y0],\n self.mesh_rotation_angle,\n return_centre=True,\n )\n if surface_file:\n elev_mg = mtmesh.interpolate_elevation_to_grid(\n xg,\n yg,\n surface_file=surface_file,\n utm_epsg=self.model_epsg,\n datum_epsg=self.center_point.datum_epsg,\n method=method,\n fast=fast,\n )\n elif surface:\n # Always use fast=False when reading from EDI data because\n # we're already providing a subset of the grid.\n elev_mg = mtmesh.interpolate_elevation_to_grid(\n xg,\n yg,\n surface=surface,\n utm_epsg=self.model_epsg,\n datum_epsg=self.center_point.datum_epsg,\n method=method,\n fast=False,\n )\n else:\n raise ValueError(\"'surface_file' or 'surface' must be provided\")\n\n # get a name for surface\n if get_surface_name:\n if surface_file is not None:\n surface_file = Path(surface_file)\n surface_name = surface_file.name\n else:\n ii = 1\n surface_name = \"surface%01i\" % ii\n while surface_name in list(self.surface_dict.keys()):\n ii += 1\n surface_name = \"surface%01i\" % ii\n return elev_mg, surface_name\n else:\n return elev_mg\n\n def add_topography_from_data(\n self,\n interp_method=\"nearest\",\n air_resistivity=1e12,\n topography_buffer=None,\n airlayer_type=\"log_up\",\n ):\n \"\"\"\n Wrapper around add_topography_to_model that allows creating\n a surface model from EDI data. The Data grid and station\n elevations will be used to make a 'surface' tuple that will\n be passed to add_topography_to_model so a surface model\n can be interpolated from it.\n\n The surface tuple is of format (lon, lat, elev) containing\n station locations.\n\n Args:\n data_object (mtpy.modeling.ModEM.data.Data): A ModEm data\n object that has been filled with data from EDI files.\n interp_method (str, optional): Same as\n add_topography_to_model.\n air_resistivity (float, optional): Same as\n add_topography_to_model.\n topography_buffer (float): Same as\n add_topography_to_model.\n airlayer_type (str, optional): Same as\n add_topography_to_model.\n \"\"\"\n lon = self.station_locations.longitude.to_numpy()\n lat = self.station_locations.latitude.to_numpy()\n elev = self.station_locations.elevation.to_numpy()\n surface = lon, lat, elev\n self.add_topography_to_model(\n surface=surface,\n interp_method=interp_method,\n air_resistivity=air_resistivity,\n topography_buffer=topography_buffer,\n airlayer_type=airlayer_type,\n )\n\n def add_topography_to_model(\n self,\n topography_file=None,\n surface=None,\n topography_array=None,\n interp_method=\"nearest\",\n air_resistivity=1e12,\n topography_buffer=None,\n airlayer_type=\"log_up\",\n max_elev=None,\n shift_east=0,\n shift_north=0,\n ):\n \"\"\"\n if air_layers is non-zero, will add topo: read in topograph file,\n make a surface model.\n\n Call project_stations_on_topography in the end, which will re-write\n the .dat file.\n\n If n_airlayers is zero, then cannot add topo data, only bathymetry is needed.\n\n :param topography_file: file containing topography (arcgis ascii grid)\n :param topography_array: alternative to topography_file - array of\n elevation values on model grid\n :param interp_method: interpolation method for topography,\n 'nearest', 'linear', or 'cubic'\n :param air_resistivity: resistivity value to assign to air\n :param topography_buffer: buffer around stations to calculate minimum\n and maximum topography value to use for\n meshing\n :param airlayer_type: how to set air layer thickness - options are\n 'constant' for constant air layer thickness,\n or 'log', for logarithmically increasing air\n layer thickness upward\n \"\"\"\n # first, get surface data\n if topography_file:\n self.surface_dict[\"topography\"] = self.interpolate_elevation(\n surface_file=topography_file,\n method=interp_method,\n shift_east=shift_east,\n shift_north=shift_north,\n )\n elif surface:\n self.surface_dict[\"topography\"] = self.interpolate_elevation(\n surface=surface,\n method=interp_method,\n shift_east=shift_east,\n shift_north=shift_north,\n )\n elif topography_array:\n self.surface_dict[\"topography\"] = topography_array\n else:\n raise ValueError(\n \"'topography_file', 'surface' or \"\n + \"topography_array must be provided\"\n )\n\n if self.n_air_layers is None or self.n_air_layers == 0:\n self._logger.warn(\n \"No air layers specified, so will not add air/topography !!!\"\n )\n self._logger.warn(\n \"Only bathymetry will be added below according to the topofile: sea-water low resistivity!!!\"\n )\n\n elif (\n self.n_air_layers > 0\n ): # FZ: new logic, add equal blocksize air layers on top of the simple flat-earth grid\n # get grid centre\n gcx, gcy = [\n np.mean([arr[:-1], arr[1:]], axis=0)\n for arr in (self.grid_east, self.grid_north)\n ]\n # get core cells\n if topography_buffer is None:\n topography_buffer = (\n 5\n * (self.cell_size_east**2 + self.cell_size_north**2)\n ** 0.5\n )\n core_cells = mtmesh.get_station_buffer(\n gcx,\n gcy,\n self.station_locations[\"model_east\"],\n self.station_locations[\"model_north\"],\n buf=topography_buffer,\n )\n topo_core = self.surface_dict[\"topography\"][core_cells]\n topo_core_min = max(topo_core.min(), 0)\n\n if airlayer_type == \"log_up\":\n # log increasing airlayers, in reversed order\n new_air_nodes = mtmesh.make_log_increasing_array(\n self.z1_layer,\n topo_core.max() - topo_core_min,\n self.n_air_layers,\n increment_factor=0.999,\n )[::-1]\n elif airlayer_type == \"log_down\":\n # make a new mesh\n n_layers = self.n_layers + self.n_air_layers\n self.nodes_z, z_grid = self.make_z_mesh(n_layers)\n\n # adjust level to topography min\n if max_elev is not None:\n self.grid_z -= max_elev\n ztops = np.where(\n self.surface_dict[\"topography\"] > max_elev\n )\n self.surface_dict[\"topography\"][ztops] = max_elev\n else:\n self.grid_z -= topo_core.max()\n\n elif airlayer_type == \"constant\":\n if max_elev is not None:\n air_cell_thickness = np.ceil(\n (max_elev - topo_core_min) / self.n_air_layers\n )\n else:\n air_cell_thickness = np.ceil(\n (topo_core.max() - topo_core_min) / self.n_air_layers\n )\n new_air_nodes = np.array(\n [air_cell_thickness] * self.n_air_layers\n )\n\n if \"down\" not in airlayer_type:\n # sum to get grid cell locations\n new_airlayers = np.array(\n [\n new_air_nodes[:ii].sum()\n for ii in range(len(new_air_nodes) + 1)\n ]\n )\n # maximum topography cell on the grid\n topo_max_grid = topo_core_min + new_airlayers[-1]\n # round to nearest whole number and convert subtract the max elevation (so that sea level is at topo_core_min)\n new_airlayers = np.around(new_airlayers - topo_max_grid)\n # add new air layers, cut_off some tailing layers to preserve array size.\n self.grid_z = np.concatenate(\n [new_airlayers[:-1], self.grid_z + new_airlayers[-1]],\n axis=0,\n )\n\n self._logger.debug(\"self.grid_z[0:2] {}\".format(self.grid_z[0:2]))\n\n # update the z-centre as the top air layer\n self.grid_center[2] = self.grid_z[0]\n\n # update the resistivity model\n new_res_model = (\n np.ones(\n (\n self.nodes_north.size,\n self.nodes_east.size,\n self.nodes_z.size,\n )\n )\n * self.res_initial_value\n )\n\n if \"down\" not in airlayer_type:\n new_res_model[:, :, self.n_air_layers :] = self.res_model\n\n self.res_model = new_res_model\n\n # assign topography\n top = np.zeros_like(self.surface_dict[\"topography\"]) + self.grid_z[0]\n bottom = -self.surface_dict[\"topography\"]\n self.assign_resistivity_from_surface_data(top, bottom, air_resistivity)\n # assign bathymetry\n self.assign_resistivity_from_surface_data(\n np.zeros_like(top), bottom, 0.3\n )\n\n return\n\n def _validate_extent(self, east, west, south, north, extent_ratio=2.0):\n \"\"\"\n validate the provided ew_ext and ns_ext to make sure the model fits\n within these extents and allows enough space for padding according to\n the extent ratio provided. If not, then update ew_ext and ns_ext parameters\n\n \"\"\"\n inner_ew_ext = west - east\n inner_ns_ext = north - south\n\n if self.ew_ext < extent_ratio * inner_ew_ext:\n self._logger.warn(\n \"Provided or default ew_ext not sufficient to fit stations + padding, updating extent\"\n )\n self.ew_ext = np.ceil(extent_ratio * inner_ew_ext)\n\n if self.ns_ext < extent_ratio * inner_ns_ext:\n self._logger.warn(\n \"Provided or default ns_ext not sufficient to fit stations + padding, updating extent\"\n )\n self.ns_ext = np.ceil(extent_ratio * inner_ns_ext)\n\n def _get_xyzres(self, location_type, origin, model_epsg, clip):\n # try getting centre location info from file\n if type(origin) == str:\n try:\n origin = np.loadtxt(origin)\n except:\n print(\n \"Please provide origin as a list, array or tuple or as a valid filename containing this info\"\n )\n origin = [0, 0]\n\n # reshape the data and get grid centres\n x, y, z = [\n np.mean([arr[1:], arr[:-1]], axis=0)\n for arr in [\n self.grid_east + origin[0],\n self.grid_north + origin[1],\n self.grid_z,\n ]\n ]\n xsize, ysize = x.shape[0], y.shape[0]\n x, y, z = np.meshgrid(\n x[clip[0] : xsize - clip[0]], y[clip[1] : ysize - clip[1]], z\n )\n\n # set format for saving data\n fmt = [\"%.1f\", \"%.1f\", \"%.3e\"]\n\n # convert to lat/long if needed\n if location_type == \"LL\":\n if np.any(origin) == 0:\n print(\n \"Warning, origin coordinates provided as zero, output lat/long are likely to be incorrect\"\n )\n # project using epsg_project as preference as it is faster, but if pyproj not installed, use gdal\n\n xp, yp = project_point(x, y, model_epsg, 4326)\n\n # update format to accommodate lat/lon\n fmt[:2] = [\"%.6f\", \"%.6f\"]\n else:\n xp, yp = x, y\n\n resvals = self.res_model[\n clip[1] : ysize - clip[1], clip[0] : xsize - clip[0]\n ]\n\n return xp, yp, z, resvals, fmt\n\n def write_xyzres(\n self,\n savefile=None,\n location_type=\"EN\",\n origin=[0, 0],\n model_epsg=None,\n log_res=False,\n model_utm_zone=None,\n clip=[0, 0],\n ):\n \"\"\"\n save a model file as a space delimited x y z res file\n\n \"\"\"\n xp, yp, z, resvals, fmt = self._get_xyzres(\n location_type, origin, model_epsg, clip\n )\n fmt.insert(2, \"%.1f\")\n xp, yp, z, resvals = (\n xp.flatten(),\n yp.flatten(),\n z.flatten(),\n resvals.flatten(),\n )\n\n np.savetxt(savefile, np.vstack([xp, yp, z, resvals]).T, fmt=fmt)\n\n def write_xyres(\n self,\n save_path=None,\n location_type=\"EN\",\n origin=[0, 0],\n model_epsg=None,\n depth_index=\"all\",\n outfile_basename=\"DepthSlice\",\n log_res=False,\n clip=[0, 0],\n ):\n \"\"\"\n write files containing depth slice data (x, y, res for each depth)\n\n origin = x,y coordinate of zero point of ModEM_grid, or name of file\n containing this info (full path or relative to model files)\n save_path = path to save to, default is the model object save path\n location_type = 'EN' or 'LL' xy points saved as eastings/northings or\n longitude/latitude, if 'LL' need to also provide model_epsg\n model_epsg = epsg number that was used to project the model\n outfile_basename = string for basename for saving the depth slices.\n log_res = True/False - option to save resistivity values as log10\n instead of linear\n clip = number of cells to clip on each of the east/west and north/south edges\n\n \"\"\"\n if save_path is None:\n save_path = Path(self.save_path)\n else:\n save_path = Path(save_path)\n # make a directory to save the files\n save_path = save_path.joinpath(outfile_basename)\n if not save_path.exists():\n save_path.mkdir()\n\n xp, yp, z, resvals, fmt = self._get_xyzres(\n location_type, origin, model_epsg, clip\n )\n xp = xp[:, :, 0].flatten()\n yp = yp[:, :, 0].flatten()\n\n # make depth indices into a list\n if depth_index == \"all\":\n depthindices = list(range(z.shape[2]))\n elif np.iterable(depth_index):\n depthindices = np.array(depth_index).astype(int)\n else:\n depthindices = [depth_index]\n\n for k in depthindices:\n fname = save_path.joinpath(\n outfile_basename + \"_%1im.xyz\" % self.grid_z[k]\n )\n\n # get relevant depth slice\n vals = resvals[:, :, k].flatten()\n\n if log_res:\n vals = np.log10(vals)\n fmt[-1] = \"%.3f\"\n data = np.vstack([xp, yp, vals]).T\n\n np.savetxt(fname, data, fmt=fmt)\n\n def write_vtk_file(\n self,\n vtk_save_path=None,\n vtk_fn_basename=\"ModEM_model_res\",\n shift_east=0,\n shift_north=0,\n shift_z=0,\n units=\"km\",\n coordinate_system=\"nez+\",\n label=\"resistivity\",\n ):\n \"\"\"\n Write a VTK file to plot in 3D rendering programs like Paraview\n\n :param vtk_save_path: directory to save vtk file to, defaults to None\n :type vtk_save_path: string or Path, optional\n :param vtk_fn_basename: filename basename of vtk file, note that .vtr\n extension is automatically added, defaults to \"ModEM_stations\"\n :type vtk_fn_basename: string, optional\n :type geographic: boolean, optional\n :param shift_east: shift in east directions in meters, defaults to 0\n :type shift_east: float, optional\n :param shift_north: shift in north direction in meters, defaults to 0\n :type shift_north: float, optional\n :param shift_z: shift in elevation + down in meters, defaults to 0\n :type shift_z: float, optional\n :param units: Units of the spatial grid [ km | m | ft ], defaults to \"km\"\n :type units: string, optional\n :type : string\n :param coordinate_system: coordinate system for the station, either the\n normal MT right-hand coordinate system with z+ down or the sinister\n z- down [ nez+ | enz- ], defaults to nez+\n :return: full path to VTK file\n :rtype: Path\n\n Write VTK file\n >>> model.write_vtk_file(vtk_fn_basename=\"modem_model\")\n\n Write VTK file in geographic coordinates with z+ up\n >>> model.write_vtk_station_file(vtk_fn_basename=\"modem_model\",\n >>> ... coordinate_system='enz-')\n \"\"\"\n\n if isinstance(units, str):\n if units.lower() == \"km\":\n scale = 1.0 / 1000.00\n elif units.lower() == \"m\":\n scale = 1.0\n elif units.lower() == \"ft\":\n scale = 3.2808\n elif isinstance(units, (int, float)):\n scale = units\n\n if vtk_save_path is None:\n vtk_fn = self.save_path.joinpath(vtk_fn_basename)\n else:\n vtk_fn = Path(vtk_save_path).joinpath(vtk_fn_basename)\n\n # use cellData, this makes the grid properly as grid is n+1\n if coordinate_system == \"nez+\":\n vtk_x = (self.grid_north + shift_north) * scale\n vtk_y = (self.grid_east + shift_east) * scale\n vtk_z = (self.grid_z + shift_z) * scale\n cell_data = {label: self.res_model}\n\n elif coordinate_system == \"enz-\":\n vtk_y = (self.grid_north + shift_north) * scale\n vtk_x = (self.grid_east + shift_east) * scale\n vtk_z = -1 * (self.grid_z + shift_z) * scale\n cell_data = {label: np.rot90(self.res_model)}\n\n gridToVTK(vtk_fn.as_posix(), vtk_x, vtk_y, vtk_z, cellData=cell_data)\n\n self._logger.info(\"Wrote model file to {}\".format(vtk_fn))\n\n def write_geosoft_xyz(\n self,\n save_fn,\n c_east=0,\n c_north=0,\n c_z=0,\n pad_north=0,\n pad_east=0,\n pad_z=0,\n ):\n \"\"\"\n Write an XYZ file readable by Geosoft\n\n All input units are in meters.\n\n :param save_fn: full path to save file to\n :type save_fn: string or Path\n :param c_east: center point in the east direction, defaults to 0\n :type c_east: float, optional\n :param c_north: center point in the north direction, defaults to 0\n :type c_north: float, optional\n :param c_z: center point elevation, defaults to 0\n :type c_z: float, optional\n :param pad_north: number of cells to cut from the north-south edges, defaults to 0\n :type pad_north: int, optional\n :param pad_east: number of cells to cut from the east-west edges, defaults to 0\n :type pad_east: int, optional\n :param pad_z: number of cells to cut from the bottom, defaults to 0\n :type pad_z: int, optional\n\n\n \"\"\"\n lines = [\n r\"/ ------------------------------------------------------------------------------\",\n r\"/ XYZ IMPORT [01/25/2021]\",\n r\"/ VOXEL [.\\electrical_resistivity.geosoft_voxel]\",\n r\"/ ------------------------------------------------------------------------------\",\n r\"/ X,Y,Z,Data\",\n ]\n\n # --> write model xyz file\n for kk, zz in enumerate(self.grid_z[0:-pad_z]):\n for jj, yy in enumerate(self.grid_east[pad_east:-pad_east]):\n for ii, xx in enumerate(self.grid_north[pad_north:-pad_north]):\n lines.append(\n f\"{yy + c_east:.3f} {xx + c_north:.3f} {-(zz + c_z):.3f} {self.res_model[ii, jj, kk]:.3f}\"\n )\n\n with open(save_fn, \"w\") as fid:\n fid.write(\"\\n\".join(lines))\n\n def write_out_file(\n self, save_fn, geographic_east, geographic_north, geographic_elevation\n ):\n \"\"\"\n will write an .out file for LeapFrog.\n\n Note that y is assumed to be S --> N, e is assumed to be W --> E and\n z is positive upwards. This means that index [0, 0, 0] is the\n southwest corner of the first layer.\n\n :param save_fn: full path to save file to\n :type save_fn: string or Path\n :param geographic_east: geographic center in easting (meters)\n :type geographic_east: float\n :param geographic_north: geographic center in northing (meters)\n :type geographic_north: float\n :param geographic_elevation: elevation of geographic center (meters)\n :type geographic_elevation: float\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n # get resistivity model\n if self.res_model is None:\n self.res_model = np.zeros(\n (\n self.nodes_north.size,\n self.nodes_east.size,\n self.nodes_z.size,\n )\n )\n self.res_model[:, :, :] = self.res_initial_value\n\n elif type(self.res_model) in [float, int]:\n self.res_initial_value = self.res_model\n self.res_model = np.zeros(\n (\n self.nodes_north.size,\n self.nodes_east.size,\n self.nodes_z.size,\n )\n )\n self.res_model[:, :, :] = self.res_initial_value\n\n shift_east = (\n geographic_east\n - (\n self.nodes_east[0]\n - self.nodes_east[1] / 2\n - self.grid_center[1] / 2\n )\n ) / 1000.0\n shift_north = (\n geographic_north\n + (\n self.nodes_north[0]\n - self.nodes_north[1] / 2\n - self.grid_center[0] / 2\n )\n ) / 1000.0\n\n shift_elevation = geographic_elevation / 1000.0\n\n # --> write file\n with open(save_fn, \"w\") as ifid:\n ifid.write(\"\\n\")\n ifid.write(\n \"{0:>5}{1:>5}{2:>5}{3:>5} {4}\\n\".format(\n self.nodes_east.size,\n self.nodes_north.size,\n self.nodes_z.size,\n 0,\n \"VAL\",\n )\n )\n\n # write S --> N node block\n for ii, nnode in enumerate(self.nodes_east):\n ifid.write(\"{0:>12.3f}\".format(abs(nnode)))\n\n ifid.write(\"\\n\")\n\n # write W --> E node block\n for jj, enode in enumerate(self.nodes_north):\n ifid.write(\"{0:>12.3f}\".format(abs(enode)))\n ifid.write(\"\\n\")\n\n # write top --> bottom node block\n for kk, zz in enumerate(self.nodes_z):\n ifid.write(\"{0:>12.3f}\".format(abs(zz)))\n ifid.write(\"\\n\")\n\n # write the resistivity in log e format\n write_res_model = self.res_model[::-1, :, :]\n\n # write out the layers from resmodel\n count = 1\n for zz in range(self.nodes_z.size):\n ifid.write(f\"{count}\\n\")\n for nn in range(self.nodes_north.size):\n for ee in range(self.nodes_east.size):\n ifid.write(\n \"{0:>13.5E}\".format(write_res_model[nn, ee, zz])\n )\n ifid.write(\"\\n\")\n count += 1\n\n # write footer\n ifid.write(\"\\n\")\n ifid.write(\"WINGLINK\\n\")\n ifid.write(\" Project (site name)\\n\")\n ifid.write(\" 1 1 (i j block numbers)\\n\")\n ifid.write(\n f\" {shift_east:.3f} {shift_north:.3f} (real world coordinates)\\n\"\n )\n ifid.write(\" 0.0000000E+00 (rotation)\\n\")\n ifid.write(f\" {shift_elevation:.3f} (top elevation)\\n\")\n ifid.write(\"\\n\")\n\n self._logger.info(\"Wrote file to: {0}\".format(save_fn))\n\n def write_ubc_files(self, basename, c_east=0, c_north=0, c_z=0):\n \"\"\"\n Write a UBC .msh and .mod file\n\n :param save_fn: DESCRIPTION\n :type save_fn: TYPE\n :param c_east: DESCRIPTION, defaults to 0\n :type c_east: TYPE, optional\n :param c_north: DESCRIPTION, defaults to 0\n :type c_north: TYPE, optional\n :param c_z: DESCRIPTION, defaults to 0\n :type c_z: TYPE, optional\n :return: DESCRIPTION\n :rtype: TYPE\n\n\n .. note:: not complete yet.\n \"\"\"\n\n # write mesh first\n lines = [\n f\"{self.nodes_east.size} {self.nodes_north.size} {self.nodes_z.size}\"\n ]\n lines.append(\n str(self.nodes_east.tolist())\n .replace(\"[\", \"\")\n .replace(\"]\", \"\")\n .replace(\",\", \"\")\n )\n lines.append(\n str(self.nodes_north.tolist())\n .replace(\"[\", \"\")\n .replace(\"]\", \"\")\n .replace(\",\", \"\")\n )\n lines.append(\n str(self.nodes_z.tolist())\n .replace(\"[\", \"\")\n .replace(\"]\", \"\")\n .replace(\",\", \"\")\n )\n\n with open(self.save_path.joinpath(basename + \".msh\"), \"w\") as fid:\n fid.write(\"\\n\".join(lines))" } ]
from pathlib import Path from loguru import logger from .exception import CovarianceError from .model import Model from pyevtk.hl import gridToVTK import numpy as np
20,102
""" ================== ModEM ================== # Generate files for ModEM # revised by JP 2017 # revised by AK 2017 to bring across functionality from ak branch """ # ============================================================================= # Imports # ============================================================================= # ============================================================================= class Covariance(object): """ read and write covariance files """ def __init__(self, grid_dimensions=None, **kwargs): self._logger = logger self.grid_dimensions = grid_dimensions self.smoothing_east = 0.3 self.smoothing_north = 0.3 self.smoothing_z = 0.3 self.smoothing_num = 1 self.exception_list = [] self.mask_arr = None self.save_path = Path().cwd() self.fn_basename = "covariance.cov" self._header_str = "\n".join( [ "+{0}+".format("-" * 77), "| This file defines model covariance for a recursive autoregression scheme. |", "| The model space may be divided into distinct areas using integer masks. |", "| Mask 0 is reserved for air; mask 9 is reserved for ocean. Smoothing between |", "| air, ocean and the rest of the model is turned off automatically. You can |", "| also define exceptions to override smoothing between any two model areas. |", "| To turn off smoothing set it to zero. This header is 16 lines long. |", "| 1. Grid dimensions excluding air layers (Nx, Ny, NzEarth) |", "| 2. Smoothing in the X direction (NzEarth real values) |", "| 3. Smoothing in the Y direction (NzEarth real values) |", "| 4. Vertical smoothing (1 real value) |", "| 5. Number of times the smoothing should be applied (1 integer >= 0) |", "| 6. Number of exceptions (1 integer >= 0) |", "| 7. Exceptions in the for e.g. 2 3 0. (to turn off smoothing between 3 & 4) |", "| 8. Two integer layer indices and Nx x Ny block of masks, repeated as needed.|", "+{0}+".format("-" * 77), ] ) for key in list(kwargs.keys()): if hasattr(self, key): setattr(self, key, kwargs[key]) else: self._logger.warn( "Argument {}={} is not supportted thus not been set.".format( key, kwargs[key] ) ) @property def cov_fn(self): return self.save_path.joinpath(self.fn_basename) @cov_fn.setter def cov_fn(self, value): if value is not None: value = Path(value) self.save_path = value.parent self.fn_basename = value.name def write_covariance_file( self, cov_fn=None, save_path=None, fn_basename=None, model_fn=None, sea_water=0.3, air=1e12, ): # """ write a covariance file """ if model_fn is not None: mod_obj = Model() mod_obj.read_model_file(model_fn) # update save_path from model path if not provided separately if save_path is None: save_path = mod_obj.save_path self.grid_dimensions = mod_obj.res_model.shape if self.mask_arr is None: self.mask_arr = np.ones_like(mod_obj.res_model) self.mask_arr[np.where(mod_obj.res_model >= air * 0.9)] = 0 self.mask_arr[ np.where( (mod_obj.res_model <= sea_water * 1.1) & (mod_obj.res_model >= sea_water * 0.9) ) ] = 9 if self.grid_dimensions is None:
""" ================== ModEM ================== # Generate files for ModEM # revised by JP 2017 # revised by AK 2017 to bring across functionality from ak branch """ # ============================================================================= # Imports # ============================================================================= # ============================================================================= class Covariance(object): """ read and write covariance files """ def __init__(self, grid_dimensions=None, **kwargs): self._logger = logger self.grid_dimensions = grid_dimensions self.smoothing_east = 0.3 self.smoothing_north = 0.3 self.smoothing_z = 0.3 self.smoothing_num = 1 self.exception_list = [] self.mask_arr = None self.save_path = Path().cwd() self.fn_basename = "covariance.cov" self._header_str = "\n".join( [ "+{0}+".format("-" * 77), "| This file defines model covariance for a recursive autoregression scheme. |", "| The model space may be divided into distinct areas using integer masks. |", "| Mask 0 is reserved for air; mask 9 is reserved for ocean. Smoothing between |", "| air, ocean and the rest of the model is turned off automatically. You can |", "| also define exceptions to override smoothing between any two model areas. |", "| To turn off smoothing set it to zero. This header is 16 lines long. |", "| 1. Grid dimensions excluding air layers (Nx, Ny, NzEarth) |", "| 2. Smoothing in the X direction (NzEarth real values) |", "| 3. Smoothing in the Y direction (NzEarth real values) |", "| 4. Vertical smoothing (1 real value) |", "| 5. Number of times the smoothing should be applied (1 integer >= 0) |", "| 6. Number of exceptions (1 integer >= 0) |", "| 7. Exceptions in the for e.g. 2 3 0. (to turn off smoothing between 3 & 4) |", "| 8. Two integer layer indices and Nx x Ny block of masks, repeated as needed.|", "+{0}+".format("-" * 77), ] ) for key in list(kwargs.keys()): if hasattr(self, key): setattr(self, key, kwargs[key]) else: self._logger.warn( "Argument {}={} is not supportted thus not been set.".format( key, kwargs[key] ) ) @property def cov_fn(self): return self.save_path.joinpath(self.fn_basename) @cov_fn.setter def cov_fn(self, value): if value is not None: value = Path(value) self.save_path = value.parent self.fn_basename = value.name def write_covariance_file( self, cov_fn=None, save_path=None, fn_basename=None, model_fn=None, sea_water=0.3, air=1e12, ): # """ write a covariance file """ if model_fn is not None: mod_obj = Model() mod_obj.read_model_file(model_fn) # update save_path from model path if not provided separately if save_path is None: save_path = mod_obj.save_path self.grid_dimensions = mod_obj.res_model.shape if self.mask_arr is None: self.mask_arr = np.ones_like(mod_obj.res_model) self.mask_arr[np.where(mod_obj.res_model >= air * 0.9)] = 0 self.mask_arr[ np.where( (mod_obj.res_model <= sea_water * 1.1) & (mod_obj.res_model >= sea_water * 0.9) ) ] = 9 if self.grid_dimensions is None:
raise CovarianceError(
0
2023-10-11 22:24:50+00:00
24k
weavel-ai/promptmodel-python
promptmodel/llms/llm_proxy.py
[ { "identifier": "LLM", "path": "promptmodel/llms/llm.py", "snippet": "class LLM:\n def __init__(self):\n pass\n\n @classmethod\n def __parse_output_pattern__(\n cls,\n raw_output: Optional[str] = None,\n parsing_type: Optional[ParsingType] = None,\n ) -> ParseResult:\n if parsing_type is None:\n return ParseResult(parsed_outputs={}, error=False, error_log=None)\n if raw_output is None:\n return ParseResult(parsed_outputs={}, error=True, error_log=\"No content\")\n parsing_pattern = get_pattern_by_type(parsing_type)\n whole_pattern = parsing_pattern[\"whole\"]\n parsed_results = re.findall(whole_pattern, raw_output, flags=re.DOTALL)\n parsed_outputs = {}\n error: bool = False\n error_log: str = None\n\n try:\n for parsed_result in parsed_results:\n key = parsed_result[0]\n type_str = parsed_result[1]\n value = convert_str_to_type(parsed_result[2], type_str)\n parsed_outputs[key] = value\n except Exception as e:\n error = True\n error_log = str(e)\n\n return ParseResult(\n parsed_outputs=parsed_outputs,\n error=error,\n error_log=error_log,\n )\n\n def __validate_openai_messages(\n self, messages: List[Dict[str, str]]\n ) -> List[OpenAIMessage]:\n \"\"\"Validate and convert list of dictionaries to list of OpenAIMessage.\"\"\"\n res = []\n for message in messages:\n res.append(OpenAIMessage(**message))\n return res\n\n def run(\n self,\n messages: List[Dict[str, str]],\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> LLMResponse:\n \"\"\"Return the response from openai chat completion.\"\"\"\n response = None\n if functions == []:\n functions = None\n try:\n response: ModelResponse = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n content: Optional[str] = getattr(\n response.choices[0].message, \"content\", None\n )\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[List[ChatCompletionMessageToolCall]] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=content,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n )\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n async def arun(\n self,\n messages: List[Dict[str, str]],\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> LLMResponse:\n \"\"\"Return the response from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n response: ModelResponse = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n content: Optional[str] = getattr(\n response.choices[0].message, \"content\", None\n )\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[ChatCompletionMessageToolCall] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=content,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n )\n\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n def stream(\n self,\n messages: List[Dict[str, str]], # input\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> Generator[LLMStreamResponse, None, None]:\n \"\"\"Stream openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n # load_prompt()\n start_time = datetime.datetime.now()\n response = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n for chunk in self.__llm_stream_response_generator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def astream(\n self,\n messages: List[Dict[str, str]],\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n *args,\n **kwargs,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n \"\"\"Parse & stream output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n start_time = datetime.datetime.now()\n response = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n async for chunk in self.__llm_stream_response_agenerator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def run_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n ) -> LLMResponse:\n \"\"\"Parse and return output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n parsed_success = True\n parse_result = None\n error_log = None\n try:\n response: ModelResponse = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n raw_output = getattr(response.choices[0].message, \"content\", None)\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[List[ChatCompletionMessageToolCall]] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n if not call_func and not call_tools:\n # function call does not appear in output\n\n parse_result: ParseResult = self.__parse_output_pattern__(\n raw_output, parsing_type\n )\n\n # if output_keys exist & parsed_outputs does not match with output_keys -> error\n # if parse_result.error -> error\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or parse_result.error:\n parsed_success = False\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not parse_result.error_log\n else parse_result.error_log\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=raw_output,\n parsed_outputs=parse_result.parsed_outputs if parse_result else None,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n error=not parsed_success,\n error_log=error_log,\n )\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n async def arun_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n ) -> LLMResponse:\n \"\"\"Generate openai chat completion asynchronously, and parse the output.\n Example prompt is as follows:\n -----\n Given a topic, you are required to generate a story.\n You must follow the provided output format.\n\n Topic:\n {topic}\n\n Output format:\n [Story]\n ...\n [/Story]\n\n Now generate the output:\n \"\"\"\n if functions == []:\n functions = None\n response = None\n parsed_success = True\n parse_result = None\n error_log = None\n try:\n response: ModelResponse = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n raw_output = getattr(response.choices[0].message, \"content\", None)\n\n call_func: Optional[FunctionCall] = getattr(\n response.choices[0].message, \"function_call\", None\n )\n\n call_tools: Optional[List[ChatCompletionMessageToolCall]] = getattr(\n response.choices[0].message, \"tool_calls\", None\n )\n\n if not call_func and not call_tools:\n # function call does not appear in output\n parse_result: ParseResult = self.__parse_output_pattern__(\n raw_output, parsing_type\n )\n\n # if output_keys exist & parsed_outputs does not match with output_keys -> error\n # if parse_result.error -> error\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or parse_result.error:\n parsed_success = False\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not parse_result.error_log\n else parse_result.error_log\n )\n\n return LLMResponse(\n api_response=response,\n raw_output=raw_output,\n parsed_outputs=parse_result.parsed_outputs if parse_result else None,\n function_call=call_func if call_func else None,\n tool_calls=call_tools if call_tools else None,\n error=not parsed_success,\n error_log=error_log,\n )\n except Exception as e:\n if response is not None:\n return LLMResponse(api_response=response, error=True, error_log=str(e))\n else:\n return LLMResponse(api_response=None, error=True, error_log=str(e))\n\n def stream_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n **kwargs,\n ) -> Generator[LLMStreamResponse, None, None]:\n \"\"\"Parse & stream output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n if parsing_type == ParsingType.COLON.value:\n # cannot stream colon type\n yield LLMStreamResponse(\n error=True, error_log=\"Cannot stream colon type\"\n )\n return\n start_time = datetime.datetime.now()\n response = completion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n parsed_outputs = {}\n error_occurs = False\n error_log = None\n\n if (functions and len(functions) > 0) or (tools and len(tools) > 0):\n # if function exists, cannot parsing in stream time\n # just stream raw output and parse after stream\n streamed_outputs = {\n \"content\": \"\",\n \"function_call\": None,\n \"api_response\": None,\n }\n response_with_api_res = None\n for chunk in self.__llm_stream_response_generator__(\n messages, response, start_time, functions, tools\n ):\n if chunk.raw_output:\n streamed_outputs[\"content\"] += chunk.raw_output\n if chunk.function_call:\n streamed_outputs[\"function_call\"] = chunk.function_call\n if (\n chunk.api_response\n and getattr(chunk.api_response.choices[0], \"delta\", None)\n is None\n ): # only get the last api_response, not delta response\n streamed_outputs[\"api_response\"] = chunk.api_response\n response_with_api_res = chunk\n else:\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n if not streamed_outputs[\"function_call\"]:\n # if function call does not exist in output\n # able to parse\n parse_result: ParseResult = self.__parse_output_pattern__(\n streamed_outputs[\"content\"], parsing_type\n )\n\n error_occurs = parse_result.error or error_occurs\n error_log = parse_result.error_log if not error_log else error_log\n\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or error_occurs:\n error_occurs = True\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not error_log\n else error_log\n )\n yield LLMStreamResponse(\n api_response=streamed_outputs[\"api_response\"],\n error=True,\n error_log=error_log,\n )\n else:\n response_with_api_res.parsed_outputs = (\n parse_result.parsed_outputs\n )\n yield response_with_api_res\n else:\n yield response_with_api_res\n else:\n if parsing_type is None:\n for chunk in self.__llm_stream_response_generator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n elif parsing_type == ParsingType.DOUBLE_SQUARE_BRACKET.value:\n for chunk in self.__double_type_sp_generator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n else:\n for chunk in self.__single_type_sp_generator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n if (\n output_keys is not None\n and set(parsed_outputs.keys()) != set(output_keys)\n ) and not error_occurs:\n error_occurs = True\n error_log = \"Output keys do not match with parsed output keys\"\n yield LLMStreamResponse(error=True, error_log=error_log)\n\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def astream_and_parse(\n self,\n messages: List[Dict[str, str]],\n parsing_type: Optional[ParsingType] = None,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n output_keys: Optional[List[str]] = None,\n model: Optional[str] = DEFAULT_MODEL,\n api_key: Optional[str] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n \"\"\"Parse & stream output from openai chat completion.\"\"\"\n if functions == []:\n functions = None\n response = None\n try:\n if parsing_type == ParsingType.COLON.value:\n # cannot stream colon type\n yield LLMStreamResponse(\n error=True, error_log=\"Cannot stream colon type\"\n )\n return\n start_time = datetime.datetime.now()\n response = await acompletion(\n model=model,\n messages=[\n message.model_dump(exclude_none=True)\n for message in self.__validate_openai_messages(messages)\n ],\n stream=True,\n functions=functions,\n tools=tools,\n api_key=api_key,\n )\n\n parsed_outputs = {}\n error_occurs = False # error in stream time\n error_log = None\n if (functions and len(functions) > 0) or (tools and len(tools) > 0):\n # if function exists, cannot parsing in stream time\n # just stream raw output and parse after stream\n streamed_outputs = {\n \"content\": \"\",\n \"function_call\": None,\n \"api_response\": None,\n }\n response_with_api_res = None\n async for chunk in self.__llm_stream_response_agenerator__(\n messages, response, start_time, functions, tools\n ):\n if chunk.raw_output:\n streamed_outputs[\"content\"] += chunk.raw_output\n if chunk.function_call:\n streamed_outputs[\"function_call\"] = chunk.function_call\n if (\n chunk.api_response\n and getattr(chunk.api_response.choices[0], \"delta\", None)\n is None\n ):\n streamed_outputs[\"api_response\"] = chunk.api_response\n response_with_api_res = chunk\n else:\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n if not streamed_outputs[\"function_call\"]:\n # if function call does not exist in output\n # able to parse\n parse_result: ParseResult = self.__parse_output_pattern__(\n streamed_outputs[\"content\"], parsing_type\n )\n\n error_occurs = parse_result.error or error_occurs\n error_log = parse_result.error_log if not error_log else error_log\n if (\n output_keys is not None\n and set(parse_result.parsed_outputs.keys()) != set(output_keys)\n ) or error_occurs:\n error_occurs = True\n error_log = (\n \"Output keys do not match with parsed output keys\"\n if not error_log\n else error_log\n )\n yield LLMStreamResponse(\n api_response=streamed_outputs[\"api_response\"],\n error=True,\n error_log=error_log,\n )\n else:\n response_with_api_res.parsed_outputs = (\n parse_result.parsed_outputs\n )\n yield response_with_api_res\n else:\n yield response_with_api_res\n else:\n if parsing_type is None:\n async for chunk in self.__llm_stream_response_agenerator__(\n messages, response, start_time, functions, tools\n ):\n yield chunk\n\n if chunk.error and not error_occurs:\n error_occurs = True\n error_log = chunk.error_log\n\n elif parsing_type == ParsingType.DOUBLE_SQUARE_BRACKET.value:\n async for chunk in self.__double_type_sp_agenerator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n else:\n async for chunk in self.__single_type_sp_agenerator__(\n messages, response, parsing_type, start_time, functions, tools\n ):\n yield chunk\n if chunk.parsed_outputs:\n parsed_outputs = update_dict(\n parsed_outputs, chunk.parsed_outputs\n )\n if chunk.error and not error_occurs:\n error_occurs = True\n\n if (\n output_keys is not None\n and set(parsed_outputs.keys()) != set(output_keys)\n ) and not error_occurs:\n error_occurs = True\n error_log = \"Output keys do not match with parsed output keys\"\n yield LLMStreamResponse(error=True, error_log=error_log)\n\n except Exception as e:\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def make_model_response(\n self,\n chunk: ModelResponse,\n response_ms,\n messages: List[Dict[str, str]],\n raw_output: str,\n functions: Optional[List[Any]] = None,\n function_call: Optional[Dict[str, Any]] = None,\n tools: Optional[List[Any]] = None,\n tool_calls: Optional[List[Dict[str, Any]]] = None,\n ) -> ModelResponse:\n count_start_time = datetime.datetime.now()\n prompt_token: int = num_tokens_for_messages(\n messages=messages, model=chunk[\"model\"]\n )\n completion_token: int = num_tokens_for_messages(\n model=chunk[\"model\"],\n messages=[{\"role\": \"assistant\", \"content\": raw_output}],\n )\n\n if functions and len(functions) > 0:\n functions_token = num_tokens_from_functions_input(\n functions=functions, model=chunk[\"model\"]\n )\n prompt_token += functions_token\n\n if tools and len(tools) > 0:\n tools_token = num_tokens_from_functions_input(\n functions=[tool[\"function\"] for tool in tools], model=chunk[\"model\"]\n )\n prompt_token += tools_token\n # if function_call:\n # function_call_token = num_tokens_from_function_call_output(\n # function_call_output=function_call, model=chunk[\"model\"]\n # )\n # completion_token += function_call_token\n\n count_end_time = datetime.datetime.now()\n logger.debug(\n f\"counting token time : {(count_end_time - count_start_time).total_seconds() * 1000} ms\"\n )\n\n usage = Usage(\n **{\n \"prompt_tokens\": prompt_token,\n \"completion_tokens\": completion_token,\n \"total_tokens\": prompt_token + completion_token,\n }\n )\n\n last_message = Message(\n role=chunk.choices[0].delta.role\n if getattr(chunk.choices[0].delta, \"role\", None)\n else \"assistant\",\n content=raw_output if raw_output != \"\" else None,\n function_call=function_call if function_call else None,\n tool_calls=tool_calls if tool_calls else None,\n )\n choices = [\n Choices(finish_reason=chunk.choices[0].finish_reason, message=last_message)\n ]\n\n res = ModelResponse(\n id=chunk[\"id\"],\n created=chunk[\"created\"],\n model=chunk[\"model\"],\n stream=True,\n )\n res.choices = choices\n res.usage = usage\n res._response_ms = response_ms\n\n return res\n\n def __llm_stream_response_generator__(\n self,\n messages: List[Dict[str, str]],\n response: Generator[ModelResponse, None, None],\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> Generator[LLMStreamResponse, None, None]:\n raw_output = \"\"\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n try:\n for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n raw_output += chunk.choices[0].delta.content\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=chunk.choices[0].delta.content,\n )\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def __single_type_sp_generator__(\n self,\n messages: List[Dict[str, str]],\n response: Generator[ModelResponse, None, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> Generator[LLMStreamResponse, None, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n if len(keys) == 0:\n break # no key\n active_key, active_type = keys[\n 0\n ] # Updated to unpack both key and type\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[\n 0\n ].replace(end_tag, \"\")\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n elif (\n stream_value.find(end_token) != -1\n ): # if pattern ends = (\"[blah]\" != end_pattern) appeared in buffer\n if (\n active_type == \"List\"\n or active_type == \"Dict\"\n and end_token.find(\"]\") != -1\n ):\n try:\n buffer_dict = json.loads(buffer)\n stream_pause = False\n continue\n except Exception as exception:\n logger.error(exception)\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(\n start_token\n )[0]\n },\n )\n stream_pause = False\n buffer = \"\"\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={active_key: buffer},\n )\n stream_pause = False\n buffer = \"\"\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n def __double_type_sp_generator__(\n self,\n messages: List[Dict[str, str]],\n response: Generator[ModelResponse, None, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> Generator[LLMStreamResponse, None, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n if len(keys) == 0:\n break # no key\n active_key, active_type = keys[0]\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[0]\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n elif (\n stream_value.find(end_token) != -1\n ): # if (\"[blah]\" != end_pattern) appeared in buffer\n if (\n buffer.find(end_token + end_token) != -1\n ): # if ]] in buffer -> error\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(start_token)[0]\n },\n )\n buffer = buffer.split(end_token + end_token)[-1]\n stream_pause = False\n break\n else:\n if (\n buffer.find(start_token + start_token) != -1\n ): # if [[ in buffer -> pause\n break\n else:\n # if [ in buffer (== [blah]) -> stream\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n stream_pause = False\n break\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def __llm_stream_response_agenerator__(\n self,\n messages: List[Dict[str, str]],\n response: AsyncGenerator[ModelResponse, None],\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n raw_output = \"\"\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n try:\n async for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def __single_type_sp_agenerator__(\n self,\n messages: List[Dict[str, str]],\n response: AsyncGenerator[ModelResponse, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n async for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n if len(keys) == 0:\n break # no key\n\n active_key, active_type = keys[\n 0\n ] # Updated to unpack both key and type\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[\n 0\n ].replace(end_tag, \"\")\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n elif (\n stream_value.find(end_token) != -1\n ): # if pattern ends = (\"[blah]\" != end_pattern) appeared in buffer\n if (\n active_type == \"List\"\n or active_type == \"Dict\"\n and end_token.find(\"]\") != -1\n ):\n try:\n buffer_dict = json.loads(buffer)\n stream_pause = False\n continue\n except Exception as exception:\n logger.error(exception)\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(\n start_token\n )[0]\n },\n )\n stream_pause = False\n buffer = \"\"\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={active_key: buffer},\n )\n stream_pause = False\n buffer = \"\"\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))\n\n async def __double_type_sp_agenerator__(\n self,\n messages: List[Dict[str, str]],\n response: AsyncGenerator[ModelResponse, None],\n parsing_type: ParsingType,\n start_time: datetime.datetime,\n functions: Optional[List[Any]] = None,\n tools: Optional[List[Any]] = None,\n ) -> AsyncGenerator[LLMStreamResponse, None]:\n try:\n parsing_pattern = get_pattern_by_type(parsing_type)\n start_tag = parsing_pattern[\"start\"]\n start_fstring = parsing_pattern[\"start_fstring\"]\n end_fstring = parsing_pattern[\"end_fstring\"]\n start_token = parsing_pattern[\"start_token\"]\n end_token = parsing_pattern[\"end_token\"]\n\n buffer = \"\"\n raw_output = \"\"\n active_key = None\n stream_pause = False\n end_tag = None\n function_call = {\"name\": \"\", \"arguments\": \"\"}\n tool_calls = []\n\n async for chunk in response:\n yield_api_response_with_fc = False\n if getattr(chunk.choices[0].delta, \"function_call\", None) is not None:\n for key, value in (\n chunk.choices[0].delta.function_call.model_dump().items()\n ):\n if value is not None:\n function_call[key] += value\n\n yield LLMStreamResponse(\n api_response=chunk,\n function_call=chunk.choices[0].delta.function_call,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"tool_calls\", None) is not None:\n # tool_calls: list\n tool_calls_delta: List[Any] = chunk.choices[0].delta.tool_calls\n index = tool_calls_delta[0].index\n if index == len(tool_calls):\n tool_calls.append(\n {\n \"id\": tool_calls_delta[0].id,\n \"function\": {},\n \"type\": \"function\",\n }\n )\n tool_delta: ChoiceDeltaToolCallFunction = tool_calls_delta[\n 0\n ].function\n tool_calls[index][\"function\"] = update_dict(\n tool_calls[index][\"function\"], tool_delta.model_dump()\n )\n\n yield LLMStreamResponse(\n api_response=chunk,\n tool_calls=chunk.choices[0].delta.tool_calls,\n )\n yield_api_response_with_fc = True\n\n if getattr(chunk.choices[0].delta, \"content\", None) is not None:\n stream_value: str = chunk.choices[0].delta.content\n raw_output += stream_value\n yield LLMStreamResponse(\n api_response=chunk if not yield_api_response_with_fc else None,\n raw_output=stream_value,\n )\n\n buffer += stream_value\n\n while True:\n if active_key is None:\n keys = re.findall(start_tag, buffer, flags=re.DOTALL)\n # if len(keys) > 1:\n # yield LLMStreamResponse(\n # error=True,\n # error_log=\"Parsing error : Nested key detected\",\n # )\n # break\n if len(keys) == 0:\n break # no key\n active_key, active_type = keys[0]\n end_tag = end_fstring.format(key=active_key)\n # delete start tag from buffer\n start_pattern = start_fstring.format(\n key=active_key, type=active_type\n )\n buffer = buffer.split(start_pattern)[-1]\n\n else:\n if (\n stream_value.find(start_token) != -1\n ): # start token appers in chunk -> pause\n stream_pause = True\n break\n elif stream_pause:\n if (\n buffer.find(end_tag) != -1\n ): # if end tag appears in buffer\n yield LLMStreamResponse(\n parsed_outputs={\n active_key: buffer.split(end_tag)[0]\n }\n )\n buffer = buffer.split(end_tag)[-1]\n active_key = None\n stream_pause = False\n # break\n elif (\n stream_value.find(end_token) != -1\n ): # if (\"[blah]\" != end_pattern) appeared in buffer\n if (\n buffer.find(end_token + end_token) != -1\n ): # if ]] in buffer -> error\n yield LLMStreamResponse(\n error=True,\n error_log=\"Parsing error : Invalid end tag detected\",\n parsed_outputs={\n active_key: buffer.split(start_token)[0]\n },\n )\n buffer = buffer.split(end_token + end_token)[-1]\n stream_pause = False\n break\n else:\n if (\n buffer.find(start_token + start_token) != -1\n ): # if [[ in buffer -> pause\n break\n else:\n # if [ in buffer (== [blah]) -> stream\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n stream_pause = False\n break\n break\n else:\n # no start token, no stream_pause (not inside of tag)\n if buffer:\n yield LLMStreamResponse(\n parsed_outputs={active_key: buffer}\n )\n buffer = \"\"\n break\n\n if chunk.choices[0].finish_reason != None:\n end_time = datetime.datetime.now()\n response_ms = (end_time - start_time).total_seconds() * 1000\n yield LLMStreamResponse(\n api_response=self.make_model_response(\n chunk,\n response_ms,\n messages,\n raw_output,\n functions=functions,\n function_call=function_call\n if chunk.choices[0].finish_reason == \"function_call\"\n else None,\n tools=tools,\n tool_calls=tool_calls\n if chunk.choices[0].finish_reason == \"tool_calls\"\n else None,\n )\n )\n except Exception as e:\n logger.error(e)\n yield LLMStreamResponse(error=True, error_log=str(e))" }, { "identifier": "DeployedPrompt", "path": "promptmodel/database/models.py", "snippet": "class DeployedPrompt(BaseModel):\n id = AutoField()\n version_uuid = ForeignKeyField(\n DeployedFunctionModelVersion,\n field=DeployedFunctionModelVersion.uuid,\n backref=\"prompts\",\n on_delete=\"CASCADE\",\n )\n role = CharField()\n step = IntegerField()\n content = TextField()" }, { "identifier": "DeployedFunctionModel", "path": "promptmodel/database/models.py", "snippet": "class DeployedFunctionModel(BaseModel):\n uuid = UUIDField(unique=True, default=uuid4)\n name = CharField()" }, { "identifier": "DeployedFunctionModelVersion", "path": "promptmodel/database/models.py", "snippet": "class DeployedFunctionModelVersion(BaseModel):\n uuid = UUIDField(unique=True, default=uuid4)\n version = IntegerField(null=False)\n from_version = IntegerField(null=True)\n function_model_uuid = ForeignKeyField(\n DeployedFunctionModel,\n field=DeployedFunctionModel.uuid,\n backref=\"versions\",\n on_delete=\"CASCADE\",\n )\n model = CharField()\n is_published = BooleanField(default=False)\n is_ab_test = BooleanField(default=False)\n ratio = FloatField(null=True)\n parsing_type = CharField(\n null=True,\n default=None,\n constraints=[\n Check(\n f\"parsing_type IN ('{ParsingType.COLON.value}', '{ParsingType.SQUARE_BRACKET.value}', '{ParsingType.DOUBLE_SQUARE_BRACKET.value}')\"\n )\n ],\n )\n output_keys = JSONField(null=True, default=None)\n functions = JSONField(default=[])" }, { "identifier": "get_deployed_prompts", "path": "promptmodel/database/crud.py", "snippet": "def get_deployed_prompts(function_model_name: str) -> Tuple[List[DeployedPrompt], str]:\n try:\n with db.atomic():\n versions: List[DeployedFunctionModelVersion] = list(\n DeployedFunctionModelVersion.select()\n .join(DeployedFunctionModel)\n .where(\n DeployedFunctionModelVersion.function_model_uuid\n == DeployedFunctionModel.get(\n DeployedFunctionModel.name == function_model_name\n ).uuid\n )\n )\n prompts: List[DeployedPrompt] = list(\n DeployedPrompt.select()\n .where(\n DeployedPrompt.version_uuid.in_(\n [version.uuid for version in versions]\n )\n )\n .order_by(DeployedPrompt.step.asc())\n )\n # select version by ratio\n selected_version = select_version_by_ratio(\n [version.__data__ for version in versions]\n )\n selected_prompts = list(\n filter(\n lambda prompt: str(prompt.version_uuid.uuid)\n == str(selected_version[\"uuid\"]),\n prompts,\n )\n )\n\n version_details = {\n \"model\": selected_version[\"model\"],\n \"version\" : selected_version[\"version\"],\n \"uuid\": selected_version[\"uuid\"],\n \"parsing_type\": selected_version[\"parsing_type\"],\n \"output_keys\": selected_version[\"output_keys\"],\n }\n\n return selected_prompts, version_details\n except Exception as e:\n logger.error(e)\n return None, None" }, { "identifier": "CacheManager", "path": "promptmodel/promptmodel_init.py", "snippet": "class CacheManager:\n _instance = None\n _lock = threading.Lock()\n\n def __new__(cls):\n with cls._lock:\n if cls._instance is None:\n instance = super(CacheManager, cls).__new__(cls)\n instance.last_update_time = 0 # to manage update frequency\n instance.update_interval = 60 * 60 * 6 # seconds, 6 hours\n instance.program_alive = True\n instance.background_tasks = []\n initialize_db()\n atexit.register(instance._terminate)\n asyncio.run(instance.update_cache()) # updae cache first synchronously\n instance.cache_thread = threading.Thread(\n target=instance._run_cache_loop\n )\n instance.cache_thread.daemon = True\n instance.cache_thread.start()\n cls._instance = instance\n return cls._instance\n\n def cache_update_background_task(self, config):\n asyncio.run(update_deployed_db(config))\n\n def _run_cache_loop(self):\n asyncio.run(self._update_cache_periodically())\n\n async def _update_cache_periodically(self):\n while True:\n await asyncio.sleep(self.update_interval) # Non-blocking sleep\n await self.update_cache()\n\n async def update_cache(self):\n # Current time\n current_time = time.time()\n config = read_config()\n\n if not config:\n upsert_config({\"version\": 0}, section=\"project\")\n config = {\"project\": {\"version\": 0}}\n if \"project\" not in config:\n upsert_config({\"version\": 0}, section=\"project\")\n config = {\"project\": {\"version\": 0}}\n\n if \"version\" not in config[\"project\"]:\n upsert_config({\"version\": 0}, section=\"project\")\n config = {\"project\": {\"version\": 0}}\n\n # Check if we need to update the cache\n if current_time - self.last_update_time > self.update_interval:\n # Update cache logic\n try:\n await update_deployed_db(config)\n except:\n # try once more\n await update_deployed_db(config)\n # Update the last update time\n self.last_update_time = current_time\n\n def _terminate(self):\n self.program_alive = False\n\n # async def cleanup_background_tasks(self):\n # for task in self.background_tasks:\n # if not task.done():\n # task.cancel()\n # try:\n # await task\n # except asyncio.CancelledError:\n # pass # 작업이 취소됨" }, { "identifier": "read_config", "path": "promptmodel/utils/config_utils.py", "snippet": "def read_config():\n \"\"\"\n Reads the configuration from the given filename.\n\n :return: A dictionary containing the configuration.\n \"\"\"\n if not os.path.exists(CONFIG_FILE):\n return {}\n\n with open(CONFIG_FILE, \"r\") as file:\n config = yaml.safe_load(file) or {}\n return config" }, { "identifier": "upsert_config", "path": "promptmodel/utils/config_utils.py", "snippet": "def upsert_config(new_config: Dict[str, Any], section: str = None):\n \"\"\"\n Upserts the given configuration file with the given configuration.\n\n :param new_config: A dictionary containing the new configuration.\n :param section: The section of the configuration to update.\n \"\"\"\n config = read_config()\n if section:\n config_section = config.get(section, {})\n new_config = {section: merge_dict(config_section, new_config)}\n config = merge_dict(config, new_config)\n # If . directory does not exist, create it\n if not os.path.exists(\"./.promptmodel\"):\n os.mkdir(\"./.promptmodel\")\n\n with open(CONFIG_FILE, \"w\") as file:\n yaml.safe_dump(config, file, default_flow_style=False)" }, { "identifier": "select_version_by_ratio", "path": "promptmodel/utils/random_utils.py", "snippet": "def select_version_by_ratio(versions):\n epsilon = 1e-10\n ratios = [version[\"ratio\"] for version in versions]\n\n if not abs(sum(ratios) - 1.0) <= epsilon:\n raise ValueError(f\"Sum of ratios must be 1.0, now {sum(ratios)}\")\n\n cumulative_ratios = []\n cumulative_sum = 0\n for ratio in ratios:\n cumulative_sum += ratio\n cumulative_ratios.append(cumulative_sum)\n\n random_value = random.random()\n for idx, cumulative_ratio in enumerate(cumulative_ratios):\n if random_value <= cumulative_ratio:\n return versions[idx]" }, { "identifier": "logger", "path": "promptmodel/utils/logger.py", "snippet": "def debug(msg: Any, *args):\ndef success(msg: Any, *args):\ndef info(msg: Any, *args):\ndef warning(msg: Any, *args):\ndef error(msg: Any, *args):" }, { "identifier": "run_async_in_sync", "path": "promptmodel/utils/async_utils.py", "snippet": "def run_async_in_sync(coro: Coroutine):\n try:\n loop = asyncio.get_running_loop()\n except RuntimeError: # No running loop\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n result = loop.run_until_complete(coro)\n # loop.close()\n return result\n\n return loop.run_until_complete(coro)" }, { "identifier": "num_tokens_for_messages_for_each", "path": "promptmodel/utils/token_counting.py", "snippet": "def num_tokens_for_messages_for_each(\n messages: List[Dict[str, str]], model: str = \"gpt-3.5-turbo-0613\"\n) -> List[int]:\n processed_messages = [\n {**message, \"function_call\": str(message[\"function_call\"])}\n if \"function_call\" in message\n else message\n for message in messages\n ]\n processed_messages = [\n {**message, \"tool_calls\": str(message[\"tool_calls\"])}\n if \"tool_calls\" in message\n else message\n for message in processed_messages\n ]\n return [\n token_counter(model=model, messages=[message]) for message in processed_messages\n ]" }, { "identifier": "num_tokens_from_functions_input", "path": "promptmodel/utils/token_counting.py", "snippet": "def num_tokens_from_functions_input(\n functions: Optional[List[Any]] = None, model=\"gpt-3.5-turbo-0613\"\n) -> int:\n \"\"\"Return the number of tokens used by a list of functions.\"\"\"\n if functions is None:\n return 0\n num_tokens = 0\n for function in functions:\n function_tokens = token_counter(model=model, text=function[\"name\"])\n function_tokens += token_counter(model=model, text=function[\"description\"])\n\n if \"parameters\" in function:\n parameters = function[\"parameters\"]\n if \"properties\" in parameters:\n for properties_key in parameters[\"properties\"]:\n function_tokens += token_counter(model=model, text=properties_key)\n v = parameters[\"properties\"][properties_key]\n for field in v:\n if field == \"type\":\n function_tokens += 2\n function_tokens += token_counter(\n model=model, text=v[\"type\"]\n )\n elif field == \"description\":\n function_tokens += 2\n function_tokens += token_counter(\n model=model, text=v[\"description\"]\n )\n elif field == \"enum\":\n function_tokens -= 3\n for o in v[\"enum\"]:\n function_tokens += 3\n function_tokens += token_counter(model=model, text=o)\n else:\n print(f\"Warning: not supported field {field}\")\n function_tokens += 11\n\n num_tokens += function_tokens\n\n num_tokens += 12\n return num_tokens" }, { "identifier": "update_dict", "path": "promptmodel/utils/output_utils.py", "snippet": "def update_dict(\n target: Dict[str, str],\n source: Dict[str, str],\n):\n for key, value in source.items():\n if value is not None:\n if key not in target:\n target[key] = value\n else:\n target[key] += value\n return target" }, { "identifier": "AsyncAPIClient", "path": "promptmodel/apis/base.py", "snippet": "class AsyncAPIClient:\n \"\"\"\n A class to represent an Async API request client.\n Used in Deployment stage.\n\n ...\n\n Methods\n -------\n get_headers():\n Generates headers for the API request.\n execute(method=\"GET\", params=None, data=None, json=None, **kwargs):\n Executes the API request.\n \"\"\"\n\n @classmethod\n async def _get_headers(cls, use_cli_key: bool = True) -> Dict:\n \"\"\"\n Reads, decrypts the api_key, and returns headers for API request.\n\n Returns\n -------\n dict\n a dictionary containing the Authorization header\n \"\"\"\n config = read_config()\n if use_cli_key:\n if \"connection\" not in config:\n print(\n \"User not logged in. Please run [violet]prompt login[/violet] first.\"\n )\n exit()\n\n encrypted_key = config[\"connection\"][\"encrypted_api_key\"]\n if encrypted_key is None:\n raise Exception(\"No API key found. Please run 'prompt login' first.\")\n decrypted_key = decrypt_message(encrypted_key)\n else:\n decrypted_key = os.environ.get(\"PROMPTMODEL_API_KEY\")\n if decrypted_key is None:\n raise Exception(\n \"PROMPTMODEL_API_KEY was not found in the current environment.\"\n )\n headers = {\"Authorization\": f\"Bearer {decrypted_key}\"}\n return headers\n\n @classmethod\n async def execute(\n cls,\n path: str,\n method=\"GET\",\n params: Dict = None,\n data: Dict = None,\n json: Dict = None,\n ignore_auth_error: bool = False,\n use_cli_key: bool = True,\n **kwargs,\n ) -> requests.Response:\n \"\"\"\n Executes the API request with the decrypted API key in the headers.\n\n Parameters\n ----------\n method : str, optional\n The HTTP method of the request (default is \"GET\")\n params : dict, optional\n The URL parameters to be sent with the request\n data : dict, optional\n The request body to be sent with the request\n json : dict, optional\n The JSON-encoded request body to be sent with the request\n ignore_auth_error: bool, optional\n Whether to ignore authentication errors (default is False)\n **kwargs : dict\n Additional arguments to pass to the requests.request function\n\n Returns\n -------\n requests.Response\n The response object returned by the requests library\n \"\"\"\n url = f\"{ENDPOINT_URL}{path}\"\n headers = await cls._get_headers(use_cli_key)\n try:\n async with httpx.AsyncClient(http2=True) as _client:\n response = await _client.request(\n method,\n url,\n headers=headers,\n params=params,\n data=data,\n json=json,\n **kwargs,\n )\n if not response:\n print(f\"[red]Error: {response}[/red]\")\n if response.status_code == 200:\n return response\n elif response.status_code == 403:\n if not ignore_auth_error:\n print(\"[red]Authentication failed.[/red]\")\n else:\n print(f\"[red]Error: {response}[/red]\")\n\n return response\n except requests.exceptions.ConnectionError:\n print(\"[red]Could not connect to the Promptmodel API.[/red]\")\n except requests.exceptions.Timeout:\n print(\"[red]The request timed out.[/red]\")\n except Exception as exception:\n print(f\"[red]Error: {exception}[/red]\")" }, { "identifier": "LLMResponse", "path": "promptmodel/types/response.py", "snippet": "class LLMResponse(OpenAIObject):\n api_response: Optional[ModelResponse] = None\n raw_output: Optional[str] = None\n parsed_outputs: Optional[Dict[str, Any]] = None\n error: Optional[bool] = None\n error_log: Optional[str] = None\n function_call: Optional[FunctionCall] = None\n tool_calls: Optional[List[ChatCompletionMessageToolCall]] = None\n pm_detail: Optional[PMDetail] = None" }, { "identifier": "LLMStreamResponse", "path": "promptmodel/types/response.py", "snippet": "class LLMStreamResponse(OpenAIObject):\n api_response: Optional[ModelResponse] = None\n raw_output: Optional[str] = None\n parsed_outputs: Optional[Dict[str, Any]] = None\n error: Optional[bool] = None\n error_log: Optional[str] = None\n function_call: Optional[ChoiceDeltaFunctionCall] = None\n tool_calls: Optional[List[ChoiceDeltaToolCall]] = None\n pm_detail: Optional[PMDetail] = None" }, { "identifier": "FunctionModelConfig", "path": "promptmodel/types/response.py", "snippet": "class FunctionModelConfig(BaseModel):\n \"\"\"Response Class for FunctionModel.get_config()\n prompts: List[Dict[str, Any]] = []\n each prompt can have role, content, name, function_call, and tool_calls\n version_detail: Dict[str, Any] = {}\n version_detail has \"model\", \"uuid\", \"parsing_type\" and \"output_keys\".\n model: str\n model name (e.g. \"gpt-3.5-turbo\")\n name: str\n name of the FunctionModel.\n version_uuid: str\n version uuid of the FunctionModel.\n version: int\n version id of the FunctionModel.\n parsing_type: Optional[str] = None\n parsing type of the FunctionModel.\n output_keys: Optional[List[str]] = None\n output keys of the FunctionModel.\n \"\"\"\n\n prompts: List[Dict[str, Any]]\n model: str\n name: str\n version_uuid: str\n version: int\n parsing_type: Optional[str] = None\n output_keys: Optional[List[str]] = None" }, { "identifier": "ChatModelConfig", "path": "promptmodel/types/response.py", "snippet": "class ChatModelConfig(BaseModel):\n system_prompt: str\n model: str\n name: str\n version_uuid: str\n version: int\n message_logs: Optional[List[Dict]] = []" }, { "identifier": "UnitConfig", "path": "promptmodel/types/response.py", "snippet": "class UnitConfig(BaseModel):\n \"\"\"Response Class for UnitLogger.get_config().\n Created after calling UnitLogger.log_start()\n name: str\n name of the UnitLogger.\n version_uuid: str\n version uuid of the UnitLogger.\n version: int\n version id of the UnitLogger.\n log_uuid: str\n log_uuid for current trace.\n \"\"\"\n\n name: str\n version_uuid: str\n log_uuid: str\n version: int" }, { "identifier": "PMDetail", "path": "promptmodel/types/response.py", "snippet": "class PMDetail(BaseModel):\n model: str\n name: str\n version_uuid: str\n version: int\n log_uuid: str" }, { "identifier": "ChatLogRequest", "path": "promptmodel/types/request.py", "snippet": "class ChatLogRequest(BaseModel):\n uuid: Optional[str] = None\n message: Dict[str, Any]\n metadata: Optional[Dict] = None\n api_response: Optional[ModelResponse] = None\n\n def __post_init__(\n self,\n ):\n if self.api_response is not None and self.message is None:\n self.message = self.api_response.choices[0].message.model_dump()" } ]
from typing import ( Any, AsyncGenerator, Callable, Dict, Generator, List, Optional, Tuple, Union, ) from uuid import UUID from threading import Thread from rich import print from uuid import uuid4 from litellm.utils import ModelResponse, get_max_tokens from promptmodel.llms.llm import LLM from promptmodel.database.models import ( DeployedPrompt, DeployedFunctionModel, DeployedFunctionModelVersion, ) from promptmodel.database.crud import ( get_deployed_prompts, ) from promptmodel.promptmodel_init import CacheManager from promptmodel.utils.config_utils import read_config, upsert_config from promptmodel.utils.random_utils import select_version_by_ratio from promptmodel.utils import logger from promptmodel.utils.async_utils import run_async_in_sync from promptmodel.utils.token_counting import ( num_tokens_for_messages_for_each, num_tokens_from_functions_input, ) from promptmodel.utils.output_utils import update_dict from promptmodel.apis.base import AsyncAPIClient from promptmodel.types.response import ( LLMResponse, LLMStreamResponse, FunctionModelConfig, ChatModelConfig, UnitConfig, PMDetail, ) from promptmodel.types.request import ChatLogRequest
17,920
class LLMProxy(LLM): def __init__( self, name: str, version: Optional[Union[str, int]] = "deploy", unit_config: Optional[UnitConfig] = None ): super().__init__() self._name = name self.version = version self.unit_config = unit_config def _wrap_gen(self, gen: Callable[..., Any]) -> Callable[..., Any]: def wrapper(inputs: Dict[str, Any], **kwargs): prompts, version_details = run_async_in_sync( LLMProxy.fetch_prompts(self._name, self.version) ) call_args = self._prepare_call_args( prompts, version_details, inputs, kwargs ) log_uuid = str(uuid4()) # Call the generator with the arguments stream_response: Generator[LLMStreamResponse, None, None] = gen(**call_args) api_response = None dict_cache = {} # to store aggregated dictionary values string_cache = "" # to store aggregated string values error_occurs = False error_log = None for item in stream_response: if ( item.api_response and "delta" not in item.api_response.choices[0] ): # only get the last api_response, not delta response api_response = item.api_response if item.parsed_outputs:
class LLMProxy(LLM): def __init__( self, name: str, version: Optional[Union[str, int]] = "deploy", unit_config: Optional[UnitConfig] = None ): super().__init__() self._name = name self.version = version self.unit_config = unit_config def _wrap_gen(self, gen: Callable[..., Any]) -> Callable[..., Any]: def wrapper(inputs: Dict[str, Any], **kwargs): prompts, version_details = run_async_in_sync( LLMProxy.fetch_prompts(self._name, self.version) ) call_args = self._prepare_call_args( prompts, version_details, inputs, kwargs ) log_uuid = str(uuid4()) # Call the generator with the arguments stream_response: Generator[LLMStreamResponse, None, None] = gen(**call_args) api_response = None dict_cache = {} # to store aggregated dictionary values string_cache = "" # to store aggregated string values error_occurs = False error_log = None for item in stream_response: if ( item.api_response and "delta" not in item.api_response.choices[0] ): # only get the last api_response, not delta response api_response = item.api_response if item.parsed_outputs:
dict_cache = update_dict(dict_cache, item.parsed_outputs)
13
2023-10-09 03:35:44+00:00
24k
cambridgeltl/ClaPS
run_prune_search.py
[ { "identifier": "PromptedClassificationReward", "path": "rewards/text_classification_reward.py", "snippet": "class PromptedClassificationReward:\n def __init__(\n self,\n args,\n task_lm: str,\n is_mask_lm: Optional[bool],\n num_classes: int,\n verbalizers: List[str],\n reward_type: str = \"entropy\",\n compute_zscore: bool = True,\n incorrect_coeff: float = 180.0, # lambda_1 in paper\n correct_coeff: float = 200.0, # lambda_2 in paper\n use_bn_calibration: bool = False,\n bn_calibrator: Optional[BatchNormCalibrate] = None,\n template: Optional[str] = None,\n gpu_id: Optional[int] = None,\n ):\n \"\"\"\n Few shot text classification reward (adapted from RLPrompt repository)\n Args:\n task_lm: the string specifying the language model type of the task LM\n is_mask_lm: bool. Whether the LM is masked, or left-to-right.\n compute_zscore: bool. Whether do reward normalization by normalizing the\n mean and standard deviation across the batch.\n incorrect_coeff, correct_coeff:\n num_classes: number of classes in the labels\n verbalizers: a list of verbalizers (for e.g., for sentiment classification)\n reward_type: the type of the reward.\n \"gap\" -- use the one proposed in RLPrompt\n \"ll\" -- use the usual cross entropy loss\n template: the template to organize the queries and prompts.\n default one is [Input][Prompt][MASK].\n default template is adopted when it is not specified.\n bn_calibrator: an optional batch norm calibrator. When provided,\n in inference mode the logits will be first normalised by it first. The\n calibrator must be initialized when passed to this class.\n This class essentially provides the objective function for BO/RL/any other\n prompt optimizer.\n \"\"\"\n super().__init__()\n if torch.cuda.is_available():\n if gpu_id:\n self.device = torch.device(f\"cuda:{gpu_id}\")\n else:\n self.device = torch.device(\"cuda\")\n else:\n self.device = torch.device(\"cpu\")\n # self.device = torch.device(\"cpu\")\n self.args = args\n self.task_lm = task_lm\n if is_mask_lm is None:\n # If False, then treat as left-to-right LM\n self.is_mask_lm = True if \"bert\" in self.task_lm else False\n else:\n self.is_mask_lm = is_mask_lm\n assert reward_type in [\"gap\", \"cross_entropy\", \"entropy\"]\n self.reward_type = reward_type\n print(\"Task LM:\", self.task_lm)\n if self.is_mask_lm:\n assert self.task_lm in SUPPORTED_MASK_LMS\n self._tokenizer = AutoTokenizer.from_pretrained(self.task_lm)\n self._generator = AutoModelForMaskedLM.from_pretrained(self.task_lm).to(\n self.device\n )\n else:\n self._generator = T5ForConditionalGeneration.from_pretrained(\n self.task_lm\n ).to(self.device)\n self._tokenizer = AutoTokenizer.from_pretrained(\n self.task_lm, use_fast=False\n )\n\n self.compute_zscore = compute_zscore\n self.incorrect_coeff = incorrect_coeff\n self.correct_coeff = correct_coeff\n self.num_classes = num_classes\n print(\"Num classes:\", self.num_classes)\n self.verbalizers = verbalizers\n print(\"Verbalizers:\", self.verbalizers)\n self.verbalizer_ids = [\n self._tokenizer.convert_tokens_to_ids(v) for v in self.verbalizers\n ]\n print(\"Verbalizer ids:\", self.verbalizer_ids)\n if template is None:\n self.template = self.load_default_template() # prompt templates\n else:\n self.template = template\n self.use_bn_calibration = use_bn_calibration\n self.bn_calibrator = bn_calibrator\n self._counter = 0\n\n def to(self, device):\n self._generator.to(device)\n\n def load_default_template(self) -> List[str]:\n template_dict = {\n \"xnli\": [\n \" {prompt} {sentence_1} {sentence_2} Entailment: \", \n \" {prompt}. In this task, the goal is to predict textual entailment with 'yes' 'maybe' 'no'. sentence A implies sentence B entailment: yes; sentence A is neutral to sentence B entailment: maybe; sentence A contradicts sentence B entailment: no. Sentence A: {sentence_1}, Sentence B: {sentence_2}, Entailment: \", \n ],\n \"mnli\": [\n \" {prompt} {sentence_1} {sentence_2} Entailment: \",\n \" {prompt}. In this task, the goal is to predict textual entailment with 'yes' 'maybe' 'no'. sentence A implies sentence B entailment: yes; sentence A is neutral to sentence B entailment: maybe; sentence A contradicts sentence B entailment: no. Sentence A: {sentence_1}, Sentence B: {sentence_2}, Entailment: \", \n ],\n \"snli\": [\n \" {prompt} {sentence_1} {sentence_2} Entailment: \",\n \" {prompt}. In this task, the goal is to predict textual entailment with 'yes' 'maybe' 'no'. sentence A implies sentence B entailment: yes; sentence A is neutral to sentence B entailment: maybe; sentence A contradicts sentence B entailment: no. Sentence A: {sentence_1}, Sentence B: {sentence_2}, Entailment: \",\n ],\n \"rte\": [\n \" {prompt}. Sentence 1: {sentence_1}, Sentence 2: {sentence_2}, Textual Entailment: \",\n ],\n \"sst2\": [\n \" {prompt}. Sentence: {sentence_1}, Sentiment: \",\n ],\n \"mrpc\": [\n \" {prompt}. Sentence 1: {sentence_1}, Sentence 2: {sentence_2}, Semantically Equivalent: \",\n ],\n \"qnli\": [\n \" {prompt}. Question: {sentence_1}, Sentence: {sentence_2}, Entailment: \",\n ],\n \"qqp\": [\n \" {prompt}. Sentence 1: {sentence_1}, Sentence 2: {sentence_2}, Semantically Equivalent: \",\n ],\n \"ag_news\": [\n \" {prompt}. Classify the news articles into the categories of World, Sports, Business, and Technology. {sentence_1}: \",\n \"{prompt}\\n\\n{sentence_1}\\n\\nWhich topic is this article about?\\nWorld, Sports, Business, Technology, \",\n ],\n }\n if \"anli\" in self.args[\"dataset_name\"]:\n template = template_dict[\"anli\"][self.args[\"template_id\"]]\n elif (\n \"xnli\" in self.args[\"dataset_name\"]\n or \"americas_nli\" in self.args[\"dataset_name\"]\n ):\n template = template_dict[\"xnli\"][self.args[\"template_id\"]]\n else:\n if self.args[\"dataset_name\"] in template_dict:\n template = template_dict[self.args[\"dataset_name\"]][\n self.args[\"template_id\"]\n ]\n if self.is_mask_lm:\n mask_token = self._tokenizer.mask_token\n print(mask_token)\n simple_list = [\"SetFit/sst2\", \"SetFit/CR\", \"rotten_tomatoes\", \"SetFit/sst5\"]\n long_list = [\"yelp_polarity\", \"yelp_review_full\"]\n hard_list = [\"ag_news\"]\n rl_list = [\n \"rl-agnews\",\n \"rl-cr\",\n \"rl-mr\",\n \"rl-sst-2\",\n \"rl-sst-5\",\n \"rl-yelp-2\",\n \"rl-yelp-5\",\n ]\n if self.args[\"dataset_name\"] in simple_list:\n template = f\" {{prompt}} {{sentence_1}} It was {mask_token}.\"\n elif self.args[\"dataset_name\"] in long_list:\n template = f\" {{prompt}} It was {mask_token}. {{sentence_1}}\"\n elif self.args[\"dataset_name\"] in hard_list:\n template = f\" {{prompt}} {mask_token} News: {{sentence_1}}\"\n elif self.args[\"dataset_name\"] in rl_list:\n template = f\" {{prompt}} {{sentence_1}} It was {mask_token}.\"\n return template\n\n def __call__(self, *args: Any, **kwds: Any) -> Any:\n return self.forward(*args, **kwds)\n\n def forward(\n self,\n source_texts: List[str],\n source_2_texts: List[str],\n class_labels: List[int],\n output_tokens: Union[List[List[str]], List[str], str],\n # output_token: Union[List[str], str],\n to_tensor: bool,\n mode: str = \"train\",\n verbose: bool = True,\n accumulate_class: bool = False,\n ) -> Tuple[Union[List[float], torch.Tensor], Dict[str, Any]]:\n \"\"\"\n This computes the reward of the current prompt.\n source_texts: a list of string. Usually samples from the validation set\n class_labels: a list of integers. Usually the labels of the validation set\n prompts:\n Either List[List[str]]: List of tokens. The length of the list should be the same as the number of source_texts.\n OR List[str]: List of (decoded) prompts.\n OR: str. A single prompt\n \"\"\"\n assert mode in [\"train\", \"infer\"]\n if mode == \"train\":\n self._counter += 1\n\n # Process prompts and verbalizer indices\n if isinstance(output_tokens, list):\n if isinstance(output_tokens[0], list):\n prompt_tokens = output_tokens\n prompt_strings = self._convert_tokens_to_string(prompt_tokens)\n elif isinstance(output_tokens[0], str):\n prompt_strings = output_tokens\n elif isinstance(output_tokens, str):\n prompt_strings = [output_tokens] # Single prompt string\n\n rewards: List[torch.Tensor] = []\n accs: List[float] = []\n confs: List[float] = []\n entropies: List[float] = []\n class_logits: List[torch.Tensor] = []\n\n counter_list = []\n input_rewards: Dict[str, List[float]] = defaultdict(list)\n quantities_to_log = {}\n for i, prompt in enumerate(prompt_strings):\n # Compute LM logits\n current_prompts = [prompt for _ in source_texts]\n formatted_templates = self._format_prompts(\n source_texts, source_2_texts, current_prompts\n )\n all_logits = self._get_logits(formatted_templates)\n (\n reward,\n acc,\n correct_predictions,\n conf,\n entropy,\n class_logit,\n ) = _compute_reward(\n all_logits,\n target=class_labels,\n reward_type=self.reward_type,\n verbalizer_ids=self.verbalizer_ids,\n correct_coeff=self.correct_coeff,\n incorrect_coeff=self.incorrect_coeff,\n bn_calibrator=self.bn_calibrator if self.use_bn_calibration else None,\n )\n\n rewards.append(reward)\n accs.append(acc.item())\n confs.append(conf.item())\n entropies.append(entropy.item())\n counter_list.append(correct_predictions)\n class_logits.append(class_logit)\n\n # keep track of rewards for z-score normalization\n input_rewards[\"z\"] += [reward.item()]\n\n # Print examples\n if verbose:\n print_strs = [\n \"Accuracy:\",\n acc.item(),\n \"|\",\n \"Reward:\",\n round(reward.item(), 2),\n ]\n print(*print_strs)\n rewards_tensor = torch.stack(rewards)\n accs_tensor = torch.tensor(accs)\n confs_tensor = torch.tensor(confs)\n entropies_tensor = torch.tensor(entropies)\n # compute the expected calibration error (ECE) by accs_tensor and confs_tensor\n ece = torch.abs(accs_tensor - confs_tensor).mean()\n\n # z-score normalization (2nd stage)\n if mode == \"train\" and self.compute_zscore:\n input_reward_means = {k: np.mean(v) for k, v in input_rewards.items()}\n input_reward_stds = {k: np.std(v) for k, v in input_rewards.items()}\n # not source strings\n idx_means = torch.tensor(input_reward_means[\"z\"]).float()\n idx_stds = torch.tensor(input_reward_stds[\"z\"]).float()\n rewards_tensor = (rewards_tensor - idx_means) / (idx_stds + 1e-4)\n quantities_to_log[prompt_strings[i]][\"resized_reward\"] = []\n for i in range(rewards_tensor.size(0)):\n quantities_to_log[prompt_strings[i]][\"resized_reward\"].append(\n rewards_tensor[i].item()\n )\n elif mode == \"infer\": # Optional: Predict Val Prompts\n score = rewards_tensor.mean().item()\n if verbose:\n print(f\"Our prompt: {prompt_strings}. Score={score}. Acc={acc}\")\n for pt in prompt_strings:\n print(self._tokenizer.tokenize(pt))\n print(accumulate_class)\n print(\"counter_list\", counter_list)\n print(\"ece\", ece)\n if accumulate_class:\n return (\n prompt_strings,\n rewards_tensor,\n accs_tensor,\n counter_list,\n ece,\n entropies_tensor,\n class_logits, # <- list of tensors. n elements = n prompts\n )\n else:\n return prompt_strings, rewards_tensor, accs_tensor\n\n if to_tensor is True:\n return rewards_tensor, accs_tensor, quantities_to_log\n else:\n return rewards_tensor.tolist(), accs, quantities_to_log\n\n def kl_divergence_row_by_row(self, p, q):\n kl_div = torch.sum(p * torch.log(p / q), dim=1)\n return kl_div\n\n def compute_default_kl(\n self,\n source_texts: List[str],\n source_2_texts: List[str],\n class_labels: List[int],\n output_tokens: Union[List[List[str]], List[str], str],\n to_tensor: bool,\n ) -> torch.Tensor:\n \"\"\"\n This computes the probs of the naive prompt (instruction).\n source_texts: a list of string. Usually samples from the validation set\n class_labels: a list of integers. Usually the labels of the validation set\n prompts:\n Either List[List[str]]: List of tokens. The length of the list should be the same as the number of source_texts.\n OR List[str]: List of (decoded) prompts.\n OR: str. A single prompt\n \"\"\"\n default_templates = self._format_prompts(\n source_texts, source_2_texts, [\"\" for _ in source_texts]\n )\n default_logits = self._get_logits(default_templates)\n default_probs = _compute_probs(\n default_logits,\n target=class_labels,\n reward_type=self.reward_type,\n verbalizer_ids=self.verbalizer_ids,\n correct_coeff=self.correct_coeff,\n incorrect_coeff=self.incorrect_coeff,\n )\n return default_probs\n\n def compute_default_reward(\n self,\n source_texts: List[str],\n source_2_texts: List[str],\n class_labels: List[int],\n output_tokens: Union[List[List[str]], List[str], str],\n to_tensor: bool,\n ) -> torch.Tensor:\n \"\"\"\n This computes the rewards of the naive prompt (instruction).\n source_texts: a list of string. Usually samples from the validation set\n class_labels: a list of integers. Usually the labels of the validation set\n prompts:\n Either List[List[str]]: List of tokens. The length of the list should be the same as the number of source_texts.\n OR List[str]: List of (decoded) prompts.\n OR: str. A single prompt\n \"\"\"\n default_templates = self._format_prompts(\n source_texts, source_2_texts, [\"\" for _ in source_texts]\n )\n default_logits = self._get_logits(default_templates)\n default_reward, _, _, _, _, _ = _compute_reward(\n default_logits,\n target=class_labels,\n reward_type=self.reward_type,\n verbalizer_ids=self.verbalizer_ids,\n correct_coeff=self.correct_coeff,\n incorrect_coeff=self.incorrect_coeff,\n )\n return default_reward\n\n def compute_kl(\n self,\n source_texts: List[str],\n source_2_texts: List[str],\n class_labels: List[int],\n output_tokens: Union[List[List[str]], List[str], str],\n to_tensor: bool,\n default_probs: torch.Tensor,\n ) -> torch.Tensor:\n \"\"\"\n This computes the kl-divergence of the current prompt to the naive prompt (instruction).\n source_texts: a list of string. Usually samples from the validation set\n class_labels: a list of integers. Usually the labels of the validation set\n prompts:\n Either List[List[str]]: List of tokens. The length of the list should be the same as the number of source_texts.\n OR List[str]: List of (decoded) prompts.\n OR: str. A single prompt\n \"\"\"\n # Process prompts and verbalizer indices\n if isinstance(output_tokens, list):\n if isinstance(output_tokens[0], list):\n prompt_tokens = output_tokens\n prompt_strings = self._convert_tokens_to_string(prompt_tokens)\n elif isinstance(output_tokens[0], str):\n prompt_strings = output_tokens\n elif isinstance(output_tokens, str):\n prompt_strings = [output_tokens] # Single prompt string\n\n rewards: List[torch.Tensor] = []\n input_rewards: Dict[str, List[float]] = defaultdict(list)\n for i, prompt in enumerate(prompt_strings):\n # Compute LM logits\n current_prompts = [prompt for _ in source_texts]\n formatted_templates = self._format_prompts(\n source_texts, source_2_texts, current_prompts\n )\n all_logits = self._get_logits(formatted_templates)\n prompt_probs = _compute_probs(\n all_logits,\n target=class_labels,\n reward_type=self.reward_type,\n verbalizer_ids=self.verbalizer_ids,\n correct_coeff=self.correct_coeff,\n incorrect_coeff=self.incorrect_coeff,\n )\n kl = self.kl_divergence_row_by_row(prompt_probs, default_probs)\n kl = torch.sum(kl)\n rewards.append(kl)\n kl_tensor = torch.stack(rewards)\n return kl_tensor\n\n def compute_reward_diff(\n self,\n source_texts: List[str],\n source_2_texts: List[str],\n class_labels: List[int],\n output_tokens: Union[List[List[str]], List[str], str],\n to_tensor: bool,\n default_rewards: torch.Tensor,\n ) -> torch.Tensor:\n \"\"\"\n This computes the kl-divergence of the current prompt to the naive prompt (instruction).\n source_texts: a list of string. Usually samples from the validation set\n class_labels: a list of integers. Usually the labels of the validation set\n prompts:\n Either List[List[str]]: List of tokens. The length of the list should be the same as the number of source_texts.\n OR List[str]: List of (decoded) prompts.\n OR: str. A single prompt\n \"\"\"\n # Process prompts and verbalizer indices\n if isinstance(output_tokens, list):\n if isinstance(output_tokens[0], list):\n prompt_tokens = output_tokens\n prompt_strings = self._convert_tokens_to_string(prompt_tokens)\n elif isinstance(output_tokens[0], str):\n prompt_strings = output_tokens\n elif isinstance(output_tokens, str):\n prompt_strings = [output_tokens] # Single prompt string\n\n rewards: List[torch.Tensor] = []\n for i, prompt in enumerate(prompt_strings):\n # Compute LM logits\n current_prompts = [prompt for _ in source_texts]\n formatted_templates = self._format_prompts(\n source_texts, source_2_texts, current_prompts\n )\n all_logits = self._get_logits(formatted_templates)\n prompt_rewards, _, _, _, _, _ = _compute_reward(\n all_logits,\n target=class_labels,\n reward_type=self.reward_type,\n verbalizer_ids=self.verbalizer_ids,\n correct_coeff=self.correct_coeff,\n incorrect_coeff=self.incorrect_coeff,\n )\n reward_diff = prompt_rewards - default_rewards\n reward_diff = torch.sum(reward_diff)\n rewards.append(reward_diff)\n reward_diff_tensor = torch.stack(rewards)\n return reward_diff_tensor\n\n # Adapted from\n # https://huggingface.co/docs/transformers/v4.21.1/en/task_summary#masked-language-modeling\n def _get_mask_token_index(self, input_ids: torch.Tensor) -> np.ndarray:\n mask_token_index = torch.where(input_ids == self._tokenizer.mask_token_id)[1]\n return mask_token_index\n\n def ensure_exactly_one_mask_token(\n self, model_inputs: Dict[str, torch.Tensor]\n ) -> None:\n for input_ids in model_inputs[\"input_ids\"]:\n masked_index = self._get_mask_token_index(input_ids)\n numel = np.prod(masked_index.shape)\n assert numel == 1\n\n @torch.no_grad()\n def _get_logits(self, texts: List[str]) -> torch.Tensor:\n # for MLM, add mask token\n batch_size = len(texts)\n encoded_inputs = self._tokenizer(\n texts,\n padding=\"longest\",\n truncation=True,\n return_tensors=\"pt\",\n add_special_tokens=True,\n )\n decoder_input_ids = (\n torch.ones((batch_size, 1)) * torch.tensor(self._tokenizer.pad_token_id)\n ).int()\n if self.is_mask_lm:\n # self.ensure_exactly_one_mask_token(encoded_inputs) TODO\n token_logits = self._generator(**encoded_inputs.to(self.device)).logits\n mask_token_indices = self._get_mask_token_index(encoded_inputs[\"input_ids\"])\n out_logits = token_logits[range(batch_size), mask_token_indices, :]\n return out_logits\n else:\n token_logits = self._generator(\n input_ids=encoded_inputs[\"input_ids\"].to(self.device),\n decoder_input_ids=decoder_input_ids.to(self.device),\n ).logits\n token_logits = token_logits[:, 0, :]\n return token_logits\n\n def _convert_tokens_to_string(self, tokens: List[List[str]]) -> List[str]:\n return [self._tokenizer.convert_tokens_to_string(s) for s in tokens]\n\n def _format_prompts(\n self,\n source_strs: List[str],\n source_2_strs: List[str],\n prompt_strs: List[str],\n ) -> List[str]:\n return [\n self.template.format(sentence_1=s_1, sentence_2=s_2, prompt=p)\n for s_1, s_2, p in zip(source_strs, source_2_strs, prompt_strs)\n ]" }, { "identifier": "PromptedClassificationDataset", "path": "utils/fsc_datasets.py", "snippet": "class PromptedClassificationDataset:\n def __init__(self, args):\n self.args = args\n self.glue_list = ['sst2', 'rte', 'mrpc', 'qqp', 'mnli', 'qnli']\n self.superglue_list = ['cb', 'copa', 'boolq', 'wic', 'wsc']\n self.nli_3_list = ['mnli', 'xnli', 'anli', 'cb', 'snli']\n if 'xnli' in args['dataset_name']:\n split = self.args['dataset_name'].split('_')[1]\n self.dataset = datasets.load_dataset('xnli', split)\n elif args['dataset_name'] in self.glue_list:\n self.dataset = datasets.load_dataset('glue', args['dataset_name'])\n elif 'anli' in args['dataset_name']:\n self.dataset = datasets.load_dataset('anli')\n elif args['dataset_name'] in self.superglue_list:\n self.dataset = datasets.load_dataset('super_glue', args['dataset_name'])\n elif 'rl' in args['dataset_name']:\n pass\n else:\n self.dataset = datasets.load_dataset(args['dataset_name'])\n def get_few_shot_dataset(self, shots: int) -> tuple:\n \"\"\"\n Retrieves a few-shot dataset by selecting a specified number of instances per class from the given dataset.\n \n Args:\n dataset (dict): A dictionary containing the dataset split into \"train\", \"validation\", and \"test\" subsets.\n shots (int): The number of instances to select per class for the few-shot dataset.\n \n Returns:\n tuple: The few-shot training dataset, the original validation dataset, and the original test dataset.\n \"\"\"\n \n if self.args['dataset_name'] == 'mnli':\n train_dataset = self.dataset['train']\n val_dataset = self.dataset['validation_matched']\n test_dataset = self.dataset['test_matched']\n elif self.args['dataset_name'] == 'yelp_polarity' or self.args['dataset_name'] == 'ag_news' or self.args['dataset_name'] == 'SetFit/CR' or self.args['dataset_name'] == 'yelp_review_full':\n train_dataset = self.dataset['train']\n val_dataset = self.dataset['train']\n test_dataset = self.dataset['test']\n elif 'rl' in self.args['dataset_name']:\n train_dataset = get_rl_data('train', self.args['dataset_name'], self.args['seed'])\n val_dataset = get_rl_data('dev', self.args['dataset_name'], self.args['seed'])\n test_dataset = get_rl_data('test', self.args['dataset_name'], self.args['seed'])\n train_dataset = [x for x in train_dataset]\n val_dataset = [x for x in val_dataset]\n return train_dataset, val_dataset, test_dataset\n elif self.args['dataset_name'] == 'snli':\n train_dataset = [x for x in self.dataset['train'] if x['label'] != -1]\n val_dataset = [x for x in self.dataset['validation'] if x['label'] != -1]\n test_dataset = [x for x in self.dataset['test'] if x['label'] != -1]\n else:\n train_dataset = self.dataset['train']\n val_dataset = self.dataset['validation']\n test_dataset = self.dataset['test']\n\n train_0 = [x for x in train_dataset if x['label'] == 0][:shots]\n train_1 = [x for x in train_dataset if x['label'] == 1][:shots]\n train_2 = [x for x in train_dataset if x['label'] == 2][:shots]\n train_3 = [x for x in train_dataset if x['label'] == 3][:shots]\n train_4 = [x for x in train_dataset if x['label'] == 4][:shots]\n train_dataset = train_0 + train_1 + train_2 + train_3 + train_4\n if self.args['dataset_name'] in self.glue_list or self.args['dataset_name'] in self.superglue_list:\n val_0 = [x for x in train_dataset if x['label'] == 0][-shots:]\n val_1 = [x for x in train_dataset if x['label'] == 1][-shots:]\n val_2 = [x for x in train_dataset if x['label'] == 2][-shots:]\n new_val_dataset = val_0 + val_1 + val_2\n test_dataset = val_dataset\n print('train_dataset', train_dataset)\n return train_dataset, new_val_dataset, test_dataset\n elif self.args['dataset_name'] == 'ag_news' or self.args['dataset_name'] == 'yele_review_full':\n val_0 = [x for x in train_dataset if x['label'] == 0][-shots:]\n val_1 = [x for x in train_dataset if x['label'] == 1][-shots:]\n val_2 = [x for x in train_dataset if x['label'] == 2][-shots:]\n val_3 = [x for x in train_dataset if x['label'] == 3][-shots:]\n val_4 = [x for x in train_dataset if x['label'] == 4][-shots:]\n new_val_dataset = val_0 + val_1 + val_2 + val_3 + val_4\n test_dataset = val_dataset\n print('train_dataset', train_dataset)\n return train_dataset, new_val_dataset, test_dataset\n \n val_0 = [x for x in val_dataset if x['label'] == 0][:shots]\n val_1 = [x for x in val_dataset if x['label'] == 1][:shots]\n val_2 = [x for x in val_dataset if x['label'] == 2][:shots]\n val_dataset = val_0 + val_1 + val_2\n print('train_dataset', train_dataset)\n return train_dataset, val_dataset, test_dataset\n\n def get_verbalizer(self) -> list:\n if 'xnli' in self.args['dataset_name'] or self.args['dataset_name'] == 'mnli' or 'anli' in self.args['dataset_name'] or 'americas_nli' in self.args['dataset_name'] or self.args['dataset_name'] == 'snli':\n verbalizer_predefined = ['yes', 'maybe', 'no']\n elif self.args['dataset_name'] == 'sst2' or self.args['dataset_name'] == 'yelp_polarity':\n verbalizer_predefined = ['negative', 'positive']\n elif self.args['dataset_name'] == 'rte' or self.args['dataset_name'] == 'qnli':\n verbalizer_predefined = ['yes', 'no']\n elif self.args['dataset_name'] == 'mrpc' or self.args['dataset_name'] == 'qqp':\n verbalizer_predefined = ['no', 'yes']\n elif self.args['dataset_name'] == 'boolq':\n verbalizer_predefined = ['no', 'yes']\n elif 'indonlp/NusaX-senti' in self.args['dataset_name']:\n verbalizer_predefined = ['negative', 'neutral', 'positive']\n elif self.args['dataset_name'] == 'ag_news':\n verbalizer_predefined = ['World', 'Sports', 'Business', 'Technology']\n\n special_space = '▁'\n binary_list = ['SetFit/sst2', 'yelp_polarity', 'SetFit/CR', 'rotten_tomatoes']\n rl_binary_list = ['rl-cr', 'rl-mr', 'rl-sst-2', \n 'rl-yelp-2']\n if 'bert' in self.args['model_name']:\n special_space = 'Ġ'\n if self.args['dataset_name'] in binary_list:\n verbalizer_predefined = ['terrible', 'great']\n elif self.args['dataset_name'] == 'ag_news':\n verbalizer_predefined = ['World', 'Sports', 'Business', 'Tech']\n elif self.args['dataset_name'] == 'SetFit/sst5' or self.args['dataset_name'] == 'yelp_review_full':\n verbalizer_predefined = ['terrible', 'bad', 'okay', 'good', 'great']\n elif self.args['dataset_name'] in rl_binary_list:\n verbalizer_predefined = ['terrible', 'great']\n\n verbalizer_predefined = [special_space + v for v in verbalizer_predefined]\n return verbalizer_predefined\n \n def get_data(self, data) -> tuple:\n text_label_list = ['yelp_polarity', 'ag_news', 'SetFit/sst5', 'SetFit/CR', 'rotten_tomatoes', \"SetFit/sst2\", 'yelp_review_full']\n rl_list = ['rl-agnews', 'rl-cr', 'rl-mr', 'rl-sst-2', \n 'rl-sst-5', 'rl-yelp-2', 'rl-yelp-5']\n if 'xnli' in self.args['dataset_name'] or self.args['dataset_name'] == 'mnli' or 'anli' in self.args['dataset_name'] or 'americas_nli' in self.args['dataset_name'] or self.args['dataset_name'] == 'snli':\n return [d[\"premise\"] for d in data], [d[\"hypothesis\"] for d in data], [d[\"label\"] for d in data]\n elif self.args['dataset_name'] == 'sst2':\n return [d[\"sentence\"] for d in data], [d[\"sentence\"] for d in data], [d[\"label\"] for d in data]\n elif self.args['dataset_name'] == 'rte' or self.args['dataset_name'] == 'mrpc':\n return [d[\"sentence1\"] for d in data], [d[\"sentence2\"] for d in data], [d[\"label\"] for d in data]\n elif self.args['dataset_name'] == 'qnli':\n return [d[\"question\"] for d in data], [d[\"sentence\"] for d in data], [d[\"label\"] for d in data]\n elif self.args['dataset_name'] == 'qqp':\n return [d[\"question1\"] for d in data], [d[\"question2\"] for d in data], [d[\"label\"] for d in data]\n elif self.args['dataset_name'] == 'boolq':\n return [d[\"question\"] for d in data], [d[\"passage\"] for d in data], [d[\"label\"] for d in data]\n elif 'indonlp/NusaX-senti' in self.args['dataset_name'] or self.args['dataset_name'] in text_label_list:\n return [d[\"text\"] for d in data], [d[\"text\"] for d in data], [d[\"label\"] for d in data]\n elif self.args['dataset_name'] in rl_list:\n return [d[\"text\"] for d in data], [d[\"text\"] for d in data], [d[\"label\"] for d in data]" }, { "identifier": "GeneticAlgorithmTrainer", "path": "algs/genetics.py", "snippet": "class GeneticAlgorithmTrainer(BaseTrainer):\n def __init__(\n self,\n pop_size: int,\n mutate_size: int,\n crossover_size: int,\n epochs: int,\n mutate_frac: float,\n str_len: int,\n stages: int,\n n_classes: int,\n eval_batch_size: int,\n genetics: Genetics,\n obj_func: PromptedClassificationReward,\n prompt_dataset: PromptedClassificationDataset,\n logger: Any,\n use_bn_calibrator: bool,\n ):\n super().__init__(\n obj_func=obj_func,\n prompt_dataset=prompt_dataset,\n logger=logger,\n use_bn_calibrator=use_bn_calibrator,\n )\n self.pop_size = pop_size\n self.mutate_size = mutate_size\n self.crossover_size = crossover_size\n self.epochs = epochs\n self.mutate_frac = mutate_frac\n self.str_len = str_len\n self.stages = stages\n self.n_classes = n_classes\n self.genetics = genetics\n self.epoch_per_extend = 3\n self.extend_size = 128\n self.eval_batch_size = eval_batch_size\n\n def train(self, train_data):\n premise_texts, hypothesis_texts, class_labels = self.prompt_dataset.get_data(\n train_data\n )\n epoch_per_stage = self.epochs // self.stages\n start_str = \"\"\n best_str_list = []\n\n for _ in range(self.stages):\n pop = [\n self.genetics.random_string(self.str_len) for _ in range(self.pop_size)\n ]\n if self.logger is not None:\n self.logger.info(pop)\n old_reward = 0\n epoch_counter = 0\n for evo_epoch in range(epoch_per_stage):\n if self.str_len == 1:\n pop_ = [start_str + \" \" + p for p in pop]\n else:\n pop_ = [start_str + p for p in pop]\n reward = self.obj_func.forward(\n premise_texts,\n hypothesis_texts,\n class_labels,\n pop_,\n True,\n \"infer\",\n verbose=False,\n )[0]\n if self.logger is not None:\n self.logger.info(\n f\"Epoch = {evo_epoch}. Max reward = {reward.max()}. Best prompt = {pop_[reward.argmax()]}\"\n )\n max_reward = reward.max()\n if max_reward > old_reward:\n old_reward = max_reward\n epoch_counter = 0\n else:\n epoch_counter += 1\n\n sorted_idx = reward.argsort(descending=True)[\n : max(1, int(reward.shape[0] * self.mutate_frac))\n ]\n pop = [pop[i] for i in sorted_idx]\n mutate_cfgs, crossover_cfgs = [], []\n extend_cfgs = []\n for _ in range(self.mutate_size):\n old_cfg = np.random.choice(pop)\n cfg = self.genetics.mutate(old_cfg)\n mutate_cfgs.append(cfg)\n\n for _ in range(self.crossover_size):\n cfg1 = np.random.choice(pop)\n cfg2 = np.random.choice(pop)\n cfg = self.genetics.crossover(cfg1, cfg2)\n crossover_cfgs.append(cfg)\n\n pop += mutate_cfgs\n pop += crossover_cfgs\n\n if self.logger is not None:\n self.logger.info(\n f\"Epoch = {evo_epoch}. Population length = {len(pop)}\"\n )\n\n if self.str_len > 1:\n if pop[reward.argmax()] not in best_str_list:\n best_str_list.append(pop[reward.argmax()])\n else:\n if pop_[reward.argmax()] not in best_str_list:\n best_str_list.append(pop_[reward.argmax()])\n # if we do step by steo do the pop_\n if self.str_len == 1:\n pop_ = [start_str + \" \" + p for p in pop]\n else:\n pop_ = [start_str + p for p in pop]\n start_str = pop_[reward.argmax()]\n\n return best_str_list\n\n def random_train(self, train_data):\n premise_texts, hypothesis_texts, class_labels = self.prompt_dataset.get_data(\n train_data\n )\n start_str = \"\"\n best_str_list = []\n pop = [\n self.genetics.random_string(self.str_len)\n for _ in range(self.pop_size * self.epochs)\n ]\n # logger.info(pop)\n pop_ = [start_str + p for p in pop]\n reward = self.obj_func.forward(\n premise_texts,\n hypothesis_texts,\n class_labels,\n pop_,\n True,\n \"infer\",\n verbose=False,\n )[0]\n\n if self.logger is not None:\n self.logger.info(\n f\"Max reward = {reward.max()}. Best prompt = {pop_[reward.argmax()]}\"\n )\n if pop[reward.argmax()] not in best_str_list:\n best_str_list.append(pop[reward.argmax()])\n return best_str_list" }, { "identifier": "Genetics", "path": "algs/genetics.py", "snippet": "class Genetics:\n def __init__(self, crossover_tokenizer, vocab_id):\n self.crossover_tokenizer = crossover_tokenizer\n self.vocab_id = vocab_id\n\n def mutate(self, x, prob=0.1):\n \"\"\"\n Mutates the input string by replacing tokens with a certain probability.\n\n Args:\n x (str): The input string.\n prob (float, optional): The probability of replacing each token. Defaults to 0.1.\n\n Returns:\n str: The mutated string.\n \"\"\"\n x_list = self.crossover_tokenizer.encode(x)\n\n def pick_another(x_, candidates):\n return (\n x_\n if len(candidates) == 1\n else random.choice([v for v in candidates if v != x_])\n )\n\n for i, element in enumerate(x_list):\n if i == 0 or i == len(x_list) - 1:\n continue\n if random.random() < prob:\n x_list[i] = pick_another(element, self.vocab_id)\n\n out = self.crossover_tokenizer.decode(x_list, skip_special_tokens=True)\n return out\n\n def crossover(self, x1, x2):\n \"\"\"\n Performs crossover between two input strings.\n\n Args:\n x1 (str): The first input string.\n x2 (str): The second input string.\n\n Returns:\n str: The crossover result.\n \"\"\"\n\n def _crossover_helper(v1, v2):\n return v1 if random.random() < 0.5 else v2\n\n def _inbalance_helper(v1, v2):\n n_tokens = min(len(v1), len(v2))\n max_n = max(len(v1), len(v2))\n out_token = []\n for i in range(n_tokens):\n out_token.append(v1[i] if random.random() < 0.5 else v2[i])\n for i in range(n_tokens, max_n):\n out_token.append(v1[i] if len(v1) > n_tokens else v2[i])\n return out_token\n\n x1_tokens = self.crossover_tokenizer.encode(x1)\n x2_tokens = self.crossover_tokenizer.encode(x2)\n x = _crossover_helper(x1_tokens, x2_tokens)\n ret = self.crossover_tokenizer.decode(x, skip_special_tokens=True)\n return ret\n\n def random_string(self, length=5):\n \"\"\"\n Generates a random string of a specified length.\n\n Args:\n length (int, optional): The length of the random string. Defaults to 5.\n\n Returns:\n str: The random string.\n \"\"\"\n choices = self.vocab_id\n out = random.choices(choices, k=length)\n out = self.crossover_tokenizer.decode(out, skip_special_tokens=True)\n return out\n\n def random_extend_pop(self, pop: list, n: int) -> list:\n \"\"\"\n Extends the population with random strings.\n\n Args:\n pop (list): The population.\n n (int): The number of random strings to generate.\n\n Returns:\n list: The extended population.\n \"\"\"\n pop = [p + self.random_string(n) for p in pop]\n return pop" }, { "identifier": "ParticleSwarmOptimizer", "path": "algs/particle_swarm.py", "snippet": "class ParticleSwarmOptimizer(BaseTrainer):\n def __init__(\n self,\n pop_size: int,\n epochs: int,\n mutate_frac: float,\n str_len: int,\n n_classes: int,\n eval_batch_size: int,\n obj_func: PromptedClassificationReward,\n prompt_dataset: PromptedClassificationDataset,\n logger: Any,\n use_bn_calibrator: bool,\n vocab_id,\n crossover_tokenizer,\n ):\n super().__init__(\n obj_func=obj_func,\n prompt_dataset=prompt_dataset,\n logger=logger,\n use_bn_calibrator=use_bn_calibrator,\n )\n self.crossover_tokenizer = crossover_tokenizer\n self.vocab_id = vocab_id\n self.pop_size = pop_size\n self.epochs = epochs\n self.mutate_frac = mutate_frac\n self.str_len = str_len\n self.n_classes = n_classes\n self.eval_batch_size = eval_batch_size\n\n def do_replace(self, x_cur, pos, new_word):\n x_new = x_cur.copy()\n x_new[pos] = new_word\n return x_new\n\n def predict_batch(\n self,\n sentences,\n ):\n return np.array(\n [\n self.predict(\n s,\n )\n for s in sentences\n ]\n )\n\n def predict(\n self,\n sentence,\n ):\n # Alia for reward computation -- note that we expect\n # a list of int in terms of vocab_id for sentence argument here.\n sentence_str = self.crossover_tokenizer.decode(\n sentence, skip_special_tokens=True\n )\n tem = (\n self.obj_func.forward(\n self.premise_texts,\n self.hypothesis_texts,\n self.class_labels,\n [sentence_str],\n True,\n \"infer\",\n verbose=False,\n )[0]\n .detach()\n .cpu()\n .item()\n )\n\n return tem\n\n def select_best_replacement(self, pos, x_cur, replace_list):\n \"\"\"Select the most effective replacement to word at pos (pos)\n in (x_cur) between the words in replace_list\"\"\"\n new_x_list = [\n self.do_replace(x_cur, pos, w) if w != 0 else x_cur for w in replace_list\n ]\n # Randomly select some rather than enumerate, which is very slow\n new_x_list_str = [\n self.crossover_tokenizer.decode(s, skip_special_tokens=True)\n for s in new_x_list\n ]\n x_scores = (\n self.obj_func.forward(\n self.premise_texts,\n self.hypothesis_texts,\n self.class_labels,\n new_x_list_str,\n True,\n \"infer\",\n verbose=False,\n )[0]\n .detach()\n .cpu()\n .numpy()\n )\n # new_x_preds = self.predict_batch(new_x_list)\n # x_scores = new_x_preds # [:, target]\n orig_score = self.predict(x_cur) # [target]\n\n new_x_scores = x_scores - orig_score\n # Eliminate not that clsoe words\n\n if np.max(new_x_scores) > 0:\n best_id = np.argsort(new_x_scores)[-1]\n return [x_scores[best_id], new_x_list[best_id]]\n return [orig_score, x_cur]\n\n def perturb(self, x_cur, neigbhours, w_select_probs):\n # Pick a word that is not modified and is not UNK\n x_len = w_select_probs.shape[0]\n rand_idx = np.random.choice(x_len, 1, p=w_select_probs)[0]\n # while x_cur[rand_idx] != x_orig[rand_idx] and np.sum(x_orig != x_cur) < np.sum(\n # np.sign(w_select_probs)\n # ):\n # rand_idx = np.random.choice(x_len, 1, p=w_select_probs)[0]\n replace_list = neigbhours[rand_idx]\n x_cur[rand_idx] = np.random.choice(replace_list)\n score = self.predict(x_cur)\n return [score, x_cur]\n # return self.select_best_replacement(rand_idx, x_cur, replace_list)\n\n def turn(self, x1, x2, prob, x_len):\n x_new = copy.deepcopy(x2)\n for i in range(x_len):\n if np.random.uniform() < prob[i]:\n x_new[i] = x1[i]\n return x_new\n\n def equal(self, a, b):\n return -3 if a == b else 3\n\n def sigmod(self, n):\n return 1 / (1 + np.exp(-n))\n\n def train(self, train_data):\n (\n self.premise_texts,\n self.hypothesis_texts,\n self.class_labels,\n ) = self.prompt_dataset.get_data(train_data)\n\n neigbhours_list = [self.vocab_id for _ in range(self.str_len)]\n neighbours_len = [len(x) for x in neigbhours_list]\n x_len = self.str_len\n #\n w_select_probs = []\n for pos in range(x_len):\n if neighbours_len[pos] == 0:\n w_select_probs.append(0)\n else:\n w_select_probs.append(min(neighbours_len[pos], 10))\n w_select_probs = w_select_probs / np.sum(w_select_probs)\n\n if np.sum(neighbours_len) == 0:\n return None\n\n # Generate random population\n pop = [\n np.random.choice(self.vocab_id, self.str_len) for _ in range(self.pop_size)\n ]\n pop_scores = self.predict_batch(\n pop,\n )\n\n part_elites = copy.deepcopy(pop)\n part_elites_scores = pop_scores\n all_elite_score = np.max(pop_scores)\n pop_ranks = np.argsort(pop_scores)\n top_attack = pop_ranks[-1]\n all_elite = pop[top_attack]\n\n Omega_1 = 0.8\n Omega_2 = 0.2\n C1_origin = 0.8\n C2_origin = 0.2\n V = [np.random.uniform(-3, 3) for rrr in range(self.pop_size)]\n V_P = [[V[t] for rrr in range(x_len)] for t in range(self.pop_size)]\n\n for i in range(self.epochs):\n Omega = (Omega_1 - Omega_2) * (self.epochs - i) / self.epochs + Omega_2\n C1 = C1_origin - i / self.epochs * (C1_origin - C2_origin)\n C2 = C2_origin + i / self.epochs * (C1_origin - C2_origin)\n\n for id in range(self.pop_size):\n for dim in range(x_len):\n V_P[id][dim] = Omega * V_P[id][dim] + (1 - Omega) * (\n self.equal(pop[id][dim], part_elites[id][dim])\n + self.equal(pop[id][dim], all_elite[dim])\n )\n turn_prob = [self.sigmod(V_P[id][d]) for d in range(x_len)]\n P1 = C1\n P2 = C2\n\n if np.random.uniform() < P1:\n pop[id] = self.turn(part_elites[id], pop[id], turn_prob, x_len)\n if np.random.uniform() < P2:\n pop[id] = self.turn(all_elite, pop[id], turn_prob, x_len)\n\n pop_scores = []\n pop_scores_all = []\n for a in pop:\n pt = self.predict(a)\n\n pop_scores.append(pt)\n pop_scores_all.append(pt)\n pop_ranks = np.argsort(pop_scores)\n top_attack = pop_ranks[-1]\n\n if self.logger is not None:\n self.logger.info(\n f\"{i} -- {pop_scores[top_attack]}。 Best = {self.crossover_tokenizer.decode(all_elite, add_special_tokens=False)}\"\n )\n\n new_pop = []\n new_pop_scores = []\n for id in range(len(pop)):\n x = pop[id]\n if np.random.uniform() < self.mutate_frac:\n tem = self.perturb(x, neigbhours_list, w_select_probs)\n # if tem is None:\n # return None\n # # if tem[0] == 1:\n # # return tem[1]\n # else:\n new_pop_scores.append(tem[0])\n new_pop.append(tem[1])\n else:\n new_pop_scores.append(pop_scores[id])\n new_pop.append(x)\n pop = new_pop\n\n pop_scores = new_pop_scores\n pop_ranks = np.argsort(pop_scores)\n top_attack = pop_ranks[-1]\n for k in range(self.pop_size):\n if pop_scores[k] > part_elites_scores[k]:\n part_elites[k] = pop[k]\n part_elites_scores[k] = pop_scores[k]\n elite = pop[top_attack]\n if np.max(pop_scores) > all_elite_score:\n all_elite = elite\n all_elite_score = np.max(pop_scores)\n\n all_elite_str = self.crossover_tokenizer.decode(\n all_elite, add_special_tokens=False\n )\n\n return [all_elite_str]" }, { "identifier": "GreedyTrainer", "path": "algs/greedy.py", "snippet": "class GreedyTrainer(BaseTrainer):\n def __init__(\n self,\n obj_func: PromptedClassificationReward,\n prompt_dataset: PromptedClassificationDataset,\n vocab_id,\n crossover_tokenizer,\n str_len: int,\n n_classes: int,\n eval_batch_size: int,\n logger,\n use_bn_calibrator: bool = False,\n n_samples_bn_calibrator: int = 128,\n ):\n super().__init__(\n obj_func, prompt_dataset, logger, use_bn_calibrator, n_samples_bn_calibrator\n )\n self.vocab_id = vocab_id\n self.crossover_tokenizer = crossover_tokenizer\n self.str_len = str_len\n self.n_classes = n_classes\n self.eval_batch_size = eval_batch_size\n\n def train(self, train_data):\n premise_texts, hypothesis_texts, class_labels = self.prompt_dataset.get_data(\n train_data\n )\n prompt = \"\"\n candidate_strs = [\n self.crossover_tokenizer.decode([d], skip_special_tokens=True)\n for d in self.vocab_id\n ]\n for _ in range(self.str_len):\n pop = [prompt + candidate_str for candidate_str in candidate_strs]\n # Evaluate the reward of all pop\n reward = (\n self.obj_func.forward(\n premise_texts,\n hypothesis_texts,\n class_labels,\n pop,\n True,\n \"infer\",\n verbose=False,\n )[0]\n .detach()\n .cpu()\n .numpy()\n )\n best_reward_idx = np.argmax(reward)\n if not prompt:\n prompt = candidate_strs[best_reward_idx]\n else:\n prompt += candidate_strs[best_reward_idx]\n print(f\"Current reward = {reward[best_reward_idx]}. Best prompt = {prompt}\")\n return [prompt]" } ]
import random import numpy as np import json import argparse import os import torch import logging from tqdm import tqdm from transformers import AutoTokenizer, set_seed from rewards.text_classification_reward import PromptedClassificationReward from utils.fsc_datasets import PromptedClassificationDataset from algs.genetics import GeneticAlgorithmTrainer, Genetics from algs.particle_swarm import ParticleSwarmOptimizer from algs.greedy import GreedyTrainer
14,580
length = int(len(vocab_key) * (100 - percent) / 100) pruned_index = random.sample(list(np.arange(len(vocab_key))), length) vocab_key = [vocab_key[i] for i in pruned_index] vocab_id = [vocab_id[i] for i in pruned_index] vocab = {vocab_key[i]: vocab_id[i] for i in range(len(vocab_key))} logger.info(len(vocab_key)) return vocab, vocab_key, vocab_id def main(args): print(args) set_seed(args["seed"]) revocab_flag = args["reprune_vocab"] shots = args["num_shots"] batch_size = args["train_batch_size"] args["is_mask_lm"] = False special_space = "▁" if "bert" in args["model_name"]: args["is_mask_lm"] = True special_space = "Ġ" logging.info("......Loading dataset......") prompt_dataset = PromptedClassificationDataset(args) verbalizer_predefined = prompt_dataset.get_verbalizer() args["verbalizers"] = verbalizer_predefined logging.info("verbalizers: %s", verbalizer_predefined) args["num_labels"] = len(verbalizer_predefined) train_dataset, val_dataset, test_dataset = prompt_dataset.get_few_shot_dataset( shots ) logging.info("......truncating vocab......") crossover_tokenizer = AutoTokenizer.from_pretrained(args["model_name"]) vocab = crossover_tokenizer.get_vocab() # preprocess the vocab special_tokens = [ crossover_tokenizer.unk_token, crossover_tokenizer.pad_token, crossover_tokenizer.sep_token, crossover_tokenizer.cls_token, ] vocab = { word: index for word, index in vocab.items() if word not in special_tokens and special_space in word } for v in verbalizer_predefined: if v not in vocab: print("verbalizer not in vocab: ", v) assert v in vocab logging.info("the vocab length before action set pruning: %s", len(vocab)) dataset = train_dataset print(dataset) batch_size = min(batch_size, len(dataset)) idx = np.random.choice(len(dataset), batch_size, replace=False) data = [dataset[i] for i in idx] logging.info(f"Length of dataset = {len(data)}") obj_func = PromptedClassificationReward( args=args, reward_type=args["reward_type"], task_lm=args["model_name"], is_mask_lm=args["is_mask_lm"], num_classes=args["num_labels"], verbalizers=args["verbalizers"], use_bn_calibration=args["bn_calibrate"], ) if revocab_flag: # pruning efficiency section # random select 10% of the vocab if args["vocab_path"] != "none": # this is to do kmeans clustering and pruning vocab, _, vocab_id = load_vocab(args) kl_dict, collect_kl_np = find_kl_dict( args, data, vocab, obj_func, prompt_dataset ) else: if not args["run_manual"]: kl_dict, collect_kl_np = load_kl_dict(args) else: kl_dict = {} collect_kl_np = [] if not args["run_manual"]: vocab, _, vocab_id = action_set_pruning(args, kl_dict, collect_kl_np, vocab) else: vocab_id = [v for k, v in vocab.items()] if args["method"] == "genetic": genetics = Genetics(crossover_tokenizer, vocab_id) trainer = GeneticAlgorithmTrainer( pop_size=128, mutate_size=64, crossover_size=64, mutate_frac=0.1, str_len=5, epochs=30, stages=1, n_classes=args["num_labels"], genetics=genetics, eval_batch_size=args["eval_batch_size"], obj_func=obj_func, prompt_dataset=prompt_dataset, use_bn_calibrator=args["bn_calibrate"], logger=logger, ) elif args["method"] == "particle_swarm": trainer = ParticleSwarmOptimizer( pop_size=128, epochs=30, mutate_frac=0.1, str_len=5, n_classes=args["num_labels"], eval_batch_size=args["eval_batch_size"], obj_func=obj_func, prompt_dataset=prompt_dataset, use_bn_calibrator=args["bn_calibrate"], logger=logger, vocab_id=vocab_id, crossover_tokenizer=crossover_tokenizer, ) elif args["method"] == "greedy":
logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def remove_special_token(text: str, special_token: str) -> str: return text.replace(special_token, "") def find_kl_dict(args, data, vocab, obj_func, prompted_dataset): premise_texts, hypothesis_texts, class_labels = prompted_dataset.get_data(data) if args["prune_type"] == "kl": default_probs = obj_func.compute_default_kl( premise_texts, hypothesis_texts, class_labels, "", True ) else: default_probs = obj_func.compute_default_reward( premise_texts, hypothesis_texts, class_labels, "", True ) collect_kl = [] kl_dict = {} for v, k in tqdm(vocab.items()): if args["prune_type"] == "kl": kl = obj_func.compute_kl( premise_texts, hypothesis_texts, class_labels, v, True, default_probs ) else: kl = obj_func.compute_reward_diff( premise_texts, hypothesis_texts, class_labels, v, True, default_probs ) collect_kl.append(kl) kl_dict[v] = kl for k, v in kl_dict.items(): kl_dict[k] = float(v) with open(args["dict_path"], "w") as fp: json.dump(kl_dict, fp, indent=4, ensure_ascii=False) collect_kl_np = [] for tensor in collect_kl: collect_kl_np.append(tensor.cpu().numpy()) return kl_dict, collect_kl_np def load_kl_dict(args): # load the KL dict from json file with open(args["dict_path"], "r") as fp: kl_dict = json.load(fp) collect_kl_np = [] for k, v in kl_dict.items(): collect_kl_np.append(v) return kl_dict, collect_kl_np def load_vocab(args): with open(args["vocab_path"], "r") as fp: vocab = json.load(fp) vocab_key = [] vocab_id = [] for k, v in vocab.items(): vocab_key.append(k) vocab_id.append(v) return vocab, vocab_key, vocab_id def action_set_pruning(args, kl_dict, collect_kl_np, vocab): if not args["random_prune"]: collect_kl_np = np.array(collect_kl_np) top_10_percent = np.percentile(collect_kl_np, args["percentile"]) # filter the vocab based on the top_10_percent_idx new_vocab = { word: vocab[word] for word, value in kl_dict.items() if value > top_10_percent } vocab = new_vocab vocab_key = [] vocab_id = [] for k, v in vocab.items(): vocab_key.append(k) vocab_id.append(v) logger.info(len(vocab_key)) else: # random select 10% of the vocab vocab, vocab_key, vocab_id = random_pruning(args, vocab, args["percentile"]) logger.info(len(vocab_key)) return vocab, vocab_key, vocab_id def random_pruning(args, vocab: dict, percent: int = 99): vocab_key = [] vocab_id = [] for k, v in vocab.items(): vocab_key.append(k) vocab_id.append(v) length = int(len(vocab_key) * (100 - percent) / 100) pruned_index = random.sample(list(np.arange(len(vocab_key))), length) vocab_key = [vocab_key[i] for i in pruned_index] vocab_id = [vocab_id[i] for i in pruned_index] vocab = {vocab_key[i]: vocab_id[i] for i in range(len(vocab_key))} logger.info(len(vocab_key)) return vocab, vocab_key, vocab_id def main(args): print(args) set_seed(args["seed"]) revocab_flag = args["reprune_vocab"] shots = args["num_shots"] batch_size = args["train_batch_size"] args["is_mask_lm"] = False special_space = "▁" if "bert" in args["model_name"]: args["is_mask_lm"] = True special_space = "Ġ" logging.info("......Loading dataset......") prompt_dataset = PromptedClassificationDataset(args) verbalizer_predefined = prompt_dataset.get_verbalizer() args["verbalizers"] = verbalizer_predefined logging.info("verbalizers: %s", verbalizer_predefined) args["num_labels"] = len(verbalizer_predefined) train_dataset, val_dataset, test_dataset = prompt_dataset.get_few_shot_dataset( shots ) logging.info("......truncating vocab......") crossover_tokenizer = AutoTokenizer.from_pretrained(args["model_name"]) vocab = crossover_tokenizer.get_vocab() # preprocess the vocab special_tokens = [ crossover_tokenizer.unk_token, crossover_tokenizer.pad_token, crossover_tokenizer.sep_token, crossover_tokenizer.cls_token, ] vocab = { word: index for word, index in vocab.items() if word not in special_tokens and special_space in word } for v in verbalizer_predefined: if v not in vocab: print("verbalizer not in vocab: ", v) assert v in vocab logging.info("the vocab length before action set pruning: %s", len(vocab)) dataset = train_dataset print(dataset) batch_size = min(batch_size, len(dataset)) idx = np.random.choice(len(dataset), batch_size, replace=False) data = [dataset[i] for i in idx] logging.info(f"Length of dataset = {len(data)}") obj_func = PromptedClassificationReward( args=args, reward_type=args["reward_type"], task_lm=args["model_name"], is_mask_lm=args["is_mask_lm"], num_classes=args["num_labels"], verbalizers=args["verbalizers"], use_bn_calibration=args["bn_calibrate"], ) if revocab_flag: # pruning efficiency section # random select 10% of the vocab if args["vocab_path"] != "none": # this is to do kmeans clustering and pruning vocab, _, vocab_id = load_vocab(args) kl_dict, collect_kl_np = find_kl_dict( args, data, vocab, obj_func, prompt_dataset ) else: if not args["run_manual"]: kl_dict, collect_kl_np = load_kl_dict(args) else: kl_dict = {} collect_kl_np = [] if not args["run_manual"]: vocab, _, vocab_id = action_set_pruning(args, kl_dict, collect_kl_np, vocab) else: vocab_id = [v for k, v in vocab.items()] if args["method"] == "genetic": genetics = Genetics(crossover_tokenizer, vocab_id) trainer = GeneticAlgorithmTrainer( pop_size=128, mutate_size=64, crossover_size=64, mutate_frac=0.1, str_len=5, epochs=30, stages=1, n_classes=args["num_labels"], genetics=genetics, eval_batch_size=args["eval_batch_size"], obj_func=obj_func, prompt_dataset=prompt_dataset, use_bn_calibrator=args["bn_calibrate"], logger=logger, ) elif args["method"] == "particle_swarm": trainer = ParticleSwarmOptimizer( pop_size=128, epochs=30, mutate_frac=0.1, str_len=5, n_classes=args["num_labels"], eval_batch_size=args["eval_batch_size"], obj_func=obj_func, prompt_dataset=prompt_dataset, use_bn_calibrator=args["bn_calibrate"], logger=logger, vocab_id=vocab_id, crossover_tokenizer=crossover_tokenizer, ) elif args["method"] == "greedy":
trainer = GreedyTrainer(
5
2023-10-08 12:39:44+00:00
24k
MachinePerceptionLab/Attentive_DFPrior
src/DF_Prior.py
[ { "identifier": "config", "path": "src/config.py", "snippet": "def load_config(path, default_path=None):\ndef update_recursive(dict1, dict2):\ndef get_model(cfg):" }, { "identifier": "Mapper", "path": "src/Mapper.py", "snippet": "class Mapper(object):\n \"\"\"\n Mapper thread. \n\n \"\"\"\n\n def __init__(self, cfg, args, slam\n ):\n\n self.cfg = cfg\n self.args = args\n\n self.idx = slam.idx\n self.c = slam.shared_c\n self.bound = slam.bound\n self.logger = slam.logger\n self.mesher = slam.mesher\n self.output = slam.output\n self.verbose = slam.verbose\n self.renderer = slam.renderer\n self.low_gpu_mem = slam.low_gpu_mem\n self.mapping_idx = slam.mapping_idx\n self.mapping_cnt = slam.mapping_cnt\n self.decoders = slam.shared_decoders\n self.estimate_c2w_list = slam.estimate_c2w_list\n self.mapping_first_frame = slam.mapping_first_frame\n self.scene_id = slam.scene_id\n with torch.no_grad():\n self.tsdf_volume_shared = slam.tsdf_volume_shared\n self.tsdf_bnds = slam.tsdf_bnds\n \n \n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n self.sync_method = cfg['sync_method']\n\n self.device = cfg['mapping']['device']\n self.fix_high = cfg['mapping']['fix_high']\n self.eval_rec = cfg['meshing']['eval_rec']\n \n \n self.mesh_freq = cfg['mapping']['mesh_freq']\n self.ckpt_freq = cfg['mapping']['ckpt_freq']\n self.fix_color = cfg['mapping']['fix_color']\n self.mapping_pixels = cfg['mapping']['pixels']\n self.num_joint_iters = cfg['mapping']['iters']\n self.clean_mesh = cfg['meshing']['clean_mesh']\n self.every_frame = cfg['mapping']['every_frame']\n self.color_refine = cfg['mapping']['color_refine']\n self.w_color_loss = cfg['mapping']['w_color_loss']\n self.keyframe_every = cfg['mapping']['keyframe_every']\n self.high_iter_ratio = cfg['mapping']['high_iter_ratio']\n self.low_iter_ratio = cfg['mapping']['low_iter_ratio']\n self.mapping_window_size = cfg['mapping']['mapping_window_size']\n self.no_vis_on_first_frame = cfg['mapping']['no_vis_on_first_frame']\n self.no_log_on_first_frame = cfg['mapping']['no_log_on_first_frame']\n self.no_mesh_on_first_frame = cfg['mapping']['no_mesh_on_first_frame']\n self.frustum_feature_selection = cfg['mapping']['frustum_feature_selection']\n self.keyframe_selection_method = cfg['mapping']['keyframe_selection_method']\n self.save_selected_keyframes_info = cfg['mapping']['save_selected_keyframes_info']\n if self.save_selected_keyframes_info:\n self.selected_keyframes = {}\n\n\n self.keyframe_dict = []\n self.keyframe_list = []\n self.frame_reader = get_dataset(\n cfg, args, self.scale, device=self.device)\n self.n_img = len(self.frame_reader)\n if 'Demo' not in self.output: # disable this visualization in demo\n self.visualizer = Visualizer(freq=cfg['mapping']['vis_freq'], inside_freq=cfg['mapping']['vis_inside_freq'],\n vis_dir=os.path.join(self.output, 'mapping_vis'), renderer=self.renderer,\n verbose=self.verbose, device=self.device)\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n def get_mask_from_c2w(self, c2w, key, val_shape, depth_np):\n \"\"\"\n Frustum feature selection based on current camera pose and depth image.\n\n Args:\n c2w (tensor): camera pose of current frame.\n key (str): name of this feature grid.\n val_shape (tensor): shape of the grid.\n depth_np (numpy.array): depth image of current frame.\n\n Returns:\n mask (tensor): mask for selected optimizable feature.\n points (tensor): corresponding point coordinates.\n \"\"\"\n H, W, fx, fy, cx, cy, = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n X, Y, Z = torch.meshgrid(torch.linspace(self.bound[0][0], self.bound[0][1], val_shape[2]),\n torch.linspace(self.bound[1][0], self.bound[1][1], val_shape[1]),\n torch.linspace(self.bound[2][0], self.bound[2][1], val_shape[0]))\n\n points = torch.stack([X, Y, Z], dim=-1).reshape(-1, 3)\n points_bak = points.clone()\n c2w = c2w.cpu().numpy()\n w2c = np.linalg.inv(c2w)\n ones = np.ones_like(points[:, 0]).reshape(-1, 1)\n homo_vertices = np.concatenate(\n [points, ones], axis=1).reshape(-1, 4, 1)\n cam_cord_homo = w2c@homo_vertices\n cam_cord = cam_cord_homo[:, :3]\n K = np.array([[fx, .0, cx], [.0, fy, cy], [.0, .0, 1.0]]).reshape(3, 3)\n cam_cord[:, 0] *= -1\n uv = K@cam_cord\n z = uv[:, -1:]+1e-5\n uv = uv[:, :2]/z\n uv = uv.astype(np.float32)\n\n remap_chunk = int(3e4)\n depths = []\n for i in range(0, uv.shape[0], remap_chunk):\n depths += [cv2.remap(depth_np,\n uv[i:i+remap_chunk, 0],\n uv[i:i+remap_chunk, 1],\n interpolation=cv2.INTER_LINEAR)[:, 0].reshape(-1, 1)]\n depths = np.concatenate(depths, axis=0)\n\n edge = 0\n mask = (uv[:, 0] < W-edge)*(uv[:, 0] > edge) * \\\n (uv[:, 1] < H-edge)*(uv[:, 1] > edge)\n\n # For ray with depth==0, fill it with maximum depth\n zero_mask = (depths == 0)\n depths[zero_mask] = np.max(depths)\n\n # depth test\n mask = mask & (0 <= -z[:, :, 0]) & (-z[:, :, 0] <= depths+0.5)\n mask = mask.reshape(-1)\n\n # add feature grid near cam center\n ray_o = c2w[:3, 3]\n ray_o = torch.from_numpy(ray_o).unsqueeze(0)\n\n dist = points_bak-ray_o\n dist = torch.sum(dist*dist, axis=1)\n mask2 = dist < 0.5*0.5\n mask2 = mask2.cpu().numpy()\n mask = mask | mask2\n\n points = points[mask]\n mask = mask.reshape(val_shape[2], val_shape[1], val_shape[0])\n return mask\n\n def keyframe_selection_overlap(self, gt_color, gt_depth, c2w, keyframe_dict, k, N_samples=16, pixels=100):\n \"\"\"\n Select overlapping keyframes to the current camera observation.\n\n Args:\n gt_color (tensor): ground truth color image of the current frame.\n gt_depth (tensor): ground truth depth image of the current frame.\n c2w (tensor): camera to world matrix (3*4 or 4*4 both fine).\n keyframe_dict (list): a list containing info for each keyframe.\n k (int): number of overlapping keyframes to select.\n N_samples (int, optional): number of samples/points per ray. Defaults to 16.\n pixels (int, optional): number of pixels to sparsely sample \n from the image of the current camera. Defaults to 100.\n Returns:\n selected_keyframe_list (list): list of selected keyframe id.\n \"\"\"\n device = self.device\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n\n rays_o, rays_d, gt_depth, gt_color = get_samples(\n 0, H, 0, W, pixels, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device)\n\n gt_depth = gt_depth.reshape(-1, 1)\n gt_depth = gt_depth.repeat(1, N_samples)\n t_vals = torch.linspace(0., 1., steps=N_samples).to(device)\n near = gt_depth*0.8\n far = gt_depth+0.5\n z_vals = near * (1.-t_vals) + far * (t_vals)\n pts = rays_o[..., None, :] + rays_d[..., None, :] * \\\n z_vals[..., :, None] # [N_rays, N_samples, 3]\n vertices = pts.reshape(-1, 3).cpu().numpy()\n list_keyframe = []\n for keyframeid, keyframe in enumerate(keyframe_dict):\n c2w = keyframe['est_c2w'].cpu().numpy()\n w2c = np.linalg.inv(c2w)\n ones = np.ones_like(vertices[:, 0]).reshape(-1, 1)\n homo_vertices = np.concatenate(\n [vertices, ones], axis=1).reshape(-1, 4, 1) # (N, 4)\n cam_cord_homo = w2c@homo_vertices # (N, 4, 1)=(4,4)*(N, 4, 1)\n cam_cord = cam_cord_homo[:, :3] # (N, 3, 1)\n K = np.array([[fx, .0, cx], [.0, fy, cy],\n [.0, .0, 1.0]]).reshape(3, 3)\n cam_cord[:, 0] *= -1\n uv = K@cam_cord\n z = uv[:, -1:]+1e-5\n uv = uv[:, :2]/z\n uv = uv.astype(np.float32)\n edge = 20\n mask = (uv[:, 0] < W-edge)*(uv[:, 0] > edge) * \\\n (uv[:, 1] < H-edge)*(uv[:, 1] > edge)\n mask = mask & (z[:, :, 0] < 0)\n mask = mask.reshape(-1)\n percent_inside = mask.sum()/uv.shape[0]\n list_keyframe.append(\n {'id': keyframeid, 'percent_inside': percent_inside})\n\n list_keyframe = sorted(\n list_keyframe, key=lambda i: i['percent_inside'], reverse=True)\n selected_keyframe_list = [dic['id']\n for dic in list_keyframe if dic['percent_inside'] > 0.00]\n selected_keyframe_list = list(np.random.permutation(\n np.array(selected_keyframe_list))[:k])\n return selected_keyframe_list\n \n def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): point coordinates.\n decoders (nn.module decoders): decoders.\n c (dicts, optional): feature grids. Defaults to None.\n stage (str, optional): query stage, corresponds to different levels. Defaults to 'color'.\n device (str, optional): device name to compute on. Defaults to 'cuda:0'.\n\n Returns:\n ret (tensor): occupancy (and color) value of input points.\n \"\"\"\n\n p_split = torch.split(p, 500)\n bound = self.bound\n rets = []\n for pi in p_split:\n # mask for points out of bound\n mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0])\n mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0])\n mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0])\n mask = mask_x & mask_y & mask_z\n\n pi = pi.unsqueeze(0)\n ret, _ = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage)\n \n ret = ret.squeeze(0)\n if len(ret.shape) == 1 and ret.shape[0] == 4:\n ret = ret.unsqueeze(0)\n\n ret[~mask, 3] = 100\n rets.append(ret)\n\n ret = torch.cat(rets, dim=0)\n return ret\n\n def optimize_map(self, num_joint_iters, lr_factor, idx, cur_gt_color, cur_gt_depth, gt_cur_c2w, keyframe_dict, keyframe_list, tsdf_volume, cur_c2w):\n \"\"\"\n Mapping iterations. Sample pixels from selected keyframes,\n then optimize scene representation.\n\n Args:\n num_joint_iters (int): number of mapping iterations.\n lr_factor (float): the factor to times on current lr.\n idx (int): the index of current frame\n cur_gt_color (tensor): gt_color image of the current camera.\n cur_gt_depth (tensor): gt_depth image of the current camera.\n gt_cur_c2w (tensor): groundtruth camera to world matrix corresponding to current frame.\n keyframe_dict (list): list of keyframes info dictionary.\n keyframe_list (list): list ofkeyframe index.\n tsdf_volume (tensor): tsdf volume.\n cur_c2w (tensor): the estimated camera to world matrix of current frame. \n\n Returns:\n return None\n \"\"\"\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n c = self.c\n cfg = self.cfg\n device = self.device\n tsdf_bnds = self.tsdf_bnds.to(device)\n\n if len(keyframe_dict) == 0:\n optimize_frame = []\n else:\n if self.keyframe_selection_method == 'global':\n num = self.mapping_window_size-2\n optimize_frame = random_select(len(self.keyframe_dict)-1, num)\n elif self.keyframe_selection_method == 'overlap':\n num = self.mapping_window_size-2\n optimize_frame = self.keyframe_selection_overlap(\n cur_gt_color, cur_gt_depth, cur_c2w, keyframe_dict[:-1], num)\n\n # add the last keyframe and the current frame(use -1 to denote)\n oldest_frame = None\n if len(keyframe_list) > 0:\n optimize_frame = optimize_frame + [len(keyframe_list)-1]\n oldest_frame = min(optimize_frame)\n optimize_frame += [-1]\n\n if self.save_selected_keyframes_info:\n keyframes_info = []\n for id, frame in enumerate(optimize_frame):\n if frame != -1:\n frame_idx = keyframe_list[frame]\n tmp_gt_c2w = keyframe_dict[frame]['gt_c2w']\n tmp_est_c2w = keyframe_dict[frame]['est_c2w']\n else:\n frame_idx = idx\n tmp_gt_c2w = gt_cur_c2w\n tmp_est_c2w = cur_c2w\n keyframes_info.append(\n {'idx': frame_idx, 'gt_c2w': tmp_gt_c2w, 'est_c2w': tmp_est_c2w})\n self.selected_keyframes[idx] = keyframes_info\n\n pixs_per_image = self.mapping_pixels//len(optimize_frame)\n\n mlp_para_list = []\n decoders_para_list = []\n low_grid_para = []\n high_grid_para = []\n color_grid_para = []\n gt_depth_np = cur_gt_depth.cpu().numpy()\n if True:\n if self.frustum_feature_selection:\n masked_c_grad = {}\n mask_c2w = cur_c2w\n for key, val in c.items():\n if not self.frustum_feature_selection:\n val = Variable(val.to(device), requires_grad=True)\n c[key] = val\n if key == 'grid_low':\n low_grid_para.append(val)\n elif key == 'grid_high':\n high_grid_para.append(val)\n elif key == 'grid_color':\n color_grid_para.append(val)\n\n else:\n mask = self.get_mask_from_c2w(\n mask_c2w, key, val.shape[2:], gt_depth_np)\n mask = torch.from_numpy(mask).permute(2, 1, 0).unsqueeze(\n 0).unsqueeze(0).repeat(1, val.shape[1], 1, 1, 1)\n val = val.to(device)\n # val_grad is the optimizable part, other parameters will be fixed\n val_grad = val[mask].clone()\n val_grad = Variable(val_grad.to(\n device), requires_grad=True)\n masked_c_grad[key] = val_grad\n masked_c_grad[key+'mask'] = mask\n if key == 'grid_low':\n low_grid_para.append(val_grad)\n elif key == 'grid_high':\n high_grid_para.append(val_grad)\n elif key == 'grid_color':\n color_grid_para.append(val_grad)\n\n\n if not self.fix_high:\n decoders_para_list += list(\n self.decoders.high_decoder.parameters())\n if not self.fix_color:\n decoders_para_list += list(\n self.decoders.color_decoder.parameters())\n mlp_para_list += list(\n self.decoders.mlp.parameters())\n \n\n optimizer = torch.optim.Adam([{'params': decoders_para_list, 'lr': 0},\n {'params': mlp_para_list, 'lr': 0},\n {'params': low_grid_para, 'lr': 0},\n {'params': high_grid_para, 'lr': 0},\n {'params': color_grid_para, 'lr': 0}])\n \n\n for joint_iter in range(num_joint_iters):\n if self.frustum_feature_selection:\n for key, val in c.items():\n val_grad = masked_c_grad[key]\n mask = masked_c_grad[key+'mask']\n val = val.to(device)\n val[mask] = val_grad\n c[key] = val\n\n if joint_iter <= int(num_joint_iters*self.low_iter_ratio):\n self.stage = 'low'\n elif joint_iter <= int(num_joint_iters*self.high_iter_ratio):\n self.stage = 'high'\n else:\n self.stage = 'color'\n\n optimizer.param_groups[0]['lr'] = cfg['mapping']['stage'][self.stage]['decoders_lr']*lr_factor\n optimizer.param_groups[1]['lr'] = cfg['mapping']['stage'][self.stage]['mlp_lr']*lr_factor\n optimizer.param_groups[2]['lr'] = cfg['mapping']['stage'][self.stage]['low_lr']*lr_factor\n optimizer.param_groups[3]['lr'] = cfg['mapping']['stage'][self.stage]['high_lr']*lr_factor\n optimizer.param_groups[4]['lr'] = cfg['mapping']['stage'][self.stage]['color_lr']*lr_factor\n \n if (not (idx == 0 and self.no_vis_on_first_frame)) and ('Demo' not in self.output):\n self.visualizer.vis(\n idx, joint_iter, cur_gt_depth, cur_gt_color, cur_c2w, self.c, self.decoders, tsdf_volume, tsdf_bnds)\n\n optimizer.zero_grad()\n batch_rays_d_list = []\n batch_rays_o_list = []\n batch_gt_depth_list = []\n batch_gt_color_list = []\n\n camera_tensor_id = 0\n for frame in optimize_frame:\n if frame != -1:\n gt_depth = keyframe_dict[frame]['depth'].to(device)\n gt_color = keyframe_dict[frame]['color'].to(device)\n c2w = keyframe_dict[frame]['est_c2w']\n\n else:\n gt_depth = cur_gt_depth.to(device)\n gt_color = cur_gt_color.to(device)\n c2w = cur_c2w\n\n batch_rays_o, batch_rays_d, batch_gt_depth, batch_gt_color = get_samples(\n 0, H, 0, W, pixs_per_image, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device)\n batch_rays_o_list.append(batch_rays_o.float())\n batch_rays_d_list.append(batch_rays_d.float())\n batch_gt_depth_list.append(batch_gt_depth.float())\n batch_gt_color_list.append(batch_gt_color.float())\n\n batch_rays_d = torch.cat(batch_rays_d_list)\n batch_rays_o = torch.cat(batch_rays_o_list)\n batch_gt_depth = torch.cat(batch_gt_depth_list)\n batch_gt_color = torch.cat(batch_gt_color_list)\n\n\n # should pre-filter those out of bounding box depth value\n with torch.no_grad():\n det_rays_o = batch_rays_o.clone().detach().unsqueeze(-1) # (N, 3, 1)\n det_rays_d = batch_rays_d.clone().detach().unsqueeze(-1) # (N, 3, 1)\n t = (self.bound.unsqueeze(0).to(\n device)-det_rays_o)/det_rays_d\n t, _ = torch.min(torch.max(t, dim=2)[0], dim=1)\n inside_mask = t >= batch_gt_depth\n batch_rays_d = batch_rays_d[inside_mask]\n batch_rays_o = batch_rays_o[inside_mask]\n batch_gt_depth = batch_gt_depth[inside_mask]\n batch_gt_color = batch_gt_color[inside_mask]\n\n ret = self.renderer.render_batch_ray(c, self.decoders, batch_rays_d,\n batch_rays_o, device, tsdf_volume, tsdf_bnds, self.stage,\n batch_gt_depth)\n depth, uncertainty, color, weight = ret\n\n\n depth_mask = (batch_gt_depth > 0)\n \n if joint_iter > int(num_joint_iters*self.low_iter_ratio) and joint_iter <= int(num_joint_iters*self.low_iter_ratio)+5 and idx <= 1:\n loss = torch.abs(\n batch_gt_depth[depth_mask]-depth[depth_mask]).sum() + torch.abs(weight-torch.ones(weight.shape).to(device)).sum()\n else:\n loss = torch.abs(\n batch_gt_depth[depth_mask]-depth[depth_mask]).sum()\n \n if self.stage == 'color':\n color_loss = torch.abs(batch_gt_color - color).sum()\n weighted_color_loss = self.w_color_loss*color_loss\n loss += weighted_color_loss\n\n loss.backward(retain_graph=False)\n optimizer.step()\n optimizer.zero_grad()\n\n # put selected and updated features back to the grid\n if self.frustum_feature_selection:\n for key, val in c.items():\n val_grad = masked_c_grad[key]\n mask = masked_c_grad[key+'mask']\n val = val.detach()\n val[mask] = val_grad.clone().detach()\n c[key] = val\n\n return None\n\n\n def run(self):\n cfg = self.cfg\n idx, gt_color, gt_depth, gt_c2w = self.frame_reader[0]\n\n self.estimate_c2w_list[0] = gt_c2w.cpu()\n init = True\n prev_idx = -1\n tsdf_volume = self.tsdf_volume_shared\n \n while (1):\n while True:\n idx = self.idx[0].clone()\n if idx == self.n_img-1:\n break\n if self.sync_method == 'strict':\n if idx % self.every_frame == 0 and idx != prev_idx:\n break\n elif self.sync_method == 'loose':\n if idx == 0 or idx >= prev_idx+self.every_frame//2:\n break\n elif self.sync_method == 'free':\n break\n time.sleep(0.1)\n prev_idx = idx\n\n if self.verbose:\n print(Fore.GREEN)\n prefix = ''\n print(prefix+\"Mapping Frame \", idx.item())\n print(Style.RESET_ALL)\n\n _, gt_color, gt_depth, gt_c2w = self.frame_reader[idx]\n\n # valid c2w\n valid_c2w = gt_c2w.clone().cpu().numpy()\n if not np.isfinite(valid_c2w).any():\n self.mapping_idx[0] = idx\n continue\n\n\n if not init:\n lr_factor = cfg['mapping']['lr_factor']\n num_joint_iters = cfg['mapping']['iters']\n\n # here provides a color refinement postprocess\n if idx == self.n_img-1 and self.color_refine:\n outer_joint_iters = 5\n self.mapping_window_size *= 2\n self.low_iter_ratio = 0.0\n self.high_iter_ratio = 0.0\n num_joint_iters *= 5\n self.fix_color = True\n self.frustum_feature_selection = False\n else:\n outer_joint_iters = 1\n \n\n else:\n outer_joint_iters = 1\n lr_factor = cfg['mapping']['lr_first_factor']\n num_joint_iters = cfg['mapping']['iters_first']\n\n cur_c2w = self.estimate_c2w_list[idx].to(self.device)\n num_joint_iters = num_joint_iters//outer_joint_iters\n \n for outer_joint_iter in range(outer_joint_iters):\n\n\n _ = self.optimize_map(num_joint_iters, lr_factor, idx, gt_color, gt_depth,\n gt_c2w, self.keyframe_dict, self.keyframe_list, tsdf_volume, cur_c2w=cur_c2w)\n \n\n # add new frame to keyframe set\n if outer_joint_iter == outer_joint_iters-1:\n if (idx % self.keyframe_every == 0 or (idx == self.n_img-2)) \\\n and (idx not in self.keyframe_list):\n self.keyframe_list.append(idx)\n self.keyframe_dict.append({'gt_c2w': gt_c2w.cpu(), 'idx': idx, 'color': gt_color.cpu(\n ), 'depth': gt_depth.cpu(), 'est_c2w': cur_c2w.clone()})\n\n if self.low_gpu_mem:\n torch.cuda.empty_cache()\n\n init = False\n # mapping of first frame is done, can begin tracking\n self.mapping_first_frame[0] = 1\n\n if True:\n if ((not (idx == 0 and self.no_log_on_first_frame)) and idx % self.ckpt_freq == 0) \\\n or idx == self.n_img-1 or (idx == 4640 and self.scene_id==50):\n self.logger.log(idx, self.keyframe_dict, self.keyframe_list,\n selected_keyframes=self.selected_keyframes\n if self.save_selected_keyframes_info else None)\n\n self.mapping_idx[0] = idx\n self.mapping_cnt[0] += 1\n\n if (idx % self.mesh_freq == 0) and (not (idx == 0 and self.no_mesh_on_first_frame)):\n mesh_out_file = f'{self.output}/mesh/{idx:05d}_mesh.ply'\n self.mesher.get_mesh(mesh_out_file, self.c, self.decoders, self.keyframe_dict, self.estimate_c2w_list,\n idx, tsdf_volume, self.device,\n clean_mesh=self.clean_mesh, get_mask_use_all_frames=False)\n\n if idx == self.n_img-1 or (idx == 4640 and self.scene_id==50):\n mesh_out_file = f'{self.output}/mesh/final_mesh.ply'\n self.mesher.get_mesh(mesh_out_file, self.c, self.decoders, self.keyframe_dict, self.estimate_c2w_list,\n idx, tsdf_volume, self.device,\n clean_mesh=self.clean_mesh, get_mask_use_all_frames=False)\n os.system(\n f\"cp {mesh_out_file} {self.output}/mesh/{idx:05d}_mesh.ply\")\n if self.eval_rec:\n mesh_out_file = f'{self.output}/mesh/final_mesh_eval_rec.ply'\n self.mesher.get_mesh(mesh_out_file, self.c, self.decoders, self.keyframe_dict,\n self.estimate_c2w_list, idx, tsdf_volume, self.device,\n clean_mesh=self.clean_mesh, get_mask_use_all_frames=True)\n break\n\n if idx == self.n_img-1 or (idx == 4640 and self.scene_id==50):\n break" }, { "identifier": "Tracker", "path": "src/Tracker.py", "snippet": "class Tracker(object):\n def __init__(self, cfg, args, slam\n ):\n self.cfg = cfg\n self.args = args\n\n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n self.sync_method = cfg['sync_method']\n\n self.idx = slam.idx\n self.bound = slam.bound\n self.mesher = slam.mesher\n self.output = slam.output\n self.verbose = slam.verbose\n self.shared_c = slam.shared_c\n self.renderer = slam.renderer\n self.gt_c2w_list = slam.gt_c2w_list\n self.low_gpu_mem = slam.low_gpu_mem\n self.mapping_idx = slam.mapping_idx\n self.mapping_cnt = slam.mapping_cnt\n self.shared_decoders = slam.shared_decoders\n self.estimate_c2w_list = slam.estimate_c2w_list\n with torch.no_grad():\n self.tsdf_volume_shared = slam.tsdf_volume_shared\n self.tsdf_bnds = slam.tsdf_bnds\n\n\n self.cam_lr = cfg['tracking']['lr']\n self.device = cfg['tracking']['device']\n self.num_cam_iters = cfg['tracking']['iters']\n self.gt_camera = cfg['tracking']['gt_camera']\n self.tracking_pixels = cfg['tracking']['pixels']\n self.seperate_LR = cfg['tracking']['seperate_LR']\n self.w_color_loss = cfg['tracking']['w_color_loss']\n self.ignore_edge_W = cfg['tracking']['ignore_edge_W']\n self.ignore_edge_H = cfg['tracking']['ignore_edge_H']\n self.handle_dynamic = cfg['tracking']['handle_dynamic']\n self.use_color_in_tracking = cfg['tracking']['use_color_in_tracking']\n self.const_speed_assumption = cfg['tracking']['const_speed_assumption']\n\n self.every_frame = cfg['mapping']['every_frame'] \n self.no_vis_on_first_frame = cfg['mapping']['no_vis_on_first_frame'] # ori mapping\n\n self.prev_mapping_idx = -1\n self.frame_reader = get_dataset(\n cfg, args, self.scale, device=self.device)\n self.n_img = len(self.frame_reader)\n self.frame_loader = DataLoader(\n self.frame_reader, batch_size=1, shuffle=False, num_workers=1)\n self.visualizer = Visualizer(freq=cfg['tracking']['vis_freq'], inside_freq=cfg['tracking']['vis_inside_freq'],\n vis_dir=os.path.join(self.output, 'vis' if 'Demo' in self.output else 'tracking_vis'),\n renderer=self.renderer, verbose=self.verbose, device=self.device)\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n def optimize_cam_in_batch(self, camera_tensor, gt_color, gt_depth, batch_size, optimizer, tsdf_volume):\n \"\"\"\n Do one iteration of camera iteration. Sample pixels, render depth/color, calculate loss and backpropagation.\n\n Args:\n camera_tensor (tensor): camera tensor.\n gt_color (tensor): ground truth color image of the current frame.\n gt_depth (tensor): ground truth depth image of the current frame.\n batch_size (int): batch size, number of sampling rays.\n optimizer (torch.optim): camera optimizer.\n tsdf_volume (tensor): tsdf volume\n\n Returns:\n loss (float): The value of loss.\n \"\"\"\n device = self.device\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n optimizer.zero_grad()\n c2w = get_camera_from_tensor(camera_tensor)\n tsdf_bnds = self.tsdf_bnds.to(device)\n Wedge = self.ignore_edge_W\n Hedge = self.ignore_edge_H\n batch_rays_o, batch_rays_d, batch_gt_depth, batch_gt_color = get_samples(\n Hedge, H-Hedge, Wedge, W-Wedge, batch_size, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device)\n \n # should pre-filter those out of bounding box depth value\n with torch.no_grad():\n det_rays_o = batch_rays_o.clone().detach().unsqueeze(-1) # (N, 3, 1)\n det_rays_d = batch_rays_d.clone().detach().unsqueeze(-1) # (N, 3, 1)\n t = (self.bound.unsqueeze(0).to(device)-det_rays_o)/det_rays_d\n t, _ = torch.min(torch.max(t, dim=2)[0], dim=1)\n inside_mask = t >= batch_gt_depth\n batch_rays_d = batch_rays_d[inside_mask]\n batch_rays_o = batch_rays_o[inside_mask]\n batch_gt_depth = batch_gt_depth[inside_mask]\n batch_gt_color = batch_gt_color[inside_mask]\n\n ret = self.renderer.render_batch_ray(\n self.c, self.decoders, batch_rays_d, batch_rays_o, self.device, tsdf_volume, tsdf_bnds, stage='color', gt_depth=batch_gt_depth) #color\n depth, uncertainty, color, _ = ret\n\n uncertainty = uncertainty.detach()\n if self.handle_dynamic:\n tmp = torch.abs(batch_gt_depth-depth)/torch.sqrt(uncertainty+1e-10)\n mask = (tmp < 10*tmp.median()) & (batch_gt_depth > 0)\n else:\n mask = batch_gt_depth > 0\n\n loss = (torch.abs(batch_gt_depth-depth) /\n torch.sqrt(uncertainty+1e-10))[mask].sum()\n\n if self.use_color_in_tracking:\n color_loss = torch.abs(\n batch_gt_color - color)[mask].sum()\n loss += self.w_color_loss*color_loss\n \n loss.backward(retain_graph=False)\n optimizer.step()\n optimizer.zero_grad()\n return loss.item()\n\n def update_para_from_mapping(self):\n \"\"\"\n Update the parameters of scene representation from the mapping thread.\n\n \"\"\"\n if self.mapping_idx[0] != self.prev_mapping_idx:\n if self.verbose:\n print('Tracking: update the parameters from mapping')\n self.decoders = copy.deepcopy(self.shared_decoders).to(self.device)\n for key, val in self.shared_c.items():\n val = val.clone().to(self.device)\n self.c[key] = val\n self.prev_mapping_idx = self.mapping_idx[0].clone()\n\n def run(self):\n device = self.device\n tsdf_volume = self.tsdf_volume_shared\n tsdf_bnds = self.tsdf_bnds.to(device)\n \n self.c = {}\n if self.verbose:\n pbar = self.frame_loader\n else:\n pbar = tqdm(self.frame_loader)\n\n for idx, gt_color, gt_depth, gt_c2w in pbar:\n if not self.verbose:\n pbar.set_description(f\"Tracking Frame {idx[0]}\")\n\n idx = idx[0]\n gt_depth = gt_depth[0]\n gt_color = gt_color[0]\n gt_c2w = gt_c2w[0]\n\n if self.sync_method == 'strict':\n # strictly mapping and then tracking\n # initiate mapping every self.every_frame frames\n if idx > 0 and (idx % self.every_frame == 1 or self.every_frame == 1):\n while self.mapping_idx[0] != idx-1:\n time.sleep(0.1)\n pre_c2w = self.estimate_c2w_list[idx-1].to(device)\n elif self.sync_method == 'loose':\n # mapping idx can be later than tracking idx is within the bound of\n # [-self.every_frame-self.every_frame//2, -self.every_frame+self.every_frame//2]\n while self.mapping_idx[0] < idx-self.every_frame-self.every_frame//2:\n time.sleep(0.1)\n elif self.sync_method == 'free':\n # pure parallel, if mesh/vis happens may cause inbalance\n pass\n\n self.update_para_from_mapping()\n\n if self.verbose:\n print(Fore.MAGENTA)\n print(\"Tracking Frame \", idx.item())\n print(Style.RESET_ALL)\n \n \n\n if idx == 0 or self.gt_camera:\n c2w = gt_c2w\n if not self.no_vis_on_first_frame:\n self.visualizer.vis(\n idx, 0, gt_depth, gt_color, c2w, self.c, self.decoders, tsdf_volume, tsdf_bnds)\n \n else:\n gt_camera_tensor = get_tensor_from_camera(gt_c2w)\n if self.const_speed_assumption and idx-2 >= 0:\n pre_c2w = pre_c2w.float()\n delta = [email protected]_c2w_list[idx-2].to(\n device).float().inverse()\n estimated_new_cam_c2w = delta@pre_c2w\n else:\n estimated_new_cam_c2w = pre_c2w\n\n camera_tensor = get_tensor_from_camera(\n estimated_new_cam_c2w.detach())\n if self.seperate_LR:\n camera_tensor = camera_tensor.to(device).detach()\n T = camera_tensor[-3:]\n quad = camera_tensor[:4]\n cam_para_list_quad = [quad]\n quad = Variable(quad, requires_grad=True)\n T = Variable(T, requires_grad=True)\n camera_tensor = torch.cat([quad, T], 0)\n cam_para_list_T = [T]\n cam_para_list_quad = [quad]\n optimizer_camera = torch.optim.Adam([{'params': cam_para_list_T, 'lr': self.cam_lr},\n {'params': cam_para_list_quad, 'lr': self.cam_lr*0.2}])\n else:\n camera_tensor = Variable(\n camera_tensor.to(device), requires_grad=True)\n cam_para_list = [camera_tensor]\n optimizer_camera = torch.optim.Adam(\n cam_para_list, lr=self.cam_lr)\n\n initial_loss_camera_tensor = torch.abs(\n gt_camera_tensor.to(device)-camera_tensor).mean().item()\n candidate_cam_tensor = None\n current_min_loss = 10000000000.\n\n \n\n for cam_iter in range(self.num_cam_iters):\n if self.seperate_LR:\n camera_tensor = torch.cat([quad, T], 0).to(self.device)\n\n self.visualizer.vis(\n idx, cam_iter, gt_depth, gt_color, camera_tensor, self.c, self.decoders, tsdf_volume, tsdf_bnds)\n\n loss = self.optimize_cam_in_batch(\n camera_tensor, gt_color, gt_depth, self.tracking_pixels, optimizer_camera, tsdf_volume)\n\n if cam_iter == 0:\n initial_loss = loss\n\n loss_camera_tensor = torch.abs(\n gt_camera_tensor.to(device)-camera_tensor).mean().item()\n if self.verbose:\n if cam_iter == self.num_cam_iters-1:\n print(\n f'Re-rendering loss: {initial_loss:.2f}->{loss:.2f} ' +\n f'camera tensor error: {initial_loss_camera_tensor:.4f}->{loss_camera_tensor:.4f}')\n if loss < current_min_loss:\n current_min_loss = loss\n candidate_cam_tensor = camera_tensor.clone().detach()\n bottom = torch.from_numpy(np.array([0, 0, 0, 1.]).reshape(\n [1, 4])).type(torch.float32).to(self.device)\n c2w = get_camera_from_tensor(\n candidate_cam_tensor.clone().detach())\n c2w = torch.cat([c2w, bottom], dim=0)\n\n \n self.estimate_c2w_list[idx] = c2w.clone().cpu()\n self.gt_c2w_list[idx] = gt_c2w.clone().cpu()\n pre_c2w = c2w.clone()\n self.idx[0] = idx\n if self.low_gpu_mem:\n torch.cuda.empty_cache()" }, { "identifier": "get_dataset", "path": "src/utils/datasets.py", "snippet": "def get_dataset(cfg, args, scale, device='cuda:0'):\n return dataset_dict[cfg['dataset']](cfg, args, scale, device=device)" }, { "identifier": "Logger", "path": "src/utils/Logger.py", "snippet": "class Logger(object):\n \"\"\"\n Save checkpoints to file.\n\n \"\"\"\n\n def __init__(self, cfg, args, slam\n ):\n self.verbose = slam.verbose\n self.ckptsdir = slam.ckptsdir\n self.shared_c = slam.shared_c\n self.gt_c2w_list = slam.gt_c2w_list\n self.shared_decoders = slam.shared_decoders\n self.estimate_c2w_list = slam.estimate_c2w_list\n self.tsdf_volume = slam.tsdf_volume_shared\n\n def log(self, idx, keyframe_dict, keyframe_list, selected_keyframes=None):\n path = os.path.join(self.ckptsdir, '{:05d}.tar'.format(idx))\n torch.save({\n 'c': self.shared_c,\n 'decoder_state_dict': self.shared_decoders.state_dict(),\n 'gt_c2w_list': self.gt_c2w_list,\n 'estimate_c2w_list': self.estimate_c2w_list,\n 'keyframe_list': keyframe_list,\n 'keyframe_dict': keyframe_dict, # to save keyframe_dict into ckpt, uncomment this line\n 'selected_keyframes': selected_keyframes,\n 'idx': idx,\n 'tsdf_volume': self.tsdf_volume,\n }, path, _use_new_zipfile_serialization=False)\n\n if self.verbose:\n print('Saved checkpoints at', path)" }, { "identifier": "Mesher", "path": "src/utils/Mesher.py", "snippet": "class Mesher(object):\n\n def __init__(self, cfg, args, slam, points_batch_size=500000, ray_batch_size=100000):\n \"\"\"\n Mesher class, given a scene representation, the mesher extracts the mesh from it.\n\n Args:\n cfg (dict): parsed config dict.\n args (class 'argparse.Namespace'): argparse arguments.\n slam (class DF_Prior): DF_Prior main class.\n points_batch_size (int): maximum points size for query in one batch. \n Used to alleviate GPU memeory usage. Defaults to 500000.\n ray_batch_size (int): maximum ray size for query in one batch. \n Used to alleviate GPU memeory usage. Defaults to 100000.\n \"\"\"\n self.points_batch_size = points_batch_size\n self.ray_batch_size = ray_batch_size\n self.renderer = slam.renderer\n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n \n self.resolution = cfg['meshing']['resolution']\n self.level_set = cfg['meshing']['level_set']\n self.clean_mesh_bound_scale = cfg['meshing']['clean_mesh_bound_scale']\n self.remove_small_geometry_threshold = cfg['meshing']['remove_small_geometry_threshold']\n self.color_mesh_extraction_method = cfg['meshing']['color_mesh_extraction_method']\n self.get_largest_components = cfg['meshing']['get_largest_components']\n self.depth_test = cfg['meshing']['depth_test']\n \n self.bound = slam.bound\n self.verbose = slam.verbose\n \n\n self.marching_cubes_bound = torch.from_numpy(\n np.array(cfg['mapping']['marching_cubes_bound']) * self.scale)\n\n self.frame_reader = get_dataset(cfg, args, self.scale, device='cpu')\n self.n_img = len(self.frame_reader)\n\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n self.sample_mode = 'bilinear'\n self.tsdf_bnds = slam.tsdf_bnds\n\n\n\n def point_masks(self, input_points, keyframe_dict, estimate_c2w_list,\n idx, device, get_mask_use_all_frames=False):\n \"\"\"\n Split the input points into seen, unseen, and forcast,\n according to the estimated camera pose and depth image.\n\n Args:\n input_points (tensor): input points.\n keyframe_dict (list): list of keyframe info dictionary.\n estimate_c2w_list (tensor): estimated camera pose.\n idx (int): current frame index.\n device (str): device name to compute on.\n\n Returns:\n seen_mask (tensor): the mask for seen area.\n forecast_mask (tensor): the mask for forecast area.\n unseen_mask (tensor): the mask for unseen area.\n \"\"\"\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n if not isinstance(input_points, torch.Tensor):\n input_points = torch.from_numpy(input_points)\n input_points = input_points.clone().detach()\n seen_mask_list = []\n forecast_mask_list = []\n unseen_mask_list = []\n for i, pnts in enumerate(\n torch.split(input_points, self.points_batch_size, dim=0)):\n points = pnts.to(device).float()\n # should divide the points into three parts, seen and forecast and unseen\n # seen: union of all the points in the viewing frustum of keyframes\n # forecast: union of all the points in the extended edge of the viewing frustum of keyframes\n # unseen: all the other points\n\n seen_mask = torch.zeros((points.shape[0])).bool().to(device)\n forecast_mask = torch.zeros((points.shape[0])).bool().to(device)\n if get_mask_use_all_frames:\n for i in range(0, idx + 1, 1):\n c2w = estimate_c2w_list[i].cpu().numpy()\n w2c = np.linalg.inv(c2w)\n w2c = torch.from_numpy(w2c).to(device).float()\n ones = torch.ones_like(\n points[:, 0]).reshape(-1, 1).to(device)\n homo_points = torch.cat([points, ones], dim=1).reshape(\n -1, 4, 1).to(device).float() # (N, 4)\n # (N, 4, 1)=(4,4)*(N, 4, 1)\n cam_cord_homo = w2c @ homo_points\n cam_cord = cam_cord_homo[:, :3] # (N, 3, 1)\n\n K = torch.from_numpy(\n np.array([[fx, .0, cx], [.0, fy, cy],\n [.0, .0, 1.0]]).reshape(3, 3)).to(device)\n cam_cord[:, 0] *= -1\n uv = K.float() @ cam_cord.float()\n z = uv[:, -1:] + 1e-8\n uv = uv[:, :2] / z\n uv = uv.float()\n edge = 0\n cur_mask_seen = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_seen = cur_mask_seen & (z[:, :, 0] < 0)\n\n edge = -1000\n cur_mask_forecast = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_forecast = cur_mask_forecast & (z[:, :, 0] < 0)\n\n # forecast\n cur_mask_forecast = cur_mask_forecast.reshape(-1)\n # seen\n cur_mask_seen = cur_mask_seen.reshape(-1)\n\n seen_mask |= cur_mask_seen\n forecast_mask |= cur_mask_forecast\n else:\n for keyframe in keyframe_dict:\n c2w = keyframe['est_c2w'].cpu().numpy()\n w2c = np.linalg.inv(c2w)\n w2c = torch.from_numpy(w2c).to(device).float()\n ones = torch.ones_like(\n points[:, 0]).reshape(-1, 1).to(device)\n homo_points = torch.cat([points, ones], dim=1).reshape(\n -1, 4, 1).to(device).float()\n cam_cord_homo = w2c @ homo_points\n cam_cord = cam_cord_homo[:, :3]\n\n K = torch.from_numpy(\n np.array([[fx, .0, cx], [.0, fy, cy],\n [.0, .0, 1.0]]).reshape(3, 3)).to(device)\n cam_cord[:, 0] *= -1\n uv = K.float() @ cam_cord.float()\n z = uv[:, -1:] + 1e-8\n uv = uv[:, :2] / z\n uv = uv.float()\n edge = 0\n cur_mask_seen = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_seen = cur_mask_seen & (z[:, :, 0] < 0)\n\n edge = -1000\n cur_mask_forecast = (uv[:, 0] < W - edge) & (\n uv[:, 0] > edge) & (uv[:, 1] < H - edge) & (uv[:, 1] > edge)\n cur_mask_forecast = cur_mask_forecast & (z[:, :, 0] < 0)\n\n if self.depth_test:\n gt_depth = keyframe['depth'].to(\n device).reshape(1, 1, H, W)\n vgrid = uv.reshape(1, 1, -1, 2)\n # normalized to [-1, 1]\n vgrid[..., 0] = (vgrid[..., 0] / (W-1) * 2.0 - 1.0)\n vgrid[..., 1] = (vgrid[..., 1] / (H-1) * 2.0 - 1.0)\n depth_sample = F.grid_sample(\n gt_depth, vgrid, padding_mode='zeros', align_corners=True)\n depth_sample = depth_sample.reshape(-1)\n max_depth = torch.max(depth_sample)\n # forecast\n cur_mask_forecast = cur_mask_forecast.reshape(-1)\n proj_depth_forecast = -cam_cord[cur_mask_forecast,\n 2].reshape(-1)\n cur_mask_forecast[cur_mask_forecast.clone()] &= proj_depth_forecast < max_depth\n # seen\n cur_mask_seen = cur_mask_seen.reshape(-1)\n proj_depth_seen = - cam_cord[cur_mask_seen, 2].reshape(-1)\n cur_mask_seen[cur_mask_seen.clone()] &= \\\n (proj_depth_seen < depth_sample[cur_mask_seen]+2.4) \\\n & (depth_sample[cur_mask_seen]-2.4 < proj_depth_seen)\n else:\n max_depth = torch.max(keyframe['depth'])*1.1\n\n # forecast\n cur_mask_forecast = cur_mask_forecast.reshape(-1)\n proj_depth_forecast = -cam_cord[cur_mask_forecast,\n 2].reshape(-1)\n cur_mask_forecast[\n cur_mask_forecast.clone()] &= proj_depth_forecast < max_depth\n\n # seen\n cur_mask_seen = cur_mask_seen.reshape(-1)\n proj_depth_seen = - \\\n cam_cord[cur_mask_seen, 2].reshape(-1)\n cur_mask_seen[cur_mask_seen.clone(\n )] &= proj_depth_seen < max_depth\n\n seen_mask |= cur_mask_seen\n forecast_mask |= cur_mask_forecast\n\n forecast_mask &= ~seen_mask\n unseen_mask = ~(seen_mask | forecast_mask)\n\n seen_mask = seen_mask.cpu().numpy()\n forecast_mask = forecast_mask.cpu().numpy()\n unseen_mask = unseen_mask.cpu().numpy()\n\n seen_mask_list.append(seen_mask)\n forecast_mask_list.append(forecast_mask)\n unseen_mask_list.append(unseen_mask)\n\n seen_mask = np.concatenate(seen_mask_list, axis=0)\n forecast_mask = np.concatenate(forecast_mask_list, axis=0)\n unseen_mask = np.concatenate(unseen_mask_list, axis=0)\n return seen_mask, forecast_mask, unseen_mask\n\n def get_bound_from_frames(self, keyframe_dict, scale=1):\n \"\"\"\n Get the scene bound (convex hull),\n using sparse estimated camera poses and corresponding depth images.\n\n Args:\n keyframe_dict (list): list of keyframe info dictionary.\n scale (float): scene scale.\n\n Returns:\n return_mesh (trimesh.Trimesh): the convex hull.\n \"\"\"\n\n H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy\n\n if version.parse(o3d.__version__) >= version.parse('0.13.0'):\n # for new version as provided in environment.yaml\n volume = o3d.pipelines.integration.ScalableTSDFVolume(\n voxel_length=4.0 * scale / 512.0,\n sdf_trunc=0.04 * scale,\n color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8)\n else:\n # for lower version\n volume = o3d.integration.ScalableTSDFVolume(\n voxel_length=4.0 * scale / 512.0,\n sdf_trunc=0.04 * scale,\n color_type=o3d.integration.TSDFVolumeColorType.RGB8)\n cam_points = []\n for keyframe in keyframe_dict:\n c2w = keyframe['est_c2w'].cpu().numpy()\n # convert to open3d camera pose\n c2w[:3, 1] *= -1.0\n c2w[:3, 2] *= -1.0\n w2c = np.linalg.inv(c2w)\n cam_points.append(c2w[:3, 3])\n depth = keyframe['depth'].cpu().numpy()\n color = keyframe['color'].cpu().numpy()\n\n depth = o3d.geometry.Image(depth.astype(np.float32))\n color = o3d.geometry.Image(np.array(\n (color * 255).astype(np.uint8)))\n\n intrinsic = o3d.camera.PinholeCameraIntrinsic(W, H, fx, fy, cx, cy)\n rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(\n color,\n depth,\n depth_scale=1,\n depth_trunc=1000,\n convert_rgb_to_intensity=False)\n volume.integrate(rgbd, intrinsic, w2c)\n\n cam_points = np.stack(cam_points, axis=0)\n mesh = volume.extract_triangle_mesh()\n mesh_points = np.array(mesh.vertices)\n points = np.concatenate([cam_points, mesh_points], axis=0)\n o3d_pc = o3d.geometry.PointCloud(o3d.utility.Vector3dVector(points))\n mesh, _ = o3d_pc.compute_convex_hull()\n mesh.compute_vertex_normals()\n if version.parse(o3d.__version__) >= version.parse('0.13.0'):\n mesh = mesh.scale(self.clean_mesh_bound_scale, mesh.get_center())\n else:\n mesh = mesh.scale(self.clean_mesh_bound_scale, center=True)\n points = np.array(mesh.vertices)\n faces = np.array(mesh.triangles)\n return_mesh = trimesh.Trimesh(vertices=points, faces=faces)\n return return_mesh\n\n def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): point coordinates.\n decoders (nn.module decoders): decoders.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n c (dicts, optional): feature grids. Defaults to None.\n stage (str, optional): query stage, corresponds to different levels. Defaults to 'color'.\n device (str, optional): device name to compute on. Defaults to 'cuda:0'.\n\n Returns:\n ret (tensor): occupancy (and color) value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n bound = self.bound\n rets = []\n\n for pi in p_split:\n # mask for points out of bound\n mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0])\n mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0])\n mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0])\n mask = mask_x & mask_y & mask_z\n\n pi = pi.unsqueeze(0)\n ret, _ = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage)\n \n ret = ret.squeeze(0)\n if len(ret.shape) == 1 and ret.shape[0] == 4:\n ret = ret.unsqueeze(0)\n\n ret[~mask, 3] = 100\n rets.append(ret)\n\n ret = torch.cat(rets, dim=0)\n\n return ret\n\n def sample_grid_tsdf(self, p, tsdf_volume, device='cuda:0'):\n\n p_nor = normalize_3d_coordinate(p.clone(), self.tsdf_bnds)\n p_nor = p_nor.unsqueeze(0)\n vgrid = p_nor[:, :, None, None].float()\n # acutally trilinear interpolation if mode = 'bilinear'\n tsdf_value = F.grid_sample(tsdf_volume.to(device), vgrid.to(device), padding_mode='border', align_corners=True,\n mode='bilinear').squeeze(-1).squeeze(-1)\n return tsdf_value\n\n\n def eval_points_tsdf(self, p, tsdf_volume, device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): Point coordinates.\n tsdf_volume (tensor): tsdf volume.\n\n Returns:\n ret (tensor): tsdf value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n tsdf_vals = []\n for pi in p_split:\n pi = pi.unsqueeze(0)\n tsdf_volume_tensor = tsdf_volume\n\n tsdf_val = self.sample_grid_tsdf(pi, tsdf_volume_tensor, device)\n tsdf_val = tsdf_val.squeeze(0)\n tsdf_vals.append(tsdf_val)\n\n tsdf_values = torch.cat(tsdf_vals, dim=1)\n return tsdf_values\n\n\n def get_grid_uniform(self, resolution):\n \"\"\"\n Get query point coordinates for marching cubes.\n\n Args:\n resolution (int): marching cubes resolution.\n\n Returns:\n (dict): points coordinates and sampled coordinates for each axis.\n \"\"\"\n bound = self.marching_cubes_bound\n\n padding = 0.05\n x = np.linspace(bound[0][0] - padding, bound[0][1] + padding,\n resolution)\n y = np.linspace(bound[1][0] - padding, bound[1][1] + padding,\n resolution)\n z = np.linspace(bound[2][0] - padding, bound[2][1] + padding,\n resolution)\n\n xx, yy, zz = np.meshgrid(x, y, z)\n grid_points = np.vstack([xx.ravel(), yy.ravel(), zz.ravel()]).T\n grid_points = torch.tensor(np.vstack(\n [xx.ravel(), yy.ravel(), zz.ravel()]).T,\n dtype=torch.float)\n\n\n\n return {\"grid_points\": grid_points, \"xyz\": [x, y, z]}\n\n def get_mesh(self,\n mesh_out_file,\n c,\n decoders,\n keyframe_dict,\n estimate_c2w_list,\n idx,\n tsdf_volume,\n device='cuda:0',\n color=True,\n clean_mesh=True,\n get_mask_use_all_frames=False):\n \"\"\"\n Extract mesh from scene representation and save mesh to file.\n\n Args:\n mesh_out_file (str): output mesh filename.\n c (dicts): feature grids.\n decoders (nn.module): decoders.\n keyframe_dict (list): list of keyframe info.\n estimate_c2w_list (tensor): estimated camera pose.\n idx (int): current processed camera ID.\n tsdf volume (tensor): tsdf volume.\n device (str, optional): device name to compute on. Defaults to 'cuda:0'.\n color (bool, optional): whether to extract colored mesh. Defaults to True.\n clean_mesh (bool, optional): whether to clean the output mesh \n (remove outliers outside the convexhull and small geometry noise). \n Defaults to True.\n get_mask_use_all_frames (bool, optional): \n whether to use all frames or just keyframes when getting the seen/unseen mask. Defaults to False.\n \"\"\"\n with torch.no_grad():\n\n grid = self.get_grid_uniform(self.resolution) \n points = grid['grid_points']\n points = points.to(device)\n eval_tsdf_volume = tsdf_volume\n\n mesh_bound = self.get_bound_from_frames(\n keyframe_dict, self.scale)\n z = []\n mask = []\n for i, pnts in enumerate(torch.split(points, self.points_batch_size, dim=0)):\n mask.append(mesh_bound.contains(pnts.cpu().numpy()))\n mask = np.concatenate(mask, axis=0)\n for i, pnts in enumerate(torch.split(points, self.points_batch_size, dim=0)):\n eval_tsdf = self.eval_points_tsdf(pnts, eval_tsdf_volume, device)\n eval_tsdf_mask = ((eval_tsdf > -1.0+1e-4) & (eval_tsdf < 1.0-1e-4)).cpu().numpy()\n ret = self.eval_points(pnts, decoders, tsdf_volume, self.tsdf_bnds, c, 'high', device)\n ret = ret.cpu().numpy()[:, -1]\n\n eval_tsdf_mask = eval_tsdf_mask.reshape(ret.shape)\n z.append(ret)\n \n z = np.concatenate(z, axis=0)\n z[~mask] = 100\n z = z.astype(np.float32)\n\n z_uni_m = z.reshape(\n grid['xyz'][1].shape[0], grid['xyz'][0].shape[0],\n grid['xyz'][2].shape[0]).transpose([1, 0, 2])\n\n print('begin marching cube...')\n combine_occ_tsdf = z_uni_m\n\n try:\n if version.parse(\n skimage.__version__) > version.parse('0.15.0'):\n # for new version as provided in environment.yaml\n verts, faces, normals, values = skimage.measure.marching_cubes(\n volume=combine_occ_tsdf,\n level=self.level_set, \n spacing=(grid['xyz'][0][2] - grid['xyz'][0][1],\n grid['xyz'][1][2] - grid['xyz'][1][1],\n grid['xyz'][2][2] - grid['xyz'][2][1]))\n else:\n # for lower version\n verts, faces, normals, values = skimage.measure.marching_cubes_lewiner(\n volume=combine_occ_tsdf,\n level=self.level_set, \n spacing=(grid['xyz'][0][2] - grid['xyz'][0][1],\n grid['xyz'][1][2] - grid['xyz'][1][1],\n grid['xyz'][2][2] - grid['xyz'][2][1]))\n except:\n print(\n 'marching_cubes error. Possibly no surface extracted from the level set.'\n )\n return\n\n # convert back to world coordinates\n vertices = verts + np.array(\n [grid['xyz'][0][0], grid['xyz'][1][0], grid['xyz'][2][0]])\n\n if clean_mesh:\n points = vertices\n mesh = trimesh.Trimesh(vertices=vertices,\n faces=faces,\n process=False)\n seen_mask, _, unseen_mask = self.point_masks(\n points, keyframe_dict, estimate_c2w_list, idx, device=device, \n get_mask_use_all_frames=get_mask_use_all_frames)\n unseen_mask = ~seen_mask\n face_mask = unseen_mask[mesh.faces].all(axis=1)\n mesh.update_faces(~face_mask)\n\n # get connected components\n components = mesh.split(only_watertight=False)\n if self.get_largest_components:\n areas = np.array([c.area for c in components], dtype=np.float)\n mesh = components[areas.argmax()]\n else:\n new_components = []\n for comp in components:\n if comp.area > self.remove_small_geometry_threshold * self.scale * self.scale:\n new_components.append(comp)\n mesh = trimesh.util.concatenate(new_components)\n vertices = mesh.vertices\n faces = mesh.faces\n\n if color:\n if self.color_mesh_extraction_method == 'direct_point_query':\n # color is extracted by passing the coordinates of mesh vertices through the network\n points = torch.from_numpy(vertices)\n z = []\n for i, pnts in enumerate(\n torch.split(points, self.points_batch_size, dim=0)):\n ret = self.eval_points(\n pnts.to(device).float(), decoders, tsdf_volume, self.tsdf_bnds, c, 'color',\n device)\n z_color = ret.cpu()[..., :3]\n z.append(z_color)\n z = torch.cat(z, axis=0)\n vertex_colors = z.numpy()\n\n vertex_colors = np.clip(vertex_colors, 0, 1) * 255\n vertex_colors = vertex_colors.astype(np.uint8)\n\n\n else:\n vertex_colors = None\n\n vertices /= self.scale\n mesh = trimesh.Trimesh(vertices, faces, vertex_colors=vertex_colors)\n mesh.export(mesh_out_file)\n if self.verbose:\n print('Saved mesh at', mesh_out_file)\n\n return z_uni_m" }, { "identifier": "Renderer", "path": "src/utils/Renderer.py", "snippet": "class Renderer(object):\n def __init__(self, cfg, args, slam, points_batch_size=500000, ray_batch_size=100000):\n self.ray_batch_size = ray_batch_size\n self.points_batch_size = points_batch_size\n\n self.lindisp = cfg['rendering']['lindisp']\n self.perturb = cfg['rendering']['perturb']\n self.N_samples = cfg['rendering']['N_samples']\n self.N_surface = cfg['rendering']['N_surface']\n self.N_importance = cfg['rendering']['N_importance']\n\n self.scale = cfg['scale']\n self.occupancy = cfg['occupancy']\n self.bound = slam.bound\n self.sample_mode = 'bilinear'\n self.tsdf_bnds = slam.vol_bnds\n\n self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy\n\n self.resolution = cfg['meshing']['resolution']\n\n def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): Point coordinates.\n decoders (nn.module decoders): Decoders.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n c (dicts, optional): Feature grids. Defaults to None.\n stage (str, optional): Query stage, corresponds to different levels. Defaults to 'color'.\n device (str, optional): CUDA device. Defaults to 'cuda:0'.\n\n Returns:\n ret (tensor): occupancy (and color) value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n bound = self.bound\n rets = []\n weights = []\n\n for pi in p_split:\n # mask for points out of bound\n mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0])\n mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0])\n mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0])\n mask = mask_x & mask_y & mask_z\n\n pi = pi.unsqueeze(0)\n ret, w = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage)\n ret = ret.squeeze(0)\n\n\n if len(ret.shape) == 1 and ret.shape[0] == 4:\n ret = ret.unsqueeze(0)\n\n ret[~mask, 3] = 100 \n rets.append(ret)\n weights.append(w)\n\n ret = torch.cat(rets, dim=0)\n weight = torch.cat(weights, dim=0)\n\n return ret, weight \n\n def sample_grid_tsdf(self, p, tsdf_volume, device='cuda:0'):\n\n p_nor = normalize_3d_coordinate(p.clone(), self.tsdf_bnds)\n p_nor = p_nor.unsqueeze(0)\n vgrid = p_nor[:, :, None, None].float()\n # acutally trilinear interpolation if mode = 'bilinear'\n tsdf_value = F.grid_sample(tsdf_volume.to(device), vgrid.to(device), padding_mode='border', align_corners=True,\n mode='bilinear').squeeze(-1).squeeze(-1)\n return tsdf_value\n\n\n def eval_points_tsdf(self, p, tsdf_volume, device='cuda:0'):\n \"\"\"\n Evaluates the occupancy and/or color value for the points.\n\n Args:\n p (tensor, N*3): Point coordinates.\n \n\n Returns:\n ret (tensor): tsdf value of input points.\n \"\"\"\n\n p_split = torch.split(p, self.points_batch_size)\n tsdf_vals = []\n for pi in p_split:\n pi = pi.unsqueeze(0)\n tsdf_volume_tensor = tsdf_volume\n\n tsdf_val = self.sample_grid_tsdf(pi, tsdf_volume_tensor, device)\n tsdf_val = tsdf_val.squeeze(0)\n tsdf_vals.append(tsdf_val)\n\n tsdf_values = torch.cat(tsdf_vals, dim=1)\n return tsdf_values\n\n\n def render_batch_ray(self, c, decoders, rays_d, rays_o, device, tsdf_volume, tsdf_bnds, stage, gt_depth=None):\n \"\"\"\n Render color, depth and uncertainty of a batch of rays.\n\n Args:\n c (dict): feature grids.\n decoders (nn.module): decoders.\n rays_d (tensor, N*3): rays direction.\n rays_o (tensor, N*3): rays origin.\n device (str): device name to compute on.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n stage (str): query stage.\n gt_depth (tensor, optional): sensor depth image. Defaults to None.\n\n Returns:\n depth (tensor): rendered depth.\n uncertainty (tensor): rendered uncertainty.\n color (tensor): rendered color.\n weight (tensor): attention weight.\n \"\"\"\n eval_tsdf_volume = tsdf_volume\n \n\n N_samples = self.N_samples\n N_surface = self.N_surface\n N_importance = self.N_importance\n\n N_rays = rays_o.shape[0]\n\n if gt_depth is None:\n N_surface = 0\n near = 0.01\n else:\n gt_depth = gt_depth.reshape(-1, 1)\n gt_depth_samples = gt_depth.repeat(1, N_samples)\n near = gt_depth_samples*0.01\n\n with torch.no_grad():\n det_rays_o = rays_o.clone().detach().unsqueeze(-1) # (N, 3, 1)\n det_rays_d = rays_d.clone().detach().unsqueeze(-1) # (N, 3, 1)\n t = (self.bound.unsqueeze(0).to(device) -\n det_rays_o)/det_rays_d # (N, 3, 2)\n far_bb, _ = torch.min(torch.max(t, dim=2)[0], dim=1)\n far_bb = far_bb.unsqueeze(-1)\n far_bb += 0.01\n\n if gt_depth is not None:\n # in case the bound is too large\n far = torch.clamp(far_bb, 0, torch.max(gt_depth*1.2))\n\n else:\n far = far_bb\n if N_surface > 0:\n if False:\n # this naive implementation downgrades performance\n gt_depth_surface = gt_depth.repeat(1, N_surface)\n t_vals_surface = torch.linspace(\n 0., 1., steps=N_surface).to(device)\n z_vals_surface = 0.95*gt_depth_surface * \\\n (1.-t_vals_surface) + 1.05 * \\\n gt_depth_surface * (t_vals_surface)\n else:\n # since we want to colorize even on regions with no depth sensor readings,\n # meaning colorize on interpolated geometry region,\n # we sample all pixels (not using depth mask) for color loss.\n # Therefore, for pixels with non-zero depth value, we sample near the surface,\n # since it is not a good idea to sample 16 points near (half even behind) camera,\n # for pixels with zero depth value, we sample uniformly from camera to max_depth.\n gt_none_zero_mask = gt_depth > 0\n gt_none_zero = gt_depth[gt_none_zero_mask]\n gt_none_zero = gt_none_zero.unsqueeze(-1)\n gt_depth_surface = gt_none_zero.repeat(1, N_surface)\n t_vals_surface = torch.linspace(\n 0., 1., steps=N_surface).double().to(device)\n # emperical range 0.05*depth\n z_vals_surface_depth_none_zero = 0.95*gt_depth_surface * \\\n (1.-t_vals_surface) + 1.05 * \\\n gt_depth_surface * (t_vals_surface)\n z_vals_surface = torch.zeros(\n gt_depth.shape[0], N_surface).to(device).double()\n gt_none_zero_mask = gt_none_zero_mask.squeeze(-1)\n z_vals_surface[gt_none_zero_mask,\n :] = z_vals_surface_depth_none_zero\n near_surface = 0.001\n far_surface = torch.max(gt_depth)\n z_vals_surface_depth_zero = near_surface * \\\n (1.-t_vals_surface) + far_surface * (t_vals_surface)\n z_vals_surface_depth_zero.unsqueeze(\n 0).repeat((~gt_none_zero_mask).sum(), 1)\n z_vals_surface[~gt_none_zero_mask,\n :] = z_vals_surface_depth_zero\n\n t_vals = torch.linspace(0., 1., steps=N_samples, device=device)\n\n if not self.lindisp:\n z_vals = near * (1.-t_vals) + far * (t_vals)\n else:\n z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals))\n\n if self.perturb > 0.:\n # get intervals between samples\n mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1])\n upper = torch.cat([mids, z_vals[..., -1:]], -1)\n lower = torch.cat([z_vals[..., :1], mids], -1)\n # stratified samples in those intervals\n t_rand = torch.rand(z_vals.shape).to(device)\n z_vals = lower + (upper - lower) * t_rand\n\n if N_surface > 0:\n z_vals, _ = torch.sort(\n torch.cat([z_vals, z_vals_surface.double()], -1), -1)\n\n pts = rays_o[..., None, :] + rays_d[..., None, :] * \\\n z_vals[..., :, None] # [N_rays, N_samples+N_surface, 3]\n pointsf = pts.reshape(-1, 3)\n \n raw, weight = self.eval_points(pointsf, decoders, tsdf_volume, tsdf_bnds, c, stage, device)\n raw = raw.reshape(N_rays, N_samples+N_surface, -1)\n weight = weight.reshape(N_rays, N_samples+N_surface, -1)\n\n\n depth, uncertainty, color, weights = raw2outputs_nerf_color(\n raw, z_vals, rays_d, occupancy=self.occupancy, device=device)\n \n if N_importance > 0:\n z_vals_mid = .5 * (z_vals[..., 1:] + z_vals[..., :-1])\n z_samples = sample_pdf(\n z_vals_mid, weights[..., 1:-1], N_importance, det=(self.perturb == 0.), device=device)\n z_samples = z_samples.detach()\n z_vals, _ = torch.sort(torch.cat([z_vals, z_samples], -1), -1)\n\n pts = rays_o[..., None, :] + \\\n rays_d[..., None, :] * z_vals[..., :, None]\n pts = pts.reshape(-1, 3)\n \n raw, weight = self.eval_points(pointsf, decoders, tsdf_volume, tsdf_bnds, c, stage, device)\n raw = raw.reshape(N_rays, N_samples+N_surface, -1)\n weight = weight.reshape(N_rays, N_samples+N_surface, -1)\n\n depth, uncertainty, color, weights = raw2outputs_nerf_color(\n raw, z_vals, rays_d, occupancy=self.occupancy, device=device)\n return depth, uncertainty, color, weight\n\n\n return depth, uncertainty, color, weight\n\n\n def render_img(self, c, decoders, c2w, device, tsdf_volume, tsdf_bnds, stage, gt_depth=None):\n \"\"\"\n Renders out depth, uncertainty, and color images.\n\n Args:\n c (dict): feature grids.\n decoders (nn.module): decoders.\n c2w (tensor): camera to world matrix of current frame.\n device (str): device name to compute on.\n tsdf_volume (tensor): tsdf volume.\n tsdf_bnds (tensor): tsdf volume bounds.\n stage (str): query stage.\n gt_depth (tensor, optional): sensor depth image. Defaults to None.\n\n Returns:\n depth (tensor, H*W): rendered depth image.\n uncertainty (tensor, H*W): rendered uncertainty image.\n color (tensor, H*W*3): rendered color image.\n \"\"\"\n \n with torch.no_grad():\n H = self.H\n W = self.W\n rays_o, rays_d = get_rays(\n H, W, self.fx, self.fy, self.cx, self.cy, c2w, device)\n rays_o = rays_o.reshape(-1, 3)\n rays_d = rays_d.reshape(-1, 3)\n\n depth_list = []\n uncertainty_list = []\n color_list = []\n\n\n ray_batch_size = self.ray_batch_size\n gt_depth = gt_depth.reshape(-1)\n\n for i in range(0, rays_d.shape[0], ray_batch_size):\n rays_d_batch = rays_d[i:i+ray_batch_size]\n rays_o_batch = rays_o[i:i+ray_batch_size]\n\n iter = 10\n\n if gt_depth is None:\n ret = self.render_batch_ray(\n c, decoders, rays_d_batch, rays_o_batch, device, tsdf_volume, tsdf_bnds, stage, gt_depth=None)\n else:\n gt_depth_batch = gt_depth[i:i+ray_batch_size]\n ret = self.render_batch_ray(\n c, decoders, rays_d_batch, rays_o_batch, device, tsdf_volume, tsdf_bnds, stage, gt_depth=gt_depth_batch)\n\n depth, uncertainty, color, _= ret\n\n \n depth_list.append(depth.double())\n uncertainty_list.append(uncertainty.double())\n color_list.append(color)\n \n \n\n\n\n depth = torch.cat(depth_list, dim=0)\n uncertainty = torch.cat(uncertainty_list, dim=0)\n color = torch.cat(color_list, dim=0)\n \n depth = depth.reshape(H, W)\n uncertainty = uncertainty.reshape(H, W)\n color = color.reshape(H, W, 3)\n\n return depth, uncertainty, color " } ]
import os import time import numpy as np import torch import torch.multiprocessing import torch.multiprocessing as mp from src import config from src.Mapper import Mapper from src.Tracker import Tracker from src.utils.datasets import get_dataset from src.utils.Logger import Logger from src.utils.Mesher import Mesher from src.utils.Renderer import Renderer
20,653
# import src.fusion as fusion # import open3d as o3d torch.multiprocessing.set_sharing_strategy('file_system') class DF_Prior(): """ DF_Prior main class. Mainly allocate shared resources, and dispatch mapping and tracking process. """ def __init__(self, cfg, args): self.cfg = cfg self.args = args self.occupancy = cfg['occupancy'] self.low_gpu_mem = cfg['low_gpu_mem'] self.verbose = cfg['verbose'] self.dataset = cfg['dataset'] if args.output is None: self.output = cfg['data']['output'] else: self.output = args.output self.ckptsdir = os.path.join(self.output, 'ckpts') os.makedirs(self.output, exist_ok=True) os.makedirs(self.ckptsdir, exist_ok=True) os.makedirs(f'{self.output}/mesh', exist_ok=True) self.H, self.W, self.fx, self.fy, self.cx, self.cy = cfg['cam']['H'], cfg['cam'][ 'W'], cfg['cam']['fx'], cfg['cam']['fy'], cfg['cam']['cx'], cfg['cam']['cy'] self.update_cam() model = config.get_model(cfg) self.shared_decoders = model self.scale = cfg['scale'] self.load_bound(cfg) self.load_pretrain(cfg) self.grid_init(cfg) # need to use spawn try: mp.set_start_method('spawn', force=True) except RuntimeError: pass self.frame_reader = get_dataset(cfg, args, self.scale) self.n_img = len(self.frame_reader) self.estimate_c2w_list = torch.zeros((self.n_img, 4, 4)) self.estimate_c2w_list.share_memory_() dataset = self.cfg['data']['dataset'] scene_id = self.cfg['data']['id'] self.scene_id = scene_id print(scene_id) # load tsdf grid if dataset == 'scannet': self.tsdf_volume_shared = torch.load(f'scannet_tsdf_volume/scene{scene_id}_tsdf_volume.pt') elif dataset == 'replica': self.tsdf_volume_shared = torch.load(f'replica_tsdf_volume/{scene_id}_tsdf_volume.pt') self.tsdf_volume_shared = self.tsdf_volume_shared.to(self.cfg['mapping']['device']) self.tsdf_volume_shared.share_memory_() # load tsdf grid bound if dataset == 'scannet': self.tsdf_bnds = torch.load(f'scannet_tsdf_volume/scene{scene_id}_bounds.pt') elif dataset == 'replica': self.tsdf_bnds = torch.load(f'replica_tsdf_volume/{scene_id}_bounds.pt') self.tsdf_bnds = torch.tensor(self.tsdf_bnds).to(self.cfg['mapping']['device']) self.tsdf_bnds.share_memory_() self.vol_bnds = self.tsdf_bnds self.vol_bnds.share_memory_() self.gt_c2w_list = torch.zeros((self.n_img, 4, 4)) self.gt_c2w_list.share_memory_() self.idx = torch.zeros((1)).int() self.idx.share_memory_() self.mapping_first_frame = torch.zeros((1)).int() self.mapping_first_frame.share_memory_() # the id of the newest frame Mapper is processing self.mapping_idx = torch.zeros((1)).int() self.mapping_idx.share_memory_() self.mapping_cnt = torch.zeros((1)).int() # counter for mapping self.mapping_cnt.share_memory_() for key, val in self.shared_c.items(): val = val.to(self.cfg['mapping']['device']) val.share_memory_() self.shared_c[key] = val self.shared_decoders = self.shared_decoders.to( self.cfg['mapping']['device']) self.shared_decoders.share_memory() self.renderer = Renderer(cfg, args, self) self.mesher = Mesher(cfg, args, self) self.logger = Logger(cfg, args, self) self.mapper = Mapper(cfg, args, self)
# import src.fusion as fusion # import open3d as o3d torch.multiprocessing.set_sharing_strategy('file_system') class DF_Prior(): """ DF_Prior main class. Mainly allocate shared resources, and dispatch mapping and tracking process. """ def __init__(self, cfg, args): self.cfg = cfg self.args = args self.occupancy = cfg['occupancy'] self.low_gpu_mem = cfg['low_gpu_mem'] self.verbose = cfg['verbose'] self.dataset = cfg['dataset'] if args.output is None: self.output = cfg['data']['output'] else: self.output = args.output self.ckptsdir = os.path.join(self.output, 'ckpts') os.makedirs(self.output, exist_ok=True) os.makedirs(self.ckptsdir, exist_ok=True) os.makedirs(f'{self.output}/mesh', exist_ok=True) self.H, self.W, self.fx, self.fy, self.cx, self.cy = cfg['cam']['H'], cfg['cam'][ 'W'], cfg['cam']['fx'], cfg['cam']['fy'], cfg['cam']['cx'], cfg['cam']['cy'] self.update_cam() model = config.get_model(cfg) self.shared_decoders = model self.scale = cfg['scale'] self.load_bound(cfg) self.load_pretrain(cfg) self.grid_init(cfg) # need to use spawn try: mp.set_start_method('spawn', force=True) except RuntimeError: pass self.frame_reader = get_dataset(cfg, args, self.scale) self.n_img = len(self.frame_reader) self.estimate_c2w_list = torch.zeros((self.n_img, 4, 4)) self.estimate_c2w_list.share_memory_() dataset = self.cfg['data']['dataset'] scene_id = self.cfg['data']['id'] self.scene_id = scene_id print(scene_id) # load tsdf grid if dataset == 'scannet': self.tsdf_volume_shared = torch.load(f'scannet_tsdf_volume/scene{scene_id}_tsdf_volume.pt') elif dataset == 'replica': self.tsdf_volume_shared = torch.load(f'replica_tsdf_volume/{scene_id}_tsdf_volume.pt') self.tsdf_volume_shared = self.tsdf_volume_shared.to(self.cfg['mapping']['device']) self.tsdf_volume_shared.share_memory_() # load tsdf grid bound if dataset == 'scannet': self.tsdf_bnds = torch.load(f'scannet_tsdf_volume/scene{scene_id}_bounds.pt') elif dataset == 'replica': self.tsdf_bnds = torch.load(f'replica_tsdf_volume/{scene_id}_bounds.pt') self.tsdf_bnds = torch.tensor(self.tsdf_bnds).to(self.cfg['mapping']['device']) self.tsdf_bnds.share_memory_() self.vol_bnds = self.tsdf_bnds self.vol_bnds.share_memory_() self.gt_c2w_list = torch.zeros((self.n_img, 4, 4)) self.gt_c2w_list.share_memory_() self.idx = torch.zeros((1)).int() self.idx.share_memory_() self.mapping_first_frame = torch.zeros((1)).int() self.mapping_first_frame.share_memory_() # the id of the newest frame Mapper is processing self.mapping_idx = torch.zeros((1)).int() self.mapping_idx.share_memory_() self.mapping_cnt = torch.zeros((1)).int() # counter for mapping self.mapping_cnt.share_memory_() for key, val in self.shared_c.items(): val = val.to(self.cfg['mapping']['device']) val.share_memory_() self.shared_c[key] = val self.shared_decoders = self.shared_decoders.to( self.cfg['mapping']['device']) self.shared_decoders.share_memory() self.renderer = Renderer(cfg, args, self) self.mesher = Mesher(cfg, args, self) self.logger = Logger(cfg, args, self) self.mapper = Mapper(cfg, args, self)
self.tracker = Tracker(cfg, args, self)
2
2023-10-13 00:49:57+00:00
24k
fury-05/BookRecomendApp
.pythonlibs/lib/python3.10/site-packages/sklearn/feature_extraction/image.py
[ { "identifier": "BaseEstimator", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "class BaseEstimator(_MetadataRequester):\n \"\"\"Base class for all estimators in scikit-learn.\n\n Notes\n -----\n All estimators should specify all the parameters that can be set\n at the class level in their ``__init__`` as explicit keyword\n arguments (no ``*args`` or ``**kwargs``).\n \"\"\"\n\n @classmethod\n def _get_param_names(cls):\n \"\"\"Get parameter names for the estimator\"\"\"\n # fetch the constructor or the original constructor before\n # deprecation wrapping if any\n init = getattr(cls.__init__, \"deprecated_original\", cls.__init__)\n if init is object.__init__:\n # No explicit constructor to introspect\n return []\n\n # introspect the constructor arguments to find the model parameters\n # to represent\n init_signature = inspect.signature(init)\n # Consider the constructor parameters excluding 'self'\n parameters = [\n p\n for p in init_signature.parameters.values()\n if p.name != \"self\" and p.kind != p.VAR_KEYWORD\n ]\n for p in parameters:\n if p.kind == p.VAR_POSITIONAL:\n raise RuntimeError(\n \"scikit-learn estimators should always \"\n \"specify their parameters in the signature\"\n \" of their __init__ (no varargs).\"\n \" %s with constructor %s doesn't \"\n \" follow this convention.\" % (cls, init_signature)\n )\n # Extract and sort argument names excluding 'self'\n return sorted([p.name for p in parameters])\n\n def get_params(self, deep=True):\n \"\"\"\n Get parameters for this estimator.\n\n Parameters\n ----------\n deep : bool, default=True\n If True, will return the parameters for this estimator and\n contained subobjects that are estimators.\n\n Returns\n -------\n params : dict\n Parameter names mapped to their values.\n \"\"\"\n out = dict()\n for key in self._get_param_names():\n value = getattr(self, key)\n if deep and hasattr(value, \"get_params\") and not isinstance(value, type):\n deep_items = value.get_params().items()\n out.update((key + \"__\" + k, val) for k, val in deep_items)\n out[key] = value\n return out\n\n def set_params(self, **params):\n \"\"\"Set the parameters of this estimator.\n\n The method works on simple estimators as well as on nested objects\n (such as :class:`~sklearn.pipeline.Pipeline`). The latter have\n parameters of the form ``<component>__<parameter>`` so that it's\n possible to update each component of a nested object.\n\n Parameters\n ----------\n **params : dict\n Estimator parameters.\n\n Returns\n -------\n self : estimator instance\n Estimator instance.\n \"\"\"\n if not params:\n # Simple optimization to gain speed (inspect is slow)\n return self\n valid_params = self.get_params(deep=True)\n\n nested_params = defaultdict(dict) # grouped by prefix\n for key, value in params.items():\n key, delim, sub_key = key.partition(\"__\")\n if key not in valid_params:\n local_valid_params = self._get_param_names()\n raise ValueError(\n f\"Invalid parameter {key!r} for estimator {self}. \"\n f\"Valid parameters are: {local_valid_params!r}.\"\n )\n\n if delim:\n nested_params[key][sub_key] = value\n else:\n setattr(self, key, value)\n valid_params[key] = value\n\n for key, sub_params in nested_params.items():\n # TODO(1.4): remove specific handling of \"base_estimator\".\n # The \"base_estimator\" key is special. It was deprecated and\n # renamed to \"estimator\" for several estimators. This means we\n # need to translate it here and set sub-parameters on \"estimator\",\n # but only if the user did not explicitly set a value for\n # \"base_estimator\".\n if (\n key == \"base_estimator\"\n and valid_params[key] == \"deprecated\"\n and self.__module__.startswith(\"sklearn.\")\n ):\n warnings.warn(\n (\n f\"Parameter 'base_estimator' of {self.__class__.__name__} is\"\n \" deprecated in favor of 'estimator'. See\"\n f\" {self.__class__.__name__}'s docstring for more details.\"\n ),\n FutureWarning,\n stacklevel=2,\n )\n key = \"estimator\"\n valid_params[key].set_params(**sub_params)\n\n return self\n\n def __sklearn_clone__(self):\n return _clone_parametrized(self)\n\n def __repr__(self, N_CHAR_MAX=700):\n # N_CHAR_MAX is the (approximate) maximum number of non-blank\n # characters to render. We pass it as an optional parameter to ease\n # the tests.\n\n from .utils._pprint import _EstimatorPrettyPrinter\n\n N_MAX_ELEMENTS_TO_SHOW = 30 # number of elements to show in sequences\n\n # use ellipsis for sequences with a lot of elements\n pp = _EstimatorPrettyPrinter(\n compact=True,\n indent=1,\n indent_at_name=True,\n n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW,\n )\n\n repr_ = pp.pformat(self)\n\n # Use bruteforce ellipsis when there are a lot of non-blank characters\n n_nonblank = len(\"\".join(repr_.split()))\n if n_nonblank > N_CHAR_MAX:\n lim = N_CHAR_MAX // 2 # apprx number of chars to keep on both ends\n regex = r\"^(\\s*\\S){%d}\" % lim\n # The regex '^(\\s*\\S){%d}' % n\n # matches from the start of the string until the nth non-blank\n # character:\n # - ^ matches the start of string\n # - (pattern){n} matches n repetitions of pattern\n # - \\s*\\S matches a non-blank char following zero or more blanks\n left_lim = re.match(regex, repr_).end()\n right_lim = re.match(regex, repr_[::-1]).end()\n\n if \"\\n\" in repr_[left_lim:-right_lim]:\n # The left side and right side aren't on the same line.\n # To avoid weird cuts, e.g.:\n # categoric...ore',\n # we need to start the right side with an appropriate newline\n # character so that it renders properly as:\n # categoric...\n # handle_unknown='ignore',\n # so we add [^\\n]*\\n which matches until the next \\n\n regex += r\"[^\\n]*\\n\"\n right_lim = re.match(regex, repr_[::-1]).end()\n\n ellipsis = \"...\"\n if left_lim + len(ellipsis) < len(repr_) - right_lim:\n # Only add ellipsis if it results in a shorter repr\n repr_ = repr_[:left_lim] + \"...\" + repr_[-right_lim:]\n\n return repr_\n\n def __getstate__(self):\n if getattr(self, \"__slots__\", None):\n raise TypeError(\n \"You cannot use `__slots__` in objects inheriting from \"\n \"`sklearn.base.BaseEstimator`.\"\n )\n\n try:\n state = super().__getstate__()\n if state is None:\n # For Python 3.11+, empty instance (no `__slots__`,\n # and `__dict__`) will return a state equal to `None`.\n state = self.__dict__.copy()\n except AttributeError:\n # Python < 3.11\n state = self.__dict__.copy()\n\n if type(self).__module__.startswith(\"sklearn.\"):\n return dict(state.items(), _sklearn_version=__version__)\n else:\n return state\n\n def __setstate__(self, state):\n if type(self).__module__.startswith(\"sklearn.\"):\n pickle_version = state.pop(\"_sklearn_version\", \"pre-0.18\")\n if pickle_version != __version__:\n warnings.warn(\n InconsistentVersionWarning(\n estimator_name=self.__class__.__name__,\n current_sklearn_version=__version__,\n original_sklearn_version=pickle_version,\n ),\n )\n try:\n super().__setstate__(state)\n except AttributeError:\n self.__dict__.update(state)\n\n def _more_tags(self):\n return _DEFAULT_TAGS\n\n def _get_tags(self):\n collected_tags = {}\n for base_class in reversed(inspect.getmro(self.__class__)):\n if hasattr(base_class, \"_more_tags\"):\n # need the if because mixins might not have _more_tags\n # but might do redundant work in estimators\n # (i.e. calling more tags on BaseEstimator multiple times)\n more_tags = base_class._more_tags(self)\n collected_tags.update(more_tags)\n return collected_tags\n\n def _check_n_features(self, X, reset):\n \"\"\"Set the `n_features_in_` attribute, or check against it.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n reset : bool\n If True, the `n_features_in_` attribute is set to `X.shape[1]`.\n If False and the attribute exists, then check that it is equal to\n `X.shape[1]`. If False and the attribute does *not* exist, then\n the check is skipped.\n .. note::\n It is recommended to call reset=True in `fit` and in the first\n call to `partial_fit`. All other methods that validate `X`\n should set `reset=False`.\n \"\"\"\n try:\n n_features = _num_features(X)\n except TypeError as e:\n if not reset and hasattr(self, \"n_features_in_\"):\n raise ValueError(\n \"X does not contain any features, but \"\n f\"{self.__class__.__name__} is expecting \"\n f\"{self.n_features_in_} features\"\n ) from e\n # If the number of features is not defined and reset=True,\n # then we skip this check\n return\n\n if reset:\n self.n_features_in_ = n_features\n return\n\n if not hasattr(self, \"n_features_in_\"):\n # Skip this check if the expected number of expected input features\n # was not recorded by calling fit first. This is typically the case\n # for stateless transformers.\n return\n\n if n_features != self.n_features_in_:\n raise ValueError(\n f\"X has {n_features} features, but {self.__class__.__name__} \"\n f\"is expecting {self.n_features_in_} features as input.\"\n )\n\n def _check_feature_names(self, X, *, reset):\n \"\"\"Set or check the `feature_names_in_` attribute.\n\n .. versionadded:: 1.0\n\n Parameters\n ----------\n X : {ndarray, dataframe} of shape (n_samples, n_features)\n The input samples.\n\n reset : bool\n Whether to reset the `feature_names_in_` attribute.\n If False, the input will be checked for consistency with\n feature names of data provided when reset was last True.\n .. note::\n It is recommended to call `reset=True` in `fit` and in the first\n call to `partial_fit`. All other methods that validate `X`\n should set `reset=False`.\n \"\"\"\n\n if reset:\n feature_names_in = _get_feature_names(X)\n if feature_names_in is not None:\n self.feature_names_in_ = feature_names_in\n elif hasattr(self, \"feature_names_in_\"):\n # Delete the attribute when the estimator is fitted on a new dataset\n # that has no feature names.\n delattr(self, \"feature_names_in_\")\n return\n\n fitted_feature_names = getattr(self, \"feature_names_in_\", None)\n X_feature_names = _get_feature_names(X)\n\n if fitted_feature_names is None and X_feature_names is None:\n # no feature names seen in fit and in X\n return\n\n if X_feature_names is not None and fitted_feature_names is None:\n warnings.warn(\n f\"X has feature names, but {self.__class__.__name__} was fitted without\"\n \" feature names\"\n )\n return\n\n if X_feature_names is None and fitted_feature_names is not None:\n warnings.warn(\n \"X does not have valid feature names, but\"\n f\" {self.__class__.__name__} was fitted with feature names\"\n )\n return\n\n # validate the feature names against the `feature_names_in_` attribute\n if len(fitted_feature_names) != len(X_feature_names) or np.any(\n fitted_feature_names != X_feature_names\n ):\n message = (\n \"The feature names should match those that were passed during fit.\\n\"\n )\n fitted_feature_names_set = set(fitted_feature_names)\n X_feature_names_set = set(X_feature_names)\n\n unexpected_names = sorted(X_feature_names_set - fitted_feature_names_set)\n missing_names = sorted(fitted_feature_names_set - X_feature_names_set)\n\n def add_names(names):\n output = \"\"\n max_n_names = 5\n for i, name in enumerate(names):\n if i >= max_n_names:\n output += \"- ...\\n\"\n break\n output += f\"- {name}\\n\"\n return output\n\n if unexpected_names:\n message += \"Feature names unseen at fit time:\\n\"\n message += add_names(unexpected_names)\n\n if missing_names:\n message += \"Feature names seen at fit time, yet now missing:\\n\"\n message += add_names(missing_names)\n\n if not missing_names and not unexpected_names:\n message += (\n \"Feature names must be in the same order as they were in fit.\\n\"\n )\n\n raise ValueError(message)\n\n def _validate_data(\n self,\n X=\"no_validation\",\n y=\"no_validation\",\n reset=True,\n validate_separately=False,\n cast_to_ndarray=True,\n **check_params,\n ):\n \"\"\"Validate input data and set or check the `n_features_in_` attribute.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features), default='no validation'\n The input samples.\n If `'no_validation'`, no validation is performed on `X`. This is\n useful for meta-estimator which can delegate input validation to\n their underlying estimator(s). In that case `y` must be passed and\n the only accepted `check_params` are `multi_output` and\n `y_numeric`.\n\n y : array-like of shape (n_samples,), default='no_validation'\n The targets.\n\n - If `None`, `check_array` is called on `X`. If the estimator's\n requires_y tag is True, then an error will be raised.\n - If `'no_validation'`, `check_array` is called on `X` and the\n estimator's requires_y tag is ignored. This is a default\n placeholder and is never meant to be explicitly set. In that case\n `X` must be passed.\n - Otherwise, only `y` with `_check_y` or both `X` and `y` are\n checked with either `check_array` or `check_X_y` depending on\n `validate_separately`.\n\n reset : bool, default=True\n Whether to reset the `n_features_in_` attribute.\n If False, the input will be checked for consistency with data\n provided when reset was last True.\n .. note::\n It is recommended to call reset=True in `fit` and in the first\n call to `partial_fit`. All other methods that validate `X`\n should set `reset=False`.\n\n validate_separately : False or tuple of dicts, default=False\n Only used if y is not None.\n If False, call validate_X_y(). Else, it must be a tuple of kwargs\n to be used for calling check_array() on X and y respectively.\n\n `estimator=self` is automatically added to these dicts to generate\n more informative error message in case of invalid input data.\n\n cast_to_ndarray : bool, default=True\n Cast `X` and `y` to ndarray with checks in `check_params`. If\n `False`, `X` and `y` are unchanged and only `feature_names_in_` and\n `n_features_in_` are checked.\n\n **check_params : kwargs\n Parameters passed to :func:`sklearn.utils.check_array` or\n :func:`sklearn.utils.check_X_y`. Ignored if validate_separately\n is not False.\n\n `estimator=self` is automatically added to these params to generate\n more informative error message in case of invalid input data.\n\n Returns\n -------\n out : {ndarray, sparse matrix} or tuple of these\n The validated input. A tuple is returned if both `X` and `y` are\n validated.\n \"\"\"\n self._check_feature_names(X, reset=reset)\n\n if y is None and self._get_tags()[\"requires_y\"]:\n raise ValueError(\n f\"This {self.__class__.__name__} estimator \"\n \"requires y to be passed, but the target y is None.\"\n )\n\n no_val_X = isinstance(X, str) and X == \"no_validation\"\n no_val_y = y is None or isinstance(y, str) and y == \"no_validation\"\n\n if no_val_X and no_val_y:\n raise ValueError(\"Validation should be done on X, y or both.\")\n\n default_check_params = {\"estimator\": self}\n check_params = {**default_check_params, **check_params}\n\n if not cast_to_ndarray:\n if not no_val_X and no_val_y:\n out = X\n elif no_val_X and not no_val_y:\n out = y\n else:\n out = X, y\n elif not no_val_X and no_val_y:\n out = check_array(X, input_name=\"X\", **check_params)\n elif no_val_X and not no_val_y:\n out = _check_y(y, **check_params)\n else:\n if validate_separately:\n # We need this because some estimators validate X and y\n # separately, and in general, separately calling check_array()\n # on X and y isn't equivalent to just calling check_X_y()\n # :(\n check_X_params, check_y_params = validate_separately\n if \"estimator\" not in check_X_params:\n check_X_params = {**default_check_params, **check_X_params}\n X = check_array(X, input_name=\"X\", **check_X_params)\n if \"estimator\" not in check_y_params:\n check_y_params = {**default_check_params, **check_y_params}\n y = check_array(y, input_name=\"y\", **check_y_params)\n else:\n X, y = check_X_y(X, y, **check_params)\n out = X, y\n\n if not no_val_X and check_params.get(\"ensure_2d\", True):\n self._check_n_features(X, reset=reset)\n\n return out\n\n def _validate_params(self):\n \"\"\"Validate types and values of constructor parameters\n\n The expected type and values must be defined in the `_parameter_constraints`\n class attribute, which is a dictionary `param_name: list of constraints`. See\n the docstring of `validate_parameter_constraints` for a description of the\n accepted constraints.\n \"\"\"\n validate_parameter_constraints(\n self._parameter_constraints,\n self.get_params(deep=False),\n caller_name=self.__class__.__name__,\n )\n\n @property\n def _repr_html_(self):\n \"\"\"HTML representation of estimator.\n\n This is redundant with the logic of `_repr_mimebundle_`. The latter\n should be favorted in the long term, `_repr_html_` is only\n implemented for consumers who do not interpret `_repr_mimbundle_`.\n \"\"\"\n if get_config()[\"display\"] != \"diagram\":\n raise AttributeError(\n \"_repr_html_ is only defined when the \"\n \"'display' configuration option is set to \"\n \"'diagram'\"\n )\n return self._repr_html_inner\n\n def _repr_html_inner(self):\n \"\"\"This function is returned by the @property `_repr_html_` to make\n `hasattr(estimator, \"_repr_html_\") return `True` or `False` depending\n on `get_config()[\"display\"]`.\n \"\"\"\n return estimator_html_repr(self)\n\n def _repr_mimebundle_(self, **kwargs):\n \"\"\"Mime bundle used by jupyter kernels to display estimator\"\"\"\n output = {\"text/plain\": repr(self)}\n if get_config()[\"display\"] == \"diagram\":\n output[\"text/html\"] = estimator_html_repr(self)\n return output" }, { "identifier": "TransformerMixin", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "class TransformerMixin(_SetOutputMixin):\n \"\"\"Mixin class for all transformers in scikit-learn.\n\n If :term:`get_feature_names_out` is defined, then :class:`BaseEstimator` will\n automatically wrap `transform` and `fit_transform` to follow the `set_output`\n API. See the :ref:`developer_api_set_output` for details.\n\n :class:`OneToOneFeatureMixin` and\n :class:`ClassNamePrefixFeaturesOutMixin` are helpful mixins for\n defining :term:`get_feature_names_out`.\n \"\"\"\n\n def fit_transform(self, X, y=None, **fit_params):\n \"\"\"\n Fit to data, then transform it.\n\n Fits transformer to `X` and `y` with optional parameters `fit_params`\n and returns a transformed version of `X`.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input samples.\n\n y : array-like of shape (n_samples,) or (n_samples, n_outputs), \\\n default=None\n Target values (None for unsupervised transformations).\n\n **fit_params : dict\n Additional fit parameters.\n\n Returns\n -------\n X_new : ndarray array of shape (n_samples, n_features_new)\n Transformed array.\n \"\"\"\n # non-optimized default implementation; override when a better\n # method is possible for a given clustering algorithm\n if y is None:\n # fit method of arity 1 (unsupervised transformation)\n return self.fit(X, **fit_params).transform(X)\n else:\n # fit method of arity 2 (supervised transformation)\n return self.fit(X, y, **fit_params).transform(X)" }, { "identifier": "_fit_context", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "def _fit_context(*, prefer_skip_nested_validation):\n \"\"\"Decorator to run the fit methods of estimators within context managers.\n\n Parameters\n ----------\n prefer_skip_nested_validation : bool\n If True, the validation of parameters of inner estimators or functions\n called during fit will be skipped.\n\n This is useful to avoid validating many times the parameters passed by the\n user from the public facing API. It's also useful to avoid validating\n parameters that we pass internally to inner functions that are guaranteed to\n be valid by the test suite.\n\n It should be set to True for most estimators, except for those that receive\n non-validated objects as parameters, such as meta-estimators that are given\n estimator objects.\n\n Returns\n -------\n decorated_fit : method\n The decorated fit method.\n \"\"\"\n\n def decorator(fit_method):\n @functools.wraps(fit_method)\n def wrapper(estimator, *args, **kwargs):\n global_skip_validation = get_config()[\"skip_parameter_validation\"]\n\n # we don't want to validate again for each call to partial_fit\n partial_fit_and_fitted = (\n fit_method.__name__ == \"partial_fit\" and _is_fitted(estimator)\n )\n\n if not global_skip_validation and not partial_fit_and_fitted:\n estimator._validate_params()\n\n with config_context(\n skip_parameter_validation=(\n prefer_skip_nested_validation or global_skip_validation\n )\n ):\n return fit_method(estimator, *args, **kwargs)\n\n return wrapper\n\n return decorator" }, { "identifier": "check_array", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "def check_array(\n array,\n accept_sparse=False,\n *,\n accept_large_sparse=True,\n dtype=\"numeric\",\n order=None,\n copy=False,\n force_all_finite=True,\n ensure_2d=True,\n allow_nd=False,\n ensure_min_samples=1,\n ensure_min_features=1,\n estimator=None,\n input_name=\"\",\n):\n \"\"\"Input validation on an array, list, sparse matrix or similar.\n\n By default, the input is checked to be a non-empty 2D array containing\n only finite values. If the dtype of the array is object, attempt\n converting to float, raising on failure.\n\n Parameters\n ----------\n array : object\n Input object to check / convert.\n\n accept_sparse : str, bool or list/tuple of str, default=False\n String[s] representing allowed sparse matrix formats, such as 'csc',\n 'csr', etc. If the input is sparse but not in the allowed format,\n it will be converted to the first listed format. True allows the input\n to be any format. False means that a sparse matrix input will\n raise an error.\n\n accept_large_sparse : bool, default=True\n If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by\n accept_sparse, accept_large_sparse=False will cause it to be accepted\n only if its indices are stored with a 32-bit dtype.\n\n .. versionadded:: 0.20\n\n dtype : 'numeric', type, list of type or None, default='numeric'\n Data type of result. If None, the dtype of the input is preserved.\n If \"numeric\", dtype is preserved unless array.dtype is object.\n If dtype is a list of types, conversion on the first type is only\n performed if the dtype of the input is not in the list.\n\n order : {'F', 'C'} or None, default=None\n Whether an array will be forced to be fortran or c-style.\n When order is None (default), then if copy=False, nothing is ensured\n about the memory layout of the output array; otherwise (copy=True)\n the memory layout of the returned array is kept as close as possible\n to the original array.\n\n copy : bool, default=False\n Whether a forced copy will be triggered. If copy=False, a copy might\n be triggered by a conversion.\n\n force_all_finite : bool or 'allow-nan', default=True\n Whether to raise an error on np.inf, np.nan, pd.NA in array. The\n possibilities are:\n\n - True: Force all values of array to be finite.\n - False: accepts np.inf, np.nan, pd.NA in array.\n - 'allow-nan': accepts only np.nan and pd.NA values in array. Values\n cannot be infinite.\n\n .. versionadded:: 0.20\n ``force_all_finite`` accepts the string ``'allow-nan'``.\n\n .. versionchanged:: 0.23\n Accepts `pd.NA` and converts it into `np.nan`\n\n ensure_2d : bool, default=True\n Whether to raise a value error if array is not 2D.\n\n allow_nd : bool, default=False\n Whether to allow array.ndim > 2.\n\n ensure_min_samples : int, default=1\n Make sure that the array has a minimum number of samples in its first\n axis (rows for a 2D array). Setting to 0 disables this check.\n\n ensure_min_features : int, default=1\n Make sure that the 2D array has some minimum number of features\n (columns). The default value of 1 rejects empty datasets.\n This check is only enforced when the input data has effectively 2\n dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0\n disables this check.\n\n estimator : str or estimator instance, default=None\n If passed, include the name of the estimator in warning messages.\n\n input_name : str, default=\"\"\n The data name used to construct the error message. In particular\n if `input_name` is \"X\" and the data has NaN values and\n allow_nan is False, the error message will link to the imputer\n documentation.\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n array_converted : object\n The converted and validated array.\n \"\"\"\n if isinstance(array, np.matrix):\n raise TypeError(\n \"np.matrix is not supported. Please convert to a numpy array with \"\n \"np.asarray. For more information see: \"\n \"https://numpy.org/doc/stable/reference/generated/numpy.matrix.html\"\n )\n\n xp, is_array_api_compliant = get_namespace(array)\n\n # store reference to original array to check if copy is needed when\n # function returns\n array_orig = array\n\n # store whether originally we wanted numeric dtype\n dtype_numeric = isinstance(dtype, str) and dtype == \"numeric\"\n\n dtype_orig = getattr(array, \"dtype\", None)\n if not is_array_api_compliant and not hasattr(dtype_orig, \"kind\"):\n # not a data type (e.g. a column named dtype in a pandas DataFrame)\n dtype_orig = None\n\n # check if the object contains several dtypes (typically a pandas\n # DataFrame), and store them. If not, store None.\n dtypes_orig = None\n pandas_requires_conversion = False\n if hasattr(array, \"dtypes\") and hasattr(array.dtypes, \"__array__\"):\n # throw warning if columns are sparse. If all columns are sparse, then\n # array.sparse exists and sparsity will be preserved (later).\n with suppress(ImportError):\n from pandas import SparseDtype\n\n def is_sparse(dtype):\n return isinstance(dtype, SparseDtype)\n\n if not hasattr(array, \"sparse\") and array.dtypes.apply(is_sparse).any():\n warnings.warn(\n \"pandas.DataFrame with sparse columns found.\"\n \"It will be converted to a dense numpy array.\"\n )\n\n dtypes_orig = list(array.dtypes)\n pandas_requires_conversion = any(\n _pandas_dtype_needs_early_conversion(i) for i in dtypes_orig\n )\n if all(isinstance(dtype_iter, np.dtype) for dtype_iter in dtypes_orig):\n dtype_orig = np.result_type(*dtypes_orig)\n elif pandas_requires_conversion and any(d == object for d in dtypes_orig):\n # Force object if any of the dtypes is an object\n dtype_orig = object\n\n elif (_is_extension_array_dtype(array) or hasattr(array, \"iloc\")) and hasattr(\n array, \"dtype\"\n ):\n # array is a pandas series\n pandas_requires_conversion = _pandas_dtype_needs_early_conversion(array.dtype)\n if isinstance(array.dtype, np.dtype):\n dtype_orig = array.dtype\n else:\n # Set to None to let array.astype work out the best dtype\n dtype_orig = None\n\n if dtype_numeric:\n if (\n dtype_orig is not None\n and hasattr(dtype_orig, \"kind\")\n and dtype_orig.kind == \"O\"\n ):\n # if input is object, convert to float.\n dtype = xp.float64\n else:\n dtype = None\n\n if isinstance(dtype, (list, tuple)):\n if dtype_orig is not None and dtype_orig in dtype:\n # no dtype conversion required\n dtype = None\n else:\n # dtype conversion required. Let's select the first element of the\n # list of accepted types.\n dtype = dtype[0]\n\n if pandas_requires_conversion:\n # pandas dataframe requires conversion earlier to handle extension dtypes with\n # nans\n # Use the original dtype for conversion if dtype is None\n new_dtype = dtype_orig if dtype is None else dtype\n array = array.astype(new_dtype)\n # Since we converted here, we do not need to convert again later\n dtype = None\n\n if dtype is not None and _is_numpy_namespace(xp):\n dtype = np.dtype(dtype)\n\n if force_all_finite not in (True, False, \"allow-nan\"):\n raise ValueError(\n 'force_all_finite should be a bool or \"allow-nan\". Got {!r} instead'.format(\n force_all_finite\n )\n )\n\n if dtype is not None and _is_numpy_namespace(xp):\n # convert to dtype object to conform to Array API to be use `xp.isdtype` later\n dtype = np.dtype(dtype)\n\n estimator_name = _check_estimator_name(estimator)\n context = \" by %s\" % estimator_name if estimator is not None else \"\"\n\n # When all dataframe columns are sparse, convert to a sparse array\n if hasattr(array, \"sparse\") and array.ndim > 1:\n with suppress(ImportError):\n from pandas import SparseDtype # noqa: F811\n\n def is_sparse(dtype):\n return isinstance(dtype, SparseDtype)\n\n if array.dtypes.apply(is_sparse).all():\n # DataFrame.sparse only supports `to_coo`\n array = array.sparse.to_coo()\n if array.dtype == np.dtype(\"object\"):\n unique_dtypes = set([dt.subtype.name for dt in array_orig.dtypes])\n if len(unique_dtypes) > 1:\n raise ValueError(\n \"Pandas DataFrame with mixed sparse extension arrays \"\n \"generated a sparse matrix with object dtype which \"\n \"can not be converted to a scipy sparse matrix.\"\n \"Sparse extension arrays should all have the same \"\n \"numeric type.\"\n )\n\n if sp.issparse(array):\n _ensure_no_complex_data(array)\n array = _ensure_sparse_format(\n array,\n accept_sparse=accept_sparse,\n dtype=dtype,\n copy=copy,\n force_all_finite=force_all_finite,\n accept_large_sparse=accept_large_sparse,\n estimator_name=estimator_name,\n input_name=input_name,\n )\n else:\n # If np.array(..) gives ComplexWarning, then we convert the warning\n # to an error. This is needed because specifying a non complex\n # dtype to the function converts complex to real dtype,\n # thereby passing the test made in the lines following the scope\n # of warnings context manager.\n with warnings.catch_warnings():\n try:\n warnings.simplefilter(\"error\", ComplexWarning)\n if dtype is not None and xp.isdtype(dtype, \"integral\"):\n # Conversion float -> int should not contain NaN or\n # inf (numpy#14412). We cannot use casting='safe' because\n # then conversion float -> int would be disallowed.\n array = _asarray_with_order(array, order=order, xp=xp)\n if xp.isdtype(array.dtype, (\"real floating\", \"complex floating\")):\n _assert_all_finite(\n array,\n allow_nan=False,\n msg_dtype=dtype,\n estimator_name=estimator_name,\n input_name=input_name,\n )\n array = xp.astype(array, dtype, copy=False)\n else:\n array = _asarray_with_order(array, order=order, dtype=dtype, xp=xp)\n except ComplexWarning as complex_warning:\n raise ValueError(\n \"Complex data not supported\\n{}\\n\".format(array)\n ) from complex_warning\n\n # It is possible that the np.array(..) gave no warning. This happens\n # when no dtype conversion happened, for example dtype = None. The\n # result is that np.array(..) produces an array of complex dtype\n # and we need to catch and raise exception for such cases.\n _ensure_no_complex_data(array)\n\n if ensure_2d:\n # If input is scalar raise error\n if array.ndim == 0:\n raise ValueError(\n \"Expected 2D array, got scalar array instead:\\narray={}.\\n\"\n \"Reshape your data either using array.reshape(-1, 1) if \"\n \"your data has a single feature or array.reshape(1, -1) \"\n \"if it contains a single sample.\".format(array)\n )\n # If input is 1D raise error\n if array.ndim == 1:\n raise ValueError(\n \"Expected 2D array, got 1D array instead:\\narray={}.\\n\"\n \"Reshape your data either using array.reshape(-1, 1) if \"\n \"your data has a single feature or array.reshape(1, -1) \"\n \"if it contains a single sample.\".format(array)\n )\n\n if dtype_numeric and hasattr(array.dtype, \"kind\") and array.dtype.kind in \"USV\":\n raise ValueError(\n \"dtype='numeric' is not compatible with arrays of bytes/strings.\"\n \"Convert your data to numeric values explicitly instead.\"\n )\n if not allow_nd and array.ndim >= 3:\n raise ValueError(\n \"Found array with dim %d. %s expected <= 2.\"\n % (array.ndim, estimator_name)\n )\n\n if force_all_finite:\n _assert_all_finite(\n array,\n input_name=input_name,\n estimator_name=estimator_name,\n allow_nan=force_all_finite == \"allow-nan\",\n )\n\n if ensure_min_samples > 0:\n n_samples = _num_samples(array)\n if n_samples < ensure_min_samples:\n raise ValueError(\n \"Found array with %d sample(s) (shape=%s) while a\"\n \" minimum of %d is required%s.\"\n % (n_samples, array.shape, ensure_min_samples, context)\n )\n\n if ensure_min_features > 0 and array.ndim == 2:\n n_features = array.shape[1]\n if n_features < ensure_min_features:\n raise ValueError(\n \"Found array with %d feature(s) (shape=%s) while\"\n \" a minimum of %d is required%s.\"\n % (n_features, array.shape, ensure_min_features, context)\n )\n\n if copy:\n if _is_numpy_namespace(xp):\n # only make a copy if `array` and `array_orig` may share memory`\n if np.may_share_memory(array, array_orig):\n array = _asarray_with_order(\n array, dtype=dtype, order=order, copy=True, xp=xp\n )\n else:\n # always make a copy for non-numpy arrays\n array = _asarray_with_order(\n array, dtype=dtype, order=order, copy=True, xp=xp\n )\n\n return array" }, { "identifier": "check_random_state", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "def check_random_state(seed):\n \"\"\"Turn seed into a np.random.RandomState instance.\n\n Parameters\n ----------\n seed : None, int or instance of RandomState\n If seed is None, return the RandomState singleton used by np.random.\n If seed is an int, return a new RandomState instance seeded with seed.\n If seed is already a RandomState instance, return it.\n Otherwise raise ValueError.\n\n Returns\n -------\n :class:`numpy:numpy.random.RandomState`\n The random state object based on `seed` parameter.\n \"\"\"\n if seed is None or seed is np.random:\n return np.random.mtrand._rand\n if isinstance(seed, numbers.Integral):\n return np.random.RandomState(seed)\n if isinstance(seed, np.random.RandomState):\n return seed\n raise ValueError(\n \"%r cannot be used to seed a numpy.random.RandomState instance\" % seed\n )" }, { "identifier": "Hidden", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/_param_validation.py", "snippet": "class Hidden:\n \"\"\"Class encapsulating a constraint not meant to be exposed to the user.\n\n Parameters\n ----------\n constraint : str or _Constraint instance\n The constraint to be used internally.\n \"\"\"\n\n def __init__(self, constraint):\n self.constraint = constraint" }, { "identifier": "Interval", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/_param_validation.py", "snippet": "class Interval(_Constraint):\n \"\"\"Constraint representing a typed interval.\n\n Parameters\n ----------\n type : {numbers.Integral, numbers.Real, RealNotInt}\n The set of numbers in which to set the interval.\n\n If RealNotInt, only reals that don't have the integer type\n are allowed. For example 1.0 is allowed but 1 is not.\n\n left : float or int or None\n The left bound of the interval. None means left bound is -∞.\n\n right : float, int or None\n The right bound of the interval. None means right bound is +∞.\n\n closed : {\"left\", \"right\", \"both\", \"neither\"}\n Whether the interval is open or closed. Possible choices are:\n\n - `\"left\"`: the interval is closed on the left and open on the right.\n It is equivalent to the interval `[ left, right )`.\n - `\"right\"`: the interval is closed on the right and open on the left.\n It is equivalent to the interval `( left, right ]`.\n - `\"both\"`: the interval is closed.\n It is equivalent to the interval `[ left, right ]`.\n - `\"neither\"`: the interval is open.\n It is equivalent to the interval `( left, right )`.\n\n Notes\n -----\n Setting a bound to `None` and setting the interval closed is valid. For instance,\n strictly speaking, `Interval(Real, 0, None, closed=\"both\")` corresponds to\n `[0, +∞) U {+∞}`.\n \"\"\"\n\n def __init__(self, type, left, right, *, closed):\n super().__init__()\n self.type = type\n self.left = left\n self.right = right\n self.closed = closed\n\n self._check_params()\n\n def _check_params(self):\n if self.type not in (Integral, Real, RealNotInt):\n raise ValueError(\n \"type must be either numbers.Integral, numbers.Real or RealNotInt.\"\n f\" Got {self.type} instead.\"\n )\n\n if self.closed not in (\"left\", \"right\", \"both\", \"neither\"):\n raise ValueError(\n \"closed must be either 'left', 'right', 'both' or 'neither'. \"\n f\"Got {self.closed} instead.\"\n )\n\n if self.type is Integral:\n suffix = \"for an interval over the integers.\"\n if self.left is not None and not isinstance(self.left, Integral):\n raise TypeError(f\"Expecting left to be an int {suffix}\")\n if self.right is not None and not isinstance(self.right, Integral):\n raise TypeError(f\"Expecting right to be an int {suffix}\")\n if self.left is None and self.closed in (\"left\", \"both\"):\n raise ValueError(\n f\"left can't be None when closed == {self.closed} {suffix}\"\n )\n if self.right is None and self.closed in (\"right\", \"both\"):\n raise ValueError(\n f\"right can't be None when closed == {self.closed} {suffix}\"\n )\n else:\n if self.left is not None and not isinstance(self.left, Real):\n raise TypeError(\"Expecting left to be a real number.\")\n if self.right is not None and not isinstance(self.right, Real):\n raise TypeError(\"Expecting right to be a real number.\")\n\n if self.right is not None and self.left is not None and self.right <= self.left:\n raise ValueError(\n f\"right can't be less than left. Got left={self.left} and \"\n f\"right={self.right}\"\n )\n\n def __contains__(self, val):\n if np.isnan(val):\n return False\n\n left_cmp = operator.lt if self.closed in (\"left\", \"both\") else operator.le\n right_cmp = operator.gt if self.closed in (\"right\", \"both\") else operator.ge\n\n left = -np.inf if self.left is None else self.left\n right = np.inf if self.right is None else self.right\n\n if left_cmp(val, left):\n return False\n if right_cmp(val, right):\n return False\n return True\n\n def is_satisfied_by(self, val):\n if not isinstance(val, self.type):\n return False\n\n return val in self\n\n def __str__(self):\n type_str = \"an int\" if self.type is Integral else \"a float\"\n left_bracket = \"[\" if self.closed in (\"left\", \"both\") else \"(\"\n left_bound = \"-inf\" if self.left is None else self.left\n right_bound = \"inf\" if self.right is None else self.right\n right_bracket = \"]\" if self.closed in (\"right\", \"both\") else \")\"\n\n # better repr if the bounds were given as integers\n if not self.type == Integral and isinstance(self.left, Real):\n left_bound = float(left_bound)\n if not self.type == Integral and isinstance(self.right, Real):\n right_bound = float(right_bound)\n\n return (\n f\"{type_str} in the range \"\n f\"{left_bracket}{left_bound}, {right_bound}{right_bracket}\"\n )" }, { "identifier": "RealNotInt", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/_param_validation.py", "snippet": "class RealNotInt(Real):\n \"\"\"A type that represents reals that are not instances of int.\n\n Behaves like float, but also works with values extracted from numpy arrays.\n isintance(1, RealNotInt) -> False\n isinstance(1.0, RealNotInt) -> True\n \"\"\"" }, { "identifier": "validate_params", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/_param_validation.py", "snippet": "def validate_params(parameter_constraints, *, prefer_skip_nested_validation):\n \"\"\"Decorator to validate types and values of functions and methods.\n\n Parameters\n ----------\n parameter_constraints : dict\n A dictionary `param_name: list of constraints`. See the docstring of\n `validate_parameter_constraints` for a description of the accepted constraints.\n\n Note that the *args and **kwargs parameters are not validated and must not be\n present in the parameter_constraints dictionary.\n\n prefer_skip_nested_validation : bool\n If True, the validation of parameters of inner estimators or functions\n called by the decorated function will be skipped.\n\n This is useful to avoid validating many times the parameters passed by the\n user from the public facing API. It's also useful to avoid validating\n parameters that we pass internally to inner functions that are guaranteed to\n be valid by the test suite.\n\n It should be set to True for most functions, except for those that receive\n non-validated objects as parameters or that are just wrappers around classes\n because they only perform a partial validation.\n\n Returns\n -------\n decorated_function : function or method\n The decorated function.\n \"\"\"\n\n def decorator(func):\n # The dict of parameter constraints is set as an attribute of the function\n # to make it possible to dynamically introspect the constraints for\n # automatic testing.\n setattr(func, \"_skl_parameter_constraints\", parameter_constraints)\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n global_skip_validation = get_config()[\"skip_parameter_validation\"]\n if global_skip_validation:\n return func(*args, **kwargs)\n\n func_sig = signature(func)\n\n # Map *args/**kwargs to the function signature\n params = func_sig.bind(*args, **kwargs)\n params.apply_defaults()\n\n # ignore self/cls and positional/keyword markers\n to_ignore = [\n p.name\n for p in func_sig.parameters.values()\n if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD)\n ]\n to_ignore += [\"self\", \"cls\"]\n params = {k: v for k, v in params.arguments.items() if k not in to_ignore}\n\n validate_parameter_constraints(\n parameter_constraints, params, caller_name=func.__qualname__\n )\n\n try:\n with config_context(\n skip_parameter_validation=(\n prefer_skip_nested_validation or global_skip_validation\n )\n ):\n return func(*args, **kwargs)\n except InvalidParameterError as e:\n # When the function is just a wrapper around an estimator, we allow\n # the function to delegate validation to the estimator, but we replace\n # the name of the estimator by the name of the function in the error\n # message to avoid confusion.\n msg = re.sub(\n r\"parameter of \\w+ must be\",\n f\"parameter of {func.__qualname__} must be\",\n str(e),\n )\n raise InvalidParameterError(msg) from e\n\n return wrapper\n\n return decorator" } ]
from itertools import product from numbers import Integral, Number, Real from numpy.lib.stride_tricks import as_strided from scipy import sparse from ..base import BaseEstimator, TransformerMixin, _fit_context from ..utils import check_array, check_random_state from ..utils._param_validation import Hidden, Interval, RealNotInt, validate_params import numpy as np
14,540
`max_patches` is not None. Use an int to make the randomness deterministic. See :term:`Glossary <random_state>`. Returns ------- patches : array of shape (n_patches, patch_height, patch_width) or \ (n_patches, patch_height, patch_width, n_channels) The collection of patches extracted from the image, where `n_patches` is either `max_patches` or the total number of patches that can be extracted. Examples -------- >>> from sklearn.datasets import load_sample_image >>> from sklearn.feature_extraction import image >>> # Use the array data from the first image in this dataset: >>> one_image = load_sample_image("china.jpg") >>> print('Image shape: {}'.format(one_image.shape)) Image shape: (427, 640, 3) >>> patches = image.extract_patches_2d(one_image, (2, 2)) >>> print('Patches shape: {}'.format(patches.shape)) Patches shape: (272214, 2, 2, 3) >>> # Here are just two of these patches: >>> print(patches[1]) [[[174 201 231] [174 201 231]] [[173 200 230] [173 200 230]]] >>> print(patches[800]) [[[187 214 243] [188 215 244]] [[187 214 243] [188 215 244]]] """ i_h, i_w = image.shape[:2] p_h, p_w = patch_size if p_h > i_h: raise ValueError( "Height of the patch should be less than the height of the image." ) if p_w > i_w: raise ValueError( "Width of the patch should be less than the width of the image." ) image = check_array(image, allow_nd=True) image = image.reshape((i_h, i_w, -1)) n_colors = image.shape[-1] extracted_patches = _extract_patches( image, patch_shape=(p_h, p_w, n_colors), extraction_step=1 ) n_patches = _compute_n_patches(i_h, i_w, p_h, p_w, max_patches) if max_patches: rng = check_random_state(random_state) i_s = rng.randint(i_h - p_h + 1, size=n_patches) j_s = rng.randint(i_w - p_w + 1, size=n_patches) patches = extracted_patches[i_s, j_s, 0] else: patches = extracted_patches patches = patches.reshape(-1, p_h, p_w, n_colors) # remove the color dimension if useless if patches.shape[-1] == 1: return patches.reshape((n_patches, p_h, p_w)) else: return patches @validate_params( {"patches": [np.ndarray], "image_size": [tuple, Hidden(list)]}, prefer_skip_nested_validation=True, ) def reconstruct_from_patches_2d(patches, image_size): """Reconstruct the image from all of its patches. Patches are assumed to overlap and the image is constructed by filling in the patches from left to right, top to bottom, averaging the overlapping regions. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- patches : ndarray of shape (n_patches, patch_height, patch_width) or \ (n_patches, patch_height, patch_width, n_channels) The complete set of patches. If the patches contain colour information, channels are indexed along the last dimension: RGB patches would have `n_channels=3`. image_size : tuple of int (image_height, image_width) or \ (image_height, image_width, n_channels) The size of the image that will be reconstructed. Returns ------- image : ndarray of shape image_size The reconstructed image. """ i_h, i_w = image_size[:2] p_h, p_w = patches.shape[1:3] img = np.zeros(image_size) # compute the dimensions of the patches array n_h = i_h - p_h + 1 n_w = i_w - p_w + 1 for p, (i, j) in zip(patches, product(range(n_h), range(n_w))): img[i : i + p_h, j : j + p_w] += p for i in range(i_h): for j in range(i_w): # divide by the amount of overlap # XXX: is this the most efficient way? memory-wise yes, cpu wise? img[i, j] /= float(min(i + 1, p_h, i_h - i) * min(j + 1, p_w, i_w - j)) return img
""" The :mod:`sklearn.feature_extraction.image` submodule gathers utilities to extract features from images. """ # Authors: Emmanuelle Gouillart <[email protected]> # Gael Varoquaux <[email protected]> # Olivier Grisel # Vlad Niculae # License: BSD 3 clause __all__ = [ "PatchExtractor", "extract_patches_2d", "grid_to_graph", "img_to_graph", "reconstruct_from_patches_2d", ] ############################################################################### # From an image to a graph def _make_edges_3d(n_x, n_y, n_z=1): """Returns a list of edges for a 3D image. Parameters ---------- n_x : int The size of the grid in the x direction. n_y : int The size of the grid in the y direction. n_z : integer, default=1 The size of the grid in the z direction, defaults to 1 """ vertices = np.arange(n_x * n_y * n_z).reshape((n_x, n_y, n_z)) edges_deep = np.vstack((vertices[:, :, :-1].ravel(), vertices[:, :, 1:].ravel())) edges_right = np.vstack((vertices[:, :-1].ravel(), vertices[:, 1:].ravel())) edges_down = np.vstack((vertices[:-1].ravel(), vertices[1:].ravel())) edges = np.hstack((edges_deep, edges_right, edges_down)) return edges def _compute_gradient_3d(edges, img): _, n_y, n_z = img.shape gradient = np.abs( img[ edges[0] // (n_y * n_z), (edges[0] % (n_y * n_z)) // n_z, (edges[0] % (n_y * n_z)) % n_z, ] - img[ edges[1] // (n_y * n_z), (edges[1] % (n_y * n_z)) // n_z, (edges[1] % (n_y * n_z)) % n_z, ] ) return gradient # XXX: Why mask the image after computing the weights? def _mask_edges_weights(mask, edges, weights=None): """Apply a mask to edges (weighted or not)""" inds = np.arange(mask.size) inds = inds[mask.ravel()] ind_mask = np.logical_and(np.isin(edges[0], inds), np.isin(edges[1], inds)) edges = edges[:, ind_mask] if weights is not None: weights = weights[ind_mask] if len(edges.ravel()): maxval = edges.max() else: maxval = 0 order = np.searchsorted(np.flatnonzero(mask), np.arange(maxval + 1)) edges = order[edges] if weights is None: return edges else: return edges, weights def _to_graph( n_x, n_y, n_z, mask=None, img=None, return_as=sparse.coo_matrix, dtype=None ): """Auxiliary function for img_to_graph and grid_to_graph""" edges = _make_edges_3d(n_x, n_y, n_z) if dtype is None: # To not overwrite input dtype if img is None: dtype = int else: dtype = img.dtype if img is not None: img = np.atleast_3d(img) weights = _compute_gradient_3d(edges, img) if mask is not None: edges, weights = _mask_edges_weights(mask, edges, weights) diag = img.squeeze()[mask] else: diag = img.ravel() n_voxels = diag.size else: if mask is not None: mask = mask.astype(dtype=bool, copy=False) edges = _mask_edges_weights(mask, edges) n_voxels = np.sum(mask) else: n_voxels = n_x * n_y * n_z weights = np.ones(edges.shape[1], dtype=dtype) diag = np.ones(n_voxels, dtype=dtype) diag_idx = np.arange(n_voxels) i_idx = np.hstack((edges[0], edges[1])) j_idx = np.hstack((edges[1], edges[0])) graph = sparse.coo_matrix( ( np.hstack((weights, weights, diag)), (np.hstack((i_idx, diag_idx)), np.hstack((j_idx, diag_idx))), ), (n_voxels, n_voxels), dtype=dtype, ) if return_as is np.ndarray: return graph.toarray() return return_as(graph) @validate_params( { "img": ["array-like"], "mask": [None, np.ndarray], "return_as": [type], "dtype": "no_validation", # validation delegated to numpy }, prefer_skip_nested_validation=True, ) def img_to_graph(img, *, mask=None, return_as=sparse.coo_matrix, dtype=None): """Graph of the pixel-to-pixel gradient connections. Edges are weighted with the gradient values. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- img : array-like of shape (height, width) or (height, width, channel) 2D or 3D image. mask : ndarray of shape (height, width) or \ (height, width, channel), dtype=bool, default=None An optional mask of the image, to consider only part of the pixels. return_as : np.ndarray or a sparse matrix class, \ default=sparse.coo_matrix The class to use to build the returned adjacency matrix. dtype : dtype, default=None The data of the returned sparse matrix. By default it is the dtype of img. Returns ------- graph : ndarray or a sparse matrix class The computed adjacency matrix. Notes ----- For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was handled by returning a dense np.matrix instance. Going forward, np.ndarray returns an np.ndarray, as expected. For compatibility, user code relying on this method should wrap its calls in ``np.asarray`` to avoid type issues. """ img = np.atleast_3d(img) n_x, n_y, n_z = img.shape return _to_graph(n_x, n_y, n_z, mask, img, return_as, dtype) @validate_params( { "n_x": [Interval(Integral, left=1, right=None, closed="left")], "n_y": [Interval(Integral, left=1, right=None, closed="left")], "n_z": [Interval(Integral, left=1, right=None, closed="left")], "mask": [None, np.ndarray], "return_as": [type], "dtype": "no_validation", # validation delegated to numpy }, prefer_skip_nested_validation=True, ) def grid_to_graph( n_x, n_y, n_z=1, *, mask=None, return_as=sparse.coo_matrix, dtype=int ): """Graph of the pixel-to-pixel connections. Edges exist if 2 voxels are connected. Parameters ---------- n_x : int Dimension in x axis. n_y : int Dimension in y axis. n_z : int, default=1 Dimension in z axis. mask : ndarray of shape (n_x, n_y, n_z), dtype=bool, default=None An optional mask of the image, to consider only part of the pixels. return_as : np.ndarray or a sparse matrix class, \ default=sparse.coo_matrix The class to use to build the returned adjacency matrix. dtype : dtype, default=int The data of the returned sparse matrix. By default it is int. Returns ------- graph : np.ndarray or a sparse matrix class The computed adjacency matrix. Notes ----- For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was handled by returning a dense np.matrix instance. Going forward, np.ndarray returns an np.ndarray, as expected. For compatibility, user code relying on this method should wrap its calls in ``np.asarray`` to avoid type issues. """ return _to_graph(n_x, n_y, n_z, mask=mask, return_as=return_as, dtype=dtype) ############################################################################### # From an image to a set of small image patches def _compute_n_patches(i_h, i_w, p_h, p_w, max_patches=None): """Compute the number of patches that will be extracted in an image. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- i_h : int The image height i_w : int The image with p_h : int The height of a patch p_w : int The width of a patch max_patches : int or float, default=None The maximum number of patches to extract. If `max_patches` is a float between 0 and 1, it is taken to be a proportion of the total number of patches. If `max_patches` is None, all possible patches are extracted. """ n_h = i_h - p_h + 1 n_w = i_w - p_w + 1 all_patches = n_h * n_w if max_patches: if isinstance(max_patches, (Integral)) and max_patches < all_patches: return max_patches elif isinstance(max_patches, (Integral)) and max_patches >= all_patches: return all_patches elif isinstance(max_patches, (Real)) and 0 < max_patches < 1: return int(max_patches * all_patches) else: raise ValueError("Invalid value for max_patches: %r" % max_patches) else: return all_patches def _extract_patches(arr, patch_shape=8, extraction_step=1): """Extracts patches of any n-dimensional array in place using strides. Given an n-dimensional array it will return a 2n-dimensional array with the first n dimensions indexing patch position and the last n indexing the patch content. This operation is immediate (O(1)). A reshape performed on the first n dimensions will cause numpy to copy data, leading to a list of extracted patches. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- arr : ndarray n-dimensional array of which patches are to be extracted patch_shape : int or tuple of length arr.ndim.default=8 Indicates the shape of the patches to be extracted. If an integer is given, the shape will be a hypercube of sidelength given by its value. extraction_step : int or tuple of length arr.ndim, default=1 Indicates step size at which extraction shall be performed. If integer is given, then the step is uniform in all dimensions. Returns ------- patches : strided ndarray 2n-dimensional array indexing patches on first n dimensions and containing patches on the last n dimensions. These dimensions are fake, but this way no data is copied. A simple reshape invokes a copying operation to obtain a list of patches: result.reshape([-1] + list(patch_shape)) """ arr_ndim = arr.ndim if isinstance(patch_shape, Number): patch_shape = tuple([patch_shape] * arr_ndim) if isinstance(extraction_step, Number): extraction_step = tuple([extraction_step] * arr_ndim) patch_strides = arr.strides slices = tuple(slice(None, None, st) for st in extraction_step) indexing_strides = arr[slices].strides patch_indices_shape = ( (np.array(arr.shape) - np.array(patch_shape)) // np.array(extraction_step) ) + 1 shape = tuple(list(patch_indices_shape) + list(patch_shape)) strides = tuple(list(indexing_strides) + list(patch_strides)) patches = as_strided(arr, shape=shape, strides=strides) return patches @validate_params( { "image": [np.ndarray], "patch_size": [tuple, list], "max_patches": [ Interval(RealNotInt, 0, 1, closed="neither"), Interval(Integral, 1, None, closed="left"), None, ], "random_state": ["random_state"], }, prefer_skip_nested_validation=True, ) def extract_patches_2d(image, patch_size, *, max_patches=None, random_state=None): """Reshape a 2D image into a collection of patches. The resulting patches are allocated in a dedicated array. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- image : ndarray of shape (image_height, image_width) or \ (image_height, image_width, n_channels) The original image data. For color images, the last dimension specifies the channel: a RGB image would have `n_channels=3`. patch_size : tuple of int (patch_height, patch_width) The dimensions of one patch. max_patches : int or float, default=None The maximum number of patches to extract. If `max_patches` is a float between 0 and 1, it is taken to be a proportion of the total number of patches. If `max_patches` is None it corresponds to the total number of patches that can be extracted. random_state : int, RandomState instance, default=None Determines the random number generator used for random sampling when `max_patches` is not None. Use an int to make the randomness deterministic. See :term:`Glossary <random_state>`. Returns ------- patches : array of shape (n_patches, patch_height, patch_width) or \ (n_patches, patch_height, patch_width, n_channels) The collection of patches extracted from the image, where `n_patches` is either `max_patches` or the total number of patches that can be extracted. Examples -------- >>> from sklearn.datasets import load_sample_image >>> from sklearn.feature_extraction import image >>> # Use the array data from the first image in this dataset: >>> one_image = load_sample_image("china.jpg") >>> print('Image shape: {}'.format(one_image.shape)) Image shape: (427, 640, 3) >>> patches = image.extract_patches_2d(one_image, (2, 2)) >>> print('Patches shape: {}'.format(patches.shape)) Patches shape: (272214, 2, 2, 3) >>> # Here are just two of these patches: >>> print(patches[1]) [[[174 201 231] [174 201 231]] [[173 200 230] [173 200 230]]] >>> print(patches[800]) [[[187 214 243] [188 215 244]] [[187 214 243] [188 215 244]]] """ i_h, i_w = image.shape[:2] p_h, p_w = patch_size if p_h > i_h: raise ValueError( "Height of the patch should be less than the height of the image." ) if p_w > i_w: raise ValueError( "Width of the patch should be less than the width of the image." ) image = check_array(image, allow_nd=True) image = image.reshape((i_h, i_w, -1)) n_colors = image.shape[-1] extracted_patches = _extract_patches( image, patch_shape=(p_h, p_w, n_colors), extraction_step=1 ) n_patches = _compute_n_patches(i_h, i_w, p_h, p_w, max_patches) if max_patches: rng = check_random_state(random_state) i_s = rng.randint(i_h - p_h + 1, size=n_patches) j_s = rng.randint(i_w - p_w + 1, size=n_patches) patches = extracted_patches[i_s, j_s, 0] else: patches = extracted_patches patches = patches.reshape(-1, p_h, p_w, n_colors) # remove the color dimension if useless if patches.shape[-1] == 1: return patches.reshape((n_patches, p_h, p_w)) else: return patches @validate_params( {"patches": [np.ndarray], "image_size": [tuple, Hidden(list)]}, prefer_skip_nested_validation=True, ) def reconstruct_from_patches_2d(patches, image_size): """Reconstruct the image from all of its patches. Patches are assumed to overlap and the image is constructed by filling in the patches from left to right, top to bottom, averaging the overlapping regions. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- patches : ndarray of shape (n_patches, patch_height, patch_width) or \ (n_patches, patch_height, patch_width, n_channels) The complete set of patches. If the patches contain colour information, channels are indexed along the last dimension: RGB patches would have `n_channels=3`. image_size : tuple of int (image_height, image_width) or \ (image_height, image_width, n_channels) The size of the image that will be reconstructed. Returns ------- image : ndarray of shape image_size The reconstructed image. """ i_h, i_w = image_size[:2] p_h, p_w = patches.shape[1:3] img = np.zeros(image_size) # compute the dimensions of the patches array n_h = i_h - p_h + 1 n_w = i_w - p_w + 1 for p, (i, j) in zip(patches, product(range(n_h), range(n_w))): img[i : i + p_h, j : j + p_w] += p for i in range(i_h): for j in range(i_w): # divide by the amount of overlap # XXX: is this the most efficient way? memory-wise yes, cpu wise? img[i, j] /= float(min(i + 1, p_h, i_h - i) * min(j + 1, p_w, i_w - j)) return img
class PatchExtractor(TransformerMixin, BaseEstimator):
1
2023-10-07 13:19:48+00:00
24k
hellloxiaotian/KDNet
train_KDNet.py
[ { "identifier": "attempt_load", "path": "models/experimental.py", "snippet": "def attempt_load(weights, map_location=None):\n # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n model = Ensemble()\n # print('weights', weights) # /runs/train/yolov7_distillation19/weights/epoch_074.pt\n for w in weights if isinstance(weights, list) else [weights]:\n # attempt_download(w) # /runs/train/yolov7_distillation19/weights/epoch_074.pt\n ckpt = torch.load(w, map_location=map_location) # load\n model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model\n \n # Compatibility updates\n for m in model.modules():\n if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n m.inplace = True # pytorch 1.7.0 compatibility\n elif type(m) is nn.Upsample:\n m.recompute_scale_factor = None # torch 1.11.0 compatibility\n elif type(m) is Conv:\n m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility\n \n if len(model) == 1:\n return model[-1] # return model\n else:\n print('Ensemble created with %s\\n' % weights)\n for k in ['names', 'stride']:\n setattr(model, k, getattr(model[-1], k))\n return model # return ensemble" }, { "identifier": "attempt_loadv5", "path": "models/experimental.py", "snippet": "def attempt_loadv5(weights, device=None, inplace=True, fuse=True):\n # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n from models.yolo import Detect, Model\n\n model = Ensemble()\n for w in weights if isinstance(weights, list) else [weights]:\n ckpt = torch.load(attempt_download(w), map_location='cpu') # load\n ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model\n\n # Model compatibility updates\n if not hasattr(ckpt, 'stride'):\n ckpt.stride = torch.tensor([32.])\n if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):\n ckpt.names = dict(enumerate(ckpt.names)) # convert to dict\n\n model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode\n\n # Module compatibility updates\n for m in model.modules():\n t = type(m)\n if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):\n m.inplace = inplace # torch 1.7.0 compatibility\n if t is Detect and not isinstance(m.anchor_grid, list):\n delattr(m, 'anchor_grid')\n setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)\n elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n m.recompute_scale_factor = None # torch 1.11.0 compatibility\n\n # Return model\n if len(model) == 1:\n return model[-1]\n\n # Return detection ensemble\n print(f'Ensemble created with {weights}\\n')\n for k in 'names', 'nc', 'yaml':\n setattr(model, k, getattr(model[0], k))\n model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride\n assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'\n return model" }, { "identifier": "attempt_load_zxy", "path": "models/experimental.py", "snippet": "def attempt_load_zxy(weights, device, map_location=None):\n # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n model = Ensemble()\n for w in weights if isinstance(weights, list) else [weights]:\n attempt_download(w)\n ckpt = torch.load(w, map_location=map_location) # load\n model.append(ckpt['ema' if ckpt.get('ema') else 'model'].to(device).float().fuse().eval()) # FP32 model\n\n # Compatibility updates\n for m in model.modules():\n if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n m.inplace = True # pytorch 1.7.0 compatibility\n elif type(m) is nn.Upsample:\n m.recompute_scale_factor = None # torch 1.11.0 compatibility\n elif type(m) is Conv:\n m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility\n\n if len(model) == 1:\n return model[-1] # return model\n else:\n print('Ensemble created with %s\\n' % weights)\n for k in ['names', 'stride']:\n setattr(model, k, getattr(model[-1], k))\n return model # return ensemble" }, { "identifier": "Model", "path": "models/yolo.py", "snippet": "class Model(nn.Module):\n # def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes\n def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes\n super(Model, self).__init__()\n self.traced = False\n if isinstance(cfg, dict):\n self.yaml = cfg # model dict\n else: # is *.yaml\n import yaml # for torch hub\n self.yaml_file = Path(cfg).name\n with open(cfg) as f:\n self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict\n\n # Define model\n ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels\n if nc and nc != self.yaml['nc']:\n logger.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n self.yaml['nc'] = nc # override yaml value\n if anchors:\n logger.info(f'Overriding model.yaml anchors with anchors={anchors}')\n self.yaml['anchors'] = round(anchors) # override yaml value\n self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist\n # self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]).cuda() # model, savelist\n self.names = [str(i) for i in range(self.yaml['nc'])] # default names\n # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])\n\n # Build strides, anchors\n # m = self.model[-1] # Detect()\n m = self.model[-1] # Detect()\n if isinstance(m, Detect):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IDetect):\n print('yolo.py-IDetect')\n # print('m', m) # m IDetect\n m.cuda()\n s = 256 # 2x min stride\n # m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]).cuda() # forward\n # print('m.device2', m.device)\n check_anchor_order(m)\n # print('m.device3', m.device)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IAuxDetect):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))[:4]]) # forward\n #print(m.stride)\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_aux_biases() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IBin):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases_bin() # only run once\n # print('Strides: %s' % m.stride.tolist())\n if isinstance(m, IKeypoint):\n s = 256 # 2x min stride\n m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward\n check_anchor_order(m)\n m.anchors /= m.stride.view(-1, 1, 1)\n self.stride = m.stride\n self._initialize_biases_kpt() # only run once\n # print('Strides: %s' % m.stride.tolist())\n\n # Init weights, biases\n initialize_weights(self)\n self.info()\n logger.info('')\n\n def forward(self, x, augment=False, profile=False):\n # print('x', x.shape)\n if augment:\n img_size = x.shape[-2:] # height, width\n s = [1, 0.83, 0.67] # scales\n f = [None, 3, None] # flips (2-ud, 3-lr)\n y = [] # outputs\n for si, fi in zip(s, f):\n xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n yi = self.forward_once(xi)[0] # forward\n # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save\n yi[..., :4] /= si # de-scale\n if fi == 2:\n yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud\n elif fi == 3:\n yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr\n y.append(yi)\n # print('y', y.shape)\n return torch.cat(y, 1), None # augmented inference, train\n else:\n return self.forward_once(x, profile) # single-scale inference, train\n\n def forward_once(self, x, profile=False):\n # print('x1', x.shape)\n y, dt = [], [] # outputs\n for m in self.model:\n if m.f != -1: # if not from previous layer\n x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers\n\n if not hasattr(self, 'traced'):\n self.traced=False\n\n if self.traced:\n if isinstance(m, Detect) or isinstance(m, IDetect) or isinstance(m, IAuxDetect) or isinstance(m, IKeypoint):\n break\n\n # print('profile', profile) # Flase\n if profile:\n c = isinstance(m, (Detect, IDetect, IAuxDetect, IBin))\n o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS\n # print('o', o.shape)\n for _ in range(10):\n m(x.copy() if c else x)\n t = time_synchronized()\n for _ in range(10):\n m(x.copy() if c else x)\n dt.append((time_synchronized() - t) * 100)\n print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))\n\n # print('x3', x.shape)\n # print('m.i', m.i) # =len(y)\n x = m(x) # run\\\n \n y.append(x if m.i in self.save else None) # save output\n # print('x4', x.shape)\n\n if profile:\n print('%.1fms total' % sum(dt))\n\n # print('x', len(x)) # 3\n return x\n\n def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Detect() module\n for mi, s in zip(m.m, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def _initialize_aux_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Detect() module\n for mi, mi2, s in zip(m.m, m.m2, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n b2 = mi2.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b2.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b2.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi2.bias = torch.nn.Parameter(b2.view(-1), requires_grad=True)\n\n def _initialize_biases_bin(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Bin() module\n bc = m.bin_count\n for mi, s in zip(m.m, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n old = b[:, (0,1,2,bc+3)].data\n obj_idx = 2*bc+4\n b[:, :obj_idx].data += math.log(0.6 / (bc + 1 - 0.99))\n b[:, obj_idx].data += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b[:, (obj_idx+1):].data += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n b[:, (0,1,2,bc+3)].data = old\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def _initialize_biases_kpt(self, cf=None): # initialize biases into Detect(), cf is class frequency\n # https://arxiv.org/abs/1708.02002 section 3.3\n # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n m = self.model[-1] # Detect() module\n for mi, s in zip(m.m, m.stride): # from\n b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)\n b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)\n b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls\n mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def _print_biases(self):\n m = self.model[-1] # Detect() module\n for mi in m.m: # from\n b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)\n print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))\n\n # def _print_weights(self):\n # for m in self.model.modules():\n # if type(m) is Bottleneck:\n # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights\n\n def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers\n print('Fusing layers... ')\n for m in self.model.modules():\n if isinstance(m, RepConv):\n #print(f\" fuse_repvgg_block\")\n m.fuse_repvgg_block()\n elif isinstance(m, RepConv_OREPA):\n #print(f\" switch_to_deploy\")\n m.switch_to_deploy()\n elif type(m) is Conv and hasattr(m, 'bn'):\n m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv\n delattr(m, 'bn') # remove batchnorm\n m.forward = m.fuseforward # update forward\n elif isinstance(m, (IDetect, IAuxDetect)):\n m.fuse()\n m.forward = m.fuseforward\n self.info()\n return self\n\n def nms(self, mode=True): # add or remove NMS module\n present = type(self.model[-1]) is NMS # last layer is NMS\n if mode and not present:\n print('Adding NMS... ')\n m = NMS() # module\n m.f = -1 # from\n m.i = self.model[-1].i + 1 # index\n self.model.add_module(name='%s' % m.i, module=m) # add\n self.eval()\n elif not mode and present:\n print('Removing NMS... ')\n self.model = self.model[:-1] # remove\n return self\n\n def autoshape(self): # add autoShape module\n print('Adding autoShape... ')\n m = autoShape(self) # wrap model\n copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes\n return m\n\n def info(self, verbose=False, img_size=640): # print model information\n model_info(self, verbose, img_size)" }, { "identifier": "check_anchors", "path": "utils/autoanchor.py", "snippet": "def check_anchors(dataset, model, thr=4.0, imgsz=640):\n # Check anchor fit to data, recompute if necessary\n prefix = colorstr('autoanchor: ')\n print(f'\\n{prefix}Analyzing anchors... ', end='')\n m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()\n shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)\n scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale\n wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh\n\n def metric(k): # compute metric\n r = wh[:, None] / k[None]\n x = torch.min(r, 1. / r).min(2)[0] # ratio metric\n best = x.max(1)[0] # best_x\n aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold\n bpr = (best > 1. / thr).float().mean() # best possible recall\n return bpr, aat\n\n anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors\n bpr, aat = metric(anchors)\n print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')\n if bpr < 0.98: # threshold to recompute\n print('. Attempting to improve anchors, please wait...')\n na = m.anchor_grid.numel() // 2 # number of anchors\n try:\n anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)\n except Exception as e:\n print(f'{prefix}ERROR: {e}')\n new_bpr = metric(anchors)[0]\n if new_bpr > bpr: # replace anchors\n anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)\n m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference\n check_anchor_order(m)\n m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss\n print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')\n else:\n print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')\n print('') # newline" }, { "identifier": "create_dataloader", "path": "utils/datasets.py", "snippet": "def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,\n rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):\n # Make sure only the first process in DDP process the dataset first, and the following others can use the cache\n with torch_distributed_zero_first(rank):\n dataset = LoadImagesAndLabels(path, imgsz, batch_size,\n augment=augment, # augment images\n hyp=hyp, # augmentation hyperparameters\n rect=rect, # rectangular training\n cache_images=cache,\n single_cls=opt.single_cls,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix)\n\n batch_size = min(batch_size, len(dataset))\n nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None\n loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader\n # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()\n dataloader = loader(dataset,\n batch_size=batch_size,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)\n return dataloader, dataset" }, { "identifier": "labels_to_class_weights", "path": "utils/general.py", "snippet": "def set_logging(rank=-1):\ndef init_seeds(seed=0):\ndef get_latest_run(search_dir='.'):\ndef isdocker():\ndef emojis(str=''):\ndef check_online():\ndef check_git_status():\ndef check_requirements(requirements='requirements.txt', exclude=()):\ndef check_img_size(img_size, s=32):\ndef check_imshow():\ndef check_file(file):\ndef check_dataset(dict):\ndef make_divisible(x, divisor):\ndef clean_str(s):\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\ndef colorstr(*input):\ndef labels_to_class_weights(labels, nc=80):\ndef labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):\ndef coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)\ndef xyxy2xywh(x):\ndef xywh2xyxy(x):\ndef xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):\ndef xyn2xy(x, w=640, h=640, padw=0, padh=0):\ndef segment2box(segment, width=640, height=640):\ndef segments2boxes(segments):\ndef resample_segments(segments, n=1000):\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):\ndef clip_coords(boxes, img_shape):\ndef bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):\ndef bbox_alpha_iou(box1, box2, x1y1x2y2=False, GIoU=False, DIoU=False, CIoU=False, alpha=2, eps=1e-9):\ndef box_iou(box1, box2):\n def box_area(box):\ndef wh_iou(wh1, wh2):\ndef box_giou(box1, box2):\n def box_area(box):\ndef box_ciou(box1, box2, eps: float = 1e-7):\n def box_area(box):\ndef box_diou(box1, box2, eps: float = 1e-7):\n def box_area(box):\ndef non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,\n labels=()):\ndef non_max_suppression_kpt(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,\n labels=(), kpt_label=False, nc=None, nkpt=None):\ndef strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()\ndef print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):\ndef apply_classifier(x, model, img, im0):\ndef increment_path(path, exist_ok=True, sep=''):" }, { "identifier": "attempt_download", "path": "utils/google_utils.py", "snippet": "def attempt_download(file, repo='WongKinYiu/yolov7'):\n # Attempt file download if does not exist\n file = Path(str(file).strip().replace(\"'\", '').lower())\n\n if not file.exists():\n try:\n response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api\n assets = [x['name'] for x in response['assets']] # release assets\n tag = response['tag_name'] # i.e. 'v1.0'\n except: # fallback plan\n assets = ['yolov7.pt', 'yolov7-tiny.pt', 'yolov7x.pt', 'yolov7-d6.pt', 'yolov7-e6.pt', \n 'yolov7-e6e.pt', 'yolov7-w6.pt']\n tag = subprocess.check_output('git tag', shell=True).decode().split()[-1]\n\n name = file.name\n if name in assets:\n msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'\n redundant = False # second download option\n try: # GitHub\n url = f'https://github.com/{repo}/releases/download/{tag}/{name}'\n print(f'Downloading {url} to {file}...')\n torch.hub.download_url_to_file(url, file)\n assert file.exists() and file.stat().st_size > 1E6 # check\n except Exception as e: # GCP\n print(f'Download error: {e}')\n assert redundant, 'No secondary mirror'\n url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'\n print(f'Downloading {url} to {file}...')\n os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)\n finally:\n if not file.exists() or file.stat().st_size < 1E6: # check\n file.unlink(missing_ok=True) # remove partial downloads\n print(f'ERROR: Download failure: {msg}')\n print('')\n return" }, { "identifier": "ComputeLoss", "path": "utils/loss.py", "snippet": "class ComputeLoss:\n # Compute losses\n def __init__(self, model, autobalance=False):\n super(ComputeLoss, self).__init__()\n device = next(model.parameters()).device # get model device\n h = model.hyp # hyperparameters\n\n # Define criteria\n BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))\n BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))\n\n # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets\n\n # Focal loss\n g = h['fl_gamma'] # focal loss gamma\n if g > 0:\n BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)\n\n det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module\n self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7\n #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.1, .05]) # P3-P7\n #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.5, 0.4, .1]) # P3-P7\n self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index\n self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance\n for k in 'na', 'nc', 'nl', 'anchors':\n setattr(self, k, getattr(det, k))\n\n def __call__(self, p, targets): # predictions, targets, model\n device = targets.device\n lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)\n tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets\n\n # Losses\n for i, pi in enumerate(p): # layer index, layer predictions\n b, a, gj, gi = indices[i] # image, anchor, gridy, gridx\n tobj = torch.zeros_like(pi[..., 0], device=device) # target obj\n\n n = b.shape[0] # number of targets\n if n:\n ps = pi[b, a, gj, gi] # prediction subset corresponding to targets\n\n # Regression\n pxy = ps[:, :2].sigmoid() * 2. - 0.5\n pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]\n pbox = torch.cat((pxy, pwh), 1) # predicted box\n iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)\n lbox += (1.0 - iou).mean() # iou loss\n\n # Objectness\n tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio\n\n # Classification\n if self.nc > 1: # cls loss (only if multiple classes)\n t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets\n t[range(n), tcls[i]] = self.cp\n #t[t==self.cp] = iou.detach().clamp(0).type(t.dtype)\n lcls += self.BCEcls(ps[:, 5:], t) # BCE\n\n # Append targets to text file\n # with open('targets.txt', 'a') as file:\n # [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n obji = self.BCEobj(pi[..., 4], tobj)\n lobj += obji * self.balance[i] # obj loss\n if self.autobalance:\n self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()\n\n if self.autobalance:\n self.balance = [x / self.balance[self.ssi] for x in self.balance]\n lbox *= self.hyp['box']\n lobj *= self.hyp['obj']\n lcls *= self.hyp['cls']\n bs = tobj.shape[0] # batch size\n\n loss = lbox + lobj + lcls\n return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()\n\n def build_targets(self, p, targets):\n # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n na, nt = self.na, targets.shape[0] # number of anchors, targets\n tcls, tbox, indices, anch = [], [], [], []\n gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain\n ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)\n targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices\n\n g = 0.5 # bias\n off = torch.tensor([[0, 0],\n [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m\n # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm\n ], device=targets.device).float() * g # offsets\n\n for i in range(self.nl):\n anchors = self.anchors[i]\n gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain\n\n # Match targets to anchors\n t = targets * gain\n if nt:\n # Matches\n r = t[:, :, 4:6] / anchors[:, None] # wh ratio\n j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare\n # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n t = t[j] # filter\n\n # Offsets\n gxy = t[:, 2:4] # grid xy\n gxi = gain[[2, 3]] - gxy # inverse\n j, k = ((gxy % 1. < g) & (gxy > 1.)).T\n l, m = ((gxi % 1. < g) & (gxi > 1.)).T\n j = torch.stack((torch.ones_like(j), j, k, l, m))\n t = t.repeat((5, 1, 1))[j]\n offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n else:\n t = targets[0]\n offsets = 0\n\n # Define\n b, c = t[:, :2].long().T # image, class\n gxy = t[:, 2:4] # grid xy\n gwh = t[:, 4:6] # grid wh\n gij = (gxy - offsets).long()\n gi, gj = gij.T # grid xy indices\n\n # Append\n a = t[:, 6].long() # anchor indices\n indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices\n tbox.append(torch.cat((gxy - gij, gwh), 1)) # box\n anch.append(anchors[a]) # anchors\n tcls.append(c) # class\n\n return tcls, tbox, indices, anch" }, { "identifier": "ComputeLossOTA", "path": "utils/loss.py", "snippet": "class ComputeLossOTA:\n # Compute losses\n def __init__(self, model, autobalance=False):\n super(ComputeLossOTA, self).__init__()\n device = next(model.parameters()).device # get model device\n h = model.hyp # hyperparameters\n\n # Define criteria\n BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))\n BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))\n\n # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets\n\n # Focal loss\n g = h['fl_gamma'] # focal loss gamma\n if g > 0:\n BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)\n\n det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module\n self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7\n self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index\n self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance\n for k in 'na', 'nc', 'nl', 'anchors', 'stride':\n setattr(self, k, getattr(det, k))\n\n def __call__(self, p, targets, imgs): # predictions, targets, model \n device = targets.device\n lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)\n bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs)\n pre_gen_gains = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p] \n \n\n # Losses\n for i, pi in enumerate(p): # layer index, layer predictions\n b, a, gj, gi = bs[i], as_[i], gjs[i], gis[i] # image, anchor, gridy, gridx\n tobj = torch.zeros_like(pi[..., 0], device=device) # target obj\n\n n = b.shape[0] # number of targets\n if n:\n ps = pi[b, a, gj, gi] # prediction subset corresponding to targets\n\n # Regression\n grid = torch.stack([gi, gj], dim=1)\n pxy = ps[:, :2].sigmoid() * 2. - 0.5\n #pxy = ps[:, :2].sigmoid() * 3. - 1.\n pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]\n pbox = torch.cat((pxy, pwh), 1) # predicted box\n selected_tbox = targets[i][:, 2:6] * pre_gen_gains[i]\n selected_tbox[:, :2] -= grid\n iou = bbox_iou(pbox.T, selected_tbox, x1y1x2y2=False, CIoU=True) # iou(prediction, target)\n lbox += (1.0 - iou).mean() # iou loss\n\n # Objectness\n tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio\n\n # Classification\n selected_tcls = targets[i][:, 1].long()\n if self.nc > 1: # cls loss (only if multiple classes)\n t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets\n t[range(n), selected_tcls] = self.cp\n lcls += self.BCEcls(ps[:, 5:], t) # BCE\n\n # Append targets to text file\n # with open('targets.txt', 'a') as file:\n # [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n obji = self.BCEobj(pi[..., 4], tobj)\n lobj += obji * self.balance[i] # obj loss\n if self.autobalance:\n self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()\n\n if self.autobalance:\n self.balance = [x / self.balance[self.ssi] for x in self.balance]\n lbox *= self.hyp['box']\n lobj *= self.hyp['obj']\n lcls *= self.hyp['cls']\n bs = tobj.shape[0] # batch size\n\n loss = lbox + lobj + lcls\n return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()\n\n def build_targets(self, p, targets, imgs):\n \n #indices, anch = self.find_positive(p, targets)\n indices, anch = self.find_3_positive(p, targets)\n #indices, anch = self.find_4_positive(p, targets)\n #indices, anch = self.find_5_positive(p, targets)\n #indices, anch = self.find_9_positive(p, targets)\n device = torch.device(targets.device)\n matching_bs = [[] for pp in p]\n matching_as = [[] for pp in p]\n matching_gjs = [[] for pp in p]\n matching_gis = [[] for pp in p]\n matching_targets = [[] for pp in p]\n matching_anchs = [[] for pp in p]\n \n nl = len(p) \n \n for batch_idx in range(p[0].shape[0]):\n \n b_idx = targets[:, 0]==batch_idx\n this_target = targets[b_idx]\n if this_target.shape[0] == 0:\n continue\n \n txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]\n txyxy = xywh2xyxy(txywh)\n\n pxyxys = []\n p_cls = []\n p_obj = []\n from_which_layer = []\n all_b = []\n all_a = []\n all_gj = []\n all_gi = []\n all_anch = []\n \n for i, pi in enumerate(p):\n \n b, a, gj, gi = indices[i]\n idx = (b == batch_idx)\n b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx] \n all_b.append(b)\n all_a.append(a)\n all_gj.append(gj)\n all_gi.append(gi)\n all_anch.append(anch[i][idx])\n from_which_layer.append((torch.ones(size=(len(b),)) * i).to(device))\n \n fg_pred = pi[b, a, gj, gi] \n p_obj.append(fg_pred[:, 4:5])\n p_cls.append(fg_pred[:, 5:])\n \n grid = torch.stack([gi, gj], dim=1)\n pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.\n #pxy = (fg_pred[:, :2].sigmoid() * 3. - 1. + grid) * self.stride[i]\n pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.\n pxywh = torch.cat([pxy, pwh], dim=-1)\n pxyxy = xywh2xyxy(pxywh)\n pxyxys.append(pxyxy)\n \n pxyxys = torch.cat(pxyxys, dim=0)\n if pxyxys.shape[0] == 0:\n continue\n p_obj = torch.cat(p_obj, dim=0)\n p_cls = torch.cat(p_cls, dim=0)\n from_which_layer = torch.cat(from_which_layer, dim=0)\n all_b = torch.cat(all_b, dim=0)\n all_a = torch.cat(all_a, dim=0)\n all_gj = torch.cat(all_gj, dim=0)\n all_gi = torch.cat(all_gi, dim=0)\n all_anch = torch.cat(all_anch, dim=0)\n \n pair_wise_iou = box_iou(txyxy, pxyxys)\n\n pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)\n\n top_k, _ = torch.topk(pair_wise_iou, min(10, pair_wise_iou.shape[1]), dim=1)\n dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)\n\n gt_cls_per_image = (\n F.one_hot(this_target[:, 1].to(torch.int64), self.nc)\n .float()\n .unsqueeze(1)\n .repeat(1, pxyxys.shape[0], 1)\n )\n\n num_gt = this_target.shape[0]\n cls_preds_ = (\n p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()\n * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()\n )\n\n y = cls_preds_.sqrt_()\n pair_wise_cls_loss = F.binary_cross_entropy_with_logits(\n torch.log(y/(1-y)) , gt_cls_per_image, reduction=\"none\"\n ).sum(-1)\n del cls_preds_\n \n cost = (\n pair_wise_cls_loss\n + 3.0 * pair_wise_iou_loss\n )\n\n matching_matrix = torch.zeros_like(cost, device=device)\n\n for gt_idx in range(num_gt):\n _, pos_idx = torch.topk(\n cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False\n )\n matching_matrix[gt_idx][pos_idx] = 1.0\n\n del top_k, dynamic_ks\n anchor_matching_gt = matching_matrix.sum(0)\n if (anchor_matching_gt > 1).sum() > 0:\n _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)\n matching_matrix[:, anchor_matching_gt > 1] *= 0.0\n matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0\n fg_mask_inboxes = (matching_matrix.sum(0) > 0.0).to(device)\n matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)\n \n from_which_layer = from_which_layer[fg_mask_inboxes]\n all_b = all_b[fg_mask_inboxes]\n all_a = all_a[fg_mask_inboxes]\n all_gj = all_gj[fg_mask_inboxes]\n all_gi = all_gi[fg_mask_inboxes]\n all_anch = all_anch[fg_mask_inboxes]\n \n this_target = this_target[matched_gt_inds]\n \n for i in range(nl):\n layer_idx = from_which_layer == i\n matching_bs[i].append(all_b[layer_idx])\n matching_as[i].append(all_a[layer_idx])\n matching_gjs[i].append(all_gj[layer_idx])\n matching_gis[i].append(all_gi[layer_idx])\n matching_targets[i].append(this_target[layer_idx])\n matching_anchs[i].append(all_anch[layer_idx])\n\n for i in range(nl):\n if matching_targets[i] != []:\n matching_bs[i] = torch.cat(matching_bs[i], dim=0)\n matching_as[i] = torch.cat(matching_as[i], dim=0)\n matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)\n matching_gis[i] = torch.cat(matching_gis[i], dim=0)\n matching_targets[i] = torch.cat(matching_targets[i], dim=0)\n matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)\n else:\n matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_as[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_gjs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_gis[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_targets[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n matching_anchs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)\n\n return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs \n\n def find_3_positive(self, p, targets):\n # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n na, nt = self.na, targets.shape[0] # number of anchors, targets\n indices, anch = [], []\n gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain\n ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)\n targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices\n\n g = 0.5 # bias\n off = torch.tensor([[0, 0],\n [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m\n # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm\n ], device=targets.device).float() * g # offsets\n\n for i in range(self.nl):\n anchors = self.anchors[i]\n gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain\n\n # Match targets to anchors\n t = targets * gain\n if nt:\n # Matches\n r = t[:, :, 4:6] / anchors[:, None] # wh ratio\n j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare\n # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n t = t[j] # filter\n\n # Offsets\n gxy = t[:, 2:4] # grid xy\n gxi = gain[[2, 3]] - gxy # inverse\n j, k = ((gxy % 1. < g) & (gxy > 1.)).T\n l, m = ((gxi % 1. < g) & (gxi > 1.)).T\n j = torch.stack((torch.ones_like(j), j, k, l, m))\n t = t.repeat((5, 1, 1))[j]\n offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n else:\n t = targets[0]\n offsets = 0\n\n # Define\n b, c = t[:, :2].long().T # image, class\n gxy = t[:, 2:4] # grid xy\n gwh = t[:, 4:6] # grid wh\n gij = (gxy - offsets).long()\n gi, gj = gij.T # grid xy indices\n\n # Append\n a = t[:, 6].long() # anchor indices\n indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices\n anch.append(anchors[a]) # anchors\n\n return indices, anch" }, { "identifier": "plot_images", "path": "utils/plots.py", "snippet": "def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):\n # Plot image grid with labels\n\n if isinstance(images, torch.Tensor):\n images = images.cpu().float().numpy()\n if isinstance(targets, torch.Tensor):\n targets = targets.cpu().numpy()\n\n # un-normalise\n if np.max(images[0]) <= 1:\n images *= 255\n\n tl = 3 # line thickness\n tf = max(tl - 1, 1) # font thickness\n bs, _, h, w = images.shape # batch size, _, height, width\n bs = min(bs, max_subplots) # limit plot images\n ns = np.ceil(bs ** 0.5) # number of subplots (square)\n\n # Check if we should resize\n scale_factor = max_size / max(h, w)\n if scale_factor < 1:\n h = math.ceil(scale_factor * h)\n w = math.ceil(scale_factor * w)\n\n colors = color_list() # list of colors\n mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init\n for i, img in enumerate(images):\n if i == max_subplots: # if last batch has fewer images than we expect\n break\n\n block_x = int(w * (i // ns))\n block_y = int(h * (i % ns))\n\n img = img.transpose(1, 2, 0)\n if scale_factor < 1:\n img = cv2.resize(img, (w, h))\n\n mosaic[block_y:block_y + h, block_x:block_x + w, :] = img\n if len(targets) > 0:\n image_targets = targets[targets[:, 0] == i]\n boxes = xywh2xyxy(image_targets[:, 2:6]).T\n classes = image_targets[:, 1].astype('int')\n labels = image_targets.shape[1] == 6 # labels if no conf column\n conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)\n\n if boxes.shape[1]:\n if boxes.max() <= 1.01: # if normalized with tolerance 0.01\n boxes[[0, 2]] *= w # scale to pixels\n boxes[[1, 3]] *= h\n elif scale_factor < 1: # absolute coords need scale if image scales\n boxes *= scale_factor\n boxes[[0, 2]] += block_x\n boxes[[1, 3]] += block_y\n for j, box in enumerate(boxes.T):\n cls = int(classes[j])\n color = colors[cls % len(colors)]\n cls = names[cls] if names else cls\n if labels or conf[j] > 0.25: # 0.25 conf thresh\n label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])\n plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)\n\n # Draw image filename labels\n if paths:\n label = Path(paths[i]).name[:40] # trim to 40 char\n t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,\n lineType=cv2.LINE_AA)\n\n # Image border\n cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)\n\n if fname:\n r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size\n mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)\n # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save\n Image.fromarray(mosaic).save(fname) # PIL save\n return mosaic" }, { "identifier": "plot_labels", "path": "utils/plots.py", "snippet": "def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):\n # plot dataset labels\n print('Plotting labels... ')\n c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes\n nc = int(c.max() + 1) # number of classes\n colors = color_list()\n x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])\n\n # seaborn correlogram\n sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))\n plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)\n plt.close()\n\n # matplotlib labels\n matplotlib.use('svg') # faster\n ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()\n ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)\n ax[0].set_ylabel('instances')\n if 0 < len(names) < 30:\n ax[0].set_xticks(range(len(names)))\n ax[0].set_xticklabels(names, rotation=90, fontsize=10)\n else:\n ax[0].set_xlabel('classes')\n sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)\n sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)\n\n # rectangles\n labels[:, 1:3] = 0.5 # center\n labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000\n img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)\n for cls, *box in labels[:1000]:\n ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot\n ax[1].imshow(img)\n ax[1].axis('off')\n\n for a in [0, 1, 2, 3]:\n for s in ['top', 'right', 'left', 'bottom']:\n ax[a].spines[s].set_visible(False)\n\n plt.savefig(save_dir / 'labels.jpg', dpi=200)\n matplotlib.use('Agg')\n plt.close()\n\n # loggers\n for k, v in loggers.items() or {}:\n if k == 'wandb' and v:\n v.log({\"Labels\": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)" }, { "identifier": "plot_results", "path": "utils/plots.py", "snippet": "def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):\n # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')\n fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)\n ax = ax.ravel()\n s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',\n 'val Box', 'val Objectness', 'val Classification', '[email protected]', '[email protected]:0.95']\n if bucket:\n # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]\n files = ['results%g.txt' % x for x in id]\n c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)\n os.system(c)\n else:\n files = list(Path(save_dir).glob('results*.txt'))\n assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)\n for fi, f in enumerate(files):\n try:\n results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T\n n = results.shape[1] # number of rows\n x = range(start, min(stop, n) if stop else n)\n for i in range(10):\n y = results[i, x]\n if i in [0, 1, 2, 5, 6, 7]:\n y[y == 0] = np.nan # don't show zero loss values\n # y /= y[0] # normalize\n label = labels[fi] if len(labels) else f.stem\n ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)\n ax[i].set_title(s[i])\n # if i in [5, 6, 7]: # share train and val loss y axes\n # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])\n except Exception as e:\n print('Warning: Plotting error for %s; %s' % (f, e))\n\n ax[1].legend()\n fig.savefig(Path(save_dir) / 'results.png', dpi=200)" }, { "identifier": "plot_evolution", "path": "utils/plots.py", "snippet": "def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()\n # Plot hyperparameter evolution results in evolve.txt\n with open(yaml_file) as f:\n hyp = yaml.load(f, Loader=yaml.SafeLoader)\n x = np.loadtxt('evolve.txt', ndmin=2)\n f = fitness(x)\n # weights = (f - f.min()) ** 2 # for weighted results\n plt.figure(figsize=(10, 12), tight_layout=True)\n matplotlib.rc('font', **{'size': 8})\n for i, (k, v) in enumerate(hyp.items()):\n y = x[:, i + 7]\n # mu = (y * weights).sum() / weights.sum() # best weighted result\n mu = y[f.argmax()] # best single result\n plt.subplot(6, 5, i + 1)\n plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')\n plt.plot(mu, f.max(), 'k+', markersize=15)\n plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters\n if i % 5 != 0:\n plt.yticks([])\n print('%15s: %.3g' % (k, mu))\n plt.savefig('evolve.png', dpi=200)\n print('\\nPlot saved as evolve.png')" }, { "identifier": "ModelEMA", "path": "utils/torch_utils.py", "snippet": "class ModelEMA:\n \"\"\" Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models\n Keep a moving average of everything in the model state_dict (parameters and buffers).\n This is intended to allow functionality like\n https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage\n A smoothed version of the weights is necessary for some training schemes to perform well.\n This class is sensitive where it is initialized in the sequence of model init,\n GPU assignment and distributed training wrappers.\n \"\"\"\n\n def __init__(self, model, decay=0.9999, updates=0):\n # Create EMA\n self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA\n # if next(model.parameters()).device.type != 'cpu':\n # self.ema.half() # FP16 EMA\n self.updates = updates # number of EMA updates\n self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)\n for p in self.ema.parameters():\n p.requires_grad_(False)\n\n def update(self, model):\n # Update EMA parameters\n with torch.no_grad():\n self.updates += 1\n d = self.decay(self.updates)\n\n msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict\n for k, v in self.ema.state_dict().items():\n if v.dtype.is_floating_point:\n v *= d\n v += (1. - d) * msd[k].detach()\n\n def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):\n # Update EMA attributes\n copy_attr(self.ema, model, include, exclude)" }, { "identifier": "select_device", "path": "utils/torch_utils.py", "snippet": "def select_device(device='', batch_size=None):\n # device = 'cpu' or '0' or '0,1,2,3'\n s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string\n cpu = device.lower() == 'cpu'\n if cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False\n elif device: # non-cpu device requested\n os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable\n assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability\n\n cuda = not cpu and torch.cuda.is_available()\n if cuda:\n n = torch.cuda.device_count()\n if n > 1 and batch_size: # check that batch_size is compatible with device_count\n assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'\n space = ' ' * len(s)\n for i, d in enumerate(device.split(',') if device else range(n)):\n p = torch.cuda.get_device_properties(i)\n s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\\n\" # bytes to MB\n else:\n s += 'CPU\\n'\n\n logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe\n return torch.device('cuda:0' if cuda else 'cpu')" }, { "identifier": "intersect_dicts", "path": "utils/torch_utils.py", "snippet": "def intersect_dicts(da, db, exclude=()):\n # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values\n return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}" }, { "identifier": "torch_distributed_zero_first", "path": "utils/torch_utils.py", "snippet": "@contextmanager\ndef torch_distributed_zero_first(local_rank: int):\n \"\"\"\n Decorator to make all processes in distributed training wait for each local_master to do something.\n \"\"\"\n if local_rank not in [-1, 0]:\n torch.distributed.barrier()\n yield\n if local_rank == 0:\n torch.distributed.barrier()" }, { "identifier": "is_parallel", "path": "utils/torch_utils.py", "snippet": "def is_parallel(model):\n return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)" }, { "identifier": "getMask", "path": "utils/distill_utils.py", "snippet": "def getMask(batch_size, gt_boxes, img_size, feat, anchors, max_num_box, device):\r\n # [b, K, 4]\r\n gt_boxes = make_gt_boxes(gt_boxes, max_num_box, batch_size, img_size)\r\n feat_stride = img_size[0] / feat.size(2)\r\n anchors = torch.from_numpy(generate_anchors(feat_stride, anchors))\r\n feat = feat.cpu()\r\n height, width = feat.size(2), feat.size(3)\r\n feat_height, feat_width = feat.size(2), feat.size(3)\r\n shift_x = np.arange(0, feat_width) * feat_stride\r\n shift_y = np.arange(0, feat_height) * feat_stride\r\n shift_x, shift_y = np.meshgrid(shift_x, shift_y)\r\n shifts = torch.from_numpy(np.vstack((shift_x.ravel(), shift_y.ravel(),\r\n shift_x.ravel(), shift_y.ravel())).transpose())\r\n shifts = shifts.contiguous().type_as(feat).float()\r\n\r\n # num of anchors [3]\r\n A = anchors.size(0)\r\n K = shifts.size(0)\r\n\r\n anchors = anchors.type_as(gt_boxes)\r\n # all_anchors [K, A, 4]\r\n all_anchors = anchors.view(1, A, 4) + shifts.view(K, 1, 4)\r\n all_anchors = all_anchors.view(K * A, 4)\r\n # compute iou [all_anchors, gt_boxes]\r\n IOU_map = bbox_overlaps_batch(all_anchors, gt_boxes, img_size).view(batch_size, height, width, A, gt_boxes.shape[1])\r\n\r\n mask_batch = []\r\n for i in range(batch_size):\r\n max_iou, _ = torch.max(IOU_map[i].view(height * width * A, gt_boxes.shape[1]), dim=0)\r\n mask_per_im = torch.zeros([height, width], dtype=torch.int64).to(device)\r\n for k in range(gt_boxes.shape[1]):\r\n if torch.sum(gt_boxes[i][k]) == 0:\r\n break\r\n max_iou_per_gt = max_iou[k] * 0.5\r\n mask_per_gt = torch.sum(IOU_map[i][:, :, :, k] > max_iou_per_gt, dim=2)\r\n mask_per_im += mask_per_gt.to(device)\r\n mask_batch.append(mask_per_im)\r\n return mask_batch\r" }, { "identifier": "compute_mask_loss", "path": "utils/distill_utils.py", "snippet": "def compute_mask_loss(mask_batch, student_feature, teacher_feature, imitation_loss_weight):\r\n mask_list = []\r\n for mask in mask_batch:\r\n mask = (mask > 0).float().unsqueeze(0)\r\n mask_list.append(mask)\r\n mask_batch = torch.stack(mask_list, dim=0)\r\n norms = mask_batch.sum() * 2\r\n mask_batch_s = mask_batch.unsqueeze(4)\r\n no = student_feature.size(-1)\r\n bs, na, height, width, _ = mask_batch_s.shape\r\n mask_batch_no = mask_batch_s.expand((bs, na, height, width, no))\r\n sup_loss = (torch.pow(teacher_feature - student_feature, 2) * mask_batch_no).sum() / norms\r\n sup_loss = sup_loss * imitation_loss_weight\r\n return sup_loss\r" } ]
import argparse import logging import math import os import random import time import numpy as np import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler import torch.utils.data import yaml import test # import test.py to get mAP after each epoch from copy import deepcopy from pathlib import Path from threading import Thread from torch.cuda import amp from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from models.experimental import attempt_load from models.experimental import attempt_loadv5 from models.experimental import attempt_load_zxy from models.yolo import Model from utils.autoanchor import check_anchors from utils.datasets import create_dataloader from utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \ fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \ check_requirements, print_mutation, set_logging, one_cycle, colorstr from utils.google_utils import attempt_download from utils.loss import ComputeLoss, ComputeLossOTA from utils.plots import plot_images, plot_labels, plot_results, plot_evolution from utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first, is_parallel from utils.wandb_logging.wandb_utils import WandbLogger, check_wandb_resume from utils.distill_utils import getMask, compute_mask_loss
19,203
logger = logging.getLogger(__name__) def train(hyp, opt, device, tb_writer=None): logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items())) save_dir, epochs, batch_size, total_batch_size, weights, rank, freeze = \ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank, opt.freeze # Directories wdir = save_dir / 'weights' wdir.mkdir(parents=True, exist_ok=True) # make dir last = wdir / 'last.pt' best = wdir / 'best.pt' results_file = save_dir / 'results.txt' # Save run settings with open(save_dir / 'hyp.yaml', 'w') as f: yaml.dump(hyp, f, sort_keys=False) with open(save_dir / 'opt.yaml', 'w') as f: yaml.dump(vars(opt), f, sort_keys=False) # Configure plots = not opt.evolve # create plots cuda = device.type != 'cpu' init_seeds(2 + rank) with open(opt.data) as f: data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict is_coco = opt.data.endswith('coco.yaml') # Logging- Doing this before checking the dataset. Might update data_dict loggers = {'wandb': None} # loggers dict if rank in [-1, 0]: opt.hyp = hyp # add hyperparameters run_id = torch.load(weights, map_location=device).get('wandb_id') if weights.endswith('.pt') and os.path.isfile( weights) else None wandb_logger = WandbLogger(opt, Path(opt.save_dir).stem, run_id, data_dict) loggers['wandb'] = wandb_logger.wandb data_dict = wandb_logger.data_dict if wandb_logger.wandb: weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check # Model pretrained = weights.endswith('.pt') # load teacher model teacher = attempt_load_zxy(opt.teacher_weights, device=device) if pretrained: with torch_distributed_zero_first(rank): attempt_download(weights) # download if not found locally ckpt = torch.load(weights, map_location=device) # load checkpoint model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys state_dict = ckpt['model'].float().state_dict() # to FP32 state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect model.load_state_dict(state_dict, strict=False) # load logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report else: model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create with torch_distributed_zero_first(rank):
logger = logging.getLogger(__name__) def train(hyp, opt, device, tb_writer=None): logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items())) save_dir, epochs, batch_size, total_batch_size, weights, rank, freeze = \ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank, opt.freeze # Directories wdir = save_dir / 'weights' wdir.mkdir(parents=True, exist_ok=True) # make dir last = wdir / 'last.pt' best = wdir / 'best.pt' results_file = save_dir / 'results.txt' # Save run settings with open(save_dir / 'hyp.yaml', 'w') as f: yaml.dump(hyp, f, sort_keys=False) with open(save_dir / 'opt.yaml', 'w') as f: yaml.dump(vars(opt), f, sort_keys=False) # Configure plots = not opt.evolve # create plots cuda = device.type != 'cpu' init_seeds(2 + rank) with open(opt.data) as f: data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict is_coco = opt.data.endswith('coco.yaml') # Logging- Doing this before checking the dataset. Might update data_dict loggers = {'wandb': None} # loggers dict if rank in [-1, 0]: opt.hyp = hyp # add hyperparameters run_id = torch.load(weights, map_location=device).get('wandb_id') if weights.endswith('.pt') and os.path.isfile( weights) else None wandb_logger = WandbLogger(opt, Path(opt.save_dir).stem, run_id, data_dict) loggers['wandb'] = wandb_logger.wandb data_dict = wandb_logger.data_dict if wandb_logger.wandb: weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check # Model pretrained = weights.endswith('.pt') # load teacher model teacher = attempt_load_zxy(opt.teacher_weights, device=device) if pretrained: with torch_distributed_zero_first(rank): attempt_download(weights) # download if not found locally ckpt = torch.load(weights, map_location=device) # load checkpoint model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys state_dict = ckpt['model'].float().state_dict() # to FP32 state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect model.load_state_dict(state_dict, strict=False) # load logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report else: model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create with torch_distributed_zero_first(rank):
check_dataset(data_dict) # check
6
2023-10-08 13:05:58+00:00
24k
falesiani/torch_ga
tests/test_keras.py
[ { "identifier": "GeometricProductDense", "path": "torch_ga/layers.py", "snippet": "class GeometricProductDense(GeometricAlgebraLayer):\n \"\"\"Analagous to Keras' Dense layer but using multivector-valued matrices\n instead of scalar ones and geometric multiplication instead of standard\n multiplication.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n units: int,\n blade_indices_kernel: List[int],\n blade_indices_bias: Union[None, List[int]] = None,\n activation='None',\n use_bias=True,\n **kwargs\n ):\n super().__init__(algebra=algebra, **kwargs)\n\n self.units = units\n self.blade_indices_kernel = torch.tensor(blade_indices_kernel, dtype=torch.int64)\n if use_bias: self.blade_indices_bias = torch.tensor(blade_indices_bias, dtype=torch.int64)\n # self.blade_indices_kernel = blade_indices_kernel.to(dtype=torch.int64)\n # if use_bias: self.blade_indices_bias = blade_indices_bias.to(dtype=torch.int64) \n\n self.activation = activation\n self.use_bias = use_bias\n self.activation_fn = activations.get(activation)\n self.built = False\n\n def build(self, input_shape: list):\n if False: print(f\"input_shape={input_shape}\")\n self.num_input_units = input_shape[-2]\n shape_kernel = [\n self.units,\n self.num_input_units,\n int(self.blade_indices_kernel.shape[0])\n ]\n if False: print(f\"shape_kernel={shape_kernel}\")\n self.kernel = nn.Parameter(1./np.prod(shape_kernel)*torch.randn(size=shape_kernel)).to(dtype=torch.float)\n if self.use_bias:\n shape_bias = [self.units, self.blade_indices_bias.shape[0]]\n self.bias = nn.Parameter(1./np.prod(shape_bias)*torch.randn(size=shape_bias)).to(dtype=torch.float)\n else:\n self.bias = None\n self.built = True\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-2], self.units, self.algebra.num_blades]\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor(self.kernel, self.blade_indices_kernel)\n\n # Perform a matrix-multiply, but using geometric product instead of\n # standard multiplication. To do this we do the geometric product\n # elementwise and then sum over the common axis.\n # [..., 1, I, X] * [..., O, I, X] -> [..., O, I, X] -> [..., O, X]\n # inputs_expanded = tf.expand_dims(inputs, axis=inputs.shape.ndims - 2)\n # result = tf.reduce_sum(self.algebra.geom_prod(\n # inputs_expanded, w_geom), axis=-2)\n\n inputs_expanded = inputs.unsqueeze(len(inputs.shape) - 2)\n result = self.algebra.geom_prod(inputs_expanded, w_geom).sum(dim=-2)\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(self.bias, self.blade_indices_bias)\n result += b_geom\n if self.activation_fn:\n result = self.activation_fn(result)\n return result\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices_kernel\":\n self.blade_indices_kernel.cpu().detach().numpy(),\n \"blade_indices_bias\":\n self.blade_indices_bias.cpu().detach().numpy(),\n \"units\":\n self.units,\n # \"activation\":\n # activations.serialize(self.activation),\n \"use_bias\":\n self.use_bias,\n })\n return config" }, { "identifier": "GeometricSandwichProductDense", "path": "torch_ga/layers.py", "snippet": "class GeometricSandwichProductDense(GeometricProductDense):\n \"\"\"Analagous to Keras' Dense layer but using multivector-valued matrices\n instead of scalar ones and geometric sandwich multiplication instead of\n standard multiplication.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self, algebra, units, blade_indices_kernel, blade_indices_bias=None,\n activation=None, use_bias=True, \n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\", kernel_regularizer=None,\n # bias_regularizer=None, activity_regularizer=None,\n # kernel_constraint=None, bias_constraint=None, \n **kwargs\n ):\n super().__init__(\n algebra, units,\n blade_indices_kernel,\n blade_indices_bias=blade_indices_bias,\n activation=activation,\n use_bias=use_bias,\n # kernel_initializer=kernel_initializer,\n # bias_initializer=bias_initializer,\n # kernel_regularizer=kernel_regularizer,\n # bias_regularizer=bias_regularizer,\n # activity_regularizer=activity_regularizer,\n # kernel_constraint=kernel_constraint,\n # bias_constraint=bias_constraint, \n **kwargs\n )\n self.built = False\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor(self.kernel, self.blade_indices_kernel)\n\n # Same as GeometricProductDense but using R*x*~R instead of just R*x\n # inputs_expanded = tf.expand_dims(inputs, axis=inputs.shape.ndims - 2)\n # result = tf.reduce_sum(\n # self.algebra.geom_prod(\n # w_geom,\n # self.algebra.geom_prod(\n # inputs_expanded,\n # self.algebra.reversion(w_geom)\n # )\n # ),\n # axis=-2\n # )\n # if self.bias is not None:\n # b_geom = self.algebra.from_tensor(\n # self.bias, self.blade_indices_bias)\n # result += b_geom\n\n # return self.activation(result)\n\n inputs_expanded = inputs.unsqueeze(len(inputs.shape) - 2)\n result = self.algebra.geom_prod( w_geom, self.algebra.geom_prod(inputs_expanded, self.algebra.reversion(w_geom))).sum(dim=-2)\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(self.bias, self.blade_indices_bias)\n result += b_geom\n if self.activation_fn:\n result = self.activation_fn(result)\n return result" }, { "identifier": "GeometricProductElementwise", "path": "torch_ga/layers.py", "snippet": "class GeometricProductElementwise(GeometricAlgebraLayer):\n \"\"\"Performs the elementwise geometric product with a list of multivectors\n with as many elements as there are input units.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n blade_indices_kernel: List[int],\n blade_indices_bias: Union[None, List[int]] = None,\n activation=None,\n use_bias=True,\n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\",\n # kernel_regularizer=None,\n # bias_regularizer=None,\n # activity_regularizer=None,\n # kernel_constraint=None,\n # bias_constraint=None,\n **kwargs\n ):\n # super().__init__(algebra=algebra, activity_regularizer=activity_regularizer, **kwargs)\n super().__init__(algebra=algebra, **kwargs)\n\n self.blade_indices_kernel = torch.tensor(blade_indices_kernel, dtype=torch.int64)\n if use_bias:\n self.blade_indices_bias = torch.tensor(blade_indices_bias, dtype=torch.int64)\n \n # self.blade_indices_kernel = blade_indices_kernel.to(dtype=torch.int64)\n # if use_bias:\n # self.blade_indices_bias = blade_indices_bias.to(dtype=torch.int64)\n\n self.activation_fn = activations.get(activation)\n self.use_bias = use_bias\n # self.kernel_initializer = initializers.get(kernel_initializer)\n # self.bias_initializer = initializers.get(bias_initializer)\n # self.kernel_regularizer = regularizers.get(kernel_regularizer)\n # self.bias_regularizer = regularizers.get(bias_regularizer)\n # self.kernel_constraint = constraints.get(kernel_constraint)\n # self.bias_constraint = constraints.get(bias_constraint)\n self.built = False\n\n def build(self, input_shape: torch.Size):\n self.num_input_units = input_shape[-2]\n shape_kernel = [\n self.num_input_units,\n self.blade_indices_kernel.shape[0]\n ]\n self.kernel = nn.Parameter(1./np.prod(shape_kernel)*torch.randn(shape_kernel)).to(dtype=torch.float)\n if self.use_bias:\n shape_bias = [self.num_input_units,self.blade_indices_bias.shape[0]]\n self.bias = nn.Parameter(1./np.prod(shape_bias)*torch.randn(shape_bias)).to(dtype=torch.float)\n else:\n self.bias = None\n\n # self.kernel = self.add_weight(\n # \"kernel\",\n # shape=shape_kernel,\n # initializer=self.kernel_initializer,\n # regularizer=self.kernel_regularizer,\n # constraint=self.kernel_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # if self.use_bias:\n # shape_bias = [self.num_input_units,\n # self.blade_indices_bias.shape[0]]\n # self.bias = self.add_weight(\n # \"bias\",\n # shape=shape_bias,\n # initializer=self.bias_initializer,\n # regularizer=self.bias_regularizer,\n # constraint=self.bias_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # else:\n # self.bias = None\n self.built = True\n\n def compute_output_shape(self, input_shape):\n return torch.Size([*input_shape[:-1], self.algebra.num_blades])\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor(\n self.kernel, self.blade_indices_kernel)\n\n # Elementwise multiplication for each unit with a multivector.\n # [..., U, X] * [U, X] -> [..., U, X]\n result = self.algebra.geom_prod(inputs, w_geom)\n\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(\n self.bias, self.blade_indices_bias)\n result += b_geom\n\n if self.activation_fn:\n result = self.activation_fn(result)\n return result\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices_kernel\":\n self.blade_indices_kernel.cpu().detach().numpy(),\n \"blade_indices_bias\":\n self.blade_indices_bias.cpu().detach().numpy(),\n # \"activation\":\n # self.activation,\n # activations.serialize(self.activation),\n \"use_bias\":\n self.use_bias,\n # \"kernel_initializer\":\n # initializers.serialize(self.kernel_initializer),\n # \"bias_initializer\":\n # initializers.serialize(self.bias_initializer),\n # \"kernel_regularizer\":\n # regularizers.serialize(self.kernel_regularizer),\n # \"bias_regularizer\":\n # regularizers.serialize(self.bias_regularizer),\n # \"activity_regularizer\":\n # regularizers.serialize(self.activity_regularizer),\n # \"kernel_constraint\":\n # constraints.serialize(self.kernel_constraint),\n # \"bias_constraint\":\n # constraints.serialize(self.bias_constraint)\n })\n return config" }, { "identifier": "GeometricSandwichProductElementwise", "path": "torch_ga/layers.py", "snippet": "class GeometricSandwichProductElementwise(GeometricProductElementwise):\n \"\"\"Performs the elementwise geometric sandwich product with a list of\n multivectors with as many elements as there are input units.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self, algebra, blade_indices_kernel, blade_indices_bias=None,\n activation=None, use_bias=True, \n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\", kernel_regularizer=None,\n # bias_regularizer=None, activity_regularizer=None,\n # kernel_constraint=None, bias_constraint=None, \n **kwargs\n ):\n super().__init__(\n algebra,\n blade_indices_kernel,\n blade_indices_bias=blade_indices_bias,\n activation=activation,\n use_bias=use_bias,\n # kernel_initializer=kernel_initializer,\n # bias_initializer=bias_initializer,\n # kernel_regularizer=kernel_regularizer,\n # bias_regularizer=bias_regularizer,\n # activity_regularizer=activity_regularizer,\n # kernel_constraint=kernel_constraint,\n # bias_constraint=bias_constraint, \n **kwargs\n )\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n w_geom = self.algebra.from_tensor( self.kernel, self.blade_indices_kernel)\n\n # Elementwise multiplication Rx~R for each unit with a multivector.\n # [..., U, X] * [U, X] -> [..., U, X]\n result = self.algebra.geom_prod(\n w_geom,\n self.algebra.geom_prod(\n inputs,\n self.algebra.reversion(w_geom)\n )\n )\n\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(\n self.bias, self.blade_indices_bias)\n result += b_geom\n\n if self.activation_fn:\n result = self.activation_fn(result)\n return result" }, { "identifier": "GeometricProductConv1D", "path": "torch_ga/layers.py", "snippet": "class GeometricProductConv1D(GeometricAlgebraLayer):\n \"\"\"Analagous to Keras' Conv1D layer but using multivector-valued kernels\n instead of scalar ones and geometric product instead of\n standard multiplication.\n\n Args:\n algebra: GeometricAlgebra instance to use for the parameters\n filters: How many channels the output will have\n kernel_size: Size for the convolution kernel\n stride: Stride to use for the convolution\n padding: \"SAME\" (zero-pad input length so output\n length == input length / stride) or \"VALID\" (no padding)\n blade_indices_kernel: Blade indices to use for the kernel parameter\n blade_indices_bias: Blade indices to use for the bias parameter (if used)\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n filters: int,\n kernel_size: int,\n stride: int,\n padding: str,\n blade_indices_kernel: List[int],\n blade_indices_bias: Union[None, List[int]] = None,\n dilations: Union[None, int] = None,\n activation=None,\n use_bias=True,\n # kernel_initializer=\"glorot_uniform\",\n # bias_initializer=\"zeros\",\n # kernel_regularizer=None,\n # bias_regularizer=None,\n # activity_regularizer=None,\n # kernel_constraint=None,\n # bias_constraint=None,\n **kwargs\n ):\n super().__init__(\n algebra=algebra,\n # activity_regularizer=activity_regularizer,\n **kwargs\n )\n\n self.filters = filters\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.dilations = dilations\n\n self.blade_indices_kernel = torch.tensor( blade_indices_kernel, dtype=torch.int64)\n if use_bias:\n self.blade_indices_bias = torch.tensor( blade_indices_bias, dtype=torch.int64)\n # self.blade_indices_kernel = blade_indices_kernel.to(dtype=torch.int64)\n # if use_bias:\n # self.blade_indices_bias = blade_indices_bias.to(dtype=torch.int64)\n\n self.activation_fn = activations.get(activation)\n self.use_bias = use_bias\n # self.kernel_initializer = initializers.get(kernel_initializer)\n # self.bias_initializer = initializers.get(bias_initializer)\n # self.kernel_regularizer = regularizers.get(kernel_regularizer)\n # self.bias_regularizer = regularizers.get(bias_regularizer)\n # self.kernel_constraint = constraints.get(kernel_constraint)\n # self.bias_constraint = constraints.get(bias_constraint)\n self.built = False\n\n def build(self, input_shape: torch.Size):\n # I: [..., S, C, B]\n self.num_input_filters = input_shape[-2]\n\n # K: [K, IC, OC, B]\n shape_kernel = [\n self.kernel_size,\n self.num_input_filters,\n self.filters,\n self.blade_indices_kernel.shape[0]\n ]\n self.kernel = nn.Parameter(1./np.prod(shape_kernel)*torch.randn(size=shape_kernel)).to(dtype=torch.float)\n if self.use_bias:\n shape_bias = [self.filters, self.blade_indices_bias.shape[0]]\n self.bias = nn.Parameter(1./np.prod(shape_bias)*torch.randn(size=shape_bias)).to(dtype=torch.float)\n else:\n self.bias = None\n\n # self.kernel = self.add_weight(\n # \"kernel\",\n # shape=shape_kernel,\n # initializer=self.kernel_initializer,\n # regularizer=self.kernel_regularizer,\n # constraint=self.kernel_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # if self.use_bias:\n # shape_bias = [self.filters, self.blade_indices_bias.shape[0]]\n # self.bias = self.add_weight(\n # \"bias\",\n # shape=shape_bias,\n # initializer=self.bias_initializer,\n # regularizer=self.bias_regularizer,\n # constraint=self.bias_constraint,\n # dtype=self.dtype,\n # trainable=True\n # )\n # else:\n # self.bias = None\n self.built = True\n\n def forward(self, inputs):\n if not self.built: \n self.build(inputs.shape)\n k_geom = self.algebra.from_tensor(\n self.kernel, self.blade_indices_kernel)\n\n result = self.algebra.geom_conv1d(\n inputs, k_geom,\n stride=self.stride, padding=self.padding,\n dilations=self.dilations\n )\n\n if self.bias is not None:\n b_geom = self.algebra.from_tensor(\n self.bias, self.blade_indices_bias)\n result += b_geom\n\n if self.activation_fn:\n result = self.activation_fn(result)\n return result\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"filters\":\n self.filters,\n \"kernel_size\":\n self.kernel_size,\n \"stride\":\n self.stride,\n \"padding\":\n self.padding,\n \"dilations\":\n self.dilations,\n \"blade_indices_kernel\":\n self.blade_indices_kernel.numpy(),\n \"blade_indices_bias\":\n self.blade_indices_bias.numpy(),\n # \"activation\":\n # activations.serialize(self.activation),\n \"use_bias\":\n self.use_bias,\n # \"kernel_initializer\":\n # initializers.serialize(self.kernel_initializer),\n # \"bias_initializer\":\n # initializers.serialize(self.bias_initializer),\n # \"kernel_regularizer\":\n # regularizers.serialize(self.kernel_regularizer),\n # \"bias_regularizer\":\n # regularizers.serialize(self.bias_regularizer),\n # \"activity_regularizer\":\n # regularizers.serialize(self.activity_regularizer),\n # \"kernel_constraint\":\n # constraints.serialize(self.kernel_constraint),\n # \"bias_constraint\":\n # constraints.serialize(self.bias_constraint)\n\n })\n\n return config" }, { "identifier": "GeometricAlgebraExp", "path": "torch_ga/layers.py", "snippet": "class GeometricAlgebraExp(GeometricAlgebraLayer):\n \"\"\"Calculates the exponential function of the input. Input must square to\n a scalar.\n\n Args:\n algebra: GeometricAlgebra instance to use\n square_scalar_tolerance: Tolerance to use for the square scalar check\n or None if the check should be skipped\n \"\"\"\n\n def __init__(\n self,\n algebra: GeometricAlgebra,\n square_scalar_tolerance: Union[float, None] = 1e-4,\n **kwargs\n ):\n super().__init__(algebra=algebra, **kwargs)\n self.square_scalar_tolerance = square_scalar_tolerance\n self.built = False\n\n def compute_output_shape(self, input_shape):\n return torch.Size([*input_shape[:-1], self.algebra.num_blades])\n\n def build(self,inputs_shape): self.built = True\n\n def forward(self, inputs):\n if not self.built: self.build(inputs.shape)\n return self.algebra.exp(\n inputs, square_scalar_tolerance=self.square_scalar_tolerance\n )\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"square_scalar_tolerance\": self.square_scalar_tolerance\n })\n return config" }, { "identifier": "GeometricToTensor", "path": "torch_ga/layers.py", "snippet": "class GeometricToTensor(GeometricAlgebraLayer):\n \"\"\"Layer for extracting given blades from geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n blade_indices: blade indices to extract\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, blade_indices: List[int],\n **kwargs):\n super().__init__(algebra=algebra, **kwargs)\n self.blade_indices = torch.tensor(blade_indices).to(dtype=torch.int64)\n # self.blade_indices = blade_indices.to(dtype=torch.int64) \n self.built = False\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-1], self.blade_indices.shape[0]]\n def build(self,input_shape): self.built = True\n\n def forward(self, inputs):\n if not self.build: self.build(inputs.shape)\n # return torch.select(inputs, self.blade_indices, axis=-1)\n x = inputs[...,self.blade_indices]\n return x\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices\": self.blade_indices.numpy()\n })\n return config" }, { "identifier": "GeometricToTensorWithKind", "path": "torch_ga/layers.py", "snippet": "class GeometricToTensorWithKind(GeometricToTensor):\n \"\"\"Layer for extracting blades of a kind from geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n kind: blade indices of kind to extract\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, kind: BladeKind,\n **kwargs):\n blade_indices = algebra.get_kind_blade_indices(kind)\n super().__init__(algebra=algebra, blade_indices=blade_indices,\n **kwargs)" }, { "identifier": "TensorToGeometric", "path": "torch_ga/layers.py", "snippet": "class TensorToGeometric(GeometricAlgebraLayer):\n \"\"\"Layer for converting tensors with given blade indices to\n geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n blade_indices: blade indices to interpret the last axis of the\n input tensor as\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, blade_indices: List[int],\n **kwargs):\n super().__init__(algebra=algebra, **kwargs)\n\n self.blade_indices = torch.tensor(blade_indices, dtype=torch.int64)\n # self.blade_indices = blade_indices.to(dtype=torch.int64) \n self.built = False\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-1], self.algebra.num_blades]\n\n def forward(self, inputs):\n if not self.build: self.build(inputs.shape)\n return self.algebra.from_tensor(inputs, blade_indices=self.blade_indices)\n def build(self,input_shape): self.built = True\n def get_config(self):\n config = super().get_config()\n config.update({\n \"blade_indices\": self.blade_indices.numpy()\n })\n return config" }, { "identifier": "TensorWithKindToGeometric", "path": "torch_ga/layers.py", "snippet": "class TensorWithKindToGeometric(GeometricAlgebraLayer):\n \"\"\"Layer for converting tensors with given blade kind to\n geometric algebra tensors.\n\n Args:\n algebra: GeometricAlgebra instance to use\n kind: blade kind indices to interpret the last axis of the\n input tensor as\n \"\"\"\n\n def __init__(self, algebra: GeometricAlgebra, kind: BladeKind,\n **kwargs):\n super().__init__(algebra=algebra, **kwargs)\n self.kind = kind\n self.built = False\n\n def compute_output_shape(self, input_shape):\n return [*input_shape[:-1], self.algebra.get_kind_blade_indices(self.kind).shape[0]]\n\n def build(self,input_shape): self.built = True\n def forward(self, inputs):\n if not self.build: self.build(inputs.shape)\n\n return self.algebra.from_tensor_with_kind(inputs, kind=self.kind)\n\n def get_config(self):\n config = super().get_config()\n config.update({\n \"kind\": self.kind\n })\n return config" }, { "identifier": "BladeKind", "path": "torch_ga/blades.py", "snippet": "class BladeKind(Enum):\n \"\"\"Kind of blade depending on its degree.\"\"\"\n MV = \"mv\"\n EVEN = \"even\"\n ODD = \"odd\"\n SCALAR = \"scalar\"\n VECTOR = \"vector\"\n BIVECTOR = \"bivector\"\n TRIVECTOR = \"trivector\"\n PSEUDOSCALAR = \"pseudoscalar\"\n PSEUDOVECTOR = \"pseudovector\"\n PSEUDOBIVECTOR = \"pseudobivector\"\n PSEUDOTRIVECTOR = \"pseudotrivector\"" }, { "identifier": "GeometricAlgebra", "path": "torch_ga/torch_ga.py", "snippet": "class GeometricAlgebra:\n \"\"\"Class used for performing geometric algebra operations on `torch.Tensor` instances.\n Exposes methods for operating on `torch.Tensor` instances where their last\n axis is interpreted as blades of the algebra.\n Holds the metric and other quantities derived from it.\n \"\"\"\n\n def __init__(self, metric: List[float]):\n \"\"\"Creates a GeometricAlgebra object given a metric.\n The algebra will have as many basis vectors as there are\n elements in the metric.\n\n Args:\n metric: Metric as a list. Specifies what basis vectors square to\n \"\"\"\n self._metric = torch.tensor(metric, dtype=torch.float32)\n\n self._num_bases = len(metric)\n self._bases = list(map(str, range(self._num_bases)))\n\n self._blades, self._blade_degrees = blades_from_bases(self._bases)\n self._blade_degrees = torch.tensor(self._blade_degrees)\n self._num_blades = len(self._blades)\n self._max_degree = self._blade_degrees.max()\n\n # [Blades, Blades, Blades]\n _list = get_cayley_tensor(self.metric, self._bases, self._blades)\n # print(_list)\n if type(_list) in [list,tuple]:\n _list = np.array(_list)\n self._cayley, self._cayley_inner, self._cayley_outer = torch.tensor(\n _list,\n dtype=torch.float32\n )\n\n self._blade_mvs = torch.eye(self._num_blades)\n self._basis_mvs = self._blade_mvs[1:1+self._num_bases]\n\n # Find the dual by looking at the anti-diagonal in the Cayley tensor.\n self._dual_blade_indices = []\n self._dual_blade_signs = []\n\n for blade_index in range(self._num_blades):\n dual_index = self.num_blades - blade_index - 1\n anti_diag = self._cayley[blade_index, dual_index]\n # dual_sign = tf.gather(anti_diag, tf.where(\n # anti_diag != 0.0)[..., 0])[..., 0]\n dual_sign = anti_diag[torch.where(anti_diag != 0.0)]\n\n self._dual_blade_indices.append(dual_index)\n self._dual_blade_signs.append(dual_sign)\n\n self._dual_blade_indices = torch.tensor(\n self._dual_blade_indices, dtype=torch.int64)\n self._dual_blade_signs = torch.tensor(\n self._dual_blade_signs, dtype=torch.float32)\n\n def print(self, *args, **kwargs):\n \"\"\"Same as the default `print` function but formats `torch.Tensor`\n instances that have as many elements on their last axis\n as the algebra has blades using `mv_repr()`.\n \"\"\"\n def _is_mv(arg):\n return isinstance(arg, torch.Tensor) and len(arg.shape) > 0 and arg.shape[-1] == self.num_blades\n new_args = [self.mv_repr(arg) if _is_mv(arg) else arg for arg in args]\n\n print(*new_args, **kwargs)\n\n @property\n def metric(self) -> torch.Tensor:\n \"\"\"Metric list which contains the number that each\n basis vector in the algebra squares to\n (ie. the diagonal of the metric tensor).\n \"\"\"\n return self._metric\n\n @property\n def cayley(self) -> torch.Tensor:\n \"\"\"`MxMxM` tensor where `M` is the number of basis\n blades in the algebra. Used for calculating the\n geometric product:\n\n `a_i, b_j, cayley_ijk -> c_k`\n \"\"\"\n return self._cayley\n\n @property\n def cayley_inner(self) -> torch.Tensor:\n \"\"\"Analagous to cayley but for inner product.\"\"\"\n return self._cayley_inner\n\n @property\n def cayley_outer(self) -> torch.Tensor:\n \"\"\"Analagous to cayley but for outer product.\"\"\"\n return self._cayley_outer\n\n @property\n def blades(self) -> List[str]:\n \"\"\"List of all blade names.\n\n Blades are all possible independent combinations of\n basis vectors. Basis vectors are named starting\n from `\"0\"` and counting up. The scalar blade is the\n empty string `\"\"`.\n\n Example\n - Bases: `[\"0\", \"1\", \"2\"]`\n - Blades: `[\"\", \"0\", \"1\", \"2\", \"01\", \"02\", \"12\", \"012\"]`\n \"\"\"\n return self._blades\n\n @property\n def blade_mvs(self) -> torch.Tensor:\n \"\"\"List of all blade tensors in the algebra.\"\"\"\n return self._blade_mvs\n\n @property\n def dual_blade_indices(self) -> torch.Tensor:\n \"\"\"Indices of the dual blades for each blade.\"\"\"\n return self._dual_blade_indices\n\n @property\n def dual_blade_signs(self) -> torch.Tensor:\n \"\"\"Signs of the dual blades for each blade.\"\"\"\n return self._dual_blade_signs\n\n @property\n def num_blades(self) -> int:\n \"\"\"Total number of blades in the algebra.\"\"\"\n return self._num_blades\n\n @property\n def blade_degrees(self) -> torch.Tensor:\n \"\"\"List of blade-degree for each blade in the algebra.\"\"\"\n return self._blade_degrees\n\n @property\n def max_degree(self) -> int:\n \"\"\"Highest blade degree in the algebra.\"\"\"\n return self._max_degree\n\n @property\n def basis_mvs(self) -> torch.Tensor:\n \"\"\"List of basis vectors as torch.Tensor.\"\"\"\n return self._basis_mvs\n\n def get_kind_blade_indices(self, kind: BladeKind, invert: bool = False) -> torch.Tensor:\n \"\"\"Find all indices of blades of a given kind in the algebra.\n\n Args:\n kind: kind of blade to give indices for\n invert: whether to return all blades not of the kind\n\n Returns:\n indices of blades of a given kind in the algebra\n \"\"\"\n return get_blade_of_kind_indices(self.blade_degrees, kind, self.max_degree, invert=invert)\n\n def get_blade_indices_of_degree(self, degree: int) -> torch.Tensor:\n \"\"\"Find all indices of blades of the given degree.\n\n Args:\n degree: degree to return blades for\n\n Returns:\n indices of blades with the given degree in the algebra\n \"\"\"\n # return tf.gather(tf.range(self.num_blades), tf.where(self.blade_degrees == degree)[..., 0])\n return torch.range(self.num_blades)[torch.where(self.blade_degrees == degree)[..., 0]]\n\n def is_pure(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> bool:\n \"\"\"Returns whether the given tensor is purely of the given blades\n and has no non-zero values for blades not in the given blades.\n\n Args:\n tensor: tensor to check purity for\n blade_indices: blade indices to check purity for\n\n Returns:\n Whether the tensor is purely of the given blades\n and has no non-zero values for blades not in the given blades\n \"\"\"\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n tensor = tensor.to(dtype=torch.float32)\n if not type(blade_indices) in [torch.Tensor]:\n blade_indices = torch.tensor(blade_indices)\n \n blade_indices = blade_indices.to(dtype=torch.int64)\n\n # blade_indices = torch.tensor(\n # blade_indices, dtype=torch.int64)\n\n inverted_blade_indices = invert_blade_indices(\n self.num_blades, blade_indices)\n\n # return tf.reduce_all(tf.gather(\n # tensor,\n # inverted_blade_indices,\n # axis=-1\n # ) == 0)\n return (tensor[inverted_blade_indices]==0).sum(dim=-1)\n\n def is_pure_kind(self, tensor: torch.Tensor, kind: BladeKind) -> bool:\n \"\"\"Returns whether the given tensor is purely of a given kind\n and has no non-zero values for blades not of the kind.\n\n Args:\n tensor: tensor to check purity for\n kind: kind of blade to check purity for\n\n Returns:\n Whether the tensor is purely of a given kind\n and has no non-zero values for blades not of the kind\n \"\"\"\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n tensor = tensor.to(dtype=torch.float32)\n inverted_kind_indices = self.get_kind_blade_indices(kind, invert=True)\n # print(f\"tensor={tensor}\")\n # print(f\"kind={kind}\")\n # print(f\"inverted_kind_indices={inverted_kind_indices.T}\")\n # print(f\"inverted_kind_indices.shape={inverted_kind_indices.shape}\")\n # print(f\"tensor[inverted_kind_indices]={tensor[inverted_kind_indices].T}\")\n # print(f\"tensor[inverted_kind_indices].shape={tensor[inverted_kind_indices].shape}\")\n # print(f\"tensor[inverted_kind_indices]==0={tensor[inverted_kind_indices].T==0}\")\n\n # return tf.reduce_all(tf.gather(\n # tensor,\n # inverted_kind_indices,\n # axis=-1\n # ) == 0)\n return (tensor[inverted_kind_indices]==0).sum(dim=-1)\n\n # def from_tensor(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> torch.Tensor:\n # \"\"\"Creates a geometric algebra torch.Tensor from a torch.Tensor and blade\n # indices. The blade indices have to align with the last axis of the\n # tensor.\n\n # Args:\n # tensor: torch.Tensor to take as values for the geometric algebra tensor\n # blade_indices: Blade indices corresponding to the tensor. Can\n # be obtained from blade names eg. using get_kind_blade_indices()\n # or as indices from the blades list property.\n\n # Returns:\n # Geometric algebra torch.Tensor from tensor and blade indices\n # \"\"\"\n # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64)\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n # # print(f\"blade_indices={blade_indices}\")\n # # print(f\"tensor={tensor}\")\n \n # _shape = tensor.shape\n # is_scalar = False\n # if len(_shape)==1 :\n # _shape_final = [1]+ [self.num_blades] \n # is_scalar = True\n # else:\n # _shape_final = list(_shape[:-1]) + [self.num_blades] \n # b = torch.zeros(_shape_final)\n \n\n # # i = blade_indices.view([-1,1])\n # # v = tensor.flatten().view([-1,1])\n # i = blade_indices.nonzero().flatten()\n # v = tensor.flatten().unsqueeze(1)\n # b = b.view([-1,self.num_blades])\n # # b[:,i] = v\n # try:\n # b[:,i] = v\n # except:\n # print(f\"_shape={_shape},_shape_final={_shape_final}\")\n # print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n # print(f\"i={i},v={v},b={b}\")\n # raise\n # # raise \"whatever\"\n # b = b.reshape(_shape_final)\n\n # # _shape_tmp = list(v.shape) + [self.num_blades] \n # # print(f\"i,v,_shape_tmp,_shape_final={i},{v},{_shape_tmp},{_shape_final},i.shape={i.shape}\")\n # # b = torch.sparse_coo_tensor(i, v, size=_shape_tmp)\n # # print(f\"b={b}\")\n # # b = torch.sparse_coo_tensor(i, v, size=_shape_tmp).to_dense()\n # # b = b.reshape(_shape_final)\n # if is_scalar:\n # b=b.unsqueeze(0)\n # return b\n\n # # # Put last axis on first axis so scatter_nd becomes easier.\n # # # Later undo the transposition again.\n # # # t = tf.concat([[tensor.shape.ndims - 1],\n # # # tf.range(0, tensor.shape.ndims - 1)], axis=0)\n # # # t_inv = tf.concat([tf.range(1, tensor.shape.ndims), [0]], axis=0)\n\n # # # tensor = tf.transpose(tensor, t)\n\n # # # shape = tf.concat([\n # # # torch.tensor([self.num_blades], dtype=torch.int64),\n # # # tf.shape(tensor, torch.int64)[1:]\n # # # ], axis=0)\n\n # # # tensor = tf.scatter_nd(\n # # # tf.expand_dims(blade_indices, axis=-1),\n # # # tensor,\n # # # shape\n # # # )\n\n # # # return tf.transpose(tensor, t_inv)\n # # # t = torch.concat([torch.tensor([len(tensor.shape) - 1]), torch.range(0, len(tensor.shape)- 1)], axis=0)\n # # # t_inv = torch.concat([torch.range(1, len(tensor.shape)), torch.tensor([0])], axis=0)\n # # t = [len(tensor.shape) - 1] + list(range(0, len(tensor.shape)- 1))\n # # t_inv = list(range(1, len(tensor.shape))) + [0]\n\n # # tensor = torch.permute(tensor, t)\n\n # # a= torch.tensor([self.num_blades], dtype=torch.int64)\n # # b = torch.tensor(tensor, dtype=torch.int64)[1:]\n # # print(\"a,b:\", a,b, tensor)\n\n\n # # shape = torch.concat([\n # # torch.tensor([self.num_blades], dtype=torch.int64),\n # # torch.tensor(tensor, dtype=torch.int64)[1:]\n # # ], axis=0)\n\n\n # # # tensor = torch.scatter_nd(\n # # # blade_indices.unsqueeze(-1),\n # # # tensor,\n # # # shape\n # # # )\n # # a = torch.zeros(shape)\n # # a[blade_indices] = tensor\n # # tensor = a\n\n # # return torch.permute(tensor, t_inv) \n \n\n def from_tensor(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> torch.Tensor:\n \"\"\"Creates a geometric algebra torch.Tensor from a torch.Tensor and blade\n indices. The blade indices have to align with the last axis of the\n tensor.\n\n Args:\n tensor: torch.Tensor to take as values for the geometric algebra tensor\n blade_indices: Blade indices corresponding to the tensor. Can\n be obtained from blade names eg. using get_kind_blade_indices()\n or as indices from the blades list property.\n\n Returns:\n Geometric algebra torch.Tensor from tensor and blade indices\n \"\"\"\n # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64)\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n blade_indices = blade_indices.to(dtype=torch.int64)\n tensor = tensor.to(dtype=torch.float32)\n # print(f\"blade_indices={blade_indices}\")\n # print(f\"tensor={tensor}\")\n \n _shape = tensor.shape\n is_scalar = False\n if len(_shape)==1 :\n _shape_final = [1]+ [self.num_blades] \n is_scalar = True\n else:\n _shape_final = list(_shape[:-1]) + [self.num_blades] \n b = torch.zeros(_shape_final)\n\n if False:\n print(f\"blade_indices.shape={blade_indices.shape}\")\n print(f\"tensor.shape={tensor.shape}\")\n print(f\"_shape_final={_shape_final}\")\n \n\n\n # i = blade_indices.view([-1,1])\n # v = tensor.flatten().view([-1,1])\n # i = blade_indices.nonzero().flatten()\n i = blade_indices.flatten()\n # v = tensor.flatten().unsqueeze(1)\n v = tensor.view([-1,_shape[-1]])\n b = b.view([-1,self.num_blades])\n if False:\n print(f\"_shape={_shape},_shape_final={_shape_final}\")\n print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n print(f\"i={i},v={v},b={b}\")\n\n # b[:,i] = v\n try:\n b[:,i] = v\n except:\n print(f\"_shape={_shape},_shape_final={_shape_final}\")\n print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n print(f\"i={i},v={v},b={b}\")\n raise\n b = b.reshape(_shape_final)\n\n if False:\n print(f\"b.shape={b.shape}\")\n\n if is_scalar:\n # b=b.unsqueeze(0)\n b=b.squeeze(0)\n return b\n\n\n # # i = blade_indices.view([-1,1])\n # # v = tensor.flatten().view([-1,1])\n # i = blade_indices.nonzero().flatten()\n # v = tensor.flatten().unsqueeze(1)\n # b = b.view([-1,self.num_blades])\n # # b[:,i] = v\n # try:\n # b[:,i] = v\n # except:\n # print(f\"_shape={_shape},_shape_final={_shape_final}\")\n # print(f\"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}\")\n # print(f\"i={i},v={v},b={b}\")\n # raise\n # b = b.reshape(_shape_final)\n\n # if is_scalar:\n # b=b.unsqueeze(0)\n # return b\n\n \n\n def from_tensor_with_kind(self, tensor: torch.Tensor, kind: BladeKind) -> torch.Tensor:\n \"\"\"Creates a geometric algebra torch.Tensor from a torch.Tensor and a kind.\n The kind's blade indices have to align with the last axis of the\n tensor.\n\n Args:\n tensor: torch.Tensor to take as values for the geometric algebra tensor\n kind: Kind corresponding to the tensor\n\n Returns:\n Geometric algebra torch.Tensor from tensor and kind\n \"\"\"\n # Put last axis on first axis so scatter_nd becomes easier.\n # Later undo the transposition again.\n # tensor = torch.tensor(tensor, dtype=torch.float32)\n tensor = tensor.to(dtype=torch.float32)\n kind_indices = self.get_kind_blade_indices(kind)\n if False:\n print(f\"tensor={tensor}\")\n print(f\"kind_indices={kind_indices}\")\n return self.from_tensor(tensor, kind_indices)\n\n def from_scalar(self, scalar: numbers.Number) -> torch.Tensor:\n \"\"\"Creates a geometric algebra torch.Tensor with scalar elements.\n\n Args:\n scalar: Elements to be used as scalars\n\n Returns:\n Geometric algebra torch.Tensor from scalars\n \"\"\"\n # return self.from_tensor_with_kind(tf.expand_dims(scalar, axis=-1), BladeKind.SCALAR)\n # print(\"torch.tensor([scalar]).unsqueeze(-1).shape\",torch.tensor([scalar]).unsqueeze(-1).shape)\n return self.from_tensor_with_kind(torch.tensor([scalar]).unsqueeze(-1), BladeKind.SCALAR).squeeze(0)\n\n def e(self, *blades: List[str]) -> torch.Tensor:\n \"\"\"Returns a geometric algebra torch.Tensor with the given blades set\n to 1.\n\n Args:\n blades: list of blade names, can be unnormalized\n\n Returns:\n torch.Tensor with blades set to 1\n \"\"\"\n blade_signs, blade_indices = get_blade_indices_from_names(\n blades, self.blades)\n\n assert type(blade_indices) in [torch.Tensor], \"should be a tensor\"\n if False: blade_indices = torch.tensor(blade_indices)\n\n # # Don't allow duplicate indices\n # tf.Assert(\n # blade_indices.shape[0] == tf.unique(blade_indices)[0].shape[0],\n # [blades]\n # )\n\n # x = (\n # tf.expand_dims(blade_signs, axis=-1) *\n # tf.gather(self.blade_mvs, blade_indices)\n # )\n\n # # a, b -> b\n # return tf.reduce_sum(x, axis=-2)\n\n # print(f\"blade_indices={blade_indices}\")\n # print(f\"torch.unique(blade_indices)={torch.unique(blade_indices)}\")\n # print(f\"torch.unique(blade_indices)[0]={torch.unique(blade_indices)[0]}\")\n # Don't allow duplicate indices\n # assert(\n # blade_indices.shape[0] == torch.unique(blade_indices).shape[0],\n # [blades]\n # )\n assert blade_indices.shape[0] == torch.unique(blade_indices).shape[0], \"indexes not unique\"\n\n x = blade_signs.unsqueeze(-1) * self.blade_mvs[blade_indices]\n\n # a, b -> b\n return x.sum(dim=-2) \n\n def __getattr__(self, name: str) -> torch.Tensor:\n \"\"\"Returns basis blade tensors if name was a basis.\"\"\"\n if name.startswith(\"e\") and (name[1:] == \"\" or int(name[1:]) >= 0):\n return self.e(name[1:])\n raise AttributeError\n\n def dual(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the dual of the geometric algebra tensor.\n\n Args:\n tensor: Geometric algebra tensor to return dual for\n\n Returns:\n Dual of the geometric algebra tensor\n \"\"\"\n tensor = torch.tensor(tensor, dtype=torch.float32)\n # return self.dual_blade_signs * tf.gather(tensor, self.dual_blade_indices, axis=-1)\n return self.dual_blade_signs * tensor[...,self.dual_blade_indices]\n\n def grade_automorphism(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the geometric algebra tensor with odd grades negated.\n See https://en.wikipedia.org/wiki/Paravector#Grade_automorphism.\n\n Args:\n tensor: Geometric algebra tensor to return grade automorphism for\n\n Returns:\n Geometric algebra tensor with odd grades negated\n \"\"\"\n tensor = tensor.to(dtype=torch.float32)\n return mv_grade_automorphism(tensor, self.blade_degrees)\n\n def reversion(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the grade-reversed geometric algebra tensor.\n See https://en.wikipedia.org/wiki/Paravector#Reversion_conjugation.\n\n Args:\n tensor: Geometric algebra tensor to return grade-reversion for\n\n Returns:\n Grade-reversed geometric algebra tensor\n \"\"\"\n tensor = tensor.to(dtype=torch.float32)\n\n return mv_reversion(tensor, self.blade_degrees)\n\n def conjugation(self, tensor: torch.Tensor) -> torch.Tensor:\n \"\"\"Combines reversion and grade automorphism.\n See https://en.wikipedia.org/wiki/Paravector#Clifford_conjugation.\n\n Args:\n tensor: Geometric algebra tensor to return conjugate for\n\n Returns:\n Geometric algebra tensor after `reversion()` and `grade_automorphism()`\n \"\"\"\n tensor = tensor.to(dtype=torch.float32)\n return self.grade_automorphism(self.reversion(tensor))\n\n def simple_inverse(self, a: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the inverted geometric algebra tensor\n `X^-1` such that `X * X^-1 = 1`. Only works for elements that\n square to scalars. Faster than the general inverse.\n\n Args:\n a: Geometric algebra tensor to return inverse for\n\n Returns:\n inverted geometric algebra tensor\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n\n rev_a = self.reversion(a)\n divisor = self.geom_prod(a, rev_a)\n # print(f\"divisor={divisor}\")\n # print(f\"self.is_pure_kind(divisor, BladeKind.SCALAR)={self.is_pure_kind(divisor, BladeKind.SCALAR)}\")\n if not self.is_pure_kind(divisor, BladeKind.SCALAR):\n raise Exception(\n \"Can't invert multi-vector (inversion divisor V ~V not scalar: %s).\" % divisor)\n\n # Divide by scalar part\n return rev_a / divisor[..., :1]\n\n def reg_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the regressive product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the regressive product\n b: Geometric algebra tensor on the right hand side of\n the regressive product\n\n Returns:\n regressive product of a and b\n \"\"\"\n a = torch.tensor(a, dtype=torch.float32)\n b = torch.tensor(b, dtype=torch.float32)\n\n return self.dual(self.ext_prod(self.dual(a), self.dual(b)))\n\n def ext_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the exterior product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the exterior product\n b: Geometric algebra tensor on the right hand side of\n the exterior product\n\n Returns:\n exterior product of a and b\n \"\"\"\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n\n return mv_multiply(a, b, self._cayley_outer)\n\n def geom_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the geometric product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the geometric product\n b: Geometric algebra tensor on the right hand side of\n the geometric product\n\n Returns:\n geometric product of a and b\n \"\"\"\n # a = torch.tensor(a, dtype=torch.float32)\n # b = torch.tensor(b, dtype=torch.float32)\n\n # a = torch.tensor(a)\n # b = torch.tensor(b)\n\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n return mv_multiply(a, b, self._cayley)\n\n \n def element_wise_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the element-wise product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the geometric product\n b: Geometric algebra tensor on the right hand side of\n the geometric product\n\n Returns:\n geometric product of a and b\n \"\"\"\n # a = torch.tensor(a, dtype=torch.float32)\n # b = torch.tensor(b, dtype=torch.float32)\n\n # a = torch.tensor(a)\n # b = torch.tensor(b)\n\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n return mv_multiply_element_wise(a, b, self._cayley)\n\n\n def inner_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the inner product of two geometric\n algebra tensors.\n\n Args:\n a: Geometric algebra tensor on the left hand side of\n the inner product\n b: Geometric algebra tensor on the right hand side of\n the inner product\n\n Returns:\n inner product of a and b\n \"\"\"\n a = a.to(dtype=torch.float32)\n b = b.to(dtype=torch.float32)\n\n return mv_multiply(a, b, self._cayley_inner)\n\n def geom_conv1d(self, a: torch.Tensor, k: torch.Tensor,\n stride: int, padding: str,\n dilations: Union[int, None] = None) -> torch.Tensor:\n \"\"\"Returns the 1D convolution of a sequence with a geometric algebra\n tensor kernel. The convolution is performed using the geometric\n product.\n\n Args:\n a: Input geometric algebra tensor of shape\n [..., Length, ChannelsIn, Blades]\n k: Geometric algebra tensor for the convolution kernel of shape\n [KernelSize, ChannelsIn, ChannelsOut, Blades]\n stride: Stride to use for the convolution\n padding: \"SAME\" (zero-pad input length so output\n length == input length / stride) or \"VALID\" (no padding)\n Returns:\n Geometric algbra tensor of shape\n [..., OutputLength, ChannelsOut, Blades]\n representing `a` convolved with `k`\n \"\"\"\n a = a.to(dtype=torch.float32)\n k = k.to(dtype=torch.float32)\n\n # return mv_conv1d(a, k, self._cayley, stride=stride, padding=padding)\n return f_mv_conv1d(a, k, self._cayley, stride=stride, padding=padding)\n\n def mv_repr(self, a: torch.Tensor) -> str:\n \"\"\"Returns a string representation for the given\n geometric algebra tensor.\n\n Args:\n a: Geometric algebra tensor to return the representation for\n\n Returns:\n string representation for `a`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n\n if len(a.shape) == 1:\n return \"MultiVector[%s]\" % \" + \".join(\n \"%.2f*%s\" % (value, get_blade_repr(blade_name))\n for value, blade_name\n in zip(a, self.blades)\n if value != 0\n )\n else:\n return f\"MultiVector[batch_shape={a.shape[:-1]}]\"\n\n def approx_exp(self, a: torch.Tensor, order: int = 50) -> torch.Tensor:\n \"\"\"Returns an approximation of the exponential using a centered taylor series.\n\n Args:\n a: Geometric algebra tensor to return exponential for\n order: order of the approximation\n\n Returns:\n Approximation of `exp(a)`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n v = self.from_scalar(1.0)\n result = self.from_scalar(1.0)\n for i in range(1, order + 1):\n v = self.geom_prod(a, v)\n # i_factorial = tf.exp(tf.math.lgamma(i + 1.0))\n i_factorial = torch.exp(torch.lgamma(torch.tensor([i + 1.0])))\n result += v / i_factorial\n return result\n\n def exp(self, a: torch.Tensor, square_scalar_tolerance: Union[float, None] = 1e-4) -> torch.Tensor:\n \"\"\"Returns the exponential of the passed geometric algebra tensor.\n Only works for multivectors that square to scalars.\n\n Args:\n a: Geometric algebra tensor to return exponential for\n square_scalar_tolerance: Tolerance to use for the square scalar check\n or None if the check should be skipped\n\n Returns:\n `exp(a)`\n \"\"\"\n # See https://www.euclideanspace.com/maths/algebra/clifford/algebra/functions/exponent/index.htm\n # for an explanation of how to exponentiate multivectors.\n\n self_sq = self.geom_prod(a, a)\n\n if square_scalar_tolerance is not None:\n # tf.Assert(tf.reduce_all(\n # tf.abs(self_sq[..., 1:]) < square_scalar_tolerance\n # ), [self_sq])\n \n # assert torch.equal(torch.all(self_sq[..., 1:].abs() < square_scalar_tolerance),[self_sq]), \"not sure what\"\n assert torch.all(self_sq[..., 1:].abs() < square_scalar_tolerance), \"square_scalar_tolerance not met\"\n\n scalar_self_sq = self_sq[..., :1]\n\n # \"Complex\" square root (argument can be negative)\n s_sqrt = torch.sign(scalar_self_sq) * torch.sqrt(torch.abs(scalar_self_sq))\n\n # Square to +1: cosh(sqrt(||a||)) + a / sqrt(||a||) sinh(sqrt(||a||))\n # Square to -1: cos(sqrt(||a||)) + a / sqrt(||a||) sin(sqrt(||a||))\n # TODO: Does this work for values other than 1 too? eg. square to +0.5?\n # TODO: Find a solution that doesnt require calculating all possibilities\n # first.\n non_zero_result = torch.where(\n scalar_self_sq < 0,\n (self.from_tensor(torch.cos(s_sqrt), torch.tensor([0])) + a / s_sqrt * torch.sin(s_sqrt)),\n (self.from_tensor(torch.cosh(s_sqrt), torch.tensor([0])) + a / s_sqrt * torch.sinh(s_sqrt))\n )\n\n return torch.where(scalar_self_sq == 0, self.from_scalar(1.0) + a, non_zero_result)\n\n def approx_log(self, a: torch.Tensor, order: int = 50) -> torch.Tensor:\n \"\"\"Returns an approximation of the natural logarithm using a centered\n taylor series. Only converges for multivectors where `||mv - 1|| < 1`.\n\n Args:\n a: Geometric algebra tensor to return logarithm for\n order: order of the approximation\n\n Returns:\n Approximation of `log(a)`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n result = self.from_scalar(0.0)\n\n a_minus_one = a - self.from_scalar(1.0)\n v = None\n\n for i in range(1, order + 1):\n v = a_minus_one if v is None else v * a_minus_one\n result += (((-1.0) ** i) / i) * v\n\n return -result\n\n def int_pow(self, a: torch.Tensor, n: int) -> torch.Tensor:\n \"\"\"Returns the geometric algebra tensor to the power of an integer\n using repeated multiplication.\n\n Args:\n a: Geometric algebra tensor to raise\n n: integer power to raise the multivector to\n\n Returns:\n `a` to the power of `n`\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n\n if not isinstance(n, int):\n raise Exception(\"n must be an integer.\")\n if n < 0:\n raise Exception(\"Can't raise to negative powers.\")\n\n if n == 0:\n # TODO: more efficient (ones only in scalar)\n return torch.ones_like(a) * self.e(\"\")\n\n result = a\n for i in range(n - 1):\n result = self.geom_prod(result, a)\n return result\n\n def keep_blades(self, a: torch.Tensor, blade_indices: List[int]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns it with only the given\n blade_indices as non-zeros.\n\n Args:\n a: Geometric algebra tensor to copy\n blade_indices: Indices for blades to keep\n\n Returns:\n `a` with only `blade_indices` components as non-zeros\n \"\"\"\n a = a.to(dtype=torch.float32)\n blade_indices = blade_indices.to(dtype=torch.int64)\n\n # blade_values = tf.gather(a, blade_indices, axis=-1)\n blade_values = a[...,blade_indices]\n if True: \n b = self.from_tensor(blade_values, blade_indices)\n else:\n blade_mask = torch.zeros(self.num_blades)\n blade_mask[blade_indices] = 1\n b = self.from_tensor(blade_values, blade_mask)\n # print(f\"blade_values, blade_indices, b={blade_values}, {blade_indices}, {b}\")\n # print(f\"blade_mask={blade_mask}\")\n return b\n\n # return self.from_tensor(blade_values, blade_indices)\n\n def keep_blades_with_name(self, a: torch.Tensor, blade_names: Union[List[str], str]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns it with only the given\n blades as non-zeros.\n\n Args:\n a: Geometric algebra tensor to copy\n blade_names: Blades to keep\n\n Returns:\n `a` with only `blade_names` components as non-zeros\n \"\"\"\n if isinstance(blade_names, str):\n blade_names = [blade_names]\n\n _, blade_indices = get_blade_indices_from_names(blade_names, self.blades)\n\n if False:\n print(f\"self.blades={self.blades}\")\n print(f\"blade_names={blade_names}\")\n print(f\"blade_indices={blade_indices}\")\n\n return self.keep_blades(a, blade_indices)\n\n def select_blades(self, a: torch.Tensor, blade_indices: List[int]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns a `torch.Tensor` with the\n blades in blade_indices on the last axis.\n\n\n Args:\n a: Geometric algebra tensor to copy\n blade_indices: Indices for blades to select\n\n Returns:\n `torch.Tensor` based on `a` with `blade_indices` on last axis.\n \"\"\"\n a = a.to(dtype=torch.float32) \n # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64)\n blade_indices = blade_indices.to(dtype=torch.int64)\n\n # result = tf.gather(a, blade_indices, axis=-1)\n try:\n if len(a.shape)==1 or a.shape[-1]==a.size().numel():\n result = a.squeeze()[blade_indices]\n else:\n result = a[...,blade_indices]\n except:\n print(f\"a={a},blade_indices={blade_indices}\")\n print(f\"a.shape={a.shape},blade_indices.shape={blade_indices.shape},a.size().numel()={a.size().numel()}\")\n raise\n \n return result\n\n def select_blades_with_name(self, a: torch.Tensor, blade_names: Union[List[str], str]) -> torch.Tensor:\n \"\"\"Takes a geometric algebra tensor and returns a `torch.Tensor` with the\n blades in blade_names on the last axis.\n\n\n Args:\n a: Geometric algebra tensor to copy\n blade_names: Blades to keep\n\n Returns:\n `torch.Tensor` based on `a` with `blade_names` on last axis.\n \"\"\"\n a = a.to(dtype=torch.float32)\n\n is_single_blade = isinstance(blade_names, str)\n if is_single_blade:\n blade_names = [blade_names]\n\n blade_signs, blade_indices = get_blade_indices_from_names(\n blade_names, self.blades)\n\n result = blade_signs * self.select_blades(a, blade_indices)\n # if True:\n # print(f\"\")\n\n if is_single_blade:\n return result[..., 0]\n\n return result\n\n def inverse(self, a: torch.Tensor) -> torch.Tensor:\n \"\"\"Returns the inverted geometric algebra tensor\n `X^-1` such that `X * X^-1 = 1`.\n\n Using Shirokov's inverse algorithm that works in arbitrary dimensions,\n see https://arxiv.org/abs/2005.04015 Theorem 4.\n\n Args:\n a: Geometric algebra tensor to return inverse for\n\n Returns:\n inverted geometric algebra tensor\n \"\"\"\n # a = torch.tensor(a, dtype=torch.float32)\n a = a.to(dtype=torch.float32)\n if False:\n print(f\"a={a}\")\n\n n = 2 ** ((len(self.metric) + 1) // 2)\n\n # u = a.clone()\n u = a\n for k in range(1, n):\n # c = n / k * self.keep_blades_with_name(u, \"\")\n d = self.keep_blades_with_name(u, \"\")\n c = n / k * d\n u_minus_c = u - c\n if False:\n print(f\"a,d,c,u_minus_c, u = {a},{d},{c},{u_minus_c}, {u}\")\n u = self.geom_prod(a, u_minus_c)\n if False:\n print(f\"u={u}\")\n \n if False:\n print(f\"n={n}\")\n print(f\"a={a}\")\n print(f\"u={u}\")\n if not torch.all(self.is_pure_kind(u, BladeKind.SCALAR)):\n raise Exception(\n \"Can't invert multi-vector (det U not scalar: %s).\" % u)\n\n # adj / det\n return u_minus_c / u[..., :1]\n\n def __call__(self, a: torch.Tensor) -> MultiVector:\n \"\"\"Creates a `MultiVector` from a geometric algebra tensor.\n Mainly used as a wrapper for the algebra's functions for convenience.\n\n Args:\n a: Geometric algebra tensor to return `MultiVector` for\n\n Returns:\n `MultiVector` for `a`\n \"\"\"\n a = a.to(dtype=torch.float32)\n return MultiVector(a, self)\n # return MultiVector(torch.tensor(a), self)" } ]
import unittest as ut import h5py import torch import torch.nn as nn import torch.nn.functional as F import torch from io import BytesIO from torch_ga.layers import ( GeometricProductDense, GeometricSandwichProductDense, GeometricProductElementwise, GeometricSandwichProductElementwise, GeometricProductConv1D, GeometricAlgebraExp, GeometricToTensor, GeometricToTensorWithKind, TensorToGeometric, TensorWithKindToGeometric, ) from torch_ga.blades import BladeKind from torch_ga import GeometricAlgebra
16,737
torch.manual_seed(0) class TestKerasLayers(ut.TestCase): def assertTensorsEqual(self, a, b): # self.assertTrue(tf.reduce_all(a == b), "%s not equal to %s" % (a, b)) print(f"assertTensorsEqual(a={a},b={b})") assert torch.all(a.squeeze() == b.squeeze()), "%s not equal to %s" % (a, b) def test_tensor_to_geometric(self): sta = GeometricAlgebra([1, -1, -1, -1]) tensor = torch.ones([32, 4]) gt_geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4]
torch.manual_seed(0) class TestKerasLayers(ut.TestCase): def assertTensorsEqual(self, a, b): # self.assertTrue(tf.reduce_all(a == b), "%s not equal to %s" % (a, b)) print(f"assertTensorsEqual(a={a},b={b})") assert torch.all(a.squeeze() == b.squeeze()), "%s not equal to %s" % (a, b) def test_tensor_to_geometric(self): sta = GeometricAlgebra([1, -1, -1, -1]) tensor = torch.ones([32, 4]) gt_geom_tensor = torch.concat( [torch.zeros([32, 1]), torch.ones([32, 4]), torch.zeros([32, 11])], axis=-1 ) vector_blade_indices = [1, 2, 3, 4]
tensor_to_geom_layer = TensorToGeometric(sta, vector_blade_indices)
8
2023-10-07 13:34:07+00:00
24k
Significant-Gravitas/autostandup
bot.py
[ { "identifier": "StreaksDB", "path": "streaks/streaks_db.py", "snippet": "class StreaksDB(BaseDB):\n \"\"\"\n StreaksDB class handles all operations related to the 'streaks' table.\n Inherits from the BaseDB class.\n \"\"\"\n\n def __init__(self, host, user, password, database, port):\n \"\"\"\n Initializes the StreaksDB class and creates the 'streaks' table if it doesn't exist.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_streaks_table()\n\n def _create_streaks_table(self):\n \"\"\"\n Creates the 'streaks' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS streaks (\n discord_id BIGINT PRIMARY KEY,\n current_streak INT DEFAULT 0,\n FOREIGN KEY (discord_id) REFERENCES team_members(discord_id) ON DELETE CASCADE\n );\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def update_streak(self, discord_id: int, new_streak: int):\n \"\"\"\n Updates the streak for a given user.\n\n :param discord_id: The Discord ID of the user.\n :param new_streak: The new streak count.\n \"\"\"\n query = \"\"\"\n INSERT INTO streaks (discord_id, current_streak)\n VALUES (%s, %s)\n ON DUPLICATE KEY UPDATE current_streak = %s\n \"\"\"\n params = (discord_id, new_streak, new_streak)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def get_streak(self, discord_id: int) -> int:\n \"\"\"\n Fetches the current streak for a given user.\n\n :param discord_id: The Discord ID of the user.\n :return: The current streak count.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n c = self.conn.cursor()\n query = \"SELECT current_streak FROM streaks WHERE discord_id = %s\"\n params = (discord_id,)\n try:\n c.execute(query, params)\n row = c.fetchone()\n return row[0] if row else 0\n finally:\n c.close()\n self.close()" }, { "identifier": "TeamMemberDB", "path": "team_members/team_member_db.py", "snippet": "class TeamMemberDB(BaseDB):\n \"\"\"\n TeamMemberDB class handles operations related to the 'team_members' table.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n\n def __init__(self, host: str, user: str, password: str, database: str, port: str):\n \"\"\"\n Initializes the TeamMemberDB class and creates the 'team_members' table if it doesn't exist.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_team_members_table()\n\n def _create_team_members_table(self):\n \"\"\"\n Creates the 'team_members' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS team_members (\n discord_id BIGINT PRIMARY KEY,\n name VARCHAR(255) NOT NULL,\n time_zone VARCHAR(50) NOT NULL,\n github_username VARCHAR(255),\n on_vacation BOOLEAN DEFAULT FALSE\n );\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def insert_new_member(self, discord_id: int, name: str, time_zone: str, github_username: str):\n \"\"\"\n Inserts a new team member into the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member.\n :param name: The name of the team member.\n :param time_zone: The time zone of the team member.\n :param github_username: The GitHub username of the team member.\n \"\"\"\n query = \"\"\"\n INSERT INTO team_members (discord_id, name, time_zone, github_username)\n VALUES (%s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE name = %s, time_zone = %s, github_username = %s\n \"\"\"\n params = (discord_id, name, time_zone, github_username, name, time_zone, github_username)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def remove_member(self, discord_id: int):\n \"\"\"\n Removes a team member from the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member to remove.\n \"\"\"\n query = \"DELETE FROM team_members WHERE discord_id = %s\"\n params = (discord_id,)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def list_all_members(self) -> List[Tuple[int, str, str, str, bool]]:\n \"\"\"\n Fetches all team members from the 'team_members' table.\n\n :return: A list of tuples, each containing the Discord ID, name, time zone, GitHub username, and vacation status of a team member.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n c = self.conn.cursor()\n try:\n c.execute(\"SELECT discord_id, name, time_zone, github_username, on_vacation FROM team_members\")\n return c.fetchall()\n finally:\n c.close()\n self.close()\n\n def update_member_timezone(self, discord_id: int, new_time_zone: str):\n \"\"\"\n Updates the timezone of a team member in the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member.\n :param new_time_zone: The new timezone to be set for the team member.\n \"\"\"\n query = \"UPDATE team_members SET time_zone = %s WHERE discord_id = %s\"\n params = (new_time_zone, discord_id)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def set_vacation_status(self, discord_id: int, on_vacation: bool):\n \"\"\"\n Sets the vacation status of a team member in the 'team_members' table.\n\n :param discord_id: The Discord ID of the team member.\n :param on_vacation: The vacation status to be set for the team member.\n \"\"\"\n query = \"UPDATE team_members SET on_vacation = %s WHERE discord_id = %s\"\n params = (on_vacation, discord_id)\n try:\n self.execute_query(query, params)\n finally:\n self.close()" }, { "identifier": "UpdatesDB", "path": "updates/updates_db.py", "snippet": "class UpdatesDB(BaseDB):\n \"\"\"\n Database class for handling operations related to the 'updates' table.\n \"\"\"\n\n def __init__(self, host: str, user: str, password: str, database: str, port: str):\n \"\"\"\n Initializes the UpdatesDB class and creates the 'updates' table if it doesn't exist.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_updates_table()\n\n def _create_updates_table(self):\n \"\"\"\n Creates the 'updates' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS updates (\n id INT AUTO_INCREMENT PRIMARY KEY,\n discord_id BIGINT,\n status TEXT NOT NULL,\n summarized_status TEXT,\n timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n time_zone VARCHAR(255),\n FOREIGN KEY (discord_id) REFERENCES team_members(discord_id) ON DELETE CASCADE\n )\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def insert_status(self, discord_id: int, status: str, time_zone: str):\n \"\"\"\n Inserts a new status update into the 'updates' table.\n\n :param discord_id: The Discord ID of the team member.\n :param status: The status update.\n :param time_zone: The time zone of the user.\n \"\"\"\n # Convert current UTC time to user's local time zone\n utc_now = datetime.utcnow().replace(tzinfo=pytz.utc)\n local_now = utc_now.astimezone(pytz.timezone(time_zone))\n\n query = \"INSERT INTO updates (discord_id, status, timestamp, time_zone) VALUES (%s, %s, %s, %s)\"\n params = (discord_id, status, local_now, time_zone)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n\n def update_summarized_status(self, discord_id: int, summarized_status: str):\n \"\"\"\n Updates the summarized_status for the most recent update for a given user.\n\n :param discord_id: The Discord ID of the team member.\n :param summarized_status: The summarized status update.\n \"\"\"\n query = \"\"\"\n UPDATE updates\n SET summarized_status = %s\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n LIMIT 1\n \"\"\"\n params = (summarized_status, discord_id)\n try:\n self.execute_query(query, params)\n finally:\n self.close()\n \n def get_weekly_checkins_count(self, discord_id: int, time_zone: str) -> int:\n \"\"\"\n Fetches the number of check-ins for a given user in the current week.\n\n :param discord_id: The Discord ID of the user.\n :param time_zone: The time zone of the user.\n :return: The count of check-ins in the current week.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n # Adjusting the current time to the user's time zone\n local_tz = pytz.timezone(time_zone)\n local_now = datetime.now(local_tz)\n \n # Getting the Monday of the current week in the user's time zone\n monday = local_now - timedelta(days=local_now.weekday())\n monday = monday.replace(hour=0, minute=0, second=0, microsecond=0)\n\n query = \"\"\"\n SELECT COUNT(*) FROM updates\n WHERE discord_id = %s AND timestamp >= %s\n \"\"\"\n params = (discord_id, monday)\n try:\n c.execute(query, params)\n \n row = c.fetchone()\n return row[0] if row else 0\n finally:\n c.close()\n self.close()\n\n def get_statuses_in_date_range(self, discord_id: int, start_date: datetime, end_date: datetime) -> List[str]:\n \"\"\"\n Fetches all raw status updates for a given user within a specified date range.\n\n Args:\n discord_id: The Discord ID of the user.\n start_date: The start date of the date range.\n end_date: The end date of the date range.\n\n Returns:\n A list of raw status updates.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n query = \"\"\"\n SELECT summarized_status FROM updates\n WHERE discord_id = %s AND timestamp >= %s AND timestamp <= %s\n \"\"\"\n params = (discord_id, start_date, end_date)\n try:\n c.execute(query, params)\n \n statuses = [row[0] for row in c.fetchall()]\n return statuses\n finally:\n c.close()\n self.close()\n \n def get_all_statuses_for_user(self, discord_id: int) -> List[dict]:\n \"\"\"\n Fetches all status updates (both raw and summarized) for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A list of dictionaries, each containing the status update details for a given record.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor(dictionary=True) # Set dictionary=True to return results as dictionaries\n \n query = \"\"\"\n SELECT id, discord_id, status, summarized_status, timestamp \n FROM updates\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n \"\"\"\n params = (discord_id,)\n try:\n c.execute(query, params)\n \n statuses = c.fetchall()\n return statuses\n finally:\n c.close()\n self.close()\n \n def get_last_update_timestamp(self, discord_id: int) -> Tuple[datetime, str]:\n \"\"\"\n Fetches the timestamp and time zone of the last status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A tuple containing the timestamp of the last update and its time zone, or (None, None) if there are no updates.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n query = \"\"\"\n SELECT timestamp, time_zone FROM updates\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n LIMIT 1\n \"\"\"\n params = (discord_id,)\n try:\n c.execute(query, params)\n \n row = c.fetchone()\n return (row[0], row[1]) if row else (None, None)\n finally:\n c.close()\n self.close()\n \n def delete_newest_status(self, discord_id: int) -> None:\n \"\"\"\n Deletes the most recent status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n \"\"\"\n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n \n # Fetch the ID of the newest status update for the given user\n query_get_id = \"\"\"\n SELECT id FROM updates\n WHERE discord_id = %s\n ORDER BY timestamp DESC\n LIMIT 1\n \"\"\"\n try:\n c.execute(query_get_id, (discord_id,))\n \n row = c.fetchone()\n if row:\n status_id = row[0]\n \n # Now, delete the status update using its ID\n query_delete = \"\"\"\n DELETE FROM updates WHERE id = %s\n \"\"\"\n c.execute(query_delete, (status_id,))\n \n self.conn.commit()\n finally:\n c.close()\n self.close()" }, { "identifier": "WeeklyPostsDB", "path": "weekly_posts/weekly_posts_db.py", "snippet": "class WeeklyPostsDB(BaseDB):\n \"\"\"\n Database class that handles operations related to the 'weekly_posts' table.\n \"\"\"\n\n def __init__(self, host: str, user: str, password: str, database: str, port: str):\n \"\"\"\n Initializes the WeeklyPostsDB class, connects to the MySQL database,\n and creates the 'weekly_posts' table if it doesn't exist.\n\n :param host: The MySQL host address.\n :param user: The MySQL user.\n :param password: The MySQL password.\n :param database: The MySQL database name.\n :param port: The MySQL port number.\n \"\"\"\n super().__init__(host, user, password, database, port)\n self._create_weekly_posts_table()\n\n def _create_weekly_posts_table(self):\n \"\"\"\n Creates the 'weekly_posts' table if it doesn't already exist.\n \"\"\"\n query = '''\n CREATE TABLE IF NOT EXISTS weekly_posts (\n post_id BIGINT PRIMARY KEY,\n timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n );\n '''\n try:\n self.execute_query(query)\n finally:\n self.close()\n\n def get_weekly_post_data(self) -> Optional[Dict[str, datetime.datetime]]:\n \"\"\"\n Fetches the most recent weekly post data from the 'weekly_posts' table.\n\n :return: A dictionary containing the post ID and timestamp, or None if no data exists.\n \"\"\"\n query = \"SELECT post_id, timestamp FROM weekly_posts ORDER BY timestamp DESC LIMIT 1\"\n \n if not self.conn.is_connected():\n print(\"Reconnecting to MySQL\")\n self.connect()\n\n c = self.conn.cursor()\n try:\n c.execute(query)\n row = c.fetchone()\n\n if row:\n return {'post_id': row[0], 'timestamp': row[1]}\n return None\n finally:\n c.close()\n self.close()\n\n def save_weekly_post_data(self, post_id: int, timestamp: datetime.datetime):\n \"\"\"\n Inserts or updates the weekly post data in the 'weekly_posts' table.\n\n :param post_id: The ID of the weekly post.\n :param timestamp: The timestamp of the weekly post.\n \"\"\"\n query = \"\"\"\n INSERT INTO weekly_posts (post_id, timestamp)\n VALUES (%s, %s)\n ON DUPLICATE KEY UPDATE timestamp = %s\n \"\"\"\n params = (post_id, timestamp, timestamp)\n try:\n self.execute_query(query, params)\n finally:\n self.close()" }, { "identifier": "StreaksManager", "path": "streaks/streaks_manager.py", "snippet": "class StreaksManager:\n \"\"\"\n Manages the streaks for team members.\n \"\"\"\n \n def __init__(self, streaks_db: StreaksDB):\n \"\"\"\n Initializes a new StreaksManager instance.\n\n Args:\n streaks_db: The StreaksDB object that handles database operations.\n \"\"\"\n self.streaks_db = streaks_db\n \n def get_streak(self, discord_id: int) -> int:\n \"\"\"\n Fetches the current streak for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n The current streak count.\n \"\"\"\n return self.streaks_db.get_streak(discord_id)\n\n def update_streak(self, discord_id: int, new_streak: int):\n \"\"\"\n Updates the streak for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n new_streak: The new streak count.\n \"\"\"\n self.streaks_db.update_streak(discord_id, new_streak)\n \n def reset_streak(self, discord_id: int):\n \"\"\"\n Resets the streak for a given user to zero.\n\n Args:\n discord_id: The Discord ID of the user.\n \"\"\"\n self.streaks_db.update_streak(discord_id, 0)" }, { "identifier": "TeamMemberManager", "path": "team_members/team_member_manager.py", "snippet": "class TeamMemberManager:\n \"\"\"\n Manages operations related to team members.\n \"\"\"\n\n def __init__(self, db: TeamMemberDB):\n \"\"\"\n Initialize a TeamMemberManager object.\n\n :param db: TeamMemberDB object for interacting with the database.\n \"\"\"\n self.db = db\n self.team_members = self.load_team_members()\n\n def load_team_members(self) -> List[TeamMember]:\n \"\"\"\n Load team members from the MySQL database into a list of TeamMember objects.\n\n :return: List of TeamMember objects.\n \"\"\"\n team_members = []\n members_data = self.db.list_all_members()\n\n for member_data in members_data:\n member = TeamMember(\n discord_id=member_data[0],\n time_zone=member_data[2],\n name=member_data[1],\n github_username=member_data[3],\n on_vacation=member_data[4]\n )\n team_members.append(member)\n\n return team_members\n\n def find_member(self, discord_id: int) -> TeamMember:\n \"\"\"\n Find and return a team member by their Discord ID.\n\n :param discord_id: The Discord ID of the team member.\n :return: A TeamMember object if found, otherwise None.\n \"\"\"\n for member in self.team_members:\n if member.discord_id == discord_id:\n return member\n return None\n\n def add_member(self, discord_id: int, name: str, time_zone: str, github_username: str):\n \"\"\"\n Add a new team member to the list and the database.\n\n :param discord_id: The Discord ID of the new member.\n :param name: The name of the new member.\n :param time_zone: The time zone of the new member.\n :param github_username: The GitHub username of the new member.\n \"\"\"\n new_member = TeamMember(discord_id, time_zone, name, github_username)\n self.db.insert_new_member(discord_id, name, time_zone, github_username)\n self.team_members.append(new_member)\n\n def remove_member(self, discord_id: int):\n \"\"\"\n Remove a team member from the list and the database.\n\n :param discord_id: The Discord ID of the member to remove.\n \"\"\"\n self.db.remove_member(discord_id)\n self.team_members = [member for member in self.team_members if member.discord_id != discord_id]\n\n def update_member_timezone(self, discord_id: int, new_time_zone: str):\n \"\"\"\n Update the timezone of a team member in the database and the list.\n\n :param discord_id: The Discord ID of the member to update.\n :param new_time_zone: The new timezone string to set for the member.\n \"\"\"\n # Update the timezone in the database\n self.db.update_member_timezone(discord_id, new_time_zone)\n\n # Find the member in the team_members list and update their timezone\n member = self.find_member(discord_id)\n if member:\n member.time_zone = new_time_zone\n\n def set_member_vacation_status(self, discord_id: int, on_vacation: bool):\n \"\"\"\n Sets the vacation status of a team member.\n\n :param discord_id: The Discord ID of the team member.\n :param on_vacation: The vacation status to be set for the team member.\n \"\"\"\n # Update the vacation status in the database\n self.db.set_vacation_status(discord_id, on_vacation)\n\n # Find the member in the team_members list and update their vacation status\n member = self.find_member(discord_id)\n if member:\n member.on_vacation = on_vacation" }, { "identifier": "UpdatesManager", "path": "updates/updates_manager.py", "snippet": "class UpdatesManager:\n \"\"\"\n Manages status updates for team members.\n \"\"\"\n\n def __init__(self, updates_db: UpdatesDB):\n \"\"\"\n Initializes a new UpdatesManager instance.\n\n Args:\n updates_db: The UpdatesDB object that handles database operations.\n \"\"\"\n self.updates_db = updates_db\n\n def insert_status(self, discord_id: int, status: str, time_zone: str):\n \"\"\"\n Inserts a new status update.\n\n Args:\n discord_id: The Discord ID of the team member.\n status: The status update.\n \"\"\"\n self.updates_db.insert_status(discord_id, status, time_zone)\n\n def update_summarized_status(self, discord_id: int, summarized_status: str):\n \"\"\"\n Updates the summarized status for the most recent update for a given user.\n\n Args:\n discord_id: The Discord ID of the team member.\n summarized_status: The summarized status update.\n \"\"\"\n self.updates_db.update_summarized_status(discord_id, summarized_status)\n\n def get_weekly_checkins_count(self, discord_id: int, time_zone: str) -> int:\n \"\"\"\n Fetches the number of check-ins for a given user in the current week.\n\n Args:\n discord_id: The Discord ID of the user.\n time_zone: The time zone of the user.\n\n Returns:\n The count of check-ins in the current week.\n \"\"\"\n return self.updates_db.get_weekly_checkins_count(discord_id, time_zone)\n \n def get_all_statuses_for_user(self, discord_id: int) -> List[dict]:\n \"\"\"\n Fetches all status updates (both raw and summarized) for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A list of dictionaries, each containing the status update details for a given record.\n \"\"\"\n return self.updates_db.get_all_statuses_for_user(discord_id)\n\n def get_last_update_timestamp(self, discord_id: int) -> Tuple[datetime, str]:\n \"\"\"\n Fetches the timestamp and time zone of the last status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n\n Returns:\n A tuple containing the timestamp of the last update and its time zone, or (None, None) if there are no updates.\n \"\"\"\n return self.updates_db.get_last_update_timestamp(discord_id)\n\n def delete_newest_status(self, discord_id: int) -> None:\n \"\"\"\n Deletes the most recent status update for a given user.\n\n Args:\n discord_id: The Discord ID of the user.\n \"\"\"\n self.updates_db.delete_newest_status(discord_id)\n\n async def generate_daily_summary(self, user_message: str) -> str:\n \"\"\"\n Generates a daily summary of the user's message using a large language model.\n\n Args:\n user_message: The user's message that needs to be summarized.\n\n Returns:\n The summarized message.\n \"\"\"\n # Prepare a system message to guide OpenAI's model\n system_message = \"Please summarize the user's update into two sections: 'Did' for tasks completed yesterday and 'Do' for tasks planned for today.\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": user_message}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n summarized_message = response['choices'][0]['message']['content'].strip()\n\n return summarized_message\n \n except Exception as e:\n print(f\"An error occurred while generating the summary: {e}\")\n return \"Error in generating summary\"\n\n async def generate_weekly_summary(self, discord_id: int, start_date: datetime, end_date: datetime) -> str:\n \"\"\"\n Generates a weekly summary of the user's status updates using a large language model.\n\n Args:\n discord_id: The Discord ID of the user.\n start_date: The start date of the date range.\n end_date: The end date of the date range.\n\n Returns:\n The summarized weekly status update.\n \"\"\"\n # Fetch all raw status updates for the specified date range using the new method in UpdatesDB\n weekly_statuses = self.updates_db.get_statuses_in_date_range(discord_id, start_date, end_date)\n\n if not weekly_statuses:\n return \"There are no status updates for this week.\"\n \n # Combine all raw statuses into a single string\n combined_statuses = \"\\n\".join(weekly_statuses)\n \n # Prepare a system message to guide OpenAI's model for weekly summary\n system_message = \"Please generate a comprehensive weekly summary based on the provided daily status updates, including only tasks that have been accomplished. Ignore tasks that are not in the 'Did' section.\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": combined_statuses}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-4-0613\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n weekly_summary = response['choices'][0]['message']['content'].strip()\n\n return weekly_summary\n \n except Exception as e:\n print(f\"An error occurred while generating the weekly summary: {e}\")\n return \"Error in generating weekly summary\"\n \n async def summarize_technical_updates(self, commit_messages: List[str]) -> str:\n \"\"\"\n Summarizes the technical updates based on commit messages.\n\n Args:\n commit_messages: List of commit messages for the day.\n\n Returns:\n A summarized version of the technical updates.\n \"\"\"\n\n # Combine commit messages into a single string for the LLM\n combined_commits = \"\\n\".join(commit_messages)\n\n # If there are no commit messages, return a default message\n if not combined_commits:\n return \"No technical updates found based on commit messages.\"\n\n # Summarization using LLM\n system_message = \"Please provide a concise summary of the technical updates based on the provided commit messages.\"\n\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": combined_commits}\n ]\n\n model_engine = \"gpt-3.5-turbo-1106\"\n\n try:\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n\n # Extract the generated summary\n summarized_message = response['choices'][0]['message']['content'].strip()\n\n return summarized_message\n\n except Exception as e:\n print(f\"An error occurred while generating the technical summary: {e}\")\n return \"Error in generating technical summary.\"\n\n async def summarize_feedback_and_revisions(self, original_report: str, feedback: str) -> str:\n \"\"\"\n Takes the original report and user feedback and generates a revised summary.\n\n Args:\n original_report: The original summarized report.\n feedback: The user's feedback or suggested edits.\n\n Returns:\n The revised summary.\n \"\"\"\n # Prepare a system message to guide OpenAI's model\n system_message = \"Revise the original report based on the user's feedback.\"\n\n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": f\"Original Report: {original_report}\"},\n {\"role\": \"user\", \"content\": f\"Feedback: {feedback}\"}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n revised_summary = response['choices'][0]['message']['content'].strip()\n\n return revised_summary\n \n except Exception as e:\n print(f\"An error occurred while generating the revised summary: {e}\")\n return \"Error in generating revised summary\"\n\n async def summarize_non_technical_updates(self, update: str) -> str:\n \"\"\"\n Summarizes a non-technical update using a large language model.\n\n Args:\n update: The raw non-technical update provided by the user.\n\n Returns:\n The summarized non-technical update.\n \"\"\"\n\n # System message to guide the LLM for a concise summary\n system_message = \"Please provide a concise summary of the non-technical update shared by the user.\"\n\n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": update}\n ]\n\n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n\n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n\n # Extract the generated summary\n summarized_message = response['choices'][0]['message']['content'].strip()\n\n return summarized_message\n\n except Exception as e:\n print(f\"An error occurred while generating the non-technical summary: {e}\")\n return \"Error in generating summary\"\n\n async def summarize_goals_for_the_day(self, goals: str) -> str:\n \"\"\"\n Summarizes the user's goals for the day using a large language model.\n\n Args:\n goals: The user's raw input on their goals for the day.\n\n Returns:\n The summarized goals for the day.\n \"\"\"\n # Initiate the conversation with the model\n system_message = \"Please provide a concise summary of the user's goals for today.\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": goals}\n ]\n \n # Specify the model engine you want to use (this is an example and can be adjusted based on your needs)\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Provide user's input and retrieve model's response\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n summarized_goals = response['choices'][0]['message']['content'].strip()\n\n # Return the summary\n return summarized_goals\n \n except Exception as e:\n print(f\"An error occurred while generating the goals summary: {e}\")\n return \"Error in generating goals summary\"\n \n async def evaluate_performance(self, user_message: str) -> str:\n \"\"\"\n Evaluates the performance of the user based on their update.\n\n Args:\n user_message: The user's message that needs to be evaluated.\n\n Returns:\n The evaluation of the user's performance.\n \"\"\"\n # Prepare a system message to guide OpenAI's model\n system_message = \"\"\"\n You are a project manager at a fast-paced tech startup, recognized for providing clear and actionable feedback during stand-up meetings. Your role is to evaluate the quality of team members' daily stand-up reports, with a focus on clear communication, comprehensive planning, and problem-solving abilities.\n It is essential to note that team members should neither be penalized nor rewarded for merely mentioning issues; instead, the emphasis should be on the clarity of the report and the quality of strategies proposed to address these issues.\n Your feedback is candid and aimed at encouraging high-quality reporting and effective planning within the startup environment.\n Please provide a two-sentence summary of the stand-up and assign a grade (A, B, C, D, or F) based on the following criteria:\n\n - A: Excellent - The report is exceptionally clear and detailed, with well-defined tasks and a thorough approach to tackling issues, exemplifying the proactive and problem-solving ethos of our startup.\n - B: Good - The report is clear and adequately detailed, outlining tasks and addressing issues with a reasonable approach, indicating a commitment to momentum and resolution.\n - C: Fair - The report is understandable but lacks detail in some areas, with a basic approach to resolving issues, suggesting a need for further strategy development.\n - D: Poor - The report is vague or missing details, with a limited or unclear approach to issues, necessitating better communication and planning skills.\n - F: Fail - The report is missing, overly vague, or lacks a coherent structure, with no apparent approach to issues, reflecting a need for significant improvement in reporting and strategizing.\n\n A comprehensive stand-up report effectively communicates what was done and what is planned, clearly identifies any issues, and connects daily tasks with broader business objectives.\n\n Provide clear and constructive feedback, aiming to foster a culture of excellence and continuous improvement in how we plan and communicate our daily activities.\n \"\"\"\n \n # Prepare the messages input for ChatCompletion\n messages = [\n {\"role\": \"system\", \"content\": system_message},\n {\"role\": \"user\", \"content\": user_message}\n ]\n \n # Specify the model engine you want to use\n model_engine = \"gpt-3.5-turbo-1106\"\n \n try:\n # Make an API call to OpenAI's ChatCompletion\n response = openai.ChatCompletion.create(\n model=model_engine,\n messages=messages\n )\n \n # Extract the generated text\n performance_evaluation = response['choices'][0]['message']['content'].strip()\n\n return performance_evaluation\n \n except Exception as e:\n print(f\"An error occurred while evaluating the performance: {e}\")\n return \"Error in evaluating performance\"" }, { "identifier": "WeeklyPostManager", "path": "weekly_posts/weekly_post_manager.py", "snippet": "class WeeklyPostManager:\n \"\"\"Manages the status post in a Discord channel.\"\"\"\n \n def __init__(self, channel, weekly_posts_db: WeeklyPostsDB):\n \"\"\"\n Initializes a new WeeklyPostManager instance.\n \"\"\"\n self.channel = channel\n self.weekly_posts_db = weekly_posts_db\n self.editable_weekly_post = None\n self.load_weekly_post_data()\n\n def load_weekly_post_data(self):\n \"\"\"\n Load the weekly post data from the database.\n \n This method queries the 'weekly_posts' table to get the ID and timestamp of \n the last weekly post. If no data exists, it sets the ID and timestamp to None.\n \"\"\"\n data = self.weekly_posts_db.get_weekly_post_data()\n self.editable_weekly_post_id = data.get('post_id', None)\n self.weekly_post_timestamp = data.get('timestamp', None)\n\n def save_weekly_post_data(self):\n \"\"\"\n Save the weekly post data to the database.\n \n This method inserts or updates the ID and timestamp of the current weekly post \n in the 'weekly_posts' table.\n \"\"\"\n self.weekly_posts_db.save_weekly_post_data(self.editable_weekly_post.id, datetime.now())\n\n async def initialize_post(self, team_members: List[TeamMember]):\n \"\"\"\n Initializes or retrieves the weekly status post on Discord.\n\n This function checks if a valid weekly post already exists for the current week.\n If it does, it retrieves that post. Otherwise, it sends a new message in the Discord\n channel with the list of team members and their statuses.\n\n Args:\n team_members: A list of TeamMember objects to be displayed in the post.\n \"\"\"\n current_week_number = datetime.now().isocalendar()[1]\n saved_week_number = self.weekly_post_timestamp.isocalendar()[1] if self.weekly_post_timestamp else None\n\n # Skip initialization if the post already exists and is for the current week\n if self.editable_weekly_post_id and current_week_number == saved_week_number:\n self.editable_weekly_post = await self.channel.fetch_message(self.editable_weekly_post_id)\n return\n\n utc_now = pytz.utc.localize(datetime.utcnow())\n today_weekday = utc_now.weekday()\n last_monday = utc_now - timedelta(days=today_weekday)\n next_sunday = last_monday + timedelta(days=6)\n\n start_date = self.format_date(last_monday)\n end_date = self.format_date(next_sunday)\n\n # Calculate the max name length for alignment purposes\n max_name_length = max([len(m.name) for m in team_members])\n\n member_list = []\n for m in team_members:\n # Include the streak with the fire emoji if the streak is greater than 0\n streak_str = f\" {m.current_streak}🔥\" if m.current_streak > 0 else \"\"\n\n # Construct the new line for the member with the updated information\n new_line = f\"# `{m.name.ljust(max_name_length)} {'❓' * 5} {streak_str}`\"\n member_list.append(new_line)\n\n member_list_str = '\\n'.join(member_list)\n\n await self.channel.send(f\"# Weekly Status Updates\")\n await self.channel.send(f\"## {start_date} to {end_date}\")\n if member_list_str:\n self.editable_weekly_post = await self.channel.send(f\"{member_list_str}\")\n self.save_weekly_post_data() # Save the ID and timestamp after creating the post\n\n async def rebuild_post(self, team_members: List[TeamMember]):\n \"\"\"\n Rebuilds the entire weekly status post from the team members' data.\n\n Args:\n team_members: A list of TeamMember objects with updated statuses and streaks.\n \"\"\"\n # If there are no team members, delete the post and return\n if not team_members:\n if self.editable_weekly_post:\n await self.editable_weekly_post.delete()\n self.editable_weekly_post = None\n return\n\n # Calculate the max name length for alignment purposes\n max_name_length = max([len(m.name) for m in team_members])\n\n member_list = []\n for m in team_members:\n # Get the streak and number of weekly check-ins for the member\n streak = m.current_streak\n check_ins = m.weekly_checkins\n\n # Generate the marks based on the number of check-ins\n marks = \"✅\" * check_ins + \"❓\" * (5 - check_ins)\n\n # Include the streak with the fire emoji if the streak is greater than 0\n streak_str = f\" {streak}🔥\" if streak > 0 else \"\"\n\n # Construct the new line for the member with the updated information\n new_line = f\"# `{m.name.ljust(max_name_length)} {marks} {streak_str}`\"\n member_list.append(new_line)\n\n new_content = '\\n'.join(member_list)\n\n # Update the existing post or create a new one if it doesn't exist\n if self.editable_weekly_post:\n self.editable_weekly_post = await self.editable_weekly_post.edit(content=new_content)\n else:\n self.editable_weekly_post = await self.channel.send(new_content)\n\n # Save the ID and timestamp of the post\n self.save_weekly_post_data()\n\n def format_date(self, dt: datetime) -> str:\n \"\"\"\n Formats a datetime object into a human-readable string.\n\n Args:\n dt: The datetime object to format.\n\n Returns:\n A human-readable date string.\n \"\"\"\n suffix = ['th', 'st', 'nd', 'rd']\n day = int(dt.strftime('%d'))\n if 4 <= day <= 20 or 24 <= day <= 30:\n suffix_index = 0 # use 'th'\n else:\n suffix_index = day % 10 # use 'st', 'nd', 'rd' as appropriate\n\n return dt.strftime(f\"%B {day}{suffix[suffix_index]}\")" }, { "identifier": "Scheduler", "path": "scheduler.py", "snippet": "class Scheduler:\n \"\"\"Scheduler class to manage timed jobs for sending status requests.\n\n Attributes:\n scheduler: The APScheduler object.\n job_ids: A dictionary to store lists of job IDs for each member.\n \"\"\"\n \n def __init__(self) -> None:\n \"\"\"Initialize the Scheduler object and start the APScheduler.\"\"\"\n self.scheduler: AsyncIOScheduler = AsyncIOScheduler()\n self.job_ids: Dict[int, List[str]] = {} # Store job IDs indexed by member's Discord ID\n self.weekly_post_job_id = None # To store the ID of the scheduled weekly post job\n self.scheduler.start()\n\n def add_job(self, func: callable, member: TeamMember, weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, updates_manager: UpdatesManager) -> None:\n \"\"\"Add a new job to the scheduler for a specific team member.\n \n Args:\n func: The function to call when the job is run.\n member: The TeamMember object for whom the job is added.\n \"\"\"\n time_zone = pytz.timezone(member.time_zone)\n \n weekday_trigger = CronTrigger(day_of_week='mon,tue,wed,thu,fri', hour=10, timezone=time_zone)\n weekend_trigger = CronTrigger(day_of_week='sat,sun', hour=11, timezone=time_zone)\n\n weekday_job = self.scheduler.add_job(func, weekday_trigger, args=[member, weekly_post_manager, streaks_manager, updates_manager])\n weekend_job = self.scheduler.add_job(func, weekend_trigger, args=[member, weekly_post_manager, streaks_manager, updates_manager])\n\n self.job_ids.setdefault(member.discord_id, []).extend([weekday_job.id, weekend_job.id])\n\n def remove_job(self, discord_id: int) -> None:\n \"\"\"Remove jobs for a specific team member.\n \n Args:\n discord_id: The Discord ID of the member for whom the job should be removed.\n \"\"\"\n job_ids = self.job_ids.get(discord_id, [])\n for job_id in job_ids:\n self.scheduler.remove_job(job_id)\n\n if discord_id in self.job_ids:\n del self.job_ids[discord_id] # Remove the job IDs from the dictionary\n\n def schedule_weekly_post(self, func: callable, weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, team_members: List[TeamMember]) -> None:\n \"\"\"Schedules the weekly post based on the latest time zone among the team members.\"\"\"\n \n # Determine the latest time zone\n latest_time_zone = max([member.time_zone for member in team_members], key=lambda tz: pytz.timezone(tz).utcoffset(datetime.utcnow()))\n\n # Set the trigger for 9:10 AM in the earliest time zone on Monday\n trigger = CronTrigger(day_of_week='mon', hour=9, minute=10, timezone=latest_time_zone)\n\n # Schedule the function with the trigger\n job = self.scheduler.add_job(func, trigger, args=[weekly_post_manager, streaks_manager, team_members])\n self.weekly_post_job_id = job.id\n\n def unschedule_weekly_post(self) -> None:\n \"\"\"Removes the weekly post job from the scheduler.\"\"\"\n if self.weekly_post_job_id:\n self.scheduler.remove_job(self.weekly_post_job_id)\n self.weekly_post_job_id = None\n\n def get_all_scheduled_jobs(self, team_member_manager) -> List[str]:\n \"\"\"Retrieve all scheduled jobs as a list of strings.\"\"\"\n job_descriptions = []\n\n for job in self.scheduler.get_jobs():\n # Determine the associated team member by looking up the job ID in the job_ids dictionary\n member_discord_id = next((discord_id for discord_id, job_ids in self.job_ids.items() if job.id in job_ids), None)\n member_name = team_member_manager.find_member(member_discord_id).name if member_discord_id else \"Unknown\"\n\n # Calculate the remaining time until the next run\n now = datetime.now(job.next_run_time.tzinfo) # Get the current time with the same timezone as the job's next_run_time\n remaining_time = job.next_run_time - now\n remaining_time_str = str(remaining_time).split('.')[0] # Remove the microseconds part\n\n # If this job is the weekly post job\n if job.id == self.weekly_post_job_id:\n job_descriptions.append(f\"ID: {job.id}, Type: Weekly Post, Next Run: {job.next_run_time}, Remaining Time: {remaining_time_str}, Func: {job.func.__name__}\")\n else:\n job_descriptions.append(f\"ID: {job.id}, Member: {member_name}, Next Run: {job.next_run_time}, Remaining Time: {remaining_time_str}, Func: {job.func.__name__}\")\n\n return job_descriptions" }, { "identifier": "TeamMember", "path": "team_members/team_member.py", "snippet": "class TeamMember:\n \"\"\"TeamMember class to store individual team member details.\n \n Attributes:\n discord_id: The Discord ID of the team member.\n time_zone: The time zone in which the team member resides.\n name: The name of the team member.\n github_username: The GitHub username of the team member.\n current_streak: The current streak of daily updates/check-ins of the team member.\n weekly_checkins: The number of check-ins for the current week.\n \"\"\"\n \n def __init__(self, discord_id: int, time_zone: str, name: str, github_username: str,\n current_streak: int = 0, weekly_checkins: int = 0, on_vacation: bool = False) -> None:\n \"\"\"Initialize a new TeamMember object.\n \n Args:\n discord_id: The Discord ID of the team member.\n time_zone: The time zone of the team member.\n name: The name of the team member.\n github_username: The GitHub username of the team member.\n current_streak: The current streak of daily updates/check-ins. Defaults to 0.\n weekly_checkins: The number of check-ins for the current week. Defaults to 0.\n \"\"\"\n self.discord_id: int = discord_id\n self.time_zone: str = time_zone\n self.name: str = name\n self.github_username: str = github_username\n self.current_streak: int = current_streak\n self.weekly_checkins: int = weekly_checkins\n self.on_vacation: bool = on_vacation\n \n def update_streak(self, streak: int) -> None:\n \"\"\"Update the current streak of the team member.\n \n Args:\n streak: The new streak count.\n \"\"\"\n self.current_streak = streak\n \n def reset_streak(self) -> None:\n \"\"\"Reset the current streak of the team member to 0.\"\"\"\n self.current_streak = 0\n\n def update_weekly_checkins(self, count: int):\n \"\"\"\n Update the weekly check-ins count.\n\n Args:\n count: The new count of weekly check-ins.\n \"\"\"\n self.weekly_checkins = count\n \n def increment_weekly_checkins(self) -> None:\n \"\"\"Increment the number of check-ins for the current week by 1.\"\"\"\n self.weekly_checkins += 1\n \n def reset_weekly_checkins(self) -> None:\n \"\"\"Reset the number of check-ins for the current week to 0.\"\"\"\n self.weekly_checkins = 0" } ]
import os import pytz import asyncio import openai import requests from typing import List from dotenv import load_dotenv from datetime import datetime, timedelta from multiprocessing import Process from streaks.streaks_db import StreaksDB from team_members.team_member_db import TeamMemberDB from updates.updates_db import UpdatesDB from weekly_posts.weekly_posts_db import WeeklyPostsDB from streaks.streaks_manager import StreaksManager from team_members.team_member_manager import TeamMemberManager from updates.updates_manager import UpdatesManager from weekly_posts.weekly_post_manager import WeeklyPostManager from scheduler import Scheduler from team_members.team_member import TeamMember from discord.ext import commands, tasks from discord import Intents, DMChannel from flask import Flask from asyncio import Task, ensure_future, CancelledError
15,376
return # Find the member object using the Discord ID member_to_update = team_member_manager.find_member(discord_id) if member_to_update: # Update the streak in the database streaks_manager.update_streak(discord_id, new_streak) member_to_update.update_streak(new_streak) # Update the Discord post using WeeklyPostManager await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send(f"Streak for user with Discord ID {discord_id} updated to {new_streak}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='forcepostrebuild') async def force_post_rebuild(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to force a post rebuild.") return # Rebuild the post await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send("Post rebuilt successfully.") @bot.command(name='deletelateststatus') async def delete_latest_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to delete status updates.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Delete the newest status using the UpdatesManager's method updates_manager.delete_newest_status(discord_id) await ctx.send(f"Latest status update for user with Discord ID {discord_id} deleted successfully.") @bot.command(name='viewuser') async def view_user(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to view user data.") return # Get the member's statuses using the UpdatesManager's method statuses = updates_manager.get_all_statuses_for_user(discord_id) if not statuses: await ctx.send(f"No status updates found for user with Discord ID {discord_id}.") return # Loop through the statuses and send individual messages for status in statuses: await ctx.send(f"### **Timestamp:** {status['timestamp']}") await ctx.send(f"### **Raw Status:** {status['status']}") await ctx.send(f"### **Summarized Status:** \n{status['summarized_status']}") @bot.command(name='setvacationstatus') async def set_vacation_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to set vacation status.") return member = team_member_manager.find_member(discord_id) if member: new_status = not member.on_vacation team_member_manager.set_member_vacation_status(discord_id, new_status) await ctx.send(f"Vacation status for user with Discord ID {discord_id} set to {'on vacation' if new_status else 'not on vacation'}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='weeklysummary') async def weekly_summary(ctx, discord_id: int, start_date: str, end_date: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to generate weekly summaries.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Convert the start_date and end_date strings to datetime objects # Adjusting the date format to MM-DD-YYYY and setting the time try: start_date = datetime.strptime(start_date, '%m-%d-%Y') end_date = datetime.strptime(end_date, '%m-%d-%Y') # Setting the time to ensure the whole week is captured start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0) end_date = end_date.replace(hour=23, minute=59, second=59, microsecond=999999) except ValueError: await ctx.send("Invalid date format. Please use MM-DD-YYYY.") return # Generate the weekly summary weekly_summary = await updates_manager.generate_weekly_summary(discord_id, start_date, end_date) # Send the weekly summary to the admin user admin_user = bot.get_user(ADMIN_DISCORD_ID) if admin_user: await admin_user.send(f"**{member.name}'s Weekly Summary for {start_date.strftime('%m-%d-%Y')} to {end_date.strftime('%m-%d-%Y')}:**\n{weekly_summary}") else: await ctx.send("Unable to find the admin user.") @bot.event async def on_ready(): print("Bot is online!") # Log that the bot is online streaks_db = StreaksDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT) team_member_db = TeamMemberDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT)
# Import required modules app = Flask(__name__) # Load environment variables from the .env file load_dotenv() # Retrieve bot, guild, and channel tokens from environment variables BOT_TOKEN = os.getenv('DISCORD_BOT_TOKEN') GUILD_TOKEN = int(os.getenv('DISCORD_GUILD_TOKEN')) CHANNEL_TOKEN = int(os.getenv('DISCORD_CHANNEL_TOKEN')) ADMIN_DISCORD_ID = int(os.getenv('ADMIN_DISCORD_ID')) # Retrieve database credentials from environment variables MYSQL_HOST = os.getenv('MYSQL_HOST') MYSQL_USER = os.getenv('MYSQL_USER') MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD') MYSQL_DB = os.getenv('MYSQL_DB') MYSQL_PORT = os.getenv('MYSQL_PORT') ORG_NAME = os.getenv('GITHUB_ORG_NAME') ORG_TOKEN = os.getenv('GITHUB_ORG_TOKEN') OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') # Initialize bot with default intents intents = Intents.default() intents.members = True intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents) openai.api_key = OPENAI_API_KEY # TODO: Remove these globals streaks_manager = None weekly_post_manager = None team_member_manager = None updates_manager = None scheduler = None ongoing_status_requests = {} THUMBS_UP_EMOJI = "👍" PENCIL_EMOJI = "✏️" REPORT_SUBMISSION_EMOJI = '📝' async def weekly_state_reset(weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, team_members: List[TeamMember]): # Reset streaks for the previous week for member in team_members: if not member.on_vacation and member.weekly_checkins < 5: streaks_manager.reset_streak(member.discord_id) member.reset_streak() member.reset_weekly_checkins() # Initialize new weekly post await weekly_post_manager.initialize_post(team_members) def get_all_commit_messages_for_user(org_name: str, token: str, member: TeamMember) -> list: """Retrieve all commit messages for a user across all repos in an organization from the last 24 hours.""" headers = { "Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json" } last_update_timestamp, user_time_zone = updates_manager.get_last_update_timestamp(member.discord_id) if last_update_timestamp: # Convert the timestamp to UTC local_tz = pytz.timezone(user_time_zone) localized_timestamp = local_tz.localize(last_update_timestamp) utc_timestamp = localized_timestamp.astimezone(pytz.utc) # Format the timestamp for the GitHub API and append 'Z' since_date = utc_timestamp.isoformat() if not since_date.endswith('Z'): since_date = utc_timestamp.isoformat().replace('+00:00', '') + 'Z' else: # If no updates found, default to last 24 hours since_date = (datetime.utcnow() - timedelta(days=1)).isoformat() + 'Z' all_commit_messages = [] # Paginate through all repositories in the organization repos_url = f"https://api.github.com/orgs/{org_name}/repos?type=all&per_page=100" while repos_url: response = requests.get(repos_url, headers=headers) if response.status_code != 200: # Log error and break loop print(f"Failed to fetch repos: {response.status_code} {response.text}") break repos = response.json() # Iterate over each repository for repo in repos: repo_name = repo["name"] commits_url = f"https://api.github.com/repos/{org_name}/{repo_name}/commits?author={member.github_username}&since={since_date}&per_page=100" # Paginate through commits for the repository while commits_url: response = requests.get(commits_url, headers=headers) if response.status_code != 200: # Log error and continue to the next repository print(f"Failed to fetch commits for {repo_name}: {response.status_code} {response.text}") break commits = response.json() repo_commit_messages = [commit["commit"]["message"] for commit in commits] all_commit_messages.extend(repo_commit_messages) # Check for the 'next' link for commits pagination commits_url = get_pagination_link(response.headers, 'next') # Check for the 'next' link for repositories pagination repos_url = get_pagination_link(response.headers, 'next') return all_commit_messages def get_pagination_link(headers, rel): """Extract pagination link for the 'rel' type from the Link header.""" link = headers.get('Link', None) if link: links = link.split(', ') for link in links: if 'rel="{}"'.format(rel) in link: return link.split('; ')[0].strip('<>') return None async def send_status_request(member: TeamMember, weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, updates_manager: UpdatesManager): if member.weekly_checkins == 5: return # If already completed 5 check-ins, do nothing user = bot.get_user(member.discord_id) if user: # Notify the admin that a status request is being sent admin_user = bot.get_user(ADMIN_DISCORD_ID) if admin_user: await admin_user.send(f"Status request sent to {member.name}.") # Cancel the previous task if it exists ongoing_task: Task = ongoing_status_requests.get(member.discord_id) if ongoing_task: ongoing_task.cancel() # Retrieve all commit messages for the member commit_messages = get_all_commit_messages_for_user(ORG_NAME, ORG_TOKEN, member) if not commit_messages: summarized_report = "You have no commits for the previous working day." msg = f"{summarized_report}\nReact with {THUMBS_UP_EMOJI} to confirm, {PENCIL_EMOJI} to iterate with AI, or {REPORT_SUBMISSION_EMOJI} to submit your own report." else: summarized_report = await updates_manager.summarize_technical_updates(commit_messages) msg = f"Here's your summarized report based on your commits:\n{summarized_report}\nReact with {THUMBS_UP_EMOJI} to confirm, {PENCIL_EMOJI} to iterate with AI, or {REPORT_SUBMISSION_EMOJI} to submit your own report." raw_updates = summarized_report # Send initial message and wait for reaction await user.send( f"# Good morning {member.name}, time for your daily status update!\n" f"### I'm first going to check your commit messages and try to build a technical report for you.\n" f"### Next I will ask you for any non-technical updates from your previous work day.\n" f"### Finally I will ask you what you plan to work on today." ) sent_message = await user.send(msg) await sent_message.add_reaction(THUMBS_UP_EMOJI) await sent_message.add_reaction(PENCIL_EMOJI) await sent_message.add_reaction(REPORT_SUBMISSION_EMOJI) def check(m) -> bool: return m.author == user and isinstance(m.channel, DMChannel) # Store the new wait_for reaction task in the global dictionary ongoing_task = ensure_future(bot.wait_for('reaction_add', check=lambda r, u: u == user and r.message.id == sent_message.id and isinstance(r.message.channel, DMChannel) and str(r.emoji) in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI])) ongoing_status_requests[member.discord_id] = ongoing_task reaction, reactor = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the reaction for emoji in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI]: await sent_message.remove_reaction(emoji, bot.user) while str(reaction.emoji) in [PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI]: if str(reaction.emoji) == PENCIL_EMOJI: await user.send("What would you like me to change?") # Store the new wait_for message (feedback) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task feedback = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the feedback # Send original + feedback to LLM for reformatting summarized_report = await updates_manager.summarize_feedback_and_revisions(summarized_report, feedback.content) elif str(reaction.emoji) == REPORT_SUBMISSION_EMOJI: await user.send("Please submit your technical report directly.") # Store the new wait_for message (report submission) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task direct_report = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the report summarized_report = direct_report.content break # Exit the while loop as the user has submitted their report directly msg = f"Here's the revised report:\n{summarized_report}\nReact with {THUMBS_UP_EMOJI} to confirm, {PENCIL_EMOJI} to iterate with AI, or {REPORT_SUBMISSION_EMOJI} to submit your own report." last_sent_message = await send_long_message(user, msg) if last_sent_message: await last_sent_message.add_reaction(THUMBS_UP_EMOJI) await last_sent_message.add_reaction(PENCIL_EMOJI) await last_sent_message.add_reaction(REPORT_SUBMISSION_EMOJI) # Store the new wait_for reaction task in the global dictionary ongoing_task = ensure_future(bot.wait_for('reaction_add', check=lambda r, u: u == user and r.message.id == last_sent_message.id and isinstance(r.message.channel, DMChannel) and str(r.emoji) in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI])) ongoing_status_requests[member.discord_id] = ongoing_task reaction, user = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the reaction for emoji in [THUMBS_UP_EMOJI, PENCIL_EMOJI, REPORT_SUBMISSION_EMOJI]: await last_sent_message.remove_reaction(emoji, bot.user) # Prompt user for non-technical updates from the previous day non_technical_msg_prompt = "Please provide any non-technical updates from your previous working day, e.g., important meetings, interviews, etc." await user.send(non_technical_msg_prompt) # Store the new wait_for message (non-technical update) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task non_technical_update_raw = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the non-technical update raw_updates += f"\n\n{non_technical_update_raw.content}" # Summarize non-technical update with LLM non_technical_update = await updates_manager.summarize_non_technical_updates(non_technical_update_raw.content) # Prompt user for their goals for the day goals_msg_prompt = "What do you plan to work on or accomplish today?" await user.send(goals_msg_prompt) # Store the new wait_for message (goals for the day) task in the global dictionary ongoing_task = ensure_future(bot.wait_for('message', check=check)) ongoing_status_requests[member.discord_id] = ongoing_task goals_for_today_raw = await ongoing_task ongoing_status_requests.pop(member.discord_id, None) # Remove the task once we get the goals # Summarize goals for the day with LLM goals_for_today = await updates_manager.summarize_goals_for_the_day(goals_for_today_raw.content) # Update the streak for this member streak = streaks_manager.get_streak(member.discord_id) streaks_manager.update_streak(member.discord_id, streak + 1) member.update_streak(streaks_manager.get_streak(member.discord_id)) member.increment_weekly_checkins() raw_updates += f"\n\n{goals_for_today_raw.content}" final_updates = f"{summarized_report}\n\n{non_technical_update}\n\n{goals_for_today}" updates_manager.insert_status(member.discord_id, raw_updates, member.time_zone) updates_manager.update_summarized_status(member.discord_id, final_updates) # Update the Discord post using WeeklyPostManager await weekly_post_manager.rebuild_post(team_member_manager.team_members) # Member name update as a header member_update_header = f"## {member.name}'s Update:" # Compile the final report with Markdown formatting final_report = ( f"\n### Technical Update:\n" f"{summarized_report}\n" f"### Non-Technical Update:\n" f"{non_technical_update}\n" f"### Goals for Today:\n" f"{goals_for_today}" ) stand_up_feedback = await updates_manager.evaluate_performance(final_report) # Concatenate the member name update with the final report and send to the designated Discord channel complete_message = f"{member_update_header}{final_report}" guild = bot.get_guild(GUILD_TOKEN) channel_to_post_in = guild.get_channel(CHANNEL_TOKEN) await user.send(stand_up_feedback) await send_long_message(channel_to_post_in, complete_message) async def send_long_message(destination, msg): max_length = 2000 # Discord's max character limit for a message sent_messages = [] # Keep track of all messages sent while len(msg) > 0: # If the message is shorter than the max length, send it as is if len(msg) <= max_length: sent_message = await destination.send(msg) sent_messages.append(sent_message) break # The message is sent, so break out of the loop # Find the nearest newline character before the max_length split_index = msg.rfind('\n', 0, max_length) # If no newline is found, just split at max_length if split_index == -1: split_index = max_length # Split the message at the found index and send the first part part_to_send = msg[:split_index].strip() sent_message = await destination.send(part_to_send) sent_messages.append(sent_message) # Wait a bit to respect Discord's rate limits await asyncio.sleep(1) # Remove the part that was sent from the message msg = msg[split_index:].strip() # Return the last message sent for reaction addition return sent_messages[-1] if sent_messages else None @bot.command(name='viewscheduledjobs') async def view_scheduled_jobs(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to view scheduled jobs.") return # Get all scheduled jobs using the Scheduler's method scheduled_jobs = scheduler.get_all_scheduled_jobs(team_member_manager) # Send the scheduled jobs to the admin user for job in scheduled_jobs: await ctx.send(job) @bot.command(name='statusrequest') async def status_request(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to request status.") return # Find the member object using the Discord ID member_to_request = team_member_manager.find_member(discord_id) if member_to_request: for member in team_member_manager.team_members: scheduler.remove_job(member.discord_id) scheduler.unschedule_weekly_post() # Send the status request to the member await ctx.send(f"Status request sent to user with Discord ID {discord_id}.") for member in team_member_manager.team_members: scheduler.add_job(send_status_request, member, weekly_post_manager, streaks_manager, updates_manager) scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await send_status_request(member_to_request, weekly_post_manager, streaks_manager, updates_manager) await ctx.send(f"Status request received from user with Discord ID {discord_id}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='adduser') async def add_user(ctx, discord_id: int, time_zone: str, name: str, github_username: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to add users.") return # Add the new member using team_member_manager team_member_manager.add_member(discord_id, name, time_zone, github_username) # Update the weekly post to include the new member new_member = team_member_manager.find_member(discord_id) if new_member: await weekly_post_manager.rebuild_post(team_member_manager.team_members) scheduler.add_job(send_status_request, new_member, weekly_post_manager, streaks_manager, updates_manager) scheduler.unschedule_weekly_post() scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await ctx.send(f"User {name} added successfully.") @bot.command(name='removeuser') async def remove_user(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to remove users.") return # Find the member object member_to_remove = team_member_manager.find_member(discord_id) if member_to_remove: # Remove the member from the database team_member_manager.remove_member(discord_id) # Update the weekly post to remove the member await weekly_post_manager.rebuild_post(team_member_manager.team_members) scheduler.remove_job(discord_id) scheduler.unschedule_weekly_post() scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await ctx.send(f"User with Discord ID {discord_id} removed successfully.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='listusers') async def list_users(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to list users.") return # List users using team_member_manager users = [(member.discord_id, member.name, member.time_zone, member.github_username, member.current_streak) for member in team_member_manager.team_members] user_list = '\n'.join([f"Name: {user[1]}, Discord ID: {user[0]}, Time Zone: {user[2]}, GitHub Username: {user[3]}, Current Streak: {user[4]}" for user in users]) await ctx.send(f"List of users:\n{user_list}") @bot.command(name='updatetimezone') async def update_timezone(ctx, discord_id: int, new_time_zone: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to update timezones.") return # Find the member object using the Discord ID member_to_update = team_member_manager.find_member(discord_id) if member_to_update: # Update the timezone in the database team_member_manager.update_member_timezone(discord_id, new_time_zone) scheduler.remove_job(discord_id) scheduler.add_job(send_status_request, member_to_update, weekly_post_manager, streaks_manager, updates_manager) scheduler.unschedule_weekly_post() scheduler.schedule_weekly_post(weekly_state_reset, weekly_post_manager, streaks_manager, team_member_manager.team_members) await ctx.send(f"Timezone for user with Discord ID {discord_id} updated to {new_time_zone}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='updatestreak') async def update_streak(ctx, discord_id: int, new_streak: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to update streaks.") return # Find the member object using the Discord ID member_to_update = team_member_manager.find_member(discord_id) if member_to_update: # Update the streak in the database streaks_manager.update_streak(discord_id, new_streak) member_to_update.update_streak(new_streak) # Update the Discord post using WeeklyPostManager await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send(f"Streak for user with Discord ID {discord_id} updated to {new_streak}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='forcepostrebuild') async def force_post_rebuild(ctx): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to force a post rebuild.") return # Rebuild the post await weekly_post_manager.rebuild_post(team_member_manager.team_members) await ctx.send("Post rebuilt successfully.") @bot.command(name='deletelateststatus') async def delete_latest_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to delete status updates.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Delete the newest status using the UpdatesManager's method updates_manager.delete_newest_status(discord_id) await ctx.send(f"Latest status update for user with Discord ID {discord_id} deleted successfully.") @bot.command(name='viewuser') async def view_user(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to view user data.") return # Get the member's statuses using the UpdatesManager's method statuses = updates_manager.get_all_statuses_for_user(discord_id) if not statuses: await ctx.send(f"No status updates found for user with Discord ID {discord_id}.") return # Loop through the statuses and send individual messages for status in statuses: await ctx.send(f"### **Timestamp:** {status['timestamp']}") await ctx.send(f"### **Raw Status:** {status['status']}") await ctx.send(f"### **Summarized Status:** \n{status['summarized_status']}") @bot.command(name='setvacationstatus') async def set_vacation_status(ctx, discord_id: int): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to set vacation status.") return member = team_member_manager.find_member(discord_id) if member: new_status = not member.on_vacation team_member_manager.set_member_vacation_status(discord_id, new_status) await ctx.send(f"Vacation status for user with Discord ID {discord_id} set to {'on vacation' if new_status else 'not on vacation'}.") else: await ctx.send(f"No user with Discord ID {discord_id} found.") @bot.command(name='weeklysummary') async def weekly_summary(ctx, discord_id: int, start_date: str, end_date: str): if ctx.message.author.id != ADMIN_DISCORD_ID or not isinstance(ctx.channel, DMChannel): await ctx.send("You're not authorized to generate weekly summaries.") return # Find the member object using the Discord ID member = team_member_manager.find_member(discord_id) if not member: await ctx.send(f"No user with Discord ID {discord_id} found.") return # Convert the start_date and end_date strings to datetime objects # Adjusting the date format to MM-DD-YYYY and setting the time try: start_date = datetime.strptime(start_date, '%m-%d-%Y') end_date = datetime.strptime(end_date, '%m-%d-%Y') # Setting the time to ensure the whole week is captured start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0) end_date = end_date.replace(hour=23, minute=59, second=59, microsecond=999999) except ValueError: await ctx.send("Invalid date format. Please use MM-DD-YYYY.") return # Generate the weekly summary weekly_summary = await updates_manager.generate_weekly_summary(discord_id, start_date, end_date) # Send the weekly summary to the admin user admin_user = bot.get_user(ADMIN_DISCORD_ID) if admin_user: await admin_user.send(f"**{member.name}'s Weekly Summary for {start_date.strftime('%m-%d-%Y')} to {end_date.strftime('%m-%d-%Y')}:**\n{weekly_summary}") else: await ctx.send("Unable to find the admin user.") @bot.event async def on_ready(): print("Bot is online!") # Log that the bot is online streaks_db = StreaksDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT) team_member_db = TeamMemberDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT)
weekly_posts_db = WeeklyPostsDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_PORT)
3
2023-10-12 02:01:46+00:00
24k
azuline/rose
rose/virtualfs.py
[ { "identifier": "SUPPORTED_AUDIO_EXTENSIONS", "path": "rose/audiotags.py", "snippet": "SUPPORTED_AUDIO_EXTENSIONS = [\n \".mp3\",\n \".m4a\",\n \".ogg\",\n \".opus\",\n \".flac\",\n]" }, { "identifier": "AudioTags", "path": "rose/audiotags.py", "snippet": "class AudioTags:\n id: str | None\n release_id: str | None\n title: str | None\n year: int | None\n tracknumber: str | None\n tracktotal: int | None\n discnumber: str | None\n disctotal: int | None\n album: str | None\n genre: list[str]\n label: list[str]\n releasetype: str\n\n albumartists: ArtistMapping\n trackartists: ArtistMapping\n\n duration_sec: int\n\n path: Path\n\n @classmethod\n def from_file(cls, p: Path) -> AudioTags:\n \"\"\"Read the tags of an audio file on disk.\"\"\"\n if not any(p.suffix.lower() == ext for ext in SUPPORTED_AUDIO_EXTENSIONS):\n raise UnsupportedFiletypeError(f\"{p.suffix} not a supported filetype\")\n try:\n m = mutagen.File(p) # type: ignore\n except mutagen.MutagenError as e: # type: ignore\n raise UnsupportedFiletypeError(f\"Failed to open file: {e}\") from e\n if isinstance(m, mutagen.mp3.MP3):\n # ID3 returns trackno/discno tags as no/total. We have to parse.\n tracknumber = discnumber = tracktotal = disctotal = None\n if tracknos := _get_tag(m.tags, [\"TRCK\"]):\n try:\n tracknumber, tracktotalstr = tracknos.split(\"/\", 1)\n tracktotal = _parse_int(tracktotalstr)\n except ValueError:\n tracknumber = tracknos\n if discnos := _get_tag(m.tags, [\"TPOS\"]):\n try:\n discnumber, disctotalstr = discnos.split(\"/\", 1)\n disctotal = _parse_int(disctotalstr)\n except ValueError:\n discnumber = discnos\n\n def _get_paired_frame(x: str) -> str | None:\n if not m.tags:\n return None\n for tag in [\"TIPL\", \"IPLS\"]:\n try:\n frame = m.tags[tag]\n except KeyError:\n continue\n return r\" \\\\ \".join([p[1] for p in frame.people if p[0].lower() == x.lower()])\n return None\n\n return AudioTags(\n id=_get_tag(m.tags, [\"TXXX:ROSEID\"]),\n release_id=_get_tag(m.tags, [\"TXXX:ROSERELEASEID\"]),\n title=_get_tag(m.tags, [\"TIT2\"]),\n year=_parse_year(_get_tag(m.tags, [\"TDRC\", \"TYER\"])),\n tracknumber=tracknumber,\n tracktotal=tracktotal,\n discnumber=discnumber,\n disctotal=disctotal,\n album=_get_tag(m.tags, [\"TALB\"]),\n genre=_split_tag(_get_tag(m.tags, [\"TCON\"], split=True)),\n label=_split_tag(_get_tag(m.tags, [\"TPUB\"], split=True)),\n releasetype=_normalize_rtype(_get_tag(m.tags, [\"TXXX:RELEASETYPE\"], first=True)),\n albumartists=parse_artist_string(main=_get_tag(m.tags, [\"TPE2\"], split=True)),\n trackartists=parse_artist_string(\n main=_get_tag(m.tags, [\"TPE1\"], split=True),\n remixer=_get_tag(m.tags, [\"TPE4\"], split=True),\n composer=_get_tag(m.tags, [\"TCOM\"], split=True),\n conductor=_get_tag(m.tags, [\"TPE3\"], split=True),\n producer=_get_paired_frame(\"producer\"),\n dj=_get_paired_frame(\"DJ-mix\"),\n ),\n duration_sec=round(m.info.length),\n path=p,\n )\n if isinstance(m, mutagen.mp4.MP4):\n tracknumber = discnumber = tracktotal = disctotal = None\n with contextlib.suppress(ValueError):\n tracknumber, tracktotalstr = _get_tuple_tag(m.tags, [\"trkn\"]) # type: ignore\n tracktotal = _parse_int(tracktotalstr)\n with contextlib.suppress(ValueError):\n discnumber, disctotalstr = _get_tuple_tag(m.tags, [\"disk\"]) # type: ignore\n disctotal = _parse_int(disctotalstr)\n\n return AudioTags(\n id=_get_tag(m.tags, [\"----:net.sunsetglow.rose:ID\"]),\n release_id=_get_tag(m.tags, [\"----:net.sunsetglow.rose:RELEASEID\"]),\n title=_get_tag(m.tags, [\"\\xa9nam\"]),\n year=_parse_year(_get_tag(m.tags, [\"\\xa9day\"])),\n tracknumber=str(tracknumber),\n tracktotal=tracktotal,\n discnumber=str(discnumber),\n disctotal=disctotal,\n album=_get_tag(m.tags, [\"\\xa9alb\"]),\n genre=_split_tag(_get_tag(m.tags, [\"\\xa9gen\"], split=True)),\n label=_split_tag(_get_tag(m.tags, [\"----:com.apple.iTunes:LABEL\"], split=True)),\n releasetype=_normalize_rtype(\n _get_tag(m.tags, [\"----:com.apple.iTunes:RELEASETYPE\"], first=True)\n ),\n albumartists=parse_artist_string(main=_get_tag(m.tags, [\"aART\"], split=True)),\n trackartists=parse_artist_string(\n main=_get_tag(m.tags, [\"\\xa9ART\"], split=True),\n remixer=_get_tag(m.tags, [\"----:com.apple.iTunes:REMIXER\"], split=True),\n producer=_get_tag(m.tags, [\"----:com.apple.iTunes:PRODUCER\"], split=True),\n composer=_get_tag(m.tags, [\"\\xa9wrt\"], split=True),\n conductor=_get_tag(m.tags, [\"----:com.apple.iTunes:CONDUCTOR\"], split=True),\n dj=_get_tag(m.tags, [\"----:com.apple.iTunes:DJMIXER\"], split=True),\n ),\n duration_sec=round(m.info.length), # type: ignore\n path=p,\n )\n if isinstance(m, (mutagen.flac.FLAC, mutagen.oggvorbis.OggVorbis, mutagen.oggopus.OggOpus)):\n return AudioTags(\n id=_get_tag(m.tags, [\"roseid\"]),\n release_id=_get_tag(m.tags, [\"rosereleaseid\"]),\n title=_get_tag(m.tags, [\"title\"]),\n year=_parse_year(_get_tag(m.tags, [\"date\", \"year\"])),\n tracknumber=_get_tag(m.tags, [\"tracknumber\"], first=True),\n tracktotal=_parse_int(_get_tag(m.tags, [\"tracktotal\"], first=True)),\n discnumber=_get_tag(m.tags, [\"discnumber\"], first=True),\n disctotal=_parse_int(_get_tag(m.tags, [\"disctotal\"], first=True)),\n album=_get_tag(m.tags, [\"album\"]),\n genre=_split_tag(_get_tag(m.tags, [\"genre\"], split=True)),\n label=_split_tag(\n _get_tag(m.tags, [\"organization\", \"label\", \"recordlabel\"], split=True)\n ),\n releasetype=_normalize_rtype(_get_tag(m.tags, [\"releasetype\"], first=True)),\n albumartists=parse_artist_string(\n main=_get_tag(m.tags, [\"albumartist\"], split=True)\n ),\n trackartists=parse_artist_string(\n main=_get_tag(m.tags, [\"artist\"], split=True),\n remixer=_get_tag(m.tags, [\"remixer\"], split=True),\n producer=_get_tag(m.tags, [\"producer\"], split=True),\n composer=_get_tag(m.tags, [\"composer\"], split=True),\n conductor=_get_tag(m.tags, [\"conductor\"], split=True),\n dj=_get_tag(m.tags, [\"djmixer\"], split=True),\n ),\n duration_sec=round(m.info.length), # type: ignore\n path=p,\n )\n raise UnsupportedFiletypeError(f\"{p} is not a supported audio file\")\n\n @no_type_check\n def flush(self, *, validate: bool = True) -> None:\n \"\"\"Flush the current tags to the file on disk.\"\"\"\n m = mutagen.File(self.path)\n if not validate and \"pytest\" not in sys.modules:\n raise Exception(\"Validate can only be turned off by tests.\")\n\n self.releasetype = (self.releasetype or \"unknown\").lower()\n if validate and self.releasetype not in SUPPORTED_RELEASE_TYPES:\n raise UnsupportedTagValueTypeError(\n f\"Release type {self.releasetype} is not a supported release type.\\n\"\n f\"Supported release types: {', '.join(SUPPORTED_RELEASE_TYPES)}\"\n )\n\n if isinstance(m, mutagen.mp3.MP3):\n if m.tags is None:\n m.tags = mutagen.id3.ID3()\n\n def _write_standard_tag(key: str, value: str | None) -> None:\n m.tags.delall(key)\n frame = getattr(mutagen.id3, key)(text=value)\n if value:\n m.tags.add(frame)\n\n def _write_tag_with_description(name: str, value: str | None) -> None:\n key, desc = name.split(\":\", 1)\n # Since the ID3 tags work with the shared prefix key before `:`, manually preserve\n # the other tags with the shared prefix key.\n keep_fields = [f for f in m.tags.getall(key) if getattr(f, \"desc\", None) != desc]\n m.tags.delall(key)\n if value:\n frame = getattr(mutagen.id3, key)(desc=desc, text=value)\n m.tags.add(frame)\n for f in keep_fields:\n m.tags.add(f)\n\n _write_tag_with_description(\"TXXX:ROSEID\", self.id)\n _write_tag_with_description(\"TXXX:ROSERELEASEID\", self.release_id)\n _write_standard_tag(\"TIT2\", self.title)\n _write_standard_tag(\"TDRC\", str(self.year).zfill(4))\n _write_standard_tag(\"TRCK\", self.tracknumber)\n _write_standard_tag(\"TPOS\", self.discnumber)\n _write_standard_tag(\"TALB\", self.album)\n _write_standard_tag(\"TCON\", \";\".join(self.genre))\n _write_standard_tag(\"TPUB\", \";\".join(self.label))\n _write_tag_with_description(\"TXXX:RELEASETYPE\", self.releasetype)\n _write_standard_tag(\"TPE2\", format_artist_string(self.albumartists))\n _write_standard_tag(\"TPE1\", format_artist_string(self.trackartists))\n # Wipe the alt. role artist tags, since we encode the full artist into the main tag.\n m.tags.delall(\"TPE4\")\n m.tags.delall(\"TCOM\")\n m.tags.delall(\"TPE3\")\n # Delete all paired text frames, since these represent additional artist roles. We don't\n # want to preserve them.\n m.tags.delall(\"TIPL\")\n m.tags.delall(\"IPLS\")\n m.save()\n return\n if isinstance(m, mutagen.mp4.MP4):\n if m.tags is None:\n m.tags = mutagen.mp4.MP4Tags()\n m.tags[\"----:net.sunsetglow.rose:ID\"] = (self.id or \"\").encode()\n m.tags[\"----:net.sunsetglow.rose:RELEASEID\"] = (self.release_id or \"\").encode()\n m.tags[\"\\xa9nam\"] = self.title or \"\"\n m.tags[\"\\xa9day\"] = str(self.year).zfill(4)\n m.tags[\"\\xa9alb\"] = self.album or \"\"\n m.tags[\"\\xa9gen\"] = \";\".join(self.genre)\n m.tags[\"----:com.apple.iTunes:LABEL\"] = \";\".join(self.label).encode()\n m.tags[\"----:com.apple.iTunes:RELEASETYPE\"] = self.releasetype.encode()\n m.tags[\"aART\"] = format_artist_string(self.albumartists)\n m.tags[\"\\xa9ART\"] = format_artist_string(self.trackartists)\n # Wipe the alt. role artist tags, since we encode the full artist into the main tag.\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:REMIXER\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:PRODUCER\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"\\xa9wrt\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:CONDUCTOR\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"----:com.apple.iTunes:DJMIXER\"]\n\n # The track and disc numbers in MP4 are a bit annoying, because they must be a\n # single-element list of 2-tuple ints. We preserve the previous tracktotal/disctotal (as\n # Rose does not care about those values), and then attempt to write our own tracknumber\n # and discnumber.\n try:\n prev_tracktotal = m.tags[\"trkn\"][0][1]\n except (KeyError, IndexError):\n prev_tracktotal = 1\n try:\n prev_disctotal = m.tags[\"disk\"][0][1]\n except (KeyError, IndexError):\n prev_disctotal = 1\n try:\n m.tags[\"trkn\"] = [(int(self.tracknumber or \"0\"), prev_tracktotal)]\n m.tags[\"disk\"] = [(int(self.discnumber or \"0\"), prev_disctotal)]\n except ValueError as e:\n raise UnsupportedTagValueTypeError(\n \"Could not write m4a trackno/discno tags: must be integers. \"\n f\"Got: {self.tracknumber=} / {self.discnumber=}\"\n ) from e\n\n m.save()\n return\n if isinstance(m, (mutagen.flac.FLAC, mutagen.oggvorbis.OggVorbis, mutagen.oggopus.OggOpus)):\n if m.tags is None:\n if isinstance(m, mutagen.flac.FLAC):\n m.tags = mutagen.flac.VCFLACDict()\n elif isinstance(m, mutagen.oggvorbis.OggVorbis):\n m.tags = mutagen.oggvorbis.OggVCommentDict()\n else:\n m.tags = mutagen.oggopus.OggOpusVComment()\n assert not isinstance(m.tags, mutagen.flac.MetadataBlock)\n m.tags[\"roseid\"] = self.id or \"\"\n m.tags[\"rosereleaseid\"] = self.release_id or \"\"\n m.tags[\"title\"] = self.title or \"\"\n m.tags[\"date\"] = str(self.year).zfill(4)\n m.tags[\"tracknumber\"] = self.tracknumber or \"\"\n m.tags[\"discnumber\"] = self.discnumber or \"\"\n m.tags[\"album\"] = self.album or \"\"\n m.tags[\"genre\"] = \";\".join(self.genre)\n m.tags[\"organization\"] = \";\".join(self.label)\n m.tags[\"releasetype\"] = self.releasetype\n m.tags[\"albumartist\"] = format_artist_string(self.albumartists)\n m.tags[\"artist\"] = format_artist_string(self.trackartists)\n # Wipe the alt. role artist tags, since we encode the full artist into the main tag.\n with contextlib.suppress(KeyError):\n del m.tags[\"remixer\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"producer\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"composer\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"conductor\"]\n with contextlib.suppress(KeyError):\n del m.tags[\"djmixer\"]\n m.save()\n return\n\n raise RoseError(f\"Impossible: unknown mutagen type: {type(m)=} ({repr(m)=})\")" }, { "identifier": "STORED_DATA_FILE_REGEX", "path": "rose/cache.py", "snippet": "STORED_DATA_FILE_REGEX = re.compile(r\"\\.rose\\.([^.]+)\\.toml\")" }, { "identifier": "CachedRelease", "path": "rose/cache.py", "snippet": "class CachedRelease:\n id: str\n source_path: Path\n cover_image_path: Path | None\n added_at: str # ISO8601 timestamp\n datafile_mtime: str\n albumtitle: str\n releasetype: str\n year: int | None\n new: bool\n disctotal: int\n genres: list[str]\n labels: list[str]\n albumartists: ArtistMapping\n metahash: str\n\n @classmethod\n def from_view(cls, c: Config, row: dict[str, Any], aliases: bool = True) -> CachedRelease:\n return CachedRelease(\n id=row[\"id\"],\n source_path=Path(row[\"source_path\"]),\n cover_image_path=Path(row[\"cover_image_path\"]) if row[\"cover_image_path\"] else None,\n added_at=row[\"added_at\"],\n datafile_mtime=row[\"datafile_mtime\"],\n albumtitle=row[\"albumtitle\"],\n releasetype=row[\"releasetype\"],\n year=row[\"year\"],\n disctotal=row[\"disctotal\"],\n new=bool(row[\"new\"]),\n genres=_split(row[\"genres\"]) if row[\"genres\"] else [],\n labels=_split(row[\"labels\"]) if row[\"labels\"] else [],\n albumartists=_unpack_artists(\n c, row[\"albumartist_names\"], row[\"albumartist_roles\"], aliases=aliases\n ),\n metahash=row[\"metahash\"],\n )\n\n def dump(self) -> dict[str, Any]:\n return {\n \"id\": self.id,\n \"source_path\": str(self.source_path.resolve()),\n \"cover_image_path\": str(self.cover_image_path.resolve())\n if self.cover_image_path\n else None,\n \"added_at\": self.added_at,\n \"albumtitle\": self.albumtitle,\n \"releasetype\": self.releasetype,\n \"year\": self.year,\n \"new\": self.new,\n \"disctotal\": self.disctotal,\n \"genres\": self.genres,\n \"labels\": self.labels,\n \"albumartists\": self.albumartists.dump(),\n }" }, { "identifier": "CachedTrack", "path": "rose/cache.py", "snippet": "class CachedTrack:\n id: str\n source_path: Path\n source_mtime: str\n tracktitle: str\n tracknumber: str\n tracktotal: int\n discnumber: str\n disctotal: int\n duration_seconds: int\n trackartists: ArtistMapping\n metahash: str\n\n release: CachedRelease\n\n @classmethod\n def from_view(\n cls, c: Config, row: dict[str, Any], release: CachedRelease, aliases: bool = True\n ) -> CachedTrack:\n return CachedTrack(\n id=row[\"id\"],\n source_path=Path(row[\"source_path\"]),\n source_mtime=row[\"source_mtime\"],\n tracktitle=row[\"tracktitle\"],\n tracknumber=row[\"tracknumber\"],\n tracktotal=row[\"tracktotal\"],\n discnumber=row[\"discnumber\"],\n disctotal=row[\"disctotal\"],\n duration_seconds=row[\"duration_seconds\"],\n trackartists=_unpack_artists(\n c,\n row[\"trackartist_names\"],\n row[\"trackartist_roles\"],\n aliases=aliases,\n ),\n metahash=row[\"metahash\"],\n release=release,\n )\n\n def dump(self, with_release_info: bool = True) -> dict[str, Any]:\n r = {\n \"id\": self.id,\n \"source_path\": str(self.source_path.resolve()),\n \"tracktitle\": self.tracktitle,\n \"tracknumber\": self.tracknumber,\n \"tracktotal\": self.tracktotal,\n \"discnumber\": self.discnumber,\n \"disctotal\": self.disctotal,\n \"duration_seconds\": self.duration_seconds,\n \"trackartists\": self.trackartists.dump(),\n }\n if with_release_info:\n r.update(\n {\n \"release_id\": self.release.id,\n \"added_at\": self.release.added_at,\n \"albumtitle\": self.release.albumtitle,\n \"releasetype\": self.release.releasetype,\n \"year\": self.release.year,\n \"new\": self.release.new,\n \"genres\": self.release.genres,\n \"labels\": self.release.labels,\n \"albumartists\": self.release.albumartists.dump(),\n }\n )\n return r" }, { "identifier": "artist_exists", "path": "rose/cache.py", "snippet": "def artist_exists(c: Config, artist_sanitized: str) -> bool:\n args: list[str] = [artist_sanitized]\n for alias in c.sanitized_artist_aliases_map.get(artist_sanitized, []):\n args.append(alias)\n with connect(c) as conn:\n cursor = conn.execute(\n f\"\"\"\n SELECT EXISTS(\n SELECT * FROM releases_artists\n WHERE artist_sanitized IN ({','.join(['?']*len(args))})\n )\n \"\"\",\n args,\n )\n return bool(cursor.fetchone()[0])" }, { "identifier": "calculate_release_logtext", "path": "rose/cache.py", "snippet": "def calculate_release_logtext(\n title: str,\n year: int | None,\n artists: ArtistMapping,\n) -> str:\n logtext = f\"{artistsfmt(artists)} - \"\n if year:\n logtext += f\"{year}. \"\n logtext += title\n return logtext" }, { "identifier": "calculate_track_logtext", "path": "rose/cache.py", "snippet": "def calculate_track_logtext(title: str, artists: ArtistMapping, suffix: str) -> str:\n return f\"{artistsfmt(artists)} - {title or 'Unknown Title'}{suffix}\"" }, { "identifier": "genre_exists", "path": "rose/cache.py", "snippet": "def genre_exists(c: Config, genre_sanitized: str) -> bool:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT EXISTS(SELECT * FROM releases_genres WHERE genre_sanitized = ?)\",\n (genre_sanitized,),\n )\n return bool(cursor.fetchone()[0])" }, { "identifier": "get_collage", "path": "rose/cache.py", "snippet": "def get_collage(c: Config, collage_name: str) -> tuple[CachedCollage, list[CachedRelease]] | None:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT name, source_mtime FROM collages WHERE name = ?\",\n (collage_name,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n collage = CachedCollage(\n name=row[\"name\"],\n source_mtime=row[\"source_mtime\"],\n # Accumulated below when we query the releases.\n release_ids=[],\n )\n cursor = conn.execute(\n \"\"\"\n SELECT r.*\n FROM releases_view r\n JOIN collages_releases cr ON cr.release_id = r.id\n WHERE cr.collage_name = ? AND NOT cr.missing\n ORDER BY cr.position ASC\n \"\"\",\n (collage_name,),\n )\n releases: list[CachedRelease] = []\n for row in cursor:\n collage.release_ids.append(row[\"id\"])\n releases.append(CachedRelease.from_view(c, row))\n\n return (collage, releases)" }, { "identifier": "get_playlist", "path": "rose/cache.py", "snippet": "def get_playlist(c: Config, playlist_name: str) -> tuple[CachedPlaylist, list[CachedTrack]] | None:\n with connect(c) as conn:\n cursor = conn.execute(\n \"\"\"\n SELECT\n name\n , source_mtime\n , cover_path\n FROM playlists\n WHERE name = ?\n \"\"\",\n (playlist_name,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n playlist = CachedPlaylist(\n name=row[\"name\"],\n source_mtime=row[\"source_mtime\"],\n cover_path=Path(row[\"cover_path\"]) if row[\"cover_path\"] else None,\n # Accumulated below when we query the tracks.\n track_ids=[],\n )\n\n cursor = conn.execute(\n \"\"\"\n SELECT t.*\n FROM tracks_view t\n JOIN playlists_tracks pt ON pt.track_id = t.id\n WHERE pt.playlist_name = ? AND NOT pt.missing\n ORDER BY pt.position ASC\n \"\"\",\n (playlist_name,),\n )\n trackrows = cursor.fetchall()\n\n release_ids = [r[\"release_id\"] for r in trackrows]\n cursor = conn.execute(\n f\"\"\"\n SELECT *\n FROM releases_view\n WHERE id IN ({','.join(['?']*len(release_ids))})\n \"\"\",\n release_ids,\n )\n releases_map: dict[str, CachedRelease] = {}\n for row in cursor:\n releases_map[row[\"id\"]] = CachedRelease.from_view(c, row)\n\n tracks: list[CachedTrack] = []\n for row in trackrows:\n playlist.track_ids.append(row[\"id\"])\n tracks.append(CachedTrack.from_view(c, row, releases_map[row[\"release_id\"]]))\n\n return playlist, tracks" }, { "identifier": "get_release", "path": "rose/cache.py", "snippet": "def get_release(c: Config, release_id: str) -> CachedRelease | None:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT * FROM releases_view WHERE id = ?\",\n (release_id,),\n )\n row = cursor.fetchone()\n if not row:\n return None\n return CachedRelease.from_view(c, row)" }, { "identifier": "get_track", "path": "rose/cache.py", "snippet": "def get_track(c: Config, uuid: str) -> CachedTrack | None:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT * FROM tracks_view WHERE id = ?\", (uuid,))\n trackrow = cursor.fetchone()\n if not trackrow:\n return None\n cursor = conn.execute(\"SELECT * FROM releases_view WHERE id = ?\", (trackrow[\"release_id\"],))\n release = CachedRelease.from_view(c, cursor.fetchone())\n return CachedTrack.from_view(c, trackrow, release)" }, { "identifier": "get_tracks_associated_with_release", "path": "rose/cache.py", "snippet": "def get_tracks_associated_with_release(\n c: Config,\n release: CachedRelease,\n) -> list[CachedTrack]:\n with connect(c) as conn:\n cursor = conn.execute(\n \"\"\"\n SELECT *\n FROM tracks_view\n WHERE release_id = ?\n ORDER BY release_id, FORMAT('%4d.%4d', discnumber, tracknumber)\n \"\"\",\n (release.id,),\n )\n rval = []\n for row in cursor:\n rval.append(CachedTrack.from_view(c, row, release))\n return rval" }, { "identifier": "label_exists", "path": "rose/cache.py", "snippet": "def label_exists(c: Config, label_sanitized: str) -> bool:\n with connect(c) as conn:\n cursor = conn.execute(\n \"SELECT EXISTS(SELECT * FROM releases_labels WHERE label_sanitized = ?)\",\n (label_sanitized,),\n )\n return bool(cursor.fetchone()[0])" }, { "identifier": "list_artists", "path": "rose/cache.py", "snippet": "def list_artists(c: Config) -> list[tuple[str, str]]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT artist, artist_sanitized FROM releases_artists\")\n return [(row[\"artist\"], row[\"artist_sanitized\"]) for row in cursor]" }, { "identifier": "list_collages", "path": "rose/cache.py", "snippet": "def list_collages(c: Config) -> list[str]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT name FROM collages\")\n return [r[\"name\"] for r in cursor]" }, { "identifier": "list_genres", "path": "rose/cache.py", "snippet": "def list_genres(c: Config) -> list[tuple[str, str]]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT genre, genre_sanitized FROM releases_genres\")\n return [(row[\"genre\"], row[\"genre_sanitized\"]) for row in cursor]" }, { "identifier": "list_labels", "path": "rose/cache.py", "snippet": "def list_labels(c: Config) -> list[tuple[str, str]]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT label, label_sanitized FROM releases_labels\")\n return [(row[\"label\"], row[\"label_sanitized\"]) for row in cursor]" }, { "identifier": "list_playlists", "path": "rose/cache.py", "snippet": "def list_playlists(c: Config) -> list[str]:\n with connect(c) as conn:\n cursor = conn.execute(\"SELECT DISTINCT name FROM playlists\")\n return [r[\"name\"] for r in cursor]" }, { "identifier": "list_releases_delete_this", "path": "rose/cache.py", "snippet": "def list_releases_delete_this(\n c: Config,\n sanitized_artist_filter: str | None = None,\n sanitized_genre_filter: str | None = None,\n sanitized_label_filter: str | None = None,\n new: bool | None = None,\n) -> list[CachedRelease]:\n with connect(c) as conn:\n query = \"SELECT * FROM releases_view WHERE 1=1\"\n args: list[str | bool] = []\n if sanitized_artist_filter:\n sanitized_artists: list[str] = [sanitized_artist_filter]\n for alias in c.sanitized_artist_aliases_map.get(sanitized_artist_filter, []):\n sanitized_artists.append(alias)\n query += f\"\"\"\n AND EXISTS (\n SELECT * FROM releases_artists\n WHERE release_id = id AND artist_sanitized IN ({','.join(['?']*len(sanitized_artists))})\n )\n \"\"\"\n args.extend(sanitized_artists)\n if sanitized_genre_filter:\n query += \"\"\"\n AND EXISTS (\n SELECT * FROM releases_genres\n WHERE release_id = id AND genre_sanitized = ?\n )\n \"\"\"\n args.append(sanitized_genre_filter)\n if sanitized_label_filter:\n query += \"\"\"\n AND EXISTS (\n SELECT * FROM releases_labels\n WHERE release_id = id AND label_sanitized = ?\n )\n \"\"\"\n args.append(sanitized_label_filter)\n if new is not None:\n query += \" AND new = ?\"\n args.append(new)\n query += \" ORDER BY source_path\"\n\n cursor = conn.execute(query, args)\n releases: list[CachedRelease] = []\n for row in cursor:\n releases.append(CachedRelease.from_view(c, row))\n return releases" }, { "identifier": "update_cache_for_releases", "path": "rose/cache.py", "snippet": "def update_cache_for_releases(\n c: Config,\n # Leave as None to update all releases.\n release_dirs: list[Path] | None = None,\n force: bool = False,\n # For testing.\n force_multiprocessing: bool = False,\n) -> None:\n \"\"\"\n Update the read cache to match the data for any passed-in releases. If a directory lacks a\n .rose.{uuid}.toml datafile, create the datafile for the release and set it to the initial state.\n\n This is a hot path and is thus performance-optimized. The bottleneck is disk accesses, so we\n structure this function in order to minimize them. We solely read files that have changed since\n last run and batch writes together. We trade higher memory for reduced disk accesses.\n Concretely, we:\n\n 1. Execute one big SQL query at the start to fetch the relevant previous caches.\n 2. Skip reading a file's data if the mtime has not changed since the previous cache update.\n 3. Batch SQLite write operations to the end of this function, and only execute a SQLite upsert\n if the read data differs from the previous caches.\n\n We also shard the directories across multiple processes and execute them simultaneously.\n \"\"\"\n release_dirs = release_dirs or [\n Path(d.path) for d in os.scandir(c.music_source_dir) if d.is_dir()\n ]\n release_dirs = [\n d\n for d in release_dirs\n if d.name != \"!collages\"\n and d.name != \"!playlists\"\n and d.name not in c.ignore_release_directories\n ]\n if not release_dirs:\n logger.debug(\"No-Op: No whitelisted releases passed into update_cache_for_releases\")\n return\n logger.debug(f\"Refreshing the read cache for {len(release_dirs)} releases\")\n if len(release_dirs) < 10:\n logger.debug(f\"Refreshing cached data for {', '.join([r.name for r in release_dirs])}\")\n\n # If the number of releases changed is less than 50; do not bother with all that multiprocessing\n # gunk: instead, directly call the executor.\n #\n # This has an added benefit of not spawning processes from the virtual filesystem and watchdog\n # processes, as those processes always update the cache for one release at a time and are\n # multithreaded. Starting other processes from threads is bad!\n if not force_multiprocessing and len(release_dirs) < 50:\n logger.debug(\n f\"Running cache update executor in same process because {len(release_dirs)=} < 50\"\n )\n _update_cache_for_releases_executor(c, release_dirs, force)\n return\n\n # Batch size defaults to equal split across all processes. However, if the number of directories\n # is small, we shrink the # of processes to save on overhead.\n num_proc = c.max_proc\n if len(release_dirs) < c.max_proc * 50:\n num_proc = max(1, math.ceil(len(release_dirs) // 50))\n batch_size = len(release_dirs) // num_proc + 1\n\n manager = multiprocessing.Manager()\n # Have each process propagate the collages and playlists it wants to update back upwards. We\n # will dispatch the force updater only once in the main process, instead of many times in each\n # process.\n collages_to_force_update = manager.list()\n playlists_to_force_update = manager.list()\n\n errors: list[BaseException] = []\n\n logger.debug(\"Creating multiprocessing pool to parallelize cache executors.\")\n with multiprocessing.Pool(processes=c.max_proc) as pool:\n # At 0, no batch. At 1, 1 batch. At 49, 1 batch. At 50, 1 batch. At 51, 2 batches.\n for i in range(0, len(release_dirs), batch_size):\n logger.debug(\n f\"Spawning release cache update process for releases [{i}, {i+batch_size})\"\n )\n pool.apply_async(\n _update_cache_for_releases_executor,\n (\n c,\n release_dirs[i : i + batch_size],\n force,\n collages_to_force_update,\n playlists_to_force_update,\n ),\n error_callback=lambda e: errors.append(e),\n )\n pool.close()\n pool.join()\n\n if errors:\n raise ExceptionGroup(\"Exception occurred in cache update subprocesses\", errors) # type: ignore\n\n if collages_to_force_update:\n update_cache_for_collages(c, uniq(list(collages_to_force_update)), force=True)\n if playlists_to_force_update:\n update_cache_for_playlists(c, uniq(list(playlists_to_force_update)), force=True)" }, { "identifier": "add_release_to_collage", "path": "rose/collages.py", "snippet": "def add_release_to_collage(\n c: Config,\n collage_name: str,\n release_id: str,\n) -> None:\n release_logtext = get_release_logtext(c, release_id)\n if not release_logtext:\n raise ReleaseDoesNotExistError(f\"Release {release_id} does not exist\")\n\n path = collage_path(c, collage_name)\n if not path.exists():\n raise CollageDoesNotExistError(f\"Collage {collage_name} does not exist\")\n\n with lock(c, collage_lock_name(collage_name)):\n with path.open(\"rb\") as fp:\n data = tomllib.load(fp)\n data[\"releases\"] = data.get(\"releases\", [])\n # Check to see if release is already in the collage. If so, no op. We don't support\n # duplicate collage entries.\n for r in data[\"releases\"]:\n if r[\"uuid\"] == release_id:\n logger.info(f\"No-Op: Release {release_logtext} already in collage {collage_name}\")\n return\n data[\"releases\"].append({\"uuid\": release_id, \"description_meta\": release_logtext})\n with path.open(\"wb\") as fp:\n tomli_w.dump(data, fp)\n logger.info(f\"Added release {release_logtext} to collage {collage_name}\")\n update_cache_for_collages(c, [collage_name], force=True)" }, { "identifier": "create_collage", "path": "rose/collages.py", "snippet": "def create_collage(c: Config, name: str) -> None:\n (c.music_source_dir / \"!collages\").mkdir(parents=True, exist_ok=True)\n path = collage_path(c, name)\n with lock(c, collage_lock_name(name)):\n if path.exists():\n raise CollageAlreadyExistsError(f\"Collage {name} already exists\")\n path.touch()\n logger.info(f\"Created collage {name} in source directory\")\n update_cache_for_collages(c, [name], force=True)" }, { "identifier": "delete_collage", "path": "rose/collages.py", "snippet": "def delete_collage(c: Config, name: str) -> None:\n path = collage_path(c, name)\n with lock(c, collage_lock_name(name)):\n if not path.exists():\n raise CollageDoesNotExistError(f\"Collage {name} does not exist\")\n send2trash(path)\n logger.info(f\"Deleted collage {name} from source directory\")\n update_cache_evict_nonexistent_collages(c)" }, { "identifier": "remove_release_from_collage", "path": "rose/collages.py", "snippet": "def remove_release_from_collage(c: Config, collage_name: str, release_id: str) -> None:\n release_logtext = get_release_logtext(c, release_id)\n if not release_logtext:\n raise ReleaseDoesNotExistError(f\"Release {release_id} does not exist\")\n\n path = collage_path(c, collage_name)\n if not path.exists():\n raise CollageDoesNotExistError(f\"Collage {collage_name} does not exist\")\n with lock(c, collage_lock_name(collage_name)):\n with path.open(\"rb\") as fp:\n data = tomllib.load(fp)\n old_releases = data.get(\"releases\", [])\n new_releases = [r for r in old_releases if r[\"uuid\"] != release_id]\n if old_releases == new_releases:\n logger.info(f\"No-Op: Release {release_logtext} not in collage {collage_name}\")\n return\n data[\"releases\"] = new_releases\n with path.open(\"wb\") as fp:\n tomli_w.dump(data, fp)\n logger.info(f\"Removed release {release_logtext} from collage {collage_name}\")\n update_cache_for_collages(c, [collage_name], force=True)" }, { "identifier": "rename_collage", "path": "rose/collages.py", "snippet": "def rename_collage(c: Config, old_name: str, new_name: str) -> None:\n old_path = collage_path(c, old_name)\n new_path = collage_path(c, new_name)\n with lock(c, collage_lock_name(old_name)), lock(c, collage_lock_name(new_name)):\n if not old_path.exists():\n raise CollageDoesNotExistError(f\"Collage {old_name} does not exist\")\n if new_path.exists():\n raise CollageAlreadyExistsError(f\"Collage {new_name} already exists\")\n old_path.rename(new_path)\n # And also rename all files with the same stem (e.g. cover arts).\n for old_adjacent_file in (c.music_source_dir / \"!collages\").iterdir():\n if old_adjacent_file.stem != old_path.stem:\n continue\n new_adjacent_file = old_adjacent_file.with_name(\n new_path.stem + old_adjacent_file.suffix\n )\n if new_adjacent_file.exists():\n continue\n old_adjacent_file.rename(new_adjacent_file)\n logger.debug(\n \"Renaming collage-adjacent file {old_adjacent_file} to {new_adjacent_file}\"\n )\n logger.info(f\"Renamed collage {old_name} to {new_name}\")\n update_cache_for_collages(c, [new_name], force=True)\n update_cache_evict_nonexistent_collages(c)" }, { "identifier": "RoseError", "path": "rose/common.py", "snippet": "class RoseError(Exception):\n pass" }, { "identifier": "sanitize_dirname", "path": "rose/common.py", "snippet": "def sanitize_dirname(name: str, enforce_maxlen: bool) -> str:\n \"\"\"\n Replace illegal characters and truncate. We have 255 bytes in ext4, and we truncate to 240 in\n order to leave room for any collision numbers.\n\n enforce_maxlen is for host filesystems, which are sometimes subject to length constraints (e.g.\n ext4).\n \"\"\"\n name = ILLEGAL_FS_CHARS_REGEX.sub(\"_\", name)\n if enforce_maxlen:\n name = name.encode(\"utf-8\")[:240].decode(\"utf-8\", \"ignore\")\n return name" }, { "identifier": "sanitize_filename", "path": "rose/common.py", "snippet": "def sanitize_filename(name: str, enforce_maxlen: bool) -> str:\n \"\"\"Same as sanitize dirname, except we preserve file extension.\"\"\"\n name = ILLEGAL_FS_CHARS_REGEX.sub(\"_\", name)\n if enforce_maxlen:\n # Preserve the extension.\n stem, ext = os.path.splitext(name)\n # But ignore if the extension is longer than 6 characters; that means it's probably bullshit.\n if len(ext.encode()) > 6:\n stem = name\n ext = \"\"\n stem = stem.encode(\"utf-8\")[:240].decode(\"utf-8\", \"ignore\")\n name = stem + ext\n return name" }, { "identifier": "Config", "path": "rose/config.py", "snippet": "class Config:\n music_source_dir: Path\n fuse_mount_dir: Path\n cache_dir: Path\n # Maximum parallel processes for cache updates. Defaults to nproc/2.\n max_proc: int\n ignore_release_directories: list[str]\n\n # A map from parent artist -> subartists.\n artist_aliases_map: dict[str, list[str]]\n # A map from subartist -> parent artists.\n artist_aliases_parents_map: dict[str, list[str]]\n\n fuse_artists_whitelist: list[str] | None\n fuse_genres_whitelist: list[str] | None\n fuse_labels_whitelist: list[str] | None\n fuse_artists_blacklist: list[str] | None\n fuse_genres_blacklist: list[str] | None\n fuse_labels_blacklist: list[str] | None\n\n cover_art_stems: list[str]\n valid_art_exts: list[str]\n\n rename_source_files: bool\n path_templates: PathTemplateConfig\n\n stored_metadata_rules: list[MetadataRule]\n\n @classmethod\n def parse(cls, config_path_override: Path | None = None) -> Config:\n # As we parse, delete consumed values from the data dictionary. If any are left over at the\n # end of the config, warn that unknown config keys were found.\n cfgpath = config_path_override or CONFIG_PATH\n cfgtext = \"\"\n try:\n with cfgpath.open(\"r\") as fp:\n cfgtext = fp.read()\n data = tomllib.loads(cfgtext)\n except FileNotFoundError as e:\n raise ConfigNotFoundError(f\"Configuration file not found ({cfgpath})\") from e\n except tomllib.TOMLDecodeError as e:\n raise ConfigDecodeError(\n f\"Failed to decode configuration file: invalid TOML: {e}\"\n ) from e\n\n try:\n music_source_dir = Path(data[\"music_source_dir\"]).expanduser()\n del data[\"music_source_dir\"]\n except KeyError as e:\n raise MissingConfigKeyError(\n f\"Missing key music_source_dir in configuration file ({cfgpath})\"\n ) from e\n except (ValueError, TypeError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for music_source_dir in configuration file ({cfgpath}): must be a path\"\n ) from e\n\n try:\n fuse_mount_dir = Path(data[\"fuse_mount_dir\"]).expanduser()\n del data[\"fuse_mount_dir\"]\n except KeyError as e:\n raise MissingConfigKeyError(\n f\"Missing key fuse_mount_dir in configuration file ({cfgpath})\"\n ) from e\n except (ValueError, TypeError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_mount_dir in configuration file ({cfgpath}): must be a path\"\n ) from e\n\n try:\n cache_dir = Path(data[\"cache_dir\"]).expanduser()\n del data[\"cache_dir\"]\n except KeyError:\n cache_dir = XDG_CACHE_ROSE\n except (TypeError, ValueError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for cache_dir in configuration file ({cfgpath}): must be a path\"\n ) from e\n cache_dir.mkdir(parents=True, exist_ok=True)\n\n try:\n max_proc = int(data[\"max_proc\"])\n del data[\"max_proc\"]\n if max_proc <= 0:\n raise ValueError(f\"must be a positive integer: got {max_proc}\")\n except KeyError:\n max_proc = max(1, multiprocessing.cpu_count() // 2)\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for max_proc in configuration file ({cfgpath}): must be a positive integer\"\n ) from e\n\n artist_aliases_map: dict[str, list[str]] = defaultdict(list)\n artist_aliases_parents_map: dict[str, list[str]] = defaultdict(list)\n try:\n for entry in data.get(\"artist_aliases\", []):\n if not isinstance(entry[\"artist\"], str):\n raise ValueError(f\"Artists must be of type str: got {type(entry['artist'])}\")\n artist_aliases_map[entry[\"artist\"]] = entry[\"aliases\"]\n if not isinstance(entry[\"aliases\"], list):\n raise ValueError(\n f\"Aliases must be of type list[str]: got {type(entry['aliases'])}\"\n )\n for s in entry[\"aliases\"]:\n if not isinstance(s, str):\n raise ValueError(f\"Each alias must be of type str: got {type(s)}\")\n artist_aliases_parents_map[s].append(entry[\"artist\"])\n with contextlib.suppress(KeyError):\n del data[\"artist_aliases\"]\n except (ValueError, TypeError, KeyError) as e:\n raise InvalidConfigValueError(\n f\"Invalid value for artist_aliases in configuration file ({cfgpath}): must be a list of {{ artist = str, aliases = list[str] }} records\"\n ) from e\n\n try:\n fuse_artists_whitelist = data[\"fuse_artists_whitelist\"]\n del data[\"fuse_artists_whitelist\"]\n if not isinstance(fuse_artists_whitelist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_artists_whitelist)}\")\n for s in fuse_artists_whitelist:\n if not isinstance(s, str):\n raise ValueError(f\"Each artist must be of type str: got {type(s)}\")\n except KeyError:\n fuse_artists_whitelist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_artists_whitelist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_genres_whitelist = data[\"fuse_genres_whitelist\"]\n del data[\"fuse_genres_whitelist\"]\n if not isinstance(fuse_genres_whitelist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_genres_whitelist)}\")\n for s in fuse_genres_whitelist:\n if not isinstance(s, str):\n raise ValueError(f\"Each genre must be of type str: got {type(s)}\")\n except KeyError:\n fuse_genres_whitelist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_genres_whitelist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_labels_whitelist = data[\"fuse_labels_whitelist\"]\n del data[\"fuse_labels_whitelist\"]\n if not isinstance(fuse_labels_whitelist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_labels_whitelist)}\")\n for s in fuse_labels_whitelist:\n if not isinstance(s, str):\n raise ValueError(f\"Each label must be of type str: got {type(s)}\")\n except KeyError:\n fuse_labels_whitelist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_labels_whitelist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_artists_blacklist = data[\"fuse_artists_blacklist\"]\n del data[\"fuse_artists_blacklist\"]\n if not isinstance(fuse_artists_blacklist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_artists_blacklist)}\")\n for s in fuse_artists_blacklist:\n if not isinstance(s, str):\n raise ValueError(f\"Each artist must be of type str: got {type(s)}\")\n except KeyError:\n fuse_artists_blacklist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_artists_blacklist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_genres_blacklist = data[\"fuse_genres_blacklist\"]\n del data[\"fuse_genres_blacklist\"]\n if not isinstance(fuse_genres_blacklist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_genres_blacklist)}\")\n for s in fuse_genres_blacklist:\n if not isinstance(s, str):\n raise ValueError(f\"Each genre must be of type str: got {type(s)}\")\n except KeyError:\n fuse_genres_blacklist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_genres_blacklist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n fuse_labels_blacklist = data[\"fuse_labels_blacklist\"]\n del data[\"fuse_labels_blacklist\"]\n if not isinstance(fuse_labels_blacklist, list):\n raise ValueError(f\"Must be a list[str]: got {type(fuse_labels_blacklist)}\")\n for s in fuse_labels_blacklist:\n if not isinstance(s, str):\n raise ValueError(f\"Each label must be of type str: got {type(s)}\")\n except KeyError:\n fuse_labels_blacklist = None\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for fuse_labels_blacklist in configuration file ({cfgpath}): {e}\"\n ) from e\n\n if fuse_artists_whitelist and fuse_artists_blacklist:\n raise InvalidConfigValueError(\n f\"Cannot specify both fuse_artists_whitelist and fuse_artists_blacklist in configuration file ({cfgpath}): must specify only one or the other\"\n )\n if fuse_genres_whitelist and fuse_genres_blacklist:\n raise InvalidConfigValueError(\n f\"Cannot specify both fuse_genres_whitelist and fuse_genres_blacklist in configuration file ({cfgpath}): must specify only one or the other\"\n )\n if fuse_labels_whitelist and fuse_labels_blacklist:\n raise InvalidConfigValueError(\n f\"Cannot specify both fuse_labels_whitelist and fuse_labels_blacklist in configuration file ({cfgpath}): must specify only one or the other\"\n )\n\n try:\n cover_art_stems = data[\"cover_art_stems\"]\n del data[\"cover_art_stems\"]\n if not isinstance(cover_art_stems, list):\n raise ValueError(f\"Must be a list[str]: got {type(cover_art_stems)}\")\n for s in cover_art_stems:\n if not isinstance(s, str):\n raise ValueError(f\"Each cover art stem must be of type str: got {type(s)}\")\n except KeyError:\n cover_art_stems = [\"folder\", \"cover\", \"art\", \"front\"]\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for cover_art_stems in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n valid_art_exts = data[\"valid_art_exts\"]\n del data[\"valid_art_exts\"]\n if not isinstance(valid_art_exts, list):\n raise ValueError(f\"Must be a list[str]: got {type(valid_art_exts)}\")\n for s in valid_art_exts:\n if not isinstance(s, str):\n raise ValueError(f\"Each art extension must be of type str: got {type(s)}\")\n except KeyError:\n valid_art_exts = [\"jpg\", \"jpeg\", \"png\"]\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for valid_art_exts in configuration file ({cfgpath}): {e}\"\n ) from e\n\n cover_art_stems = [x.lower() for x in cover_art_stems]\n valid_art_exts = [x.lower() for x in valid_art_exts]\n\n try:\n rename_source_files = data[\"rename_source_files\"]\n del data[\"rename_source_files\"]\n if not isinstance(rename_source_files, bool):\n raise ValueError(f\"Must be a bool: got {type(rename_source_files)}\")\n except KeyError:\n rename_source_files = False\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for rename_source_files in configuration file ({cfgpath}): {e}\"\n ) from e\n\n try:\n ignore_release_directories = data[\"ignore_release_directories\"]\n del data[\"ignore_release_directories\"]\n if not isinstance(ignore_release_directories, list):\n raise ValueError(f\"Must be a list[str]: got {type(ignore_release_directories)}\")\n for s in ignore_release_directories:\n if not isinstance(s, str):\n raise ValueError(f\"Each release directory must be of type str: got {type(s)}\")\n except KeyError:\n ignore_release_directories = []\n except ValueError as e:\n raise InvalidConfigValueError(\n f\"Invalid value for ignore_release_directories in configuration file ({cfgpath}): {e}\"\n ) from e\n\n stored_metadata_rules: list[MetadataRule] = []\n for d in data.get(\"stored_metadata_rules\", []):\n if not isinstance(d, dict):\n raise InvalidConfigValueError(\n f\"Invalid value in stored_metadata_rules in configuration file ({cfgpath}): list values must be a dict: got {type(d)}\"\n )\n\n try:\n matcher = d[\"matcher\"]\n except KeyError as e:\n raise InvalidConfigValueError(\n f\"Missing key `matcher` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}\"\n ) from e\n if not isinstance(matcher, str):\n raise InvalidConfigValueError(\n f\"Invalid value for `matcher` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}: must be a string\"\n )\n\n try:\n actions = d[\"actions\"]\n except KeyError as e:\n raise InvalidConfigValueError(\n f\"Missing key `actions` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}\"\n ) from e\n if not isinstance(actions, list):\n raise InvalidConfigValueError(\n f\"Invalid value for `actions` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}: must be a list of strings\"\n )\n for action in actions:\n if not isinstance(action, str):\n raise InvalidConfigValueError(\n f\"Invalid value for `actions` in stored_metadata_rules in configuration file ({cfgpath}): rule {d}: must be a list of strings: got {type(action)}\"\n )\n\n try:\n stored_metadata_rules.append(MetadataRule.parse(matcher, actions))\n except RuleSyntaxError as e:\n raise InvalidConfigValueError(\n f\"Failed to parse stored_metadata_rules in configuration file ({cfgpath}): rule {d}: {e}\"\n ) from e\n if \"stored_metadata_rules\" in data:\n del data[\"stored_metadata_rules\"]\n\n # Get the potential default template before evaluating the rest.\n default_templates = deepcopy(DEFAULT_TEMPLATE_PAIR)\n with contextlib.suppress(KeyError):\n default_templates.release = PathTemplate(data[\"path_templates\"][\"default\"][\"release\"])\n del data[\"path_templates\"][\"default\"][\"release\"]\n with contextlib.suppress(KeyError):\n default_templates.track = PathTemplate(data[\"path_templates\"][\"default\"][\"track\"])\n del data[\"path_templates\"][\"default\"][\"track\"]\n with contextlib.suppress(KeyError):\n if not data[\"path_templates\"][\"default\"]:\n del data[\"path_templates\"][\"default\"]\n\n path_templates = PathTemplateConfig.with_defaults(default_templates)\n if tmpl_config := data.get(\"path_templates\", None):\n for key in [\n \"source\",\n \"all_releases\",\n \"new_releases\",\n \"recently_added_releases\",\n \"artists\",\n \"genres\",\n \"labels\",\n \"collages\",\n ]:\n with contextlib.suppress(KeyError):\n getattr(path_templates, key).release = PathTemplate(tmpl_config[key][\"release\"])\n del tmpl_config[key][\"release\"]\n with contextlib.suppress(KeyError):\n getattr(path_templates, key).track = PathTemplate(tmpl_config[key][\"track\"])\n del tmpl_config[key][\"track\"]\n with contextlib.suppress(KeyError):\n if not tmpl_config[key]:\n del tmpl_config[key]\n\n with contextlib.suppress(KeyError):\n path_templates.playlists = PathTemplate(tmpl_config[\"playlists\"])\n del tmpl_config[\"playlists\"]\n with contextlib.suppress(KeyError):\n if not data[\"path_templates\"]:\n del data[\"path_templates\"]\n\n try:\n path_templates.parse()\n except InvalidPathTemplateError as e:\n raise InvalidConfigValueError(\n f\"Invalid path template in configuration file ({cfgpath}) for template {e.key}: {e}\"\n ) from e\n\n if data:\n unrecognized_accessors: list[str] = []\n # Do a DFS over the data keys to assemble the map of unknown keys. State is a tuple of\n # (\"accessor\", node).\n dfs_state: deque[tuple[str, dict[str, Any]]] = deque([(\"\", data)])\n while dfs_state:\n accessor, node = dfs_state.pop()\n if isinstance(node, dict):\n for k, v in node.items():\n child_accessor = k if not accessor else f\"{accessor}.{k}\"\n dfs_state.append((child_accessor, v))\n continue\n unrecognized_accessors.append(accessor)\n logger.warning(\n f\"Unrecognized options found in configuration file: {', '.join(unrecognized_accessors)}\"\n )\n\n return Config(\n music_source_dir=music_source_dir,\n fuse_mount_dir=fuse_mount_dir,\n cache_dir=cache_dir,\n max_proc=max_proc,\n artist_aliases_map=artist_aliases_map,\n artist_aliases_parents_map=artist_aliases_parents_map,\n fuse_artists_whitelist=fuse_artists_whitelist,\n fuse_genres_whitelist=fuse_genres_whitelist,\n fuse_labels_whitelist=fuse_labels_whitelist,\n fuse_artists_blacklist=fuse_artists_blacklist,\n fuse_genres_blacklist=fuse_genres_blacklist,\n fuse_labels_blacklist=fuse_labels_blacklist,\n cover_art_stems=cover_art_stems,\n valid_art_exts=valid_art_exts,\n path_templates=path_templates,\n rename_source_files=rename_source_files,\n ignore_release_directories=ignore_release_directories,\n stored_metadata_rules=stored_metadata_rules,\n )\n\n @functools.cached_property\n def valid_cover_arts(self) -> list[str]:\n return [s + \".\" + e for s in self.cover_art_stems for e in self.valid_art_exts]\n\n @functools.cached_property\n def cache_database_path(self) -> Path:\n return self.cache_dir / \"cache.sqlite3\"\n\n @functools.cached_property\n def watchdog_pid_path(self) -> Path:\n return self.cache_dir / \"watchdog.pid\"\n\n @functools.cached_property\n def sanitized_artist_aliases_map(self) -> dict[str, list[str]]:\n return {sanitize_dirname(k, False): v for k, v in self.artist_aliases_map.items()}\n\n @functools.cached_property\n def sanitized_artist_aliases_parents_map(self) -> dict[str, list[str]]:\n return {sanitize_dirname(k, False): v for k, v in self.artist_aliases_parents_map.items()}" }, { "identifier": "add_track_to_playlist", "path": "rose/playlists.py", "snippet": "def add_track_to_playlist(\n c: Config,\n playlist_name: str,\n track_id: str,\n) -> None:\n track_logtext = get_track_logtext(c, track_id)\n if not track_logtext:\n raise TrackDoesNotExistError(f\"Track {track_id} does not exist\")\n path = playlist_path(c, playlist_name)\n if not path.exists():\n raise PlaylistDoesNotExistError(f\"Playlist {playlist_name} does not exist\")\n with lock(c, playlist_lock_name(playlist_name)):\n with path.open(\"rb\") as fp:\n data = tomllib.load(fp)\n data[\"tracks\"] = data.get(\"tracks\", [])\n # Check to see if track is already in the playlist. If so, no op. We don't support\n # duplicate playlist entries.\n for r in data[\"tracks\"]:\n if r[\"uuid\"] == track_id:\n logger.info(f\"No-Op: Track {track_logtext} already in playlist {playlist_name}\")\n return\n data[\"tracks\"].append({\"uuid\": track_id, \"description_meta\": track_logtext})\n with path.open(\"wb\") as fp:\n tomli_w.dump(data, fp)\n logger.info(f\"Added track {track_logtext} to playlist {playlist_name}\")\n update_cache_for_playlists(c, [playlist_name], force=True)" }, { "identifier": "create_playlist", "path": "rose/playlists.py", "snippet": "def create_playlist(c: Config, name: str) -> None:\n (c.music_source_dir / \"!playlists\").mkdir(parents=True, exist_ok=True)\n path = playlist_path(c, name)\n with lock(c, playlist_lock_name(name)):\n if path.exists():\n raise PlaylistAlreadyExistsError(f\"Playlist {name} already exists\")\n path.touch()\n logger.info(f\"Created playlist {name} in source directory\")\n update_cache_for_playlists(c, [name], force=True)" }, { "identifier": "delete_playlist", "path": "rose/playlists.py", "snippet": "def delete_playlist(c: Config, name: str) -> None:\n path = playlist_path(c, name)\n with lock(c, playlist_lock_name(name)):\n if not path.exists():\n raise PlaylistDoesNotExistError(f\"Playlist {name} does not exist\")\n send2trash(path)\n logger.info(f\"Deleted playlist {name} from source directory\")\n update_cache_evict_nonexistent_playlists(c)" }, { "identifier": "delete_playlist_cover_art", "path": "rose/playlists.py", "snippet": "def delete_playlist_cover_art(c: Config, playlist_name: str) -> None:\n \"\"\"This function removes all potential cover arts for the playlist.\"\"\"\n path = playlist_path(c, playlist_name)\n if not path.exists():\n raise PlaylistDoesNotExistError(f\"Playlist {playlist_name} does not exist\")\n found = False\n for f in (c.music_source_dir / \"!playlists\").iterdir():\n if f.stem == playlist_name and f.suffix[1:].lower() in c.valid_art_exts:\n logger.debug(f\"Deleting existing cover art {f.name} in playlists\")\n f.unlink()\n found = True\n if found:\n logger.info(f\"Deleted cover arts of playlist {playlist_name}\")\n else:\n logger.info(f\"No-Op: No cover arts found for playlist {playlist_name}\")\n update_cache_for_playlists(c, [playlist_name])" }, { "identifier": "remove_track_from_playlist", "path": "rose/playlists.py", "snippet": "def remove_track_from_playlist(\n c: Config,\n playlist_name: str,\n track_id: str,\n) -> None:\n track_logtext = get_track_logtext(c, track_id)\n if not track_logtext:\n raise TrackDoesNotExistError(f\"Track {track_id} does not exist\")\n path = playlist_path(c, playlist_name)\n if not path.exists():\n raise PlaylistDoesNotExistError(f\"Playlist {playlist_name} does not exist\")\n with lock(c, playlist_lock_name(playlist_name)):\n with path.open(\"rb\") as fp:\n data = tomllib.load(fp)\n old_tracks = data.get(\"tracks\", [])\n new_tracks = [r for r in old_tracks if r[\"uuid\"] != track_id]\n if old_tracks == new_tracks:\n logger.info(f\"No-Op: Track {track_logtext} not in playlist {playlist_name}\")\n return\n data[\"tracks\"] = new_tracks\n with path.open(\"wb\") as fp:\n tomli_w.dump(data, fp)\n logger.info(f\"Removed track {track_logtext} from playlist {playlist_name}\")\n update_cache_for_playlists(c, [playlist_name], force=True)" }, { "identifier": "rename_playlist", "path": "rose/playlists.py", "snippet": "def rename_playlist(c: Config, old_name: str, new_name: str) -> None:\n logger.info(f\"Renamed playlist {old_name} to {new_name}\")\n old_path = playlist_path(c, old_name)\n new_path = playlist_path(c, new_name)\n with lock(c, playlist_lock_name(old_name)), lock(c, playlist_lock_name(new_name)):\n if not old_path.exists():\n raise PlaylistDoesNotExistError(f\"Playlist {old_name} does not exist\")\n if new_path.exists():\n raise PlaylistAlreadyExistsError(f\"Playlist {new_name} already exists\")\n old_path.rename(new_path)\n # And also rename all files with the same stem (e.g. cover arts).\n for old_adjacent_file in (c.music_source_dir / \"!playlists\").iterdir():\n if old_adjacent_file.stem != old_path.stem:\n continue\n new_adjacent_file = old_adjacent_file.with_name(\n new_path.stem + old_adjacent_file.suffix\n )\n if new_adjacent_file.exists():\n continue\n old_adjacent_file.rename(new_adjacent_file)\n logger.debug(\n \"Renaming playlist-adjacent file {old_adjacent_file} to {new_adjacent_file}\"\n )\n update_cache_for_playlists(c, [new_name], force=True)\n update_cache_evict_nonexistent_playlists(c)" }, { "identifier": "set_playlist_cover_art", "path": "rose/playlists.py", "snippet": "def set_playlist_cover_art(c: Config, playlist_name: str, new_cover_art_path: Path) -> None:\n \"\"\"\n This function removes all potential cover arts for the playlist, and then copies the file\n file located at the passed in path to be the playlist's art file.\n \"\"\"\n suffix = new_cover_art_path.suffix.lower()\n if suffix[1:] not in c.valid_art_exts:\n raise InvalidCoverArtFileError(\n f\"File {new_cover_art_path.name}'s extension is not supported for cover images: \"\n \"To change this, please read the configuration documentation\"\n )\n\n path = playlist_path(c, playlist_name)\n if not path.exists():\n raise PlaylistDoesNotExistError(f\"Playlist {playlist_name} does not exist\")\n for f in (c.music_source_dir / \"!playlists\").iterdir():\n if f.stem == playlist_name and f.suffix[1:].lower() in c.valid_art_exts:\n logger.debug(f\"Deleting existing cover art {f.name} in playlists\")\n f.unlink()\n shutil.copyfile(new_cover_art_path, path.with_suffix(suffix))\n logger.info(f\"Set the cover of playlist {playlist_name} to {new_cover_art_path.name}\")\n update_cache_for_playlists(c, [playlist_name])" }, { "identifier": "delete_release", "path": "rose/releases.py", "snippet": "def delete_release(c: Config, release_id: str) -> None:\n release = get_release(c, release_id)\n if not release:\n raise ReleaseDoesNotExistError(f\"Release {release_id} does not exist\")\n with lock(c, release_lock_name(release_id)):\n send2trash(release.source_path)\n release_logtext = calculate_release_logtext(\n title=release.albumtitle,\n year=release.year,\n artists=release.albumartists,\n )\n logger.info(f\"Trashed release {release_logtext}\")\n update_cache_evict_nonexistent_releases(c)\n # Update all collages so that the release is removed from whichever collages it was in.\n update_cache_for_collages(c, None, force=True)" }, { "identifier": "set_release_cover_art", "path": "rose/releases.py", "snippet": "def set_release_cover_art(\n c: Config,\n release_id: str,\n new_cover_art_path: Path,\n) -> None:\n \"\"\"\n This function removes all potential cover arts in the release source directory and copies the\n file located at the passed in path to `cover.{ext}` in the release source directory.\n \"\"\"\n suffix = new_cover_art_path.suffix.lower()\n if suffix[1:] not in c.valid_art_exts:\n raise InvalidCoverArtFileError(\n f\"File {new_cover_art_path.name}'s extension is not supported for cover images: \"\n \"To change this, please read the configuration documentation\"\n )\n\n release = get_release(c, release_id)\n if not release:\n raise ReleaseDoesNotExistError(f\"Release {release_id} does not exist\")\n\n release_logtext = calculate_release_logtext(\n title=release.albumtitle,\n year=release.year,\n artists=release.albumartists,\n )\n\n for f in release.source_path.iterdir():\n if f.name.lower() in c.valid_cover_arts:\n logger.debug(f\"Deleting existing cover art {f.name} in {release_logtext}\")\n send2trash(f)\n shutil.copyfile(new_cover_art_path, release.source_path / f\"cover{new_cover_art_path.suffix}\")\n logger.info(f\"Set the cover of release {release_logtext} to {new_cover_art_path.name}\")\n update_cache_for_releases(c, [release.source_path])" }, { "identifier": "PathTemplate", "path": "rose/templates.py", "snippet": "class PathTemplate:\n \"\"\"\n A wrapper for a template that stores the template as a string and compiles on-demand as a\n derived propery. This grants us serialization of the config.\n \"\"\"\n\n text: str\n\n @cached_property\n def compiled(self) -> jinja2.Template:\n return ENVIRONMENT.from_string(self.text)\n\n def __hash__(self) -> int:\n return hash(self.text)\n\n def __getstate__(self) -> dict[str, Any]:\n # We cannot pickle a compiled path template, so remove it from the state before we pickle\n # it. We can cheaply recompute it in the subprocess anyways.\n state = self.__dict__.copy()\n if \"compiled\" in state:\n del state[\"compiled\"]\n return state" }, { "identifier": "eval_release_template", "path": "rose/templates.py", "snippet": "def eval_release_template(\n template: PathTemplate,\n release: CachedRelease,\n position: str | None = None,\n) -> str:\n return _collapse_spacing(template.compiled.render(**_calc_release_variables(release, position)))" }, { "identifier": "eval_track_template", "path": "rose/templates.py", "snippet": "def eval_track_template(\n template: PathTemplate,\n track: CachedTrack,\n position: str | None = None,\n) -> str:\n return (\n _collapse_spacing(template.compiled.render(**_calc_track_variables(track, position)))\n + track.source_path.suffix\n )" } ]
import collections import contextlib import errno import logging import os import random import re import stat import subprocess import tempfile import time import llfuse from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path from typing import Any, Generic, Literal, TypeVar from rose.audiotags import SUPPORTED_AUDIO_EXTENSIONS, AudioTags from rose.cache import ( STORED_DATA_FILE_REGEX, CachedRelease, CachedTrack, artist_exists, calculate_release_logtext, calculate_track_logtext, genre_exists, get_collage, get_playlist, get_release, get_track, get_tracks_associated_with_release, label_exists, list_artists, list_collages, list_genres, list_labels, list_playlists, list_releases_delete_this, update_cache_for_releases, ) from rose.collages import ( add_release_to_collage, create_collage, delete_collage, remove_release_from_collage, rename_collage, ) from rose.common import RoseError, sanitize_dirname, sanitize_filename from rose.config import Config from rose.playlists import ( add_track_to_playlist, create_playlist, delete_playlist, delete_playlist_cover_art, remove_track_from_playlist, rename_playlist, set_playlist_cover_art, ) from rose.releases import ( delete_release, set_release_cover_art, ) from rose.templates import PathTemplate, eval_release_template, eval_track_template
19,928
if pf.suffix.lower() in SUPPORTED_AUDIO_EXTENSIONS and flags & os.O_CREAT == os.O_CREAT: fh = self.fhandler.next() logger.debug( f"LOGICAL: Begin playlist addition operation sequence for " f"{playlist.name=}, {p.file=}, and {fh=}" ) self.file_creation_special_ops[fh] = ( "add-track-to-playlist", p.playlist, pf.suffix, bytearray(), ) return fh # If we are trying to create a cover image in the playlist, enter the "new-cover-art" # sequence for the playlist. if p.file.lower() in self.config.valid_cover_arts and flags & os.O_CREAT == os.O_CREAT: fh = self.fhandler.next() logger.debug( f"LOGICAL: Begin new cover art sequence for playlist" f"{playlist.name=}, {p.file=}, and {fh=}" ) self.file_creation_special_ops[fh] = ( "new-cover-art", ("playlist", p.playlist), pf.suffix, bytearray(), ) return fh # Otherwise, continue on... if (track_id := self.vnames.lookup_track(p)) and ( track := get_track(self.config, track_id) ): fh = self.fhandler.wrap_host(os.open(str(track.source_path), flags)) if flags & os.O_WRONLY == os.O_WRONLY or flags & os.O_RDWR == os.O_RDWR: self.update_release_on_fh_close[fh] = track.release.id return fh if playlist.cover_path and f"cover{playlist.cover_path.suffix}" == p.file: return self.fhandler.wrap_host(os.open(playlist.cover_path, flags)) raise llfuse.FUSEError(err) raise llfuse.FUSEError(err) def read(self, fh: int, offset: int, length: int) -> bytes: logger.debug(f"LOGICAL: Received read for {fh=} {offset=} {length=}") if sop := self.file_creation_special_ops.get(fh, None): logger.debug("LOGICAL: Matched read to a file creation special op") _, _, _, b = sop return b[offset : offset + length] fh = self.fhandler.unwrap_host(fh) os.lseek(fh, offset, os.SEEK_SET) return os.read(fh, length) def write(self, fh: int, offset: int, data: bytes) -> int: logger.debug(f"LOGICAL: Received write for {fh=} {offset=} {len(data)=}") if sop := self.file_creation_special_ops.get(fh, None): logger.debug("LOGICAL: Matched write to a file creation special op") _, _, _, b = sop del b[offset:] b.extend(data) return len(data) fh = self.fhandler.unwrap_host(fh) os.lseek(fh, offset, os.SEEK_SET) return os.write(fh, data) def release(self, fh: int) -> None: logger.debug(f"LOGICAL: Received release for {fh=}") if sop := self.file_creation_special_ops.get(fh, None): logger.debug("LOGICAL: Matched release to a file creation special op") operation, ident, ext, b = sop if not b: logger.debug("LOGICAL: Aborting file creation special oprelease: no bytes to write") return if operation == "add-track-to-playlist": logger.debug("LOGICAL: Narrowed file creation special op to add track to playlist") playlist = ident with tempfile.TemporaryDirectory() as tmpdir: audiopath = Path(tmpdir) / f"f{ext}" with audiopath.open("wb") as fp: fp.write(b) audiofile = AudioTags.from_file(audiopath) track_id = audiofile.id if not track_id: logger.warning( "LOGICAL: Failed to parse track_id from file in playlist addition " f"operation sequence: {track_id=} {fh=} {playlist=} {audiofile}" ) return add_track_to_playlist(self.config, playlist, track_id) del self.file_creation_special_ops[fh] return if operation == "new-cover-art": entity_type, entity_id = ident if entity_type == "release": logger.debug( "LOGICAL: Narrowed file creation special op to write release cover art" ) with tempfile.TemporaryDirectory() as tmpdir: imagepath = Path(tmpdir) / f"f{ext}" with imagepath.open("wb") as fp: fp.write(b) set_release_cover_art(self.config, entity_id, imagepath) del self.file_creation_special_ops[fh] return if entity_type == "playlist": logger.debug( "LOGICAL: Narrowed file creation special op to write playlist cover art" ) with tempfile.TemporaryDirectory() as tmpdir: imagepath = Path(tmpdir) / f"f{ext}" with imagepath.open("wb") as fp: fp.write(b) set_playlist_cover_art(self.config, entity_id, imagepath) del self.file_creation_special_ops[fh] return raise RoseError(f"Impossible: unknown file creation special op: {operation=} {ident=}") if release_id := self.update_release_on_fh_close.get(fh, None): logger.debug( f"LOGICAL: Triggering cache update for release {release_id} after release syscall" ) if release := get_release(self.config, release_id):
""" The virtualfs module renders a virtual filesystem from the read cache. It is written in an Object-Oriented style, against my typical sensibilities, because that's how the FUSE libraries tend to be implemented. But it's OK :) Since this is a pretty hefty module, we'll cover the organization. This module contains 8 classes: 1. TTLCache: A wrapper around dict that expires key/value pairs after a given TTL. 2. VirtualPath: A semantic representation of a path in the virtual filesystem along with a parser. All virtual filesystem paths are parsed by this class into a far more ergonomic dataclass. 3. VirtualNameGenerator: A class that generates virtual directory and filenames given releases and tracks, and maintains inverse mappings for resolving release IDs from virtual paths. 4. "CanShow"er: An abstraction that encapsulates the logic of whether an artist, genre, or label should be shown in their respective virtual views, based on the whitelist/blacklist configuration parameters. 5. FileHandleGenerator: A class that keeps generates new file handles. It is a counter that wraps back to 5 when the file handles exceed ~10k, as to avoid any overflows. 6. RoseLogicalCore: A logical representation of Rose's filesystem logic, freed from the annoying implementation details that a low-level library like `llfuse` comes with. 7. INodeMapper: A class that tracks the INode <-> Path mappings. It is used to convert inodes to paths in VirtualFS. 8. VirtualFS: The main Virtual Filesystem class, which manages the annoying implementation details of a low-level virtual filesystem, and delegates logic to the above classes. It uses INodeMapper and VirtualPath to translate inodes into semantically useful dataclasses, and then passes them into RoseLogicalCore. """ from __future__ import annotations logger = logging.getLogger(__name__) K = TypeVar("K") V = TypeVar("V") T = TypeVar("T") class TTLCache(Generic[K, V]): """ TTLCache is a dictionary with a time-to-live (TTL) for each key/value pair. After the TTL passes, the key/value pair is no longer accessible. We do not currently free entries in this cache, because we expect little churn to occur in entries in normal operation. We do not have a great time to clear the cache that does not affect performance. We will probably implement freeing entries later when we give more of a shit or someone complains about the memory usage. I happen to have a lot of free RAM! """ def __init__(self, ttl_seconds: int = 5): self.ttl_seconds = ttl_seconds self.__backing: dict[K, tuple[V, float]] = {} def __contains__(self, key: K) -> bool: try: _, insert_time = self.__backing[key] except KeyError: return False return time.time() - insert_time <= self.ttl_seconds def __getitem__(self, key: K) -> V: v, insert_time = self.__backing[key] if time.time() - insert_time > self.ttl_seconds: raise KeyError(key) return v def __setitem__(self, key: K, value: V) -> None: self.__backing[key] = (value, time.time()) def __delitem__(self, key: K) -> None: del self.__backing[key] def get(self, key: K, default: T) -> V | T: try: return self[key] except KeyError: return default # In collages, playlists, and releases, we print directories with position of the release/track in # the collage. When parsing, strip it out. Otherwise we will have to handle this parsing in every # method. POSITION_REGEX = re.compile(r"^([^.]+)\. ") # In recently added, we print the date that the release was added to the library. When parsing, # strip it out. ADDED_AT_REGEX = re.compile(r"^\[[\d-]{10}\] ") @dataclass(frozen=True, slots=True) class VirtualPath: view: ( Literal[ "Root", "Releases", "Artists", "Genres", "Labels", "Collages", "Playlists", "New", "Recently Added", ] | None ) artist: str | None = None genre: str | None = None label: str | None = None collage: str | None = None playlist: str | None = None release: str | None = None file: str | None = None @property def release_parent(self) -> VirtualPath: """Parent path of a release: Used as an input to the VirtualNameGenerator.""" return VirtualPath( view=self.view, artist=self.artist, genre=self.genre, label=self.label, collage=self.collage, ) @property def track_parent(self) -> VirtualPath: """Parent path of a track: Used as an input to the VirtualNameGenerator.""" return VirtualPath( view=self.view, artist=self.artist, genre=self.genre, label=self.label, collage=self.collage, playlist=self.playlist, release=self.release, ) @classmethod def parse(cls, path: Path) -> VirtualPath: parts = str(path.resolve()).split("/")[1:] # First part is always empty string. if len(parts) == 1 and parts[0] == "": return VirtualPath(view="Root") # Let's abort early if we recognize a path that we _know_ is not valid. This is because # invalid file accesses trigger a recalculation of virtual file paths, which we decided to # do under the assumption that invalid file accesses would be _rare_. That's not true if we # keep getting requests for these stupid paths from shell plugins. if parts[-1] in [".git", ".DS_Store", ".Trash", ".Trash-1000", "HEAD", ".envrc"]: logger.debug( f"Raising ENOENT early in the VirtualPath parser because last path part {parts[-1]} in blacklist." ) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "1. Releases": if len(parts) == 1: return VirtualPath(view="Releases") if len(parts) == 2: return VirtualPath(view="Releases", release=parts[1]) if len(parts) == 3: return VirtualPath(view="Releases", release=parts[1], file=parts[2]) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "2. Releases - New": if len(parts) == 1: return VirtualPath(view="New") if len(parts) == 2: return VirtualPath(view="New", release=parts[1]) if len(parts) == 3: return VirtualPath(view="New", release=parts[1], file=parts[2]) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "3. Releases - Recently Added": if len(parts) == 1: return VirtualPath(view="Recently Added") if len(parts) == 2: return VirtualPath(view="Recently Added", release=parts[1]) if len(parts) == 3: return VirtualPath(view="Recently Added", release=parts[1], file=parts[2]) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "4. Artists": if len(parts) == 1: return VirtualPath(view="Artists") if len(parts) == 2: return VirtualPath(view="Artists", artist=parts[1]) if len(parts) == 3: return VirtualPath(view="Artists", artist=parts[1], release=parts[2]) if len(parts) == 4: return VirtualPath(view="Artists", artist=parts[1], release=parts[2], file=parts[3]) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "5. Genres": if len(parts) == 1: return VirtualPath(view="Genres") if len(parts) == 2: return VirtualPath(view="Genres", genre=parts[1]) if len(parts) == 3: return VirtualPath(view="Genres", genre=parts[1], release=parts[2]) if len(parts) == 4: return VirtualPath(view="Genres", genre=parts[1], release=parts[2], file=parts[3]) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "6. Labels": if len(parts) == 1: return VirtualPath(view="Labels") if len(parts) == 2: return VirtualPath(view="Labels", label=parts[1]) if len(parts) == 3: return VirtualPath(view="Labels", label=parts[1], release=parts[2]) if len(parts) == 4: return VirtualPath(view="Labels", label=parts[1], release=parts[2], file=parts[3]) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "7. Collages": if len(parts) == 1: return VirtualPath(view="Collages") if len(parts) == 2: return VirtualPath(view="Collages", collage=parts[1]) if len(parts) == 3: return VirtualPath(view="Collages", collage=parts[1], release=parts[2]) if len(parts) == 4: return VirtualPath( view="Collages", collage=parts[1], release=parts[2], file=parts[3] ) raise llfuse.FUSEError(errno.ENOENT) if parts[0] == "8. Playlists": if len(parts) == 1: return VirtualPath(view="Playlists") if len(parts) == 2: return VirtualPath(view="Playlists", playlist=parts[1]) if len(parts) == 3: return VirtualPath( view="Playlists", playlist=parts[1], file=parts[2], ) raise llfuse.FUSEError(errno.ENOENT) raise llfuse.FUSEError(errno.ENOENT) class VirtualNameGenerator: """ Generates virtual dirnames and filenames for releases and tracks, and maintains an inverse mapping for looking up release/track UUIDs from their virtual paths. This object's data has the following lifecycle: 1. RoseLogicalCore calls `list_virtual_x_paths` to generate all paths in a directory. 2. Once generated, path->ID can be looked up. This means that RoseLogicalCore is responsible for invoking `list_virtual_x_paths` upon cache misses / missing file accesses. We end up invoking `list_virtual_x_path` whenever a non-existent path is getattr'ed, which is somewhat excessive, however, we can decouple the virtual templates from the cache this way, and the lookup _miss_ case should be rather rare in normal operations The VirtualNameGenerator also remembers all previous path mappings for 15 minutes since last use. This allows Rose to continue to serving accesses to old paths, even after the file metadata changed. This is useful, for example, if a directory or file is renamed (due to a metadata change) while its tracks are in a mpv playlist. mpv's requests to the old paths will still resolve, but the old paths will not show up in a readdir call. If old paths collide with new paths, new paths will take precedence. """ def __init__(self, config: Config): # fmt: off self._config = config # These are the stateful maps that we use to remember path mappings. They are maps from the # (parent_path, virtual path) -> entity ID. # # Entries expire after 15 minutes, which implements the "serve accesses to previous paths" # behavior as specified in the class docstring. self._release_store: TTLCache[tuple[VirtualPath, str], str] = TTLCache(ttl_seconds=60 * 15) self._track_store: TTLCache[tuple[VirtualPath, str], str] = TTLCache(ttl_seconds=60 * 15) # Cache template evaluations because they're expensive. self._release_template_eval_cache: dict[tuple[VirtualPath, PathTemplate, str, str | None], str] = {} self._track_template_eval_cache: dict[tuple[VirtualPath, PathTemplate, str, str | None], str] = {} # fmt: on def list_release_paths( self, release_parent: VirtualPath, releases: list[CachedRelease], ) -> Iterator[tuple[CachedRelease, str]]: """ Given a parent directory and a list of releases, calculates the virtual directory names for those releases, and returns a zipped iterator of the releases and their virtual directory names. """ # For collision number generation. seen: set[str] = set() prefix_pad_size = len(str(len(releases))) for idx, release in enumerate(releases): # Determine the proper template. template = None if release_parent.view == "Releases": template = self._config.path_templates.all_releases.release elif release_parent.view == "New": template = self._config.path_templates.new_releases.release elif release_parent.view == "Recently Added": template = self._config.path_templates.recently_added_releases.release elif release_parent.view == "Artists": template = self._config.path_templates.artists.release elif release_parent.view == "Genres": template = self._config.path_templates.genres.release elif release_parent.view == "Labels": template = self._config.path_templates.labels.release elif release_parent.view == "Collages": template = self._config.path_templates.collages.release else: raise RoseError(f"VNAMES: No release template found for {release_parent=}.") logtext = calculate_release_logtext( title=release.albumtitle, year=release.year, artists=release.albumartists, ) # Generate a position if we're in a collage. position = None if release_parent.collage: position = f"{str(idx+1).zfill(prefix_pad_size)}" # Generate the virtual name. time_start = time.time() cachekey = (release_parent, template, release.metahash, position) try: vname = self._release_template_eval_cache[cachekey] logger.debug( f"VNAMES: Reused cached virtual dirname {vname} for release {logtext} in {time.time()-time_start} seconds" ) except KeyError: vname = eval_release_template(template, release, position) vname = sanitize_dirname(vname, False) self._release_template_eval_cache[cachekey] = vname logger.debug( f"VNAMES: Generated virtual dirname {vname} for release {logtext} in {time.time()-time_start} seconds" ) # Handle name collisions by appending a unique discriminator to the end. original_vname = vname collision_no = 2 while True: if vname not in seen: break vname = f"{original_vname} [{collision_no}]" collision_no += 1 logger.debug(f"VNAMES: Added collision number to virtual dirname {vname}") # Store the generated release name in the cache. time_start = time.time() self._release_store[(release_parent, vname)] = release.id seen.add(vname) logger.debug( f"VNAMES: Time cost of storing the virtual dirname: {time.time()-time_start=} seconds" ) yield release, vname def list_track_paths( self, track_parent: VirtualPath, tracks: list[CachedTrack], ) -> Iterator[tuple[CachedTrack, str]]: """ Given a parent directory and a list of tracks, calculates the virtual filenames for those tracks, and returns a zipped iterator of the tracks and their virtual filenames. """ # For collision number generation. seen: set[str] = set() prefix_pad_size = len(str(len(tracks))) for idx, track in enumerate(tracks): # Determine the proper template. template = None if track_parent.view == "Releases": template = self._config.path_templates.all_releases.track elif track_parent.view == "New": template = self._config.path_templates.new_releases.track elif track_parent.view == "Recently Added": template = self._config.path_templates.recently_added_releases.track elif track_parent.view == "Artists": template = self._config.path_templates.artists.track elif track_parent.view == "Genres": template = self._config.path_templates.genres.track elif track_parent.view == "Labels": template = self._config.path_templates.labels.track elif track_parent.view == "Collages": template = self._config.path_templates.collages.track elif track_parent.view == "Playlists": template = self._config.path_templates.playlists else: raise RoseError(f"VNAMES: No track template found for {track_parent=}.") logtext = calculate_track_logtext( title=track.tracktitle, artists=track.trackartists, suffix=track.source_path.suffix, ) # Generate a position if we're in a playlist. position = None if track_parent.playlist: position = f"{str(idx+1).zfill(prefix_pad_size)}" # Generate the virtual filename. time_start = time.time() cachekey = (track_parent, template, track.metahash, position) try: vname = self._track_template_eval_cache[cachekey] except KeyError: vname = eval_track_template(template, track, position) vname = sanitize_filename(vname, False) logger.debug( f"VNAMES: Generated virtual filename {vname} for track {logtext} in {time.time() - time_start} seconds" ) self._track_template_eval_cache[cachekey] = vname # And in case of a name collision, add an extra number at the end. Iterate to find # the first unused number. original_vname = vname collision_no = 2 while True: if vname not in seen: break # Write the collision number before the file extension. pov = Path(original_vname) vname = f"{pov.stem} [{collision_no}]{pov.suffix}" collision_no += 1 logger.debug(f"VNAMES: Added collision number to virtual filepath {vname}") seen.add(vname) # Store the generated track name in the cache. time_start = time.time() self._track_store[(track_parent, vname)] = track.id seen.add(vname) logger.debug( f"VNAMES: Time cost of storing the virtual filename: {time.time()-time_start=} seconds" ) yield track, vname def lookup_release(self, p: VirtualPath) -> str | None: """Given a release path, return the associated release ID.""" assert p.release is not None try: # Bumps the expiration time for another 15 minutes. r = self._release_store[(p.release_parent, p.release)] logger.debug(f"VNAMES: Successfully resolved release virtual name {p} to {r}") return r except KeyError: logger.debug(f"VNAMES: Failed to resolve release virtual name {p}") return None def lookup_track(self, p: VirtualPath) -> str | None: """Given a track path, return the associated track ID.""" assert p.file is not None try: # Bumps the expiration time for another 15 minutes. r = self._track_store[(p.track_parent, p.file)] logger.debug(f"VNAMES: Successfully resolved track virtual name {p} to {r}") return r except KeyError: logger.debug(f"VNAMES: Failed to resolve track virtual name {p}") return None class CanShower: """ I'm great at naming things. This is "can show"-er, determining whether we can show an artist/genre/label based on the configured whitelists and blacklists. """ def __init__(self, config: Config): self._config = config self._artist_w = None self._artist_b = None self._genre_w = None self._genre_b = None self._label_w = None self._label_b = None if config.fuse_artists_whitelist: self._artist_w = set(config.fuse_artists_whitelist) if config.fuse_artists_blacklist: self._artist_b = set(config.fuse_artists_blacklist) if config.fuse_genres_whitelist: self._genre_w = set(config.fuse_genres_whitelist) if config.fuse_genres_blacklist: self._genre_b = set(config.fuse_genres_blacklist) if config.fuse_labels_whitelist: self._label_w = set(config.fuse_labels_whitelist) if config.fuse_labels_blacklist: self._label_b = set(config.fuse_labels_blacklist) def artist(self, artist: str) -> bool: if self._artist_w: return artist in self._artist_w elif self._artist_b: return artist not in self._artist_b return True def genre(self, genre: str) -> bool: if self._genre_w: return genre in self._genre_w elif self._genre_b: return genre not in self._genre_b return True def label(self, label: str) -> bool: if self._label_w: return label in self._label_w elif self._label_b: return label not in self._label_b return True class FileHandleManager: """ FileDescriptorGenerator generates file descriptors and handles wrapping so that we do not go over the int size. Assumes that we do not cycle 10k file descriptors before the first descriptor is released. """ def __init__(self) -> None: self._state = 10 # Fake sentinel for file handler. The VirtualFS class implements this file handle as a black # hole. self.dev_null = 9 # We translate Rose's Virtual Filesystem file handles to the host machine file handles. This # means that every file handle from the host system has a corresponding "wrapper" file # handle in Rose, and we only return Rose's file handles from the virtual fs. # # When we receive a Rose file handle that maps to a host filesystem operation, we "unwrap" # the file handle back to the host file handle, and then use it. # # This prevents any accidental collisions, where Rose generates a file handle that ends up # being the same number as a file handle that the host system generates. self._rose_to_host_map: dict[int, int] = {} def next(self) -> int: self._state = max(10, self._state + 1 % 10_000) return self._state def wrap_host(self, host_fh: int) -> int: rose_fh = self.next() self._rose_to_host_map[rose_fh] = host_fh return rose_fh def unwrap_host(self, rose_fh: int) -> int: try: return self._rose_to_host_map[rose_fh] except KeyError as e: raise llfuse.FUSEError(errno.EBADF) from e FileCreationSpecialOp = Literal["add-track-to-playlist", "new-cover-art"] class RoseLogicalCore: def __init__(self, config: Config, fhandler: FileHandleManager): self.config = config self.fhandler = fhandler self.vnames = VirtualNameGenerator(config) self.can_show = CanShower(config) # This map stores the state for "file creation" operations. We currently have two file # creation operations: # # 1. Add Track to Playlist: Because track filenames are not globally unique, the best way to # figure out the track ID is to record the data written, and then parse the written bytes # to find the track ID. # 2. New Cover Art: When replacing the cover art of a release or playlist, the new cover art # may have a different "filename" from the virtual `cover.{ext}` filename. We accept any # of the supported filenames as configured by the user. When a new file matching the # cover art filenames is written, it replaces the existing cover art. # # In order to be able to inspect the written bytes, we must store state across several # syscalls (open, write, release). So the process goes: # # 1. Upon file open, if the syscall matches one of the supported file creation operations, # store the file descriptor in this map instead. # 2. On subsequent write requests to the same path and sentinel file descriptor, take the # bytes-to-write and store them in the map. # 3. On release, process the written bytes and execute the real operation against the music # library. # # The state is a mapping of fh -> (operation, identifier, ext, bytes). Identifier is typed # based on the operation, and is used to identify the playlist/release being modified. self.file_creation_special_ops: dict[ int, tuple[FileCreationSpecialOp, Any, str, bytearray] ] = {} # We want to trigger a cache update whenever we notice that a file has been updated through # the virtual filesystem. To do this, we insert the file handle and release ID on open, and # then trigger the cache update on release. We use this variable to transport that state # between the two syscalls. self.update_release_on_fh_close: dict[int, str] = {} super().__init__() @staticmethod def stat(mode: Literal["dir", "file"], realpath: Path | None = None) -> dict[str, Any]: attrs: dict[str, Any] = {} attrs["st_mode"] = (stat.S_IFDIR | 0o755) if mode == "dir" else (stat.S_IFREG | 0o644) attrs["st_nlink"] = 4 attrs["st_uid"] = os.getuid() attrs["st_gid"] = os.getgid() attrs["st_size"] = 4096 attrs["st_atime_ns"] = 0.0 attrs["st_mtime_ns"] = 0.0 attrs["st_ctime_ns"] = 0.0 if realpath: s = realpath.stat() attrs["st_size"] = s.st_size attrs["st_atime_ns"] = s.st_atime attrs["st_mtime_ns"] = s.st_mtime attrs["st_ctime_ns"] = s.st_ctime return attrs def getattr(self, p: VirtualPath) -> dict[str, Any]: logger.debug(f"LOGICAL: Received getattr for {p=}") # Common logic that gets called for each track. def getattr_track(tracks: list[CachedTrack]) -> dict[str, Any]: track_id = self.vnames.lookup_track(p) if not track_id: logger.debug( f"LOGICAL: Invoking readdir before retrying file virtual name resolution on {p}" ) # Performant way to consume an iterator completely. collections.deque(self.readdir(p.track_parent), maxlen=0) logger.debug( f"LOGICAL: Finished readdir call: retrying file virtual name resolution on {p}" ) track_id = self.vnames.lookup_track(p) if not track_id: raise llfuse.FUSEError(errno.ENOENT) for t in tracks: if t.id == track_id: return self.stat("file", t.source_path) logger.debug("LOGICAL: Resolved track_id not found in the given tracklist") raise llfuse.FUSEError(errno.ENOENT) # Common logic that gets called for each release. def getattr_release() -> dict[str, Any]: release_id = self.vnames.lookup_release(p) if not release_id: logger.debug( f"LOGICAL: Invoking readdir before retrying release virtual name resolution on {p}" ) # Performant way to consume an iterator completely. collections.deque(self.readdir(p.release_parent), maxlen=0) logger.debug( f"LOGICAL: Finished readdir call: retrying release virtual name resolution on {p}" ) release_id = self.vnames.lookup_release(p) if not release_id: raise llfuse.FUSEError(errno.ENOENT) release = get_release(self.config, release_id) # Handle a potential release deletion here. if release is None: logger.debug("LOGICAL: Resolved release_id does not exist in cache") raise llfuse.FUSEError(errno.ENOENT) # If no file, return stat for the release dir. if not p.file: return self.stat("dir", release.source_path) # Look for files: if release.cover_image_path and p.file == f"cover{release.cover_image_path.suffix}": return self.stat("file", release.cover_image_path) if p.file == f".rose.{release.id}.toml": return self.stat("file") tracks = get_tracks_associated_with_release(self.config, release) return getattr_track(tracks) # 8. Playlists if p.playlist: try: playlist, tracks = get_playlist(self.config, p.playlist) # type: ignore except TypeError as e: raise llfuse.FUSEError(errno.ENOENT) from e if p.file: if playlist.cover_path and f"cover{playlist.cover_path.suffix}" == p.file: return self.stat("file", playlist.cover_path) return getattr_track(tracks) return self.stat("dir") # 7. Collages if p.collage: if not get_collage(self.config, p.collage): raise llfuse.FUSEError(errno.ENOENT) if p.release: return getattr_release() return self.stat("dir") # 6. Labels if p.label: if not label_exists(self.config, p.label) or not self.can_show.label(p.label): raise llfuse.FUSEError(errno.ENOENT) if p.release: return getattr_release() return self.stat("dir") # 5. Genres if p.genre: if not genre_exists(self.config, p.genre) or not self.can_show.genre(p.genre): raise llfuse.FUSEError(errno.ENOENT) if p.release: return getattr_release() return self.stat("dir") # 4. Artists if p.artist: if not artist_exists(self.config, p.artist) or not self.can_show.artist(p.artist): raise llfuse.FUSEError(errno.ENOENT) if p.release: return getattr_release() return self.stat("dir") # {1,2,3}. Releases if p.release: return getattr_release() # 0. Root elif p.view: return self.stat("dir") # -1. Wtf are you doing here? raise llfuse.FUSEError(errno.ENOENT) def readdir(self, p: VirtualPath) -> Iterator[tuple[str, dict[str, Any]]]: logger.debug(f"LOGICAL: Received readdir for {p=}") # Call getattr to validate existence. We can now assume that the provided path exists. This # for example includes checks that a given album belongs to the artist/genre/label/collage # its nested under. logger.debug(f"LOGICAL: Invoking getattr in readdir to validate existence of {p}") self.getattr(p) yield from [ (".", self.stat("dir")), ("..", self.stat("dir")), ] if p.view == "Root": yield from [ ("1. Releases", self.stat("dir")), ("2. Releases - New", self.stat("dir")), ("3. Releases - Recently Added", self.stat("dir")), ("4. Artists", self.stat("dir")), ("5. Genres", self.stat("dir")), ("6. Labels", self.stat("dir")), ("7. Collages", self.stat("dir")), ("8. Playlists", self.stat("dir")), ] return if p.release: if (release_id := self.vnames.lookup_release(p)) and ( release := get_release(self.config, release_id) ): tracks = get_tracks_associated_with_release(self.config, release) for trk, vname in self.vnames.list_track_paths(p, tracks): yield vname, self.stat("file", trk.source_path) if release.cover_image_path: yield release.cover_image_path.name, self.stat("file", release.cover_image_path) yield f".rose.{release.id}.toml", self.stat("file") return raise llfuse.FUSEError(errno.ENOENT) if p.artist or p.genre or p.label or p.view in ["Releases", "New", "Recently Added"]: releases = list_releases_delete_this( self.config, sanitized_artist_filter=p.artist, sanitized_genre_filter=p.genre, sanitized_label_filter=p.label, new=True if p.view == "New" else None, ) for rls, vname in self.vnames.list_release_paths(p, releases): yield vname, self.stat("dir", rls.source_path) return if p.view == "Artists": for artist, sanitized_artist in list_artists(self.config): if not self.can_show.artist(artist): continue yield sanitized_artist, self.stat("dir") return if p.view == "Genres": for genre, sanitized_genre in list_genres(self.config): if not self.can_show.genre(genre): continue yield sanitized_genre, self.stat("dir") return if p.view == "Labels": for label, sanitized_label in list_labels(self.config): if not self.can_show.label(label): continue yield sanitized_label, self.stat("dir") return if p.view == "Collages" and p.collage: _, releases = get_collage(self.config, p.collage) # type: ignore for rls, vname in self.vnames.list_release_paths(p, releases): yield vname, self.stat("dir", rls.source_path) return if p.view == "Collages": # Don't need to sanitize because the collage names come from filenames. for collage in list_collages(self.config): yield collage, self.stat("dir") return if p.view == "Playlists" and p.playlist: pdata = get_playlist(self.config, p.playlist) if pdata is None: raise llfuse.FUSEError(errno.ENOENT) playlist, tracks = pdata for trk, vname in self.vnames.list_track_paths(p, tracks): yield vname, self.stat("file", trk.source_path) if playlist.cover_path: v = f"cover{playlist.cover_path.suffix}" yield v, self.stat("file", playlist.cover_path) return if p.view == "Playlists": # Don't need to sanitize because the playlist names come from filenames. for pname in list_playlists(self.config): yield pname, self.stat("dir") return raise llfuse.FUSEError(errno.ENOENT) def unlink(self, p: VirtualPath) -> None: logger.debug(f"LOGICAL: Received unlink for {p=}") # Possible actions: # 1. Delete a track from a playlist. # 2. Delete cover art from a playlist. # # Note: We do not support deleting cover art from a release via the delete operation. This # is because when removing a release from a collage via `rm -r`, `unlink` gets called # recurisvely on every file, including each release's cover art. If we supported removing # cover art, all cover art would be removed when we removed a release from a collage. if ( p.view == "Playlists" and p.playlist and p.file and p.file.lower() in self.config.valid_cover_arts and (pdata := get_playlist(self.config, p.playlist)) ): delete_playlist_cover_art(self.config, pdata[0].name) return if ( p.view == "Playlists" and p.playlist and p.file and (pdata := get_playlist(self.config, p.playlist)) and (track_id := self.vnames.lookup_track(p)) ): remove_track_from_playlist(self.config, p.playlist, track_id) return # Otherwise, noop. If we return an error, that prevents rmdir from being called when we rm. def mkdir(self, p: VirtualPath) -> None: logger.debug(f"LOGICAL: Received mkdir for {p=}") # Possible actions: # 1. Create a new collage. # 2. Create a new playlist. if p.collage and p.release is None: create_collage(self.config, p.collage) return if p.playlist and p.file is None: create_playlist(self.config, p.playlist) return raise llfuse.FUSEError(errno.EACCES) def rmdir(self, p: VirtualPath) -> None: logger.debug(f"LOGICAL: Received rmdir for {p=}") # Possible actions: # 1. Delete a collage. # 2. Delete a release from an existing collage. # 3. Delete a playlist. # 4. Delete a release. if p.view == "Collages" and p.collage and p.release is None: delete_collage(self.config, p.collage) return if ( p.view == "Collages" and p.collage and p.release and (release_id := self.vnames.lookup_release(p)) ): remove_release_from_collage(self.config, p.collage, release_id) return if p.view == "Playlists" and p.playlist and p.file is None: delete_playlist(self.config, p.playlist) return if p.view != "Collages" and p.release and (release_id := self.vnames.lookup_release(p)): delete_release(self.config, release_id) return raise llfuse.FUSEError(errno.EACCES) def rename(self, old: VirtualPath, new: VirtualPath) -> None: logger.debug(f"LOGICAL: Received rename for {old=} {new=}") # Possible actions: # 1. Rename a collage. # 2. Rename a playlist. if ( old.view == "Collages" and new.view == "Collages" and (old.collage and new.collage) and old.collage != new.collage and (not old.release and not new.release) ): rename_collage(self.config, old.collage, new.collage) return if ( old.view == "Playlists" and new.view == "Playlists" and (old.playlist and new.playlist) and old.playlist != new.playlist and (not old.file and not new.file) ): rename_playlist(self.config, old.playlist, new.playlist) return raise llfuse.FUSEError(errno.EACCES) def open(self, p: VirtualPath, flags: int) -> int: logger.debug(f"LOGICAL: Received open for {p=} {flags=}") err = errno.ENOENT if flags & os.O_CREAT == os.O_CREAT: err = errno.EACCES # Possible actions: # 1. Add a release to a collage (by writing the .rose.{uuid}.toml file) (O_CREAT). # 2. Read/write existing music files, cover arts, and .rose.{uuid}.toml files. # 3. Replace the cover art of a release (O_CREAT). # 4. Add a track to a playlist (O_CREAT). # 5. Replace the cover art of a playlist (O_CREAT). if ( p.collage and p.release and p.file and flags & os.O_CREAT == os.O_CREAT and (m := STORED_DATA_FILE_REGEX.match(p.file)) ): release_id = m[1] logger.debug( f"LOGICAL: Add release {release_id} to collage {p.collage}, reached goal of collage addition sequence" ) add_release_to_collage(self.config, p.collage, release_id) return self.fhandler.dev_null if ( p.release and p.file and (release_id := self.vnames.lookup_release(p)) and (release := get_release(self.config, release_id)) ): # If the file is a music file, handle it as a music file. if track_id := self.vnames.lookup_track(p): tracks = get_tracks_associated_with_release(self.config, release) for t in tracks: if t.id == track_id: fh = self.fhandler.wrap_host(os.open(str(t.source_path), flags)) if flags & os.O_WRONLY == os.O_WRONLY or flags & os.O_RDWR == os.O_RDWR: self.update_release_on_fh_close[fh] = release.id return fh # If the file is the datafile, pass it through. if p.file == f".rose.{release.id}.toml": return self.fhandler.wrap_host(os.open(str(release.source_path / p.file), flags)) # If the file matches the current cover image, then simply pass it through. if release.cover_image_path and p.file == f"cover{release.cover_image_path.suffix}": return self.fhandler.wrap_host(os.open(str(release.cover_image_path), flags)) # Otherwise, if we are writing a brand new cover image, initiate the "new-cover-art" # sequence. if p.file.lower() in self.config.valid_cover_arts and flags & os.O_CREAT == os.O_CREAT: fh = self.fhandler.next() logtext = calculate_release_logtext( title=release.albumtitle, year=release.year, artists=release.albumartists, ) logger.debug( f"LOGICAL: Begin new cover art sequence for release " f"{logtext=}, {p.file=}, and {fh=}" ) self.file_creation_special_ops[fh] = ( "new-cover-art", ("release", release.id), Path(p.file).suffix, bytearray(), ) return fh raise llfuse.FUSEError(err) if p.playlist and p.file: try: playlist, tracks = get_playlist(self.config, p.playlist) # type: ignore except TypeError as e: raise llfuse.FUSEError(errno.ENOENT) from e # If we are trying to create an audio file in the playlist, enter the # "add-track-to-playlist" operation sequence. See the __init__ for more details. pf = Path(p.file) if pf.suffix.lower() in SUPPORTED_AUDIO_EXTENSIONS and flags & os.O_CREAT == os.O_CREAT: fh = self.fhandler.next() logger.debug( f"LOGICAL: Begin playlist addition operation sequence for " f"{playlist.name=}, {p.file=}, and {fh=}" ) self.file_creation_special_ops[fh] = ( "add-track-to-playlist", p.playlist, pf.suffix, bytearray(), ) return fh # If we are trying to create a cover image in the playlist, enter the "new-cover-art" # sequence for the playlist. if p.file.lower() in self.config.valid_cover_arts and flags & os.O_CREAT == os.O_CREAT: fh = self.fhandler.next() logger.debug( f"LOGICAL: Begin new cover art sequence for playlist" f"{playlist.name=}, {p.file=}, and {fh=}" ) self.file_creation_special_ops[fh] = ( "new-cover-art", ("playlist", p.playlist), pf.suffix, bytearray(), ) return fh # Otherwise, continue on... if (track_id := self.vnames.lookup_track(p)) and ( track := get_track(self.config, track_id) ): fh = self.fhandler.wrap_host(os.open(str(track.source_path), flags)) if flags & os.O_WRONLY == os.O_WRONLY or flags & os.O_RDWR == os.O_RDWR: self.update_release_on_fh_close[fh] = track.release.id return fh if playlist.cover_path and f"cover{playlist.cover_path.suffix}" == p.file: return self.fhandler.wrap_host(os.open(playlist.cover_path, flags)) raise llfuse.FUSEError(err) raise llfuse.FUSEError(err) def read(self, fh: int, offset: int, length: int) -> bytes: logger.debug(f"LOGICAL: Received read for {fh=} {offset=} {length=}") if sop := self.file_creation_special_ops.get(fh, None): logger.debug("LOGICAL: Matched read to a file creation special op") _, _, _, b = sop return b[offset : offset + length] fh = self.fhandler.unwrap_host(fh) os.lseek(fh, offset, os.SEEK_SET) return os.read(fh, length) def write(self, fh: int, offset: int, data: bytes) -> int: logger.debug(f"LOGICAL: Received write for {fh=} {offset=} {len(data)=}") if sop := self.file_creation_special_ops.get(fh, None): logger.debug("LOGICAL: Matched write to a file creation special op") _, _, _, b = sop del b[offset:] b.extend(data) return len(data) fh = self.fhandler.unwrap_host(fh) os.lseek(fh, offset, os.SEEK_SET) return os.write(fh, data) def release(self, fh: int) -> None: logger.debug(f"LOGICAL: Received release for {fh=}") if sop := self.file_creation_special_ops.get(fh, None): logger.debug("LOGICAL: Matched release to a file creation special op") operation, ident, ext, b = sop if not b: logger.debug("LOGICAL: Aborting file creation special oprelease: no bytes to write") return if operation == "add-track-to-playlist": logger.debug("LOGICAL: Narrowed file creation special op to add track to playlist") playlist = ident with tempfile.TemporaryDirectory() as tmpdir: audiopath = Path(tmpdir) / f"f{ext}" with audiopath.open("wb") as fp: fp.write(b) audiofile = AudioTags.from_file(audiopath) track_id = audiofile.id if not track_id: logger.warning( "LOGICAL: Failed to parse track_id from file in playlist addition " f"operation sequence: {track_id=} {fh=} {playlist=} {audiofile}" ) return add_track_to_playlist(self.config, playlist, track_id) del self.file_creation_special_ops[fh] return if operation == "new-cover-art": entity_type, entity_id = ident if entity_type == "release": logger.debug( "LOGICAL: Narrowed file creation special op to write release cover art" ) with tempfile.TemporaryDirectory() as tmpdir: imagepath = Path(tmpdir) / f"f{ext}" with imagepath.open("wb") as fp: fp.write(b) set_release_cover_art(self.config, entity_id, imagepath) del self.file_creation_special_ops[fh] return if entity_type == "playlist": logger.debug( "LOGICAL: Narrowed file creation special op to write playlist cover art" ) with tempfile.TemporaryDirectory() as tmpdir: imagepath = Path(tmpdir) / f"f{ext}" with imagepath.open("wb") as fp: fp.write(b) set_playlist_cover_art(self.config, entity_id, imagepath) del self.file_creation_special_ops[fh] return raise RoseError(f"Impossible: unknown file creation special op: {operation=} {ident=}") if release_id := self.update_release_on_fh_close.get(fh, None): logger.debug( f"LOGICAL: Triggering cache update for release {release_id} after release syscall" ) if release := get_release(self.config, release_id):
update_cache_for_releases(self.config, [release.source_path])
21
2023-10-09 14:42:23+00:00
24k
zhaoyizhou1123/mbrcsl
examples/pointmaze/run_mbrcsl_maze.py
[ { "identifier": "EnsembleDynamicsModel", "path": "offlinerlkit/modules/dynamics_module.py", "snippet": "class EnsembleDynamicsModel(nn.Module):\n def __init__(\n self,\n obs_dim: int,\n action_dim: int,\n hidden_dims: Union[List[int], Tuple[int]],\n num_ensemble: int = 7,\n num_elites: int = 5,\n activation: nn.Module = Swish,\n weight_decays: Optional[Union[List[float], Tuple[float]]] = None,\n with_reward: bool = True,\n device: str = \"cpu\"\n ) -> None:\n super().__init__()\n\n self.num_ensemble = num_ensemble\n self.num_elites = num_elites\n self._with_reward = with_reward\n self.device = torch.device(device)\n\n self.activation = activation()\n\n assert len(weight_decays) == (len(hidden_dims) + 1)\n\n module_list = []\n hidden_dims = [obs_dim+action_dim] + list(hidden_dims)\n if weight_decays is None:\n weight_decays = [0.0] * (len(hidden_dims) + 1)\n for in_dim, out_dim, weight_decay in zip(hidden_dims[:-1], hidden_dims[1:], weight_decays[:-1]):\n module_list.append(EnsembleLinear(in_dim, out_dim, num_ensemble, weight_decay))\n self.backbones = nn.ModuleList(module_list)\n\n self.output_layer = EnsembleLinear(\n hidden_dims[-1],\n 2 * (obs_dim + self._with_reward),\n num_ensemble,\n weight_decays[-1]\n )\n\n self.register_parameter(\n \"max_logvar\",\n nn.Parameter(torch.ones(obs_dim + self._with_reward) * 0.5, requires_grad=True)\n )\n self.register_parameter(\n \"min_logvar\",\n nn.Parameter(torch.ones(obs_dim + self._with_reward) * -10, requires_grad=True)\n )\n\n self.register_parameter(\n \"elites\",\n nn.Parameter(torch.tensor(list(range(0, self.num_elites))), requires_grad=False)\n )\n\n self.to(self.device)\n\n def forward(self, obs_action: np.ndarray) -> Tuple[torch.Tensor, torch.Tensor]:\n obs_action = torch.as_tensor(obs_action, dtype=torch.float32).to(self.device)\n output = obs_action\n for layer in self.backbones:\n output = self.activation(layer(output))\n mean, logvar = torch.chunk(self.output_layer(output), 2, dim=-1)\n logvar = soft_clamp(logvar, self.min_logvar, self.max_logvar)\n return mean, logvar\n\n def load_save(self) -> None:\n for layer in self.backbones:\n layer.load_save()\n self.output_layer.load_save()\n\n def update_save(self, indexes: List[int]) -> None:\n for layer in self.backbones:\n layer.update_save(indexes)\n self.output_layer.update_save(indexes)\n \n def get_decay_loss(self) -> torch.Tensor:\n decay_loss = 0\n for layer in self.backbones:\n decay_loss += layer.get_decay_loss()\n decay_loss += self.output_layer.get_decay_loss()\n return decay_loss\n\n def set_elites(self, indexes: List[int]) -> None:\n assert len(indexes) <= self.num_ensemble and max(indexes) < self.num_ensemble\n self.register_parameter('elites', nn.Parameter(torch.tensor(indexes), requires_grad=False))\n \n def random_elite_idxs(self, batch_size: int) -> np.ndarray:\n idxs = np.random.choice(self.elites.data.cpu().numpy(), size=batch_size)\n return idxs" }, { "identifier": "RcslModule", "path": "offlinerlkit/modules/rcsl_module.py", "snippet": "class RcslModule(nn.Module):\n '''\n rcsl policy network\n '''\n def __init__(\n self,\n backbone: nn.Module,\n device: str = \"cpu\"\n ) -> None:\n super().__init__()\n\n self.device = torch.device(device)\n self.backbone = backbone.to(device)\n\n def forward(self, obs: Union[np.ndarray, torch.Tensor], rtg: Union[np.ndarray, torch.Tensor]) -> torch.Tensor:\n '''\n obs: (batch, obs_dim) \n rtg: (batch,) / (batch,1)\n '''\n obs = torch.as_tensor(obs, device=self.device, dtype=torch.float32)\n rtg = torch.as_tensor(rtg, device=self.device, dtype=torch.float32)\n if rtg.dim() == 1:\n rtg = rtg.unsqueeze(-1)\n in_tensor = torch.cat([obs,rtg], dim=-1) #(batch, obs_dim + 1)\n action = self.backbone(in_tensor)\n return action" }, { "identifier": "EnsembleDynamics", "path": "offlinerlkit/dynamics/ensemble_dynamics.py", "snippet": "class EnsembleDynamics(BaseDynamics):\n def __init__(\n self,\n model: nn.Module,\n optim: torch.optim.Optimizer,\n scaler: StandardScaler,\n terminal_fn: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray],\n penalty_coef: float = 0.0,\n uncertainty_mode: str = \"aleatoric\"\n ) -> None:\n super().__init__(model, optim)\n self.scaler = scaler\n self.terminal_fn = terminal_fn\n self._penalty_coef = penalty_coef\n self._uncertainty_mode = uncertainty_mode\n\n @ torch.no_grad()\n def step(\n self,\n obs: np.ndarray,\n action: np.ndarray\n ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Dict]:\n '''\n Return:\n reward (B,1) (if obs has batch)\n terminal (B,1)\n '''\n \"imagine single forward step\"\n obs_act = np.concatenate([obs, action], axis=-1)\n obs_act = self.scaler.transform(obs_act)\n mean, logvar = self.model(obs_act)\n mean = mean.cpu().numpy()\n logvar = logvar.cpu().numpy()\n mean[..., :-1] += obs # We estimated delta_obs\n std = np.sqrt(np.exp(logvar))\n\n ensemble_samples = (mean + np.random.normal(size=mean.shape) * std).astype(np.float32)\n\n # choose one model from ensemble\n num_models, batch_size, _ = ensemble_samples.shape\n model_idxs = self.model.random_elite_idxs(batch_size)\n samples = ensemble_samples[model_idxs, np.arange(batch_size)]\n \n next_obs = samples[..., :-1]\n reward = samples[..., -1:]\n terminal = self.terminal_fn(obs, action, next_obs)\n info = {}\n info[\"raw_reward\"] = reward\n\n if self._penalty_coef:\n if self._uncertainty_mode == \"aleatoric\":\n penalty = np.amax(np.linalg.norm(std, axis=2), axis=0)\n elif self._uncertainty_mode == \"pairwise-diff\":\n next_obses_mean = mean[..., :-1]\n next_obs_mean = np.mean(next_obses_mean, axis=0)\n diff = next_obses_mean - next_obs_mean\n penalty = np.amax(np.linalg.norm(diff, axis=2), axis=0)\n elif self._uncertainty_mode == \"ensemble_std\":\n next_obses_mean = mean[..., :-1]\n penalty = np.sqrt(next_obses_mean.var(0).mean(1))\n else:\n raise ValueError\n penalty = np.expand_dims(penalty, 1).astype(np.float32)\n assert penalty.shape == reward.shape\n reward = reward - self._penalty_coef * penalty\n info[\"penalty\"] = penalty\n \n return next_obs, reward, terminal, info\n \n @ torch.no_grad()\n def sample_next_obss(\n self,\n obs: torch.Tensor,\n action: torch.Tensor,\n num_samples: int\n ) -> torch.Tensor:\n obs_act = torch.cat([obs, action], dim=-1)\n obs_act = self.scaler.transform_tensor(obs_act)\n mean, logvar = self.model(obs_act)\n mean[..., :-1] += obs\n std = torch.sqrt(torch.exp(logvar))\n\n mean = mean[self.model.elites.data.cpu().numpy()]\n std = std[self.model.elites.data.cpu().numpy()]\n\n samples = torch.stack([mean + torch.randn_like(std) * std for i in range(num_samples)], 0)\n next_obss = samples[..., :-1]\n return next_obss\n\n def format_samples_for_training(self, data: Dict) -> Tuple[np.ndarray, np.ndarray]:\n obss = data[\"observations\"]\n actions = data[\"actions\"]\n next_obss = data[\"next_observations\"]\n rewards = data[\"rewards\"]\n rewards = rewards.reshape(rewards.shape[0], -1)\n delta_obss = next_obss - obss\n inputs = np.concatenate((obss, actions), axis=-1)\n targets = np.concatenate((delta_obss, rewards), axis=-1)\n return inputs, targets\n\n def train(\n self,\n data: Dict,\n logger: Logger,\n max_epochs: Optional[float] = None,\n max_epochs_since_update: int = 5,\n batch_size: int = 256,\n holdout_ratio: float = 0.2,\n logvar_loss_coef: float = 0.01\n ) -> None:\n inputs, targets = self.format_samples_for_training(data)\n data_size = inputs.shape[0]\n holdout_size = min(int(data_size * holdout_ratio), 1000)\n train_size = data_size - holdout_size\n train_splits, holdout_splits = torch.utils.data.random_split(range(data_size), (train_size, holdout_size))\n train_inputs, train_targets = inputs[train_splits.indices], targets[train_splits.indices]\n holdout_inputs, holdout_targets = inputs[holdout_splits.indices], targets[holdout_splits.indices]\n\n self.scaler.fit(train_inputs)\n train_inputs = self.scaler.transform(train_inputs)\n holdout_inputs = self.scaler.transform(holdout_inputs)\n holdout_losses = [1e10 for i in range(self.model.num_ensemble)]\n\n data_idxes = np.random.randint(train_size, size=[self.model.num_ensemble, train_size])\n def shuffle_rows(arr):\n idxes = np.argsort(np.random.uniform(size=arr.shape), axis=-1)\n return arr[np.arange(arr.shape[0])[:, None], idxes]\n\n epoch = 0\n cnt = 0\n logger.log(\"Training dynamics:\")\n while True:\n epoch += 1\n train_loss = self.learn(train_inputs[data_idxes], train_targets[data_idxes], batch_size, logvar_loss_coef)\n new_holdout_losses = self.validate(holdout_inputs, holdout_targets)\n holdout_loss = (np.sort(new_holdout_losses)[:self.model.num_elites]).mean()\n logger.logkv(\"loss/dynamics_train_loss\", train_loss)\n logger.logkv(\"loss/dynamics_holdout_loss\", holdout_loss)\n logger.set_timestep(epoch)\n logger.dumpkvs(exclude=[\"policy_training_progress\"])\n\n # shuffle data for each base learner\n data_idxes = shuffle_rows(data_idxes)\n\n indexes = []\n for i, new_loss, old_loss in zip(range(len(holdout_losses)), new_holdout_losses, holdout_losses):\n improvement = (old_loss - new_loss) / old_loss\n if improvement > 0.01:\n indexes.append(i)\n holdout_losses[i] = new_loss\n \n if len(indexes) > 0:\n self.model.update_save(indexes)\n cnt = 0\n else:\n cnt += 1\n \n if (cnt >= max_epochs_since_update) or (max_epochs and (epoch >= max_epochs)):\n break\n\n indexes = self.select_elites(holdout_losses)\n self.model.set_elites(indexes)\n self.model.load_save()\n self.save(logger.model_dir)\n self.model.eval()\n logger.log(\"elites:{} , holdout loss: {}\".format(indexes, (np.sort(holdout_losses)[:self.model.num_elites]).mean()))\n \n def learn(\n self,\n inputs: np.ndarray,\n targets: np.ndarray,\n batch_size: int = 256,\n logvar_loss_coef: float = 0.01\n ) -> float:\n self.model.train()\n train_size = inputs.shape[1]\n losses = []\n\n for batch_num in range(int(np.ceil(train_size / batch_size))):\n inputs_batch = inputs[:, batch_num * batch_size:(batch_num + 1) * batch_size]\n targets_batch = targets[:, batch_num * batch_size:(batch_num + 1) * batch_size]\n targets_batch = torch.as_tensor(targets_batch).to(self.model.device)\n \n mean, logvar = self.model(inputs_batch)\n inv_var = torch.exp(-logvar)\n # Average over batch and dim, sum over ensembles.\n mse_loss_inv = (torch.pow(mean - targets_batch, 2) * inv_var).mean(dim=(1, 2)) # MLE for Gaussian\n var_loss = logvar.mean(dim=(1, 2))\n loss = mse_loss_inv.sum() + var_loss.sum()\n loss = loss + self.model.get_decay_loss()\n loss = loss + logvar_loss_coef * self.model.max_logvar.sum() - logvar_loss_coef * self.model.min_logvar.sum()\n\n self.optim.zero_grad()\n loss.backward()\n self.optim.step()\n\n losses.append(loss.item())\n return np.mean(losses)\n \n @ torch.no_grad()\n def validate(self, inputs: np.ndarray, targets: np.ndarray) -> List[float]:\n self.model.eval()\n targets = torch.as_tensor(targets).to(self.model.device)\n mean, _ = self.model(inputs)\n loss = ((mean - targets) ** 2).mean(dim=(1, 2))\n val_loss = list(loss.cpu().numpy())\n return val_loss\n \n def select_elites(self, metrics: List) -> List[int]:\n pairs = [(metric, index) for metric, index in zip(metrics, range(len(metrics)))]\n pairs = sorted(pairs, key=lambda x: x[0])\n elites = [pairs[i][1] for i in range(self.model.num_elites)]\n return elites\n\n def save(self, save_path: str) -> None:\n torch.save(self.model.state_dict(), os.path.join(save_path, \"dynamics.pth\"))\n self.scaler.save_scaler(save_path)\n \n def load(self, load_path: str) -> None:\n self.model.load_state_dict(torch.load(os.path.join(load_path, \"dynamics.pth\"), map_location=self.model.device))\n self.scaler.load_scaler(load_path)" }, { "identifier": "StandardScaler", "path": "offlinerlkit/utils/scaler.py", "snippet": "class StandardScaler(object):\n def __init__(self, mu=None, std=None):\n self.mu = mu\n self.std = std\n\n def fit(self, data):\n \"\"\"Runs two ops, one for assigning the mean of the data to the internal mean, and\n another for assigning the standard deviation of the data to the internal standard deviation.\n This function must be called within a 'with <session>.as_default()' block.\n\n Arguments:\n data (np.ndarray): A numpy array containing the input\n\n Returns: None.\n \"\"\"\n self.mu = np.mean(data, axis=0, keepdims=True)\n self.std = np.std(data, axis=0, keepdims=True)\n self.std[self.std < 1e-12] = 1.0\n\n def transform(self, data):\n \"\"\"Transforms the input matrix data using the parameters of this scaler.\n\n Arguments:\n data (np.array): A numpy array containing the points to be transformed.\n\n Returns: (np.array) The transformed dataset.\n \"\"\"\n return (data - self.mu) / self.std\n\n def inverse_transform(self, data):\n \"\"\"Undoes the transformation performed by this scaler.\n\n Arguments:\n data (np.array): A numpy array containing the points to be transformed.\n\n Returns: (np.array) The transformed dataset.\n \"\"\"\n return self.std * data + self.mu\n \n def save_scaler(self, save_path):\n mu_path = path.join(save_path, \"mu.npy\")\n std_path = path.join(save_path, \"std.npy\")\n np.save(mu_path, self.mu)\n np.save(std_path, self.std)\n \n def load_scaler(self, load_path):\n mu_path = path.join(load_path, \"mu.npy\")\n std_path = path.join(load_path, \"std.npy\")\n self.mu = np.load(mu_path)\n self.std = np.load(std_path)\n\n def transform_tensor(self, data: torch.Tensor):\n device = data.device\n data = self.transform(data.cpu().numpy())\n data = torch.tensor(data, device=device)\n return data" }, { "identifier": "get_termination_fn", "path": "offlinerlkit/utils/termination_fns.py", "snippet": "def get_termination_fn(task):\n if 'halfcheetahvel' in task:\n return termination_fn_halfcheetahveljump\n elif 'halfcheetah' in task:\n return termination_fn_halfcheetah\n elif 'hopper' in task:\n return termination_fn_hopper\n elif 'antangle' in task:\n return termination_fn_antangle\n elif 'ant' in task:\n return termination_fn_ant\n elif 'walker2d' in task:\n return termination_fn_walker2d\n elif 'point2denv' in task:\n return termination_fn_point2denv\n elif 'point2dwallenv' in task:\n return termination_fn_point2dwallenv\n elif 'pendulum' in task:\n return termination_fn_pendulum\n elif 'humanoid' in task:\n return termination_fn_humanoid\n elif 'pen' in task:\n return termination_fn_pen\n elif 'door' in task:\n return termination_fn_door\n else:\n return termination_fn_default" }, { "identifier": "MLP", "path": "offlinerlkit/nets/mlp.py", "snippet": "class MLP(nn.Module):\n def __init__(\n self,\n input_dim: int,\n hidden_dims: Union[List[int], Tuple[int]],\n output_dim: Optional[int] = None,\n activation: nn.Module = nn.ReLU,\n dropout_rate: Optional[float] = None,\n init_last: bool = False\n ) -> None:\n super().__init__()\n hidden_dims = [input_dim] + list(hidden_dims)\n model = []\n for in_dim, out_dim in zip(hidden_dims[:-1], hidden_dims[1:]):\n model += [nn.Linear(in_dim, out_dim), activation()]\n if dropout_rate is not None:\n model += [nn.Dropout(p=dropout_rate)]\n\n self.output_dim = hidden_dims[-1]\n if output_dim is not None:\n last_layer = nn.Linear(hidden_dims[-1], output_dim)\n if init_last:\n nn.init.xavier_uniform_(last_layer.weight, gain=1e-2)\n nn.init.constant_(last_layer.bias, 0.0)\n model += [last_layer]\n self.output_dim = output_dim\n self.model = nn.Sequential(*model)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.model(x)" }, { "identifier": "Logger", "path": "offlinerlkit/utils/logger.py", "snippet": "class Logger(object):\n def __init__(self, dir: str, ouput_config: Dict) -> None:\n self._dir = dir\n self._init_dirs()\n self._init_ouput_handlers(ouput_config)\n self._name2val = defaultdict(float)\n self._name2cnt = defaultdict(int)\n self._level = INFO\n self._timestep = 0\n \n def _init_dirs(self) -> None:\n self._record_dir = os.path.join(self._dir, \"record\")\n self._checkpoint_dir = os.path.join(self._dir, \"checkpoint\")\n self._model_dir = os.path.join(self._dir, \"model\")\n self._result_dir = os.path.join(self._dir, \"result\")\n os.mkdir(self._record_dir)\n os.mkdir(self._checkpoint_dir)\n os.mkdir(self._model_dir)\n os.mkdir(self._result_dir)\n \n def _init_ouput_handlers(self, output_config: Dict) -> None:\n self._output_handlers = []\n for file_name, fmt in output_config.items():\n try:\n self._output_handlers.append(HANDLER[fmt](os.path.join(self._record_dir, file_name)))\n except KeyError:\n warnings.warn(\"Invalid output type, Valid types: stdout, csv, tensorboard\", DeprecationWarning)\n # default output to console\n self._output_handlers.append(StandardOutputHandler(sys.stdout))\n \n def log_hyperparameters(self, hyper_param: Dict) -> None:\n json_output_handler = JSONOutputHandler(os.path.join(self._record_dir, \"hyper_param\"))\n json_output_handler.writekvs(hyper_param)\n json_output_handler.close()\n for handler in self._output_handlers:\n if isinstance(handler, TensorBoardOutputHandler):\n handler.add_hyper_params_to_tb(hyper_param)\n\n def logkv(self, key: Any, val: Any) -> None:\n \"\"\"\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n \"\"\"\n self._name2val[key] = val\n\n def logkv_mean(self, key: Any, val: Number) -> None:\n \"\"\"\n The same as logkv(), but if called many times, values averaged.\n \"\"\"\n oldval, cnt = self._name2val[key], self._name2cnt[key]\n self._name2val[key] = oldval*cnt/(cnt+1) + val/(cnt+1)\n self._name2cnt[key] = cnt + 1\n\n def dumpkvs(self, exclude:Optional[Union[str, Tuple[str, ...]]]=None) -> None:\n # log timestep\n self.logkv(DEFAULT_X_NAME, self._timestep)\n for handler in self._output_handlers:\n if isinstance(handler, KVWriter):\n if exclude is not None and handler.handler_name in exclude:\n continue\n handler.writekvs(self._name2val)\n self._name2val.clear()\n self._name2cnt.clear()\n\n def log(self, s: str, level=INFO) -> None:\n for handler in self._output_handlers:\n if isinstance(handler, StandardOutputHandler):\n handler.writestr(s)\n \n def set_timestep(self, timestep: int) -> None:\n self._timestep = timestep\n for handler in self._output_handlers:\n if isinstance(handler, TensorBoardOutputHandler):\n handler.set_step(timestep)\n\n def set_level(self, level) -> None:\n self._level = level\n\n @property\n def record_dir(self) -> str:\n return self._record_dir\n \n @property\n def checkpoint_dir(self) -> str:\n return self._checkpoint_dir\n\n @property\n def model_dir(self) -> str:\n return self._model_dir\n \n @property\n def result_dir(self) -> str:\n return self._result_dir\n \n def close(self) -> None:\n for handler in self._output_handlers:\n handler.close()" }, { "identifier": "make_log_dirs", "path": "offlinerlkit/utils/logger.py", "snippet": "def make_log_dirs(\n task_name: str,\n algo_name: str,\n exp_name: str,\n args: Dict,\n part: Optional[str] = None,\n record_params: Optional[List]=None\n) -> str:\n if record_params is not None:\n for param_name in record_params:\n algo_name += f\"&{param_name}={args[param_name]}\"\n\n if part is not None:\n log_dirs = os.path.join(ROOT_DIR, task_name, algo_name, exp_name, part)\n else:\n log_dirs = os.path.join(ROOT_DIR, task_name, algo_name, exp_name)\n os.makedirs(log_dirs)\n return log_dirs" }, { "identifier": "RcslPolicyTrainer", "path": "offlinerlkit/policy_trainer/rcsl_policy_trainer.py", "snippet": "class RcslPolicyTrainer:\n def __init__(\n self,\n policy: BasePolicy,\n eval_env: Union[gym.Env, gymnasium.Env],\n offline_dataset: Dict[str, np.ndarray],\n rollout_dataset: Optional[Dict[str, np.ndarray]],\n goal: float,\n logger: Logger,\n seed,\n eval_env2: Optional[Union[gym.Env, gymnasium.Env]] = None,\n epoch: int = 1000,\n batch_size: int = 256,\n offline_ratio: float = 0,\n eval_episodes: int = 10,\n lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,\n horizon: Optional[int] = None,\n num_workers = 1,\n has_terminal = False,\n binary_return = True\n ) -> None:\n '''\n offline_ratio = 0: rollout only, 1: offline only\n '''\n self.policy = policy\n self.eval_env = eval_env\n self.eval_env2 = eval_env2\n self.horizon = horizon\n self.offline_dataset = offline_dataset\n self.rollout_dataset = rollout_dataset\n self.goal = goal\n self.logger = logger\n\n self._epoch = epoch\n self._batch_size = batch_size\n self._offline_ratio = offline_ratio\n self._eval_episodes = eval_episodes\n self.lr_scheduler = lr_scheduler\n self.num_workers = num_workers\n self.env_seed = seed\n self.binary_return = binary_return\n\n self.is_gymnasium_env = hasattr(self.eval_env, \"get_true_observation\")\n assert (not self.is_gymnasium_env) or (self.horizon is not None), \"Horizon must be specified for Gymnasium env\"\n self.has_terminal = has_terminal\n\n def train(self, holdout_ratio: float = 0.1, last_eval = False, find_best_start: Optional[int] = None, improve_threshold: float = 0.01) -> Dict[str, float]:\n '''\n last_eval: If True, only evaluates at the last epoch\n find_best_start: If >=0, begin to find the best epoch by holdout loss\n '''\n start_time = time.time()\n\n num_timesteps = 0\n last_10_performance = deque(maxlen=10)\n\n dataset = DictDataset(self.offline_dataset)\n\n if holdout_ratio == 0.:\n has_holdout = False\n train_dataset = dataset\n else:\n has_holdout = True\n holdout_size = int(len(dataset) * holdout_ratio)\n train_size = len(dataset) - holdout_size\n train_dataset, holdout_dataset = torch.utils.data.random_split(dataset, [train_size, holdout_size], \n generator=torch.Generator().manual_seed(self.env_seed))\n data_loader = DataLoader(\n train_dataset,\n batch_size = self._batch_size,\n shuffle = True,\n pin_memory = True,\n num_workers = self.num_workers\n )\n best_policy_dict = self.policy.state_dict()\n best_holdout_loss = 1e10\n epochs_since_upd = 0\n stop_by_holdout = (find_best_start is not None)\n for e in range(1, self._epoch + 1):\n\n self.policy.train()\n\n pbar = tqdm(enumerate(data_loader), desc=f\"Epoch #{e}/{self._epoch}\")\n for it, batch in pbar:\n '''\n batch: dict with keys\n 'observations'\n 'next_observations'\n 'actions'\n 'terminals'\n 'rewards'\n 'rtgs'\n\n '''\n loss_dict = self.policy.learn(batch)\n pbar.set_postfix(**loss_dict)\n\n for k, v in loss_dict.items():\n self.logger.logkv_mean(k, v)\n \n num_timesteps += 1\n\n if self.lr_scheduler is not None:\n self.lr_scheduler.step()\n\n # Test validation loss\n if has_holdout:\n holdout_loss = self.validate(holdout_dataset)\n if stop_by_holdout and e >= find_best_start: # test holdout improvement\n if (best_holdout_loss - holdout_loss) / best_holdout_loss > improve_threshold:\n best_holdout_loss = holdout_loss\n best_policy_dict = deepcopy(self.policy.state_dict())\n epochs_since_upd = 0\n else:\n epochs_since_upd += 1\n\n if last_eval and e < self._epoch: # When last_eval is True, only evaluate on last epoch\n pass\n else:\n eval_info = self._evaluate()\n ep_reward_mean, ep_reward_std = np.mean(eval_info[\"eval/episode_reward\"]), np.std(eval_info[\"eval/episode_reward\"])\n ep_reward_max, ep_reward_min = np.max(eval_info[\"eval/episode_reward\"]), np.min(eval_info[\"eval/episode_reward\"])\n ep_length_mean, ep_length_std = np.mean(eval_info[\"eval/episode_length\"]), np.std(eval_info[\"eval/episode_length\"])\n\n if not hasattr(self.eval_env, \"get_normalized_score\"): # gymnasium_env does not have normalized score\n last_10_performance.append(ep_reward_mean)\n self.logger.logkv(\"eval/episode_reward\", ep_reward_mean)\n self.logger.logkv(\"eval/episode_reward_std\", ep_reward_std) \n else: \n norm_ep_rew_mean = self.eval_env.get_normalized_score(ep_reward_mean) * 100\n norm_ep_rew_std = self.eval_env.get_normalized_score(ep_reward_std) * 100\n norm_ep_rew_max = self.eval_env.get_normalized_score(ep_reward_max) * 100\n norm_ep_rew_min = self.eval_env.get_normalized_score(ep_reward_min) * 100\n last_10_performance.append(norm_ep_rew_mean)\n self.logger.logkv(\"eval/normalized_episode_reward\", norm_ep_rew_mean)\n self.logger.logkv(\"eval/normalized_episode_reward_std\", norm_ep_rew_std)\n self.logger.logkv(\"eval/normalized_episode_reward_max\", norm_ep_rew_max)\n self.logger.logkv(\"eval/normalized_episode_reward_min\", norm_ep_rew_min)\n self.logger.logkv(\"eval/episode_length\", ep_length_mean)\n self.logger.logkv(\"eval/episode_length_std\", ep_length_std)\n\n self.logger.set_timestep(num_timesteps)\n self.logger.dumpkvs(exclude=[\"dynamics_training_progress\"])\n\n if stop_by_holdout and epochs_since_upd >= 5: # Stop, evaluate for the last time\n self.policy.load_state_dict(best_policy_dict)\n eval_info = self._evaluate()\n ep_reward_mean, ep_reward_std = np.mean(eval_info[\"eval/episode_reward\"]), np.std(eval_info[\"eval/episode_reward\"])\n self.logger.log(f\"Final evaluation: Mean {ep_reward_mean}, std {ep_reward_std}\\n\")\n break\n \n self.logger.log(\"total time: {:.2f}s\".format(time.time() - start_time))\n torch.save(self.policy.state_dict(), os.path.join(self.logger.model_dir, \"policy_final.pth\"))\n self.logger.close()\n \n return {\"last_10_performance\": np.mean(last_10_performance)}\n\n def _evaluate(self, eval_episodes: int = -1) -> Dict[str, List[float]]:\n '''\n Always set desired rtg to 0\n '''\n # Pointmaze obs has different format, needs to be treated differently\n if eval_episodes == -1:\n real_eval_episodes = self._eval_episodes\n else:\n real_eval_episodes = eval_episodes\n is_gymnasium_env = self.is_gymnasium_env\n\n self.eval_env.reset(seed=self.env_seed) # Fix seed\n \n self.policy.eval()\n if is_gymnasium_env:\n obs, _ = self.eval_env.reset()\n obs = self.eval_env.get_true_observation(obs)\n else:\n obs = self.eval_env.reset()\n \n eval_ep_info_buffer = []\n num_episodes = 0\n episode_reward, episode_length = 0, 0\n\n if not self.has_terminal: # don't use terminal signal, terminate when reach horizon\n while num_episodes < real_eval_episodes:\n rtg = torch.tensor([[self.goal]]).type(torch.float32)\n for timestep in range(self.horizon): # One epoch\n action = self.policy.select_action(obs.reshape(1, -1), rtg)\n if hasattr(self.eval_env, \"get_true_observation\"): # gymnasium env \n next_obs, reward, terminal, _, _ = self.eval_env.step(action.flatten())\n else:\n next_obs, reward, terminal, info = self.eval_env.step(action.flatten())\n if is_gymnasium_env:\n next_obs = self.eval_env.get_true_observation(next_obs)\n episode_reward += reward\n rtg = rtg - reward\n episode_length += 1\n\n obs = next_obs\n if self.binary_return:\n episode_reward = 1 if episode_reward > 0 else 0 # Clip to 1\n eval_ep_info_buffer.append(\n {\"episode_reward\": episode_reward, \"episode_length\": episode_length}\n )\n num_episodes +=1\n episode_reward, episode_length = 0, 0\n if is_gymnasium_env:\n obs, _ = self.eval_env.reset()\n obs = self.eval_env.get_true_observation(obs)\n else:\n obs = self.eval_env.reset()\n else:\n rtg = torch.tensor([[self.goal]]).type(torch.float32)\n while num_episodes < self._eval_episodes:\n action = self.policy.select_action(obs.reshape(1, -1), rtg)\n if hasattr(self.eval_env, \"get_true_observation\"): # gymnasium env \n next_obs, reward, terminal, _, _ = self.eval_env.step(action.flatten())\n else:\n next_obs, reward, terminal, _ = self.eval_env.step(action.flatten())\n if is_gymnasium_env:\n next_obs = self.eval_env.get_true_observation(next_obs)\n episode_reward += reward\n episode_length += 1\n\n obs = next_obs\n\n if terminal: # Episode finishes\n if self.binary_return:\n episode_reward = 1 if episode_reward > 0 else 0 # Clip to 1\n eval_ep_info_buffer.append(\n {\"episode_reward\": episode_reward, \"episode_length\": episode_length}\n )\n episode_reward, episode_length = 0, 0\n if is_gymnasium_env:\n obs, _ = self.eval_env.reset()\n obs = self.eval_env.get_true_observation(obs)\n else:\n obs = self.eval_env.reset()\n rtg = torch.tensor([[self.goal]]).type(torch.float32)\n \n return {\n \"eval/episode_reward\": [ep_info[\"episode_reward\"] for ep_info in eval_ep_info_buffer],\n \"eval/episode_length\": [ep_info[\"episode_length\"] for ep_info in eval_ep_info_buffer]\n }\n \n @ torch.no_grad()\n def validate(self, holdout_dataset: torch.utils.data.Dataset) -> Optional[float]:\n data_loader = DataLoader(\n holdout_dataset,\n batch_size = self._batch_size,\n shuffle = True,\n pin_memory = True,\n num_workers = self.num_workers\n )\n self.policy.eval()\n\n pbar = tqdm(enumerate(data_loader), total=len(data_loader))\n losses = []\n for it, batch in pbar:\n '''\n batch: dict with keys\n 'observations'\n 'next_observations'\n 'actions'\n 'terminals'\n 'rewards'\n 'rtgs'\n '''\n loss_dict = self.policy.validate(batch)\n\n for k, v in loss_dict.items():\n self.logger.logkv_mean(k, v)\n\n if \"holdout_loss\" in loss_dict:\n loss = loss_dict[\"holdout_loss\"]\n losses.append(loss)\n\n if len(losses) > 0:\n return(sum(losses) / len(losses))\n else:\n return None" }, { "identifier": "DiffusionPolicyTrainer", "path": "offlinerlkit/policy_trainer/diffusion_policy_trainer.py", "snippet": "class DiffusionPolicyTrainer:\n def __init__(\n self,\n policy: BasePolicy,\n offline_dataset: Dict[str, np.ndarray],\n logger: Logger,\n seed,\n epoch: int = 25,\n batch_size: int = 256,\n lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,\n horizon: Optional[int] = None,\n num_workers = 1,\n has_terminal = False\n ) -> None:\n '''\n offline_ratio = 0: rollout only, 1: offline only\n '''\n self.policy = policy\n self.horizon = horizon\n self.offline_dataset = offline_dataset\n self.logger = logger\n\n self._epoch = epoch\n self._batch_size = batch_size\n self.lr_scheduler = lr_scheduler\n self.num_workers = num_workers\n self.env_seed = seed\n self.has_terminal = has_terminal\n\n def train(self) -> Dict[str, float]:\n start_time = time.time()\n\n num_timesteps = 0\n last_10_performance = deque(maxlen=10)\n\n data_loader = DataLoader(\n DictDataset(self.offline_dataset),\n batch_size = self._batch_size,\n shuffle = True,\n pin_memory = True,\n num_workers = self.num_workers\n ) \n\n # train loop\n for e in range(1, self._epoch + 1):\n\n self.policy.train()\n\n pbar = tqdm(enumerate(data_loader), desc=f\"Epoch #{e}/{self._epoch}\")\n for it, batch in pbar:\n '''\n batch: dict with keys\n 'observations'\n 'next_observations'\n 'actions'\n 'terminals'\n 'rewards'\n 'rtgs'\n\n '''\n loss_dict = self.policy.learn(batch)\n pbar.set_postfix(**loss_dict)\n\n for k, v in loss_dict.items():\n self.logger.logkv_mean(k, v)\n \n num_timesteps += 1\n\n if self.lr_scheduler is not None:\n self.lr_scheduler.step()\n\n self.logger.set_timestep(num_timesteps)\n self.logger.dumpkvs(exclude=[\"dynamics_training_progress\"])\n \n # save checkpoint\n torch.save(self.policy.state_dict(), os.path.join(self.logger.checkpoint_dir, \"policy.pth\"))\n\n self.logger.log(\"total time: {:.2f}s\".format(time.time() - start_time))\n torch.save(self.policy.state_dict(), os.path.join(self.logger.model_dir, \"policy.pth\"))\n self.logger.close()\n \n return {\"last_10_performance\": np.mean(last_10_performance)}" }, { "identifier": "none_or_str", "path": "offlinerlkit/utils/none_or_str.py", "snippet": "def none_or_str(value):\n if value == 'None':\n return None\n return value" }, { "identifier": "set_up_seed", "path": "offlinerlkit/utils/set_up_seed.py", "snippet": "def set_up_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True" }, { "identifier": "SimpleDiffusionPolicy", "path": "offlinerlkit/policy/diffusion/simple_diffusion.py", "snippet": "class SimpleDiffusionPolicy(ConditionalDiffusionModel):\n '''\n Note: When loading DiffusionPolicy, also need to load scaler manually\n '''\n def __init__(\n self,\n obs_shape,\n act_shape,\n feature_dim,\n num_training_steps,\n num_diffusion_steps,\n device,\n **kwargs,\n ):\n super().__init__(\n input_dim=np.prod(act_shape),\n cond_shape_dict={\"obs\": obs_shape, \"feat\": (feature_dim,)},\n num_training_steps=num_training_steps,\n num_diffusion_steps=num_diffusion_steps,\n clip_sample=True,\n device=device,\n **kwargs,\n )\n\n def learn(self, batch: Dict):\n '''\n Update one batch\n '''\n obss = batch['observations'].type(torch.float32).to(self.device)\n actions = batch['actions'].type(torch.float32).to(self.device)\n rtgs = batch['rtgs']\n rtgs = rtgs.reshape(rtgs.shape[0], -1).type(torch.float32).to(self.device)\n if 'weights' in batch:\n weights = batch['weights'].type(torch.float32).to(self.device) # (batch, )\n else:\n weights = None\n\n return super().learn(actions, {\"obs\": obss, \"feat\": rtgs}, weights)\n\n def validate(self, batch: Dict):\n '''\n Update one batch\n '''\n obss = batch['observations'].type(torch.float32).to(self.device)\n actions = batch['actions'].type(torch.float32).to(self.device)\n rtgs = batch['rtgs']\n rtgs = rtgs.reshape(rtgs.shape[0], -1).type(torch.float32).to(self.device)\n if 'weights' in batch:\n weights = batch['weights'].type(torch.float32).to(self.device) # (batch, )\n else:\n weights = None\n\n return super().validate(actions, {\"obs\": obss, \"feat\": rtgs}, weights)\n\n def select_action(self, obs, feat):\n # print(f\"DiffusionPolicy: select action with obs shape {obs.shape}, feat(rtg) shape {feat.shape}\")\n obs = torch.as_tensor(obs, dtype = torch.float32, device = self.device)\n feat = torch.as_tensor(feat, dtype = torch.float32, device = self.device)\n\n with torch.no_grad():\n action = super().sample({\"obs\": obs, \"feat\": feat})\n # print(action)\n return action.cpu().numpy()\n\n def train(self) -> None:\n self.noise_pred_net.train()\n self.cond_encoders.train()\n\n def eval(self) -> None:\n self.noise_pred_net.eval()\n self.cond_encoders.eval()" }, { "identifier": "RcslPolicy", "path": "offlinerlkit/policy/rcsl/rcsl_mlp.py", "snippet": "class RcslPolicy(BasePolicy):\n \"\"\"\n wrapped rcsl policy\n \"\"\"\n\n def __init__(\n self,\n rcsl: RcslModule,\n rcsl_optim: torch.optim.Optimizer,\n device: Union[str, torch.device]\n ) -> None:\n super().__init__()\n\n self.rcsl = rcsl \n self.rcsl_optim = rcsl_optim\n\n self.device = device\n \n # One batch update\n def learn(self, batch: Dict) -> Dict[str, float]:\n obss, actions, rtgs = batch[\"observations\"], batch[\"actions\"], batch[\"rtgs\"]\n\n pred_actions = self.rcsl.forward(obss, rtgs)\n # Average over batch and dim, sum over ensembles.\n loss = torch.pow(pred_actions - actions.to(pred_actions.device), 2).mean() # MSE error\n\n self.rcsl_optim.zero_grad()\n loss.backward()\n self.rcsl_optim.step()\n\n result = {\n \"loss\": loss.item(),\n }\n \n return result\n\n @ torch.no_grad()\n def validate(self, batch: Dict) -> Dict[str, float]:\n obss, actions, rtgs = batch[\"observations\"], batch[\"actions\"], batch[\"rtgs\"]\n\n pred_actions = self.rcsl.forward(obss, rtgs)\n # Average over batch and dim, sum over ensembles.\n loss = torch.pow(pred_actions - actions.to(pred_actions.device), 2).mean() # MSE error\n\n result = {\n \"holdout_loss\": loss.item(),\n }\n \n return result\n \n def select_action(self, obs: np.ndarray, rtg: np.ndarray) -> np.ndarray:\n with torch.no_grad():\n action = self.rcsl.forward(obs, rtg)\n return action.cpu().numpy()\n \n def train(self) -> None:\n self.rcsl.train()\n\n def eval(self) -> None:\n self.rcsl.eval()" }, { "identifier": "create_env_dataset", "path": "envs/pointmaze/create_maze_dataset.py", "snippet": "def create_env_dataset(args):\n '''\n Create env and dataset (if not created)\n '''\n maze_config = json.load(open(args.maze_config_file, 'r'))\n maze = maze_config[\"maze\"]\n map = maze['map'] \n\n start = maze['start']\n goal = maze['goal']\n\n sample_args = maze_config[\"sample_args\"]\n\n print(f\"Create point maze\")\n point_maze = PointMaze(data_path = os.path.join(args.data_dir, args.data_file), \n horizon = args.horizon,\n maze_map = map,\n start = np.array(start),\n goal = np.array(goal),\n sample_args = sample_args,\n debug=False,\n render=False) \n env = point_maze.env_cls()\n trajs = point_maze.dataset[0]\n return env, trajs" }, { "identifier": "get_pointmaze_dataset", "path": "envs/pointmaze/utils/trajectory.py", "snippet": "def get_pointmaze_dataset(\n trajs: List,\n sample_ratio: float = 1.) -> Tuple[Dict, np.ndarray, float]:\n '''\n Return:\n dataset: Dict. key 'rtgs' is set to zero, it will not be used in training\n init_obss\n max offline return\n '''\n num_trajs = int(len(trajs) * sample_ratio)\n idxs = np.random.choice(len(trajs), size=(num_trajs), replace = False)\n valid_trajs = [trajs[i] for i in list(idxs)]\n\n obss = [traj.observations[0:-1] for traj in valid_trajs]\n next_obss = [traj.observations[1:] for traj in valid_trajs]\n acts = [traj.actions[0:-1] for traj in valid_trajs]\n rs = [traj.rewards[0:-1] for traj in valid_trajs]\n init_obss = [traj.observations[0:1] for traj in valid_trajs] # initial observations\n\n obss = np.concatenate(obss, axis=0)\n next_obss = np.concatenate(next_obss, axis=0)\n acts = np.concatenate(acts, axis=0)\n rs = np.concatenate(rs, axis=0)\n terminals = np.array([False]).repeat(obss.shape[0])\n weights = np.ones_like(rs).astype(np.float32)\n init_obss = np.concatenate(init_obss, axis=0)\n\n rets = [sum(traj.rewards) for traj in valid_trajs]\n rtgs = np.zeros_like(rs) \n\n dataset = {\n \"observations\": obss,\n \"next_observations\": next_obss,\n \"actions\": acts,\n \"rewards\": rs,\n \"rtgs\": rtgs,\n \"terminals\": terminals,\n \"weights\": weights}\n\n return dataset, init_obss, max(rets)" }, { "identifier": "PointMazeObsWrapper", "path": "envs/pointmaze/utils/maze_utils.py", "snippet": "class PointMazeObsWrapper(Wrapper):\n def __init__(self, env):\n super().__init__(env)\n self.observation_space = env.observation_space['observation']\n\n def observation(self, obs: Dict[str, np.ndarray]) -> np.ndarray:\n return obs['observation']\n \n def step(self, action):\n '''\n use truncated signal as terminal\n '''\n next_obs, reward, _, truncated, info = self.env.step(action)\n next_obs = self.observation(next_obs)\n return next_obs, reward, truncated, info\n\n def reset(self, seed=None):\n obs, _ = self.env.reset(seed=seed)\n return self.observation(obs)" } ]
import numpy as np import torch import roboverse import argparse import os import random import pickle import datetime from copy import deepcopy from typing import Dict, Tuple from collections import defaultdict from offlinerlkit.modules import EnsembleDynamicsModel, RcslModule from offlinerlkit.dynamics import EnsembleDynamics from offlinerlkit.utils.scaler import StandardScaler from offlinerlkit.utils.termination_fns import get_termination_fn from offlinerlkit.nets import MLP from offlinerlkit.utils.logger import Logger, make_log_dirs from offlinerlkit.policy_trainer import RcslPolicyTrainer, DiffusionPolicyTrainer from offlinerlkit.utils.none_or_str import none_or_str from offlinerlkit.utils.set_up_seed import set_up_seed from offlinerlkit.policy import SimpleDiffusionPolicy, RcslPolicy from envs.pointmaze.create_maze_dataset import create_env_dataset from envs.pointmaze.utils.trajectory import get_pointmaze_dataset from envs.pointmaze.utils.maze_utils import PointMazeObsWrapper
14,444
''' ''' diffusion behavior policy rollout - threshold: only keep trajs with ret > [threshold] (valid). Usually the max return in dataset - args.num_need_traj: number of valid trajectories needed. End rollout when get enough trajs - args.rollout_epoch: maximum rollout epoch. Should be large ''' device = args.device num_need_traj = args.num_need_traj rollout_data_all = None # Initialize rollout_dataset as nothing num_traj_all = 0 # Initialize total number of rollout trajs start_epoch = 0 # Default starting epoch returns_all = [] if args.rollout_ckpt_path is not None: print(f"Will save rollout trajectories to dir {args.rollout_ckpt_path}") os.makedirs(args.rollout_ckpt_path, exist_ok=True) data_path = os.path.join(args.rollout_ckpt_path, "rollout.dat") if os.path.exists(data_path): # Load ckpt_data ckpt_dict = pickle.load(open(data_path,"rb")) # checkpoint in dict type rollout_data_all = ckpt_dict['data'] # should be dict num_traj_all = ckpt_dict['num_traj'] returns_all = ckpt_dict['return'] start_epoch = ckpt_dict['epoch'] + 1 # trajs = ckpt_dict print(f"Loaded checkpoint. Already have {num_traj_all} valid trajectories, start from epoch {start_epoch}.") if num_traj_all >= num_need_traj: print(f"Checkpoint trajectories are enough. Skip rollout procedure.") return rollout_data_all, max(returns_all) # Still need training, get dynamics and rollout policy get_dynamics() get_rollout_policy() with torch.no_grad(): for epoch in range(start_epoch, args.rollout_epoch): batch_indexs = np.random.randint(0, init_obss_dataset.shape[0], size=args.rollout_batch) init_obss = init_obss_dataset[batch_indexs] rollout_data, rollout_info = rollout_simple(init_obss, dynamics, diffusion_policy, args.horizon) # print(pred_state) # Only keep trajs with returns > threshold returns = rollout_info['returns'] valid_cond = returns > threshold valid_trajs = np.arange(args.rollout_batch)[valid_cond] # np.array, indexs of all valid trajs valid_data_idxs = [rollout_data['traj_idxs'][i] in valid_trajs for i in range(rollout_data['traj_idxs'].shape[0])] for k in rollout_data: rollout_data[k] = rollout_data[k][valid_data_idxs] # Add rollout_data to rollout_data_all if rollout_data_all is None: # No trajs collected rollout_data_all = deepcopy(rollout_data) else: for k in rollout_data: rollout_data_all[k] = np.concatenate([rollout_data_all[k], rollout_data[k]], axis=0) num_traj_all += len(valid_trajs) returns_all += list(returns[valid_trajs]) print(f"-----------\nEpoch {epoch}, get {len(valid_trajs)} new trajs") logger.logkv("Epoch", epoch) logger.logkv("num_new_trajs", len(valid_trajs)) logger.logkv("num_total_trajs", num_traj_all) logger.dumpkvs() save_path = os.path.join(logger.checkpoint_dir, "rollout.dat") pickle.dump({'epoch': epoch, 'data': rollout_data_all, 'num_traj': num_traj_all, 'return': returns_all}, open(save_path, "wb")) if num_traj_all >= num_need_traj: # Get enough trajs, quit rollout print(f"End rollout. Total epochs used: {epoch+1}") break return rollout_data_all, max(returns_all) rollout_save_dir = make_log_dirs(args.task, args.algo_name, exp_name, vars(args), part="rollout") print(f"Logging diffusion rollout to {rollout_save_dir}") rollout_logger = Logger(rollout_save_dir, {"consoleout_backup": "stdout"}) rollout_logger.log_hyperparameters(vars(args)) rollout_dataset, max_rollout_return = get_rollout_trajs(rollout_logger, threshold = max_offline_return) # train set_up_seed(args.seed) rcsl_backbone = MLP( input_dim = obs_dim + 1, hidden_dims = args.rcsl_hidden_dims, output_dim = action_dim, init_last = True ) rcsl_module = RcslModule( rcsl_backbone, device = args.device ) rcsl_optim = torch.optim.Adam(rcsl_module.parameters(), lr=args.rcsl_lr, weight_decay=args.rcsl_weight_decay) rcsl_policy = RcslPolicy( rcsl_module, rcsl_optim, device = args.device ) # lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(rcsl_optim, args.rcsl_epoch) lr_scheduler=None task_name = args.task rcsl_log_dirs = make_log_dirs(task_name, args.algo_name, exp_name, vars(args), part='rcsl') # key: output file name, value: output handler type print(f"Logging autoregressive gaussian rcsl to {rcsl_log_dirs}") rcsl_output_config = { "consoleout_backup": "stdout", "policy_training_progress": "csv", "tb": "tensorboard" } rcsl_logger = Logger(rcsl_log_dirs, rcsl_output_config) rcsl_logger.log_hyperparameters(vars(args))
''' task: pointmaze ''' def get_args(): parser = argparse.ArgumentParser() # general parser.add_argument("--algo_name", type=str, default="mbrcsl") parser.add_argument("--task", type=str, default="pointmaze", help="task name") parser.add_argument("--seed", type=int, default=0) parser.add_argument("--num_workers", type=int, default=1, help="Dataloader workers, align with cpu number") parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") parser.add_argument("--last_eval", action="store_true") # env config (general) parser.add_argument('--data_dir', type=str, required=True) parser.add_argument('--horizon', type=int, default=200, help="max path length for pickplace") # env config (pointmaze) parser.add_argument('--maze_config_file', type=str, default='envs/pointmaze/config/maze_default.json') parser.add_argument('--data_file', type=str, default='pointmaze.dat') # ensemble dynamics parser.add_argument("--n-ensemble", type=int, default=7) parser.add_argument("--n-elites", type=int, default=5) parser.add_argument("--dynamics_hidden_dims", type=int, nargs='*', default=[200, 200, 200, 200]) parser.add_argument("--dynamics_weight_decay", type=float, nargs='*', default=[2.5e-5, 5e-5, 7.5e-5, 7.5e-5, 1e-4]) parser.add_argument("--dynamics_lr", type=float, default=1e-3) parser.add_argument("--load_dynamics_path", type=none_or_str, default=None) parser.add_argument("--dynamics_epoch", type=int, default=-1, help="-1 means None") # Behavior policy (diffusion) parser.add_argument("--behavior_epoch", type=int, default=50) parser.add_argument("--num_diffusion_iters", type=int, default=10, help="Number of diffusion steps") parser.add_argument('--behavior_batch', type=int, default=256) parser.add_argument('--load_diffusion_path', type=none_or_str, default=None) parser.add_argument('--sample_ratio', type=float, default=1., help="Use (sample_ratio * num_total_data) data to train diffusion policy") # Rollout parser.add_argument('--rollout_ckpt_path', type=none_or_str, default=None, help="file dir, used to load/store rollout trajs" ) parser.add_argument('--rollout_epoch', type=int, default=1000, help="Max number of epochs to rollout the policy") parser.add_argument('--num_need_traj', type=int, default=100, help="Needed valid trajs in rollout") parser.add_argument("--rollout-batch", type=int, default=200, help="Number of trajs to be sampled at one time") # RCSL policy (mlp) parser.add_argument("--rcsl_hidden_dims", type=int, nargs='*', default=[1024,1024]) parser.add_argument("--rcsl_lr", type=float, default=5e-5) parser.add_argument("--rcsl_batch", type=int, default=256) parser.add_argument("--rcsl_epoch", type=int, default=100) parser.add_argument("--rcsl_weight_decay", type=float, default=0.1) parser.add_argument("--eval_episodes", type=int, default=10) parser.add_argument("--holdout_ratio", type=float, default=0.1) parser.add_argument("--find_best_start", type=int, default=80) parser.add_argument("--improve_threshold", type=float, default=0.01) return parser.parse_args() def rollout_simple( init_obss: np.ndarray, dynamics: EnsembleDynamicsModel, rollout_policy: SimpleDiffusionPolicy, rollout_length: int ) -> Tuple[Dict[str, np.ndarray], Dict]: ''' Only serves for non-terminal cases Sample a batch of trajectories at the same time. Output rollout_transitions contain keys: obss, next_obss, actions rewards, (N,1) rtgs, (N,1) traj_idxs, (N) ''' num_transitions = 0 rewards_arr = np.array([]) rollout_transitions = defaultdict(list) batch_size = init_obss.shape[0] valid_idxs = np.arange(init_obss.shape[0]) # maintain current valid trajectory indexes returns = np.zeros(init_obss.shape[0]) # maintain return of each trajectory acc_returns = np.zeros(init_obss.shape[0]) # maintain accumulated return of each valid trajectory max_rewards = np.zeros(init_obss.shape[0]) # maintain max reward seen in trajectory rewards_full = np.zeros((init_obss.shape[0], rollout_length)) # full rewards (batch, H) # rollout observations = init_obss goal = np.zeros((init_obss.shape[0],1), dtype = np.float32) for t in range(rollout_length): actions = rollout_policy.select_action(observations, goal) next_observations, rewards, terminals, info = dynamics.step(observations, actions) rollout_transitions["observations"].append(observations) rollout_transitions["next_observations"].append(next_observations) rollout_transitions["actions"].append(actions) rollout_transitions["rewards"].append(rewards) rollout_transitions["terminals"].append(terminals) rollout_transitions["traj_idxs"].append(valid_idxs) rollout_transitions["acc_rets"].append(acc_returns) rewards = rewards.reshape(batch_size) # (B) rewards_full[:, t] = rewards num_transitions += len(observations) rewards_arr = np.append(rewards_arr, rewards.flatten()) returns = returns + rewards.flatten() # Update return (for valid idxs only) max_rewards = np.maximum(max_rewards, rewards.flatten()) # Update max reward acc_returns = acc_returns + rewards.flatten() observations = deepcopy(next_observations) for k, v in rollout_transitions.items(): rollout_transitions[k] = np.concatenate(v, axis=0) traj_idxs = rollout_transitions["traj_idxs"] rtgs = returns[traj_idxs] - rollout_transitions["acc_rets"] # rtgs = returns[traj_idxs] rollout_transitions["rtgs"] = rtgs[..., None] # (N,1) return rollout_transitions, \ {"num_transitions": num_transitions, "reward_mean": rewards_arr.mean(), "returns": returns, "max_rewards": max_rewards, "rewards_full": rewards_full} def train(args=get_args()): set_up_seed(args.seed) # create env and dataset if args.task == 'pointmaze': env, trajs = create_env_dataset(args) env = PointMazeObsWrapper(env) obs_space = env.observation_space args.obs_shape = obs_space.shape obs_dim = np.prod(args.obs_shape) args.action_shape = env.action_space.shape action_dim = np.prod(args.action_shape) diff_dataset, _, _ = get_pointmaze_dataset( trajs, sample_ratio =args.sample_ratio) dyn_dataset, init_obss_dataset, max_offline_return = get_pointmaze_dataset(trajs) else: raise NotImplementedError env.reset(seed=args.seed) timestamp = datetime.datetime.now().strftime("%y-%m%d-%H%M%S") exp_name = f"timestamp_{timestamp}&{args.seed}" log_dirs = make_log_dirs(args.task, args.algo_name, exp_name, vars(args), part = "dynamics") # key: output file name, value: output handler type print(f"Logging dynamics to {log_dirs}") output_config = { "consoleout_backup": "stdout", "policy_training_progress": "csv", "dynamics_training_progress": "csv", "tb": "tensorboard" } logger = Logger(log_dirs, output_config) logger.log_hyperparameters(vars(args)) dynamics_model = EnsembleDynamicsModel( obs_dim=obs_dim, action_dim=action_dim, hidden_dims=args.dynamics_hidden_dims, num_ensemble=args.n_ensemble, num_elites=args.n_elites, weight_decays=args.dynamics_weight_decay, device=args.device ) dynamics_optim = torch.optim.Adam( dynamics_model.parameters(), lr=args.dynamics_lr ) scaler = StandardScaler() termination_fn = get_termination_fn(task=args.task) dynamics = EnsembleDynamics( dynamics_model, dynamics_optim, scaler, termination_fn ) # create rollout policy diffusion_policy = SimpleDiffusionPolicy( obs_shape = args.obs_shape, act_shape= args.action_shape, feature_dim = 1, num_training_steps = args.behavior_epoch, num_diffusion_steps = args.num_diffusion_iters, device = args.device ) diff_lr_scheduler = diffusion_policy.get_lr_scheduler() diff_log_dirs = make_log_dirs(args.task, args.algo_name, exp_name, vars(args), part="diffusion") print(f"Logging diffusion to {diff_log_dirs}") # key: output file name, value: output handler type diff_output_config = { "consoleout_backup": "stdout", "policy_training_progress": "csv", "dynamics_training_progress": "csv", "tb": "tensorboard" } diff_logger = Logger(diff_log_dirs, diff_output_config) diff_logger.log_hyperparameters(vars(args)) diff_policy_trainer = DiffusionPolicyTrainer( policy = diffusion_policy, offline_dataset = diff_dataset, logger = diff_logger, seed = args.seed, epoch = args.behavior_epoch, batch_size = args.behavior_batch, lr_scheduler = diff_lr_scheduler, horizon = args.horizon, num_workers = args.num_workers, has_terminal = False, ) # Training helper functions def get_dynamics(): ''' Load or train dynamics model ''' if args.load_dynamics_path: print(f"Load dynamics from {args.load_dynamics_path}") dynamics.load(args.load_dynamics_path) else: print(f"Train dynamics") if args.dynamics_epoch == -1: max_epochs = None else: max_epochs = args.dynamics_epoch dynamics.train(dyn_dataset, logger, max_epochs = max_epochs) def get_rollout_policy(): ''' Load or train rollout policy Return: rollout policy ''' if args.load_diffusion_path is not None: print(f"Load behavior policy from {args.load_diffusion_path}") with open(args.load_diffusion_path, 'rb') as f: state_dict = torch.load(f, map_location= args.device) diffusion_policy.load_state_dict(state_dict) else: print(f"Train diffusion behavior policy") diff_policy_trainer.train() # save checkpoint periodically def get_rollout_trajs(logger: Logger, threshold) -> Tuple[Dict[str, np.ndarray], float]: ''' Rollout trajectories or load existing trajectories. If rollout, call `get_rollout_policy()` and `get_dynamics()` first to get rollout policy and dynamics Return: rollout trajectories ''' ''' diffusion behavior policy rollout - threshold: only keep trajs with ret > [threshold] (valid). Usually the max return in dataset - args.num_need_traj: number of valid trajectories needed. End rollout when get enough trajs - args.rollout_epoch: maximum rollout epoch. Should be large ''' device = args.device num_need_traj = args.num_need_traj rollout_data_all = None # Initialize rollout_dataset as nothing num_traj_all = 0 # Initialize total number of rollout trajs start_epoch = 0 # Default starting epoch returns_all = [] if args.rollout_ckpt_path is not None: print(f"Will save rollout trajectories to dir {args.rollout_ckpt_path}") os.makedirs(args.rollout_ckpt_path, exist_ok=True) data_path = os.path.join(args.rollout_ckpt_path, "rollout.dat") if os.path.exists(data_path): # Load ckpt_data ckpt_dict = pickle.load(open(data_path,"rb")) # checkpoint in dict type rollout_data_all = ckpt_dict['data'] # should be dict num_traj_all = ckpt_dict['num_traj'] returns_all = ckpt_dict['return'] start_epoch = ckpt_dict['epoch'] + 1 # trajs = ckpt_dict print(f"Loaded checkpoint. Already have {num_traj_all} valid trajectories, start from epoch {start_epoch}.") if num_traj_all >= num_need_traj: print(f"Checkpoint trajectories are enough. Skip rollout procedure.") return rollout_data_all, max(returns_all) # Still need training, get dynamics and rollout policy get_dynamics() get_rollout_policy() with torch.no_grad(): for epoch in range(start_epoch, args.rollout_epoch): batch_indexs = np.random.randint(0, init_obss_dataset.shape[0], size=args.rollout_batch) init_obss = init_obss_dataset[batch_indexs] rollout_data, rollout_info = rollout_simple(init_obss, dynamics, diffusion_policy, args.horizon) # print(pred_state) # Only keep trajs with returns > threshold returns = rollout_info['returns'] valid_cond = returns > threshold valid_trajs = np.arange(args.rollout_batch)[valid_cond] # np.array, indexs of all valid trajs valid_data_idxs = [rollout_data['traj_idxs'][i] in valid_trajs for i in range(rollout_data['traj_idxs'].shape[0])] for k in rollout_data: rollout_data[k] = rollout_data[k][valid_data_idxs] # Add rollout_data to rollout_data_all if rollout_data_all is None: # No trajs collected rollout_data_all = deepcopy(rollout_data) else: for k in rollout_data: rollout_data_all[k] = np.concatenate([rollout_data_all[k], rollout_data[k]], axis=0) num_traj_all += len(valid_trajs) returns_all += list(returns[valid_trajs]) print(f"-----------\nEpoch {epoch}, get {len(valid_trajs)} new trajs") logger.logkv("Epoch", epoch) logger.logkv("num_new_trajs", len(valid_trajs)) logger.logkv("num_total_trajs", num_traj_all) logger.dumpkvs() save_path = os.path.join(logger.checkpoint_dir, "rollout.dat") pickle.dump({'epoch': epoch, 'data': rollout_data_all, 'num_traj': num_traj_all, 'return': returns_all}, open(save_path, "wb")) if num_traj_all >= num_need_traj: # Get enough trajs, quit rollout print(f"End rollout. Total epochs used: {epoch+1}") break return rollout_data_all, max(returns_all) rollout_save_dir = make_log_dirs(args.task, args.algo_name, exp_name, vars(args), part="rollout") print(f"Logging diffusion rollout to {rollout_save_dir}") rollout_logger = Logger(rollout_save_dir, {"consoleout_backup": "stdout"}) rollout_logger.log_hyperparameters(vars(args)) rollout_dataset, max_rollout_return = get_rollout_trajs(rollout_logger, threshold = max_offline_return) # train set_up_seed(args.seed) rcsl_backbone = MLP( input_dim = obs_dim + 1, hidden_dims = args.rcsl_hidden_dims, output_dim = action_dim, init_last = True ) rcsl_module = RcslModule( rcsl_backbone, device = args.device ) rcsl_optim = torch.optim.Adam(rcsl_module.parameters(), lr=args.rcsl_lr, weight_decay=args.rcsl_weight_decay) rcsl_policy = RcslPolicy( rcsl_module, rcsl_optim, device = args.device ) # lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(rcsl_optim, args.rcsl_epoch) lr_scheduler=None task_name = args.task rcsl_log_dirs = make_log_dirs(task_name, args.algo_name, exp_name, vars(args), part='rcsl') # key: output file name, value: output handler type print(f"Logging autoregressive gaussian rcsl to {rcsl_log_dirs}") rcsl_output_config = { "consoleout_backup": "stdout", "policy_training_progress": "csv", "tb": "tensorboard" } rcsl_logger = Logger(rcsl_log_dirs, rcsl_output_config) rcsl_logger.log_hyperparameters(vars(args))
policy_trainer = RcslPolicyTrainer(
8
2023-10-11 08:36:06+00:00
24k
lmb-freiburg/ldce
ldm/models/diffusion/dpm_solver/sampler.py
[ { "identifier": "NoiseScheduleVP", "path": "ldm/models/diffusion/dpm_solver/dpm_solver.py", "snippet": "class NoiseScheduleVP:\n def __init__(\n self,\n schedule='discrete',\n betas=None,\n alphas_cumprod=None,\n continuous_beta_0=0.1,\n continuous_beta_1=20.,\n ):\n \"\"\"Create a wrapper class for the forward SDE (VP type).\n\n ***\n Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.\n We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.\n ***\n\n The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).\n We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).\n Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:\n\n log_alpha_t = self.marginal_log_mean_coeff(t)\n sigma_t = self.marginal_std(t)\n lambda_t = self.marginal_lambda(t)\n\n Moreover, as lambda(t) is an invertible function, we also support its inverse function:\n\n t = self.inverse_lambda(lambda_t)\n\n ===============================================================\n\n We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).\n\n 1. For discrete-time DPMs:\n\n For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:\n t_i = (i + 1) / N\n e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.\n We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.\n\n Args:\n betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)\n alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)\n\n Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.\n\n **Important**: Please pay special attention for the args for `alphas_cumprod`:\n The `alphas_cumprod` is the \\hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that\n q_{t_n | 0}(x_{t_n} | x_0) = N ( \\sqrt{\\hat{alpha_n}} * x_0, (1 - \\hat{alpha_n}) * I ).\n Therefore, the notation \\hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have\n alpha_{t_n} = \\sqrt{\\hat{alpha_n}},\n and\n log(alpha_{t_n}) = 0.5 * log(\\hat{alpha_n}).\n\n\n 2. For continuous-time DPMs:\n\n We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise\n schedule are the default settings in DDPM and improved-DDPM:\n\n Args:\n beta_min: A `float` number. The smallest beta for the linear schedule.\n beta_max: A `float` number. The largest beta for the linear schedule.\n cosine_s: A `float` number. The hyperparameter in the cosine schedule.\n cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.\n T: A `float` number. The ending time of the forward process.\n\n ===============================================================\n\n Args:\n schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,\n 'linear' or 'cosine' for continuous-time DPMs.\n Returns:\n A wrapper object of the forward SDE (VP type).\n \n ===============================================================\n\n Example:\n\n # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):\n >>> ns = NoiseScheduleVP('discrete', betas=betas)\n\n # For discrete-time DPMs, given alphas_cumprod (the \\hat{alpha_n} array for n = 0, 1, ..., N - 1):\n >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)\n\n # For continuous-time DPMs (VPSDE), linear schedule:\n >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)\n\n \"\"\"\n\n if schedule not in ['discrete', 'linear', 'cosine']:\n raise ValueError(\"Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'\".format(schedule))\n\n self.schedule = schedule\n if schedule == 'discrete':\n if betas is not None:\n log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)\n else:\n assert alphas_cumprod is not None\n log_alphas = 0.5 * torch.log(alphas_cumprod)\n self.total_N = len(log_alphas)\n self.T = 1.\n self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))\n self.log_alpha_array = log_alphas.reshape((1, -1,))\n else:\n self.total_N = 1000\n self.beta_0 = continuous_beta_0\n self.beta_1 = continuous_beta_1\n self.cosine_s = 0.008\n self.cosine_beta_max = 999.\n self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s\n self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))\n self.schedule = schedule\n if schedule == 'cosine':\n # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.\n # Note that T = 0.9946 may be not the optimal setting. However, we find it works well.\n self.T = 0.9946\n else:\n self.T = 1.\n\n def marginal_log_mean_coeff(self, t):\n \"\"\"\n Compute log(alpha_t) of a given continuous-time label t in [0, T].\n \"\"\"\n if self.schedule == 'discrete':\n return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1))\n elif self.schedule == 'linear':\n return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0\n elif self.schedule == 'cosine':\n log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))\n log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0\n return log_alpha_t\n\n def marginal_alpha(self, t):\n \"\"\"\n Compute alpha_t of a given continuous-time label t in [0, T].\n \"\"\"\n return torch.exp(self.marginal_log_mean_coeff(t))\n\n def marginal_std(self, t):\n \"\"\"\n Compute sigma_t of a given continuous-time label t in [0, T].\n \"\"\"\n return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))\n\n def marginal_lambda(self, t):\n \"\"\"\n Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].\n \"\"\"\n log_mean_coeff = self.marginal_log_mean_coeff(t)\n log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))\n return log_mean_coeff - log_std\n\n def inverse_lambda(self, lamb):\n \"\"\"\n Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.\n \"\"\"\n if self.schedule == 'linear':\n tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))\n Delta = self.beta_0**2 + tmp\n return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)\n elif self.schedule == 'discrete':\n log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)\n t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1]))\n return t.reshape((-1,))\n else:\n log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))\n t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s\n t = t_fn(log_alpha)\n return t" }, { "identifier": "model_wrapper", "path": "ldm/models/diffusion/dpm_solver/dpm_solver.py", "snippet": "def model_wrapper(\n model,\n noise_schedule,\n model_type=\"noise\",\n model_kwargs={},\n guidance_type=\"uncond\",\n condition=None,\n unconditional_condition=None,\n guidance_scale=1.,\n classifier_fn=None,\n classifier_kwargs={},\n):\n \"\"\"Create a wrapper function for the noise prediction model.\n\n DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to\n firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.\n\n We support four types of the diffusion model by setting `model_type`:\n\n 1. \"noise\": noise prediction model. (Trained by predicting noise).\n\n 2. \"x_start\": data prediction model. (Trained by predicting the data x_0 at time 0).\n\n 3. \"v\": velocity prediction model. (Trained by predicting the velocity).\n The \"v\" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].\n\n [1] Salimans, Tim, and Jonathan Ho. \"Progressive distillation for fast sampling of diffusion models.\"\n arXiv preprint arXiv:2202.00512 (2022).\n [2] Ho, Jonathan, et al. \"Imagen Video: High Definition Video Generation with Diffusion Models.\"\n arXiv preprint arXiv:2210.02303 (2022).\n \n 4. \"score\": marginal score function. (Trained by denoising score matching).\n Note that the score function and the noise prediction model follows a simple relationship:\n ```\n noise(x_t, t) = -sigma_t * score(x_t, t)\n ```\n\n We support three types of guided sampling by DPMs by setting `guidance_type`:\n 1. \"uncond\": unconditional sampling by DPMs.\n The input `model` has the following format:\n ``\n model(x, t_input, **model_kwargs) -> noise | x_start | v | score\n ``\n\n 2. \"classifier\": classifier guidance sampling [3] by DPMs and another classifier.\n The input `model` has the following format:\n ``\n model(x, t_input, **model_kwargs) -> noise | x_start | v | score\n `` \n\n The input `classifier_fn` has the following format:\n ``\n classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)\n ``\n\n [3] P. Dhariwal and A. Q. Nichol, \"Diffusion models beat GANs on image synthesis,\"\n in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.\n\n 3. \"classifier-free\": classifier-free guidance sampling by conditional DPMs.\n The input `model` has the following format:\n ``\n model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score\n `` \n And if cond == `unconditional_condition`, the model output is the unconditional DPM output.\n\n [4] Ho, Jonathan, and Tim Salimans. \"Classifier-free diffusion guidance.\"\n arXiv preprint arXiv:2207.12598 (2022).\n \n\n The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)\n or continuous-time labels (i.e. epsilon to T).\n\n We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:\n ``\n def model_fn(x, t_continuous) -> noise:\n t_input = get_model_input_time(t_continuous)\n return noise_pred(model, x, t_input, **model_kwargs) \n ``\n where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.\n\n ===============================================================\n\n Args:\n model: A diffusion model with the corresponding format described above.\n noise_schedule: A noise schedule object, such as NoiseScheduleVP.\n model_type: A `str`. The parameterization type of the diffusion model.\n \"noise\" or \"x_start\" or \"v\" or \"score\".\n model_kwargs: A `dict`. A dict for the other inputs of the model function.\n guidance_type: A `str`. The type of the guidance for sampling.\n \"uncond\" or \"classifier\" or \"classifier-free\".\n condition: A pytorch tensor. The condition for the guided sampling.\n Only used for \"classifier\" or \"classifier-free\" guidance type.\n unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.\n Only used for \"classifier-free\" guidance type.\n guidance_scale: A `float`. The scale for the guided sampling.\n classifier_fn: A classifier function. Only used for the classifier guidance.\n classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.\n Returns:\n A noise prediction model that accepts the noised data and the continuous time as the inputs.\n \"\"\"\n\n def get_model_input_time(t_continuous):\n \"\"\"\n Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.\n For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].\n For continuous-time DPMs, we just use `t_continuous`.\n \"\"\"\n if noise_schedule.schedule == 'discrete':\n return (t_continuous - 1. / noise_schedule.total_N) * 1000.\n else:\n return t_continuous\n\n def noise_pred_fn(x, t_continuous, cond=None):\n if t_continuous.reshape((-1,)).shape[0] == 1:\n t_continuous = t_continuous.expand((x.shape[0]))\n t_input = get_model_input_time(t_continuous)\n if cond is None:\n output = model(x, t_input, **model_kwargs)\n else:\n output = model(x, t_input, cond, **model_kwargs)\n if model_type == \"noise\":\n return output\n elif model_type == \"x_start\":\n alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)\n dims = x.dim()\n return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)\n elif model_type == \"v\":\n alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)\n dims = x.dim()\n return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x\n elif model_type == \"score\":\n sigma_t = noise_schedule.marginal_std(t_continuous)\n dims = x.dim()\n return -expand_dims(sigma_t, dims) * output\n\n def cond_grad_fn(x, t_input):\n \"\"\"\n Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).\n \"\"\"\n with torch.enable_grad():\n x_in = x.detach().requires_grad_(True)\n log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)\n return torch.autograd.grad(log_prob.sum(), x_in)[0]\n\n def model_fn(x, t_continuous):\n \"\"\"\n The noise predicition model function that is used for DPM-Solver.\n \"\"\"\n if t_continuous.reshape((-1,)).shape[0] == 1:\n t_continuous = t_continuous.expand((x.shape[0]))\n if guidance_type == \"uncond\":\n return noise_pred_fn(x, t_continuous)\n elif guidance_type == \"classifier\":\n assert classifier_fn is not None\n t_input = get_model_input_time(t_continuous)\n cond_grad = cond_grad_fn(x, t_input)\n sigma_t = noise_schedule.marginal_std(t_continuous)\n noise = noise_pred_fn(x, t_continuous)\n return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad\n elif guidance_type == \"classifier-free\":\n if guidance_scale == 1. or unconditional_condition is None:\n return noise_pred_fn(x, t_continuous, cond=condition)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t_continuous] * 2)\n c_in = torch.cat([unconditional_condition, condition])\n noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)\n return noise_uncond + guidance_scale * (noise - noise_uncond)\n\n assert model_type in [\"noise\", \"x_start\", \"v\"]\n assert guidance_type in [\"uncond\", \"classifier\", \"classifier-free\"]\n return model_fn" }, { "identifier": "DPM_Solver", "path": "ldm/models/diffusion/dpm_solver/dpm_solver.py", "snippet": "class DPM_Solver:\n def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.):\n \"\"\"Construct a DPM-Solver. \n\n We support both the noise prediction model (\"predicting epsilon\") and the data prediction model (\"predicting x0\").\n If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver).\n If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++).\n In such case, we further support the \"dynamic thresholding\" in [1] when `thresholding` is True.\n The \"dynamic thresholding\" can greatly improve the sample quality for pixel-space DPMs with large guidance scales.\n\n Args:\n model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]):\n ``\n def model_fn(x, t_continuous):\n return noise\n ``\n noise_schedule: A noise schedule object, such as NoiseScheduleVP.\n predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model.\n thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the \"dynamic thresholding\" in [1].\n max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding.\n \n [1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b.\n \"\"\"\n self.model = model_fn\n self.noise_schedule = noise_schedule\n self.predict_x0 = predict_x0\n self.thresholding = thresholding\n self.max_val = max_val\n\n def noise_prediction_fn(self, x, t):\n \"\"\"\n Return the noise prediction model.\n \"\"\"\n return self.model(x, t)\n\n def data_prediction_fn(self, x, t):\n \"\"\"\n Return the data prediction model (with thresholding).\n \"\"\"\n noise = self.noise_prediction_fn(x, t)\n dims = x.dim()\n alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)\n x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)\n if self.thresholding:\n p = 0.995 # A hyperparameter in the paper of \"Imagen\" [1].\n s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)\n s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)\n x0 = torch.clamp(x0, -s, s) / s\n return x0\n\n def model_fn(self, x, t):\n \"\"\"\n Convert the model to the noise prediction model or the data prediction model. \n \"\"\"\n if self.predict_x0:\n return self.data_prediction_fn(x, t)\n else:\n return self.noise_prediction_fn(x, t)\n\n def get_time_steps(self, skip_type, t_T, t_0, N, device):\n \"\"\"Compute the intermediate time steps for sampling.\n\n Args:\n skip_type: A `str`. The type for the spacing of the time steps. We support three types:\n - 'logSNR': uniform logSNR for the time steps.\n - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)\n - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)\n t_T: A `float`. The starting time of the sampling (default is T).\n t_0: A `float`. The ending time of the sampling (default is epsilon).\n N: A `int`. The total number of the spacing of the time steps.\n device: A torch device.\n Returns:\n A pytorch tensor of the time steps, with the shape (N + 1,).\n \"\"\"\n if skip_type == 'logSNR':\n lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))\n lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))\n logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)\n return self.noise_schedule.inverse_lambda(logSNR_steps)\n elif skip_type == 'time_uniform':\n return torch.linspace(t_T, t_0, N + 1).to(device)\n elif skip_type == 'time_quadratic':\n t_order = 2\n t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)\n return t\n else:\n raise ValueError(\"Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'\".format(skip_type))\n\n def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):\n \"\"\"\n Get the order of each step for sampling by the singlestep DPM-Solver.\n\n We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as \"DPM-Solver-fast\".\n Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:\n - If order == 1:\n We take `steps` of DPM-Solver-1 (i.e. DDIM).\n - If order == 2:\n - Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling.\n - If steps % 2 == 0, we use K steps of DPM-Solver-2.\n - If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1.\n - If order == 3:\n - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.\n - If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1.\n - If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1.\n - If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2.\n\n ============================================\n Args:\n order: A `int`. The max order for the solver (2 or 3).\n steps: A `int`. The total number of function evaluations (NFE).\n skip_type: A `str`. The type for the spacing of the time steps. We support three types:\n - 'logSNR': uniform logSNR for the time steps.\n - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.)\n - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.)\n t_T: A `float`. The starting time of the sampling (default is T).\n t_0: A `float`. The ending time of the sampling (default is epsilon).\n device: A torch device.\n Returns:\n orders: A list of the solver order of each step.\n \"\"\"\n if order == 3:\n K = steps // 3 + 1\n if steps % 3 == 0:\n orders = [3,] * (K - 2) + [2, 1]\n elif steps % 3 == 1:\n orders = [3,] * (K - 1) + [1]\n else:\n orders = [3,] * (K - 1) + [2]\n elif order == 2:\n if steps % 2 == 0:\n K = steps // 2\n orders = [2,] * K\n else:\n K = steps // 2 + 1\n orders = [2,] * (K - 1) + [1]\n elif order == 1:\n K = 1\n orders = [1,] * steps\n else:\n raise ValueError(\"'order' must be '1' or '2' or '3'.\")\n if skip_type == 'logSNR':\n # To reproduce the results in DPM-Solver paper\n timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)\n else:\n timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders)).to(device)]\n return timesteps_outer, orders\n\n def denoise_to_zero_fn(self, x, s):\n \"\"\"\n Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization. \n \"\"\"\n return self.data_prediction_fn(x, s)\n\n def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):\n \"\"\"\n DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.\n\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n s: A pytorch tensor. The starting time, with the shape (x.shape[0],).\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n model_s: A pytorch tensor. The model function evaluated at time `s`.\n If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.\n return_intermediate: A `bool`. If true, also return the model value at time `s`.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n ns = self.noise_schedule\n dims = x.dim()\n lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)\n h = lambda_t - lambda_s\n log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t)\n sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t)\n alpha_t = torch.exp(log_alpha_t)\n\n if self.predict_x0:\n phi_1 = torch.expm1(-h)\n if model_s is None:\n model_s = self.model_fn(x, s)\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n )\n if return_intermediate:\n return x_t, {'model_s': model_s}\n else:\n return x_t\n else:\n phi_1 = torch.expm1(h)\n if model_s is None:\n model_s = self.model_fn(x, s)\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n )\n if return_intermediate:\n return x_t, {'model_s': model_s}\n else:\n return x_t\n\n def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False, solver_type='dpm_solver'):\n \"\"\"\n Singlestep solver DPM-Solver-2 from time `s` to time `t`.\n\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n s: A pytorch tensor. The starting time, with the shape (x.shape[0],).\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n r1: A `float`. The hyperparameter of the second-order solver.\n model_s: A pytorch tensor. The model function evaluated at time `s`.\n If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.\n return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n if solver_type not in ['dpm_solver', 'taylor']:\n raise ValueError(\"'solver_type' must be either 'dpm_solver' or 'taylor', got {}\".format(solver_type))\n if r1 is None:\n r1 = 0.5\n ns = self.noise_schedule\n dims = x.dim()\n lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)\n h = lambda_t - lambda_s\n lambda_s1 = lambda_s + r1 * h\n s1 = ns.inverse_lambda(lambda_s1)\n log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(t)\n sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)\n alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)\n\n if self.predict_x0:\n phi_11 = torch.expm1(-r1 * h)\n phi_1 = torch.expm1(-h)\n\n if model_s is None:\n model_s = self.model_fn(x, s)\n x_s1 = (\n expand_dims(sigma_s1 / sigma_s, dims) * x\n - expand_dims(alpha_s1 * phi_11, dims) * model_s\n )\n model_s1 = self.model_fn(x_s1, s1)\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)\n )\n elif solver_type == 'taylor':\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (model_s1 - model_s)\n )\n else:\n phi_11 = torch.expm1(r1 * h)\n phi_1 = torch.expm1(h)\n\n if model_s is None:\n model_s = self.model_fn(x, s)\n x_s1 = (\n expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x\n - expand_dims(sigma_s1 * phi_11, dims) * model_s\n )\n model_s1 = self.model_fn(x_s1, s1)\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)\n )\n elif solver_type == 'taylor':\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)\n )\n if return_intermediate:\n return x_t, {'model_s': model_s, 'model_s1': model_s1}\n else:\n return x_t\n\n def singlestep_dpm_solver_third_update(self, x, s, t, r1=1./3., r2=2./3., model_s=None, model_s1=None, return_intermediate=False, solver_type='dpm_solver'):\n \"\"\"\n Singlestep solver DPM-Solver-3 from time `s` to time `t`.\n\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n s: A pytorch tensor. The starting time, with the shape (x.shape[0],).\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n r1: A `float`. The hyperparameter of the third-order solver.\n r2: A `float`. The hyperparameter of the third-order solver.\n model_s: A pytorch tensor. The model function evaluated at time `s`.\n If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.\n model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).\n If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.\n return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n if solver_type not in ['dpm_solver', 'taylor']:\n raise ValueError(\"'solver_type' must be either 'dpm_solver' or 'taylor', got {}\".format(solver_type))\n if r1 is None:\n r1 = 1. / 3.\n if r2 is None:\n r2 = 2. / 3.\n ns = self.noise_schedule\n dims = x.dim()\n lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)\n h = lambda_t - lambda_s\n lambda_s1 = lambda_s + r1 * h\n lambda_s2 = lambda_s + r2 * h\n s1 = ns.inverse_lambda(lambda_s1)\n s2 = ns.inverse_lambda(lambda_s2)\n log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)\n sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(s2), ns.marginal_std(t)\n alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)\n\n if self.predict_x0:\n phi_11 = torch.expm1(-r1 * h)\n phi_12 = torch.expm1(-r2 * h)\n phi_1 = torch.expm1(-h)\n phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.\n phi_2 = phi_1 / h + 1.\n phi_3 = phi_2 / h - 0.5\n\n if model_s is None:\n model_s = self.model_fn(x, s)\n if model_s1 is None:\n x_s1 = (\n expand_dims(sigma_s1 / sigma_s, dims) * x\n - expand_dims(alpha_s1 * phi_11, dims) * model_s\n )\n model_s1 = self.model_fn(x_s1, s1)\n x_s2 = (\n expand_dims(sigma_s2 / sigma_s, dims) * x\n - expand_dims(alpha_s2 * phi_12, dims) * model_s\n + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)\n )\n model_s2 = self.model_fn(x_s2, s2)\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)\n )\n elif solver_type == 'taylor':\n D1_0 = (1. / r1) * (model_s1 - model_s)\n D1_1 = (1. / r2) * (model_s2 - model_s)\n D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)\n D2 = 2. * (D1_1 - D1_0) / (r2 - r1)\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n + expand_dims(alpha_t * phi_2, dims) * D1\n - expand_dims(alpha_t * phi_3, dims) * D2\n )\n else:\n phi_11 = torch.expm1(r1 * h)\n phi_12 = torch.expm1(r2 * h)\n phi_1 = torch.expm1(h)\n phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.\n phi_2 = phi_1 / h - 1.\n phi_3 = phi_2 / h - 0.5\n\n if model_s is None:\n model_s = self.model_fn(x, s)\n if model_s1 is None:\n x_s1 = (\n expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x\n - expand_dims(sigma_s1 * phi_11, dims) * model_s\n )\n model_s1 = self.model_fn(x_s1, s1)\n x_s2 = (\n expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x\n - expand_dims(sigma_s2 * phi_12, dims) * model_s\n - r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s)\n )\n model_s2 = self.model_fn(x_s2, s2)\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n - (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s)\n )\n elif solver_type == 'taylor':\n D1_0 = (1. / r1) * (model_s1 - model_s)\n D1_1 = (1. / r2) * (model_s2 - model_s)\n D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)\n D2 = 2. * (D1_1 - D1_0) / (r2 - r1)\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n - expand_dims(sigma_t * phi_2, dims) * D1\n - expand_dims(sigma_t * phi_3, dims) * D2\n )\n\n if return_intermediate:\n return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2}\n else:\n return x_t\n\n def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type=\"dpm_solver\"):\n \"\"\"\n Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.\n\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n model_prev_list: A list of pytorch tensor. The previous computed model values.\n t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n if solver_type not in ['dpm_solver', 'taylor']:\n raise ValueError(\"'solver_type' must be either 'dpm_solver' or 'taylor', got {}\".format(solver_type))\n ns = self.noise_schedule\n dims = x.dim()\n model_prev_1, model_prev_0 = model_prev_list\n t_prev_1, t_prev_0 = t_prev_list\n lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)\n log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)\n sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)\n alpha_t = torch.exp(log_alpha_t)\n\n h_0 = lambda_prev_0 - lambda_prev_1\n h = lambda_t - lambda_prev_0\n r0 = h_0 / h\n D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)\n if self.predict_x0:\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(sigma_t / sigma_prev_0, dims) * x\n - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0\n - 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0\n )\n elif solver_type == 'taylor':\n x_t = (\n expand_dims(sigma_t / sigma_prev_0, dims) * x\n - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0\n + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0\n )\n else:\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x\n - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0\n - 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0\n )\n elif solver_type == 'taylor':\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x\n - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0\n - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0\n )\n return x_t\n\n def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'):\n \"\"\"\n Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.\n\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n model_prev_list: A list of pytorch tensor. The previous computed model values.\n t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n ns = self.noise_schedule\n dims = x.dim()\n model_prev_2, model_prev_1, model_prev_0 = model_prev_list\n t_prev_2, t_prev_1, t_prev_0 = t_prev_list\n lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda(t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t)\n log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)\n sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)\n alpha_t = torch.exp(log_alpha_t)\n\n h_1 = lambda_prev_1 - lambda_prev_2\n h_0 = lambda_prev_0 - lambda_prev_1\n h = lambda_t - lambda_prev_0\n r0, r1 = h_0 / h, h_1 / h\n D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1)\n D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2)\n D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1)\n D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1)\n if self.predict_x0:\n x_t = (\n expand_dims(sigma_t / sigma_prev_0, dims) * x\n - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0\n + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1\n - expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h**2 - 0.5), dims) * D2\n )\n else:\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x\n - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0\n - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1\n - expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h**2 - 0.5), dims) * D2\n )\n return x_t\n\n def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None, r2=None):\n \"\"\"\n Singlestep DPM-Solver with the order `order` from time `s` to time `t`.\n\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n s: A pytorch tensor. The starting time, with the shape (x.shape[0],).\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.\n return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n r1: A `float`. The hyperparameter of the second-order or third-order solver.\n r2: A `float`. The hyperparameter of the third-order solver.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n if order == 1:\n return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate)\n elif order == 2:\n return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate, solver_type=solver_type, r1=r1)\n elif order == 3:\n return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate, solver_type=solver_type, r1=r1, r2=r2)\n else:\n raise ValueError(\"Solver order must be 1 or 2 or 3, got {}\".format(order))\n\n def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'):\n \"\"\"\n Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.\n\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n model_prev_list: A list of pytorch tensor. The previous computed model values.\n t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],)\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3.\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n if order == 1:\n return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1])\n elif order == 2:\n return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)\n elif order == 3:\n return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type)\n else:\n raise ValueError(\"Solver order must be 1 or 2 or 3, got {}\".format(order))\n\n def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5, solver_type='dpm_solver'):\n \"\"\"\n The adaptive step size solver based on singlestep DPM-Solver.\n\n Args:\n x: A pytorch tensor. The initial value at time `t_T`.\n order: A `int`. The (higher) order of the solver. We only support order == 2 or 3.\n t_T: A `float`. The starting time of the sampling (default is T).\n t_0: A `float`. The ending time of the sampling (default is epsilon).\n h_init: A `float`. The initial step size (for logSNR).\n atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1].\n rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05.\n theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1].\n t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the \n current time and `t_0` is less than `t_err`. The default setting is 1e-5.\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_0: A pytorch tensor. The approximated solution at time `t_0`.\n\n [1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, \"Gotta go fast when generating data with score-based models,\" arXiv preprint arXiv:2105.14080, 2021.\n \"\"\"\n ns = self.noise_schedule\n s = t_T * torch.ones((x.shape[0],)).to(x)\n lambda_s = ns.marginal_lambda(s)\n lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x))\n h = h_init * torch.ones_like(s).to(x)\n x_prev = x\n nfe = 0\n if order == 2:\n r1 = 0.5\n lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True)\n higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, solver_type=solver_type, **kwargs)\n elif order == 3:\n r1, r2 = 1. / 3., 2. / 3.\n lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, return_intermediate=True, solver_type=solver_type)\n higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2, solver_type=solver_type, **kwargs)\n else:\n raise ValueError(\"For adaptive step size solver, order must be 2 or 3, got {}\".format(order))\n while torch.abs((s - t_0)).mean() > t_err:\n t = ns.inverse_lambda(lambda_s + h)\n x_lower, lower_noise_kwargs = lower_update(x, s, t)\n x_higher = higher_update(x, s, t, **lower_noise_kwargs)\n delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev)))\n norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))\n E = norm_fn((x_higher - x_lower) / delta).max()\n if torch.all(E <= 1.):\n x = x_higher\n s = t\n x_prev = x_lower\n lambda_s = ns.marginal_lambda(s)\n h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s)\n nfe += order\n print('adaptive solver nfe', nfe)\n return x\n\n def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform',\n method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',\n atol=0.0078, rtol=0.05,\n ):\n \"\"\"\n Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.\n\n =====================================================\n\n We support the following algorithms for both noise prediction model and data prediction model:\n - 'singlestep':\n Singlestep DPM-Solver (i.e. \"DPM-Solver-fast\" in the paper), which combines different orders of singlestep DPM-Solver. \n We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps).\n The total number of function evaluations (NFE) == `steps`.\n Given a fixed NFE == `steps`, the sampling procedure is:\n - If `order` == 1:\n - Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM).\n - If `order` == 2:\n - Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling.\n - If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2.\n - If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.\n - If `order` == 3:\n - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling.\n - If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1.\n - If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1.\n - If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2.\n - 'multistep':\n Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`.\n We initialize the first `order` values by lower order multistep solvers.\n Given a fixed NFE == `steps`, the sampling procedure is:\n Denote K = steps.\n - If `order` == 1:\n - We use K steps of DPM-Solver-1 (i.e. DDIM).\n - If `order` == 2:\n - We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2.\n - If `order` == 3:\n - We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3.\n - 'singlestep_fixed':\n Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3).\n We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE.\n - 'adaptive':\n Adaptive step size DPM-Solver (i.e. \"DPM-Solver-12\" and \"DPM-Solver-23\" in the paper).\n We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`.\n You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs\n (NFE) and the sample quality.\n - If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2.\n - If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3.\n\n =====================================================\n\n Some advices for choosing the algorithm:\n - For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs:\n Use singlestep DPM-Solver (\"DPM-Solver-fast\" in the paper) with `order = 3`.\n e.g.\n >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False)\n >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3,\n skip_type='time_uniform', method='singlestep')\n - For **guided sampling with large guidance scale** by DPMs:\n Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`.\n e.g.\n >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True)\n >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2,\n skip_type='time_uniform', method='multistep')\n\n We support three types of `skip_type`:\n - 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images**\n - 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**.\n - 'time_quadratic': quadratic time for the time steps.\n\n =====================================================\n Args:\n x: A pytorch tensor. The initial value at time `t_start`\n e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution.\n steps: A `int`. The total number of function evaluations (NFE).\n t_start: A `float`. The starting time of the sampling.\n If `T` is None, we use self.noise_schedule.T (default is 1.0).\n t_end: A `float`. The ending time of the sampling.\n If `t_end` is None, we use 1. / self.noise_schedule.total_N.\n e.g. if total_N == 1000, we have `t_end` == 1e-3.\n For discrete-time DPMs:\n - We recommend `t_end` == 1. / self.noise_schedule.total_N.\n For continuous-time DPMs:\n - We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15.\n order: A `int`. The order of DPM-Solver.\n skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'.\n method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'.\n denoise_to_zero: A `bool`. Whether to denoise to time 0 at the final step.\n Default is `False`. If `denoise_to_zero` is `True`, the total NFE is (`steps` + 1).\n\n This trick is firstly proposed by DDPM (https://arxiv.org/abs/2006.11239) and\n score_sde (https://arxiv.org/abs/2011.13456). Such trick can improve the FID\n for diffusion models sampling by diffusion SDEs for low-resolutional images\n (such as CIFAR-10). However, we observed that such trick does not matter for\n high-resolutional images. As it needs an additional NFE, we do not recommend\n it for high-resolutional images.\n lower_order_final: A `bool`. Whether to use lower order solvers at the final steps.\n Only valid for `method=multistep` and `steps < 15`. We empirically find that\n this trick is a key to stabilizing the sampling by DPM-Solver with very few steps\n (especially for steps <= 10). So we recommend to set it to be `True`.\n solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`.\n atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.\n rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'.\n Returns:\n x_end: A pytorch tensor. The approximated solution at time `t_end`.\n\n \"\"\"\n t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end\n t_T = self.noise_schedule.T if t_start is None else t_start\n device = x.device\n if method == 'adaptive':\n with torch.no_grad():\n x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol, solver_type=solver_type)\n elif method == 'multistep':\n assert steps >= order\n timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)\n assert timesteps.shape[0] - 1 == steps\n with torch.no_grad():\n vec_t = timesteps[0].expand((x.shape[0]))\n model_prev_list = [self.model_fn(x, vec_t)]\n t_prev_list = [vec_t]\n # Init the first `order` values by lower order multistep DPM-Solver.\n for init_order in range(1, order):\n vec_t = timesteps[init_order].expand(x.shape[0])\n x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order, solver_type=solver_type)\n model_prev_list.append(self.model_fn(x, vec_t))\n t_prev_list.append(vec_t)\n # Compute the remaining values by `order`-th order multistep DPM-Solver.\n for step in range(order, steps + 1):\n vec_t = timesteps[step].expand(x.shape[0])\n if lower_order_final and steps < 15:\n step_order = min(order, steps + 1 - step)\n else:\n step_order = order\n x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, step_order, solver_type=solver_type)\n for i in range(order - 1):\n t_prev_list[i] = t_prev_list[i + 1]\n model_prev_list[i] = model_prev_list[i + 1]\n t_prev_list[-1] = vec_t\n # We do not need to evaluate the final model value.\n if step < steps:\n model_prev_list[-1] = self.model_fn(x, vec_t)\n elif method in ['singlestep', 'singlestep_fixed']:\n if method == 'singlestep':\n timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order, skip_type=skip_type, t_T=t_T, t_0=t_0, device=device)\n elif method == 'singlestep_fixed':\n K = steps // order\n orders = [order,] * K\n timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device)\n for i, order in enumerate(orders):\n t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1]\n timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(), N=order, device=device)\n lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner)\n vec_s, vec_t = t_T_inner.tile(x.shape[0]), t_0_inner.tile(x.shape[0])\n h = lambda_inner[-1] - lambda_inner[0]\n r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h\n r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h\n x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2)\n if denoise_to_zero:\n x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)\n return x" } ]
import torch from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver
17,723
"""SAMPLING ONLY.""" class DPMSolverSampler(object): def __init__(self, model, **kwargs): super().__init__() self.model = model to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device) self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod)) def register_buffer(self, name, attr): if type(attr) == torch.Tensor: if attr.device != torch.device("cuda"): attr = attr.to(torch.device("cuda")) setattr(self, name, attr) @torch.no_grad() def sample(self, S, batch_size, shape, conditioning=None, callback=None, normals_sequence=None, img_callback=None, quantize_x0=False, eta=0., mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, verbose=True, x_T=None, log_every_t=100, unconditional_guidance_scale=1., unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... **kwargs ): if conditioning is not None: if isinstance(conditioning, dict): cbs = conditioning[list(conditioning.keys())[0]].shape[0] if cbs != batch_size: print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") else: if conditioning.shape[0] != batch_size: print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") # sampling C, H, W = shape size = (batch_size, C, H, W) # print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}') device = self.model.betas.device if x_T is None: img = torch.randn(size, device=device) else: img = x_T
"""SAMPLING ONLY.""" class DPMSolverSampler(object): def __init__(self, model, **kwargs): super().__init__() self.model = model to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device) self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod)) def register_buffer(self, name, attr): if type(attr) == torch.Tensor: if attr.device != torch.device("cuda"): attr = attr.to(torch.device("cuda")) setattr(self, name, attr) @torch.no_grad() def sample(self, S, batch_size, shape, conditioning=None, callback=None, normals_sequence=None, img_callback=None, quantize_x0=False, eta=0., mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, verbose=True, x_T=None, log_every_t=100, unconditional_guidance_scale=1., unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... **kwargs ): if conditioning is not None: if isinstance(conditioning, dict): cbs = conditioning[list(conditioning.keys())[0]].shape[0] if cbs != batch_size: print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") else: if conditioning.shape[0] != batch_size: print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") # sampling C, H, W = shape size = (batch_size, C, H, W) # print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}') device = self.model.betas.device if x_T is None: img = torch.randn(size, device=device) else: img = x_T
ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)
0
2023-10-10 09:40:10+00:00
24k
spla-tam/SplaTAM
scripts/gaussian_splatting.py
[ { "identifier": "AzureKinectDataset", "path": "datasets/gradslam_datasets/azure.py", "snippet": "class AzureKinectDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = None\n\n # # check if a file named 'poses_global_dvo.txt' exists in the basedir / sequence folder\n # if os.path.isfile(os.path.join(basedir, sequence, \"poses_global_dvo.txt\")):\n # self.pose_path = os.path.join(basedir, sequence, \"poses_global_dvo.txt\")\n\n if \"odomfile\" in kwargs.keys():\n self.pose_path = os.path.join(self.input_folder, kwargs[\"odomfile\"])\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/color/*.jpg\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n if self.pose_path is None:\n print(\"WARNING: Dataset does not contain poses. Returning identity transform.\")\n return [torch.eye(4).float() for _ in range(self.num_imgs)]\n else:\n # Determine whether the posefile ends in \".log\"\n # a .log file has the following format for each frame\n # frame_idx frame_idx+1\n # row 1 of 4x4 transform\n # row 2 of 4x4 transform\n # row 3 of 4x4 transform\n # row 4 of 4x4 transform\n # [repeat for all frames]\n #\n # on the other hand, the \"poses_o3d.txt\" or \"poses_dvo.txt\" files have the format\n # 16 entries of 4x4 transform\n # [repeat for all frames]\n if self.pose_path.endswith(\".log\"):\n # print(\"Loading poses from .log format\")\n poses = []\n lines = None\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n if len(lines) % 5 != 0:\n raise ValueError(\n \"Incorrect file format for .log odom file \" \"Number of non-empty lines must be a multiple of 5\"\n )\n num_lines = len(lines) // 5\n for i in range(0, num_lines):\n _curpose = []\n _curpose.append(list(map(float, lines[5 * i + 1].split())))\n _curpose.append(list(map(float, lines[5 * i + 2].split())))\n _curpose.append(list(map(float, lines[5 * i + 3].split())))\n _curpose.append(list(map(float, lines[5 * i + 4].split())))\n _curpose = np.array(_curpose).reshape(4, 4)\n poses.append(torch.from_numpy(_curpose))\n else:\n poses = []\n lines = None\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n for line in lines:\n if len(line.split()) == 0:\n continue\n c2w = np.array(list(map(float, line.split()))).reshape(4, 4)\n poses.append(torch.from_numpy(c2w))\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding # .permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "load_dataset_config", "path": "datasets/gradslam_datasets/dataconfig.py", "snippet": "def load_dataset_config(path, default_path=None):\n \"\"\"\n Loads config file.\n\n Args:\n path (str): path to config file.\n default_path (str, optional): whether to use default path. Defaults to None.\n\n Returns:\n cfg (dict): config dict.\n\n \"\"\"\n # load configuration from file itself\n with open(path, \"r\") as f:\n cfg_special = yaml.full_load(f)\n\n # check if we should inherit from a config\n inherit_from = cfg_special.get(\"inherit_from\")\n\n # if yes, load this config first as default\n # if no, use the default_path\n if inherit_from is not None:\n cfg = load_dataset_config(inherit_from, default_path)\n elif default_path is not None:\n with open(default_path, \"r\") as f:\n cfg = yaml.full_load(f)\n else:\n cfg = dict()\n\n # include main configuration\n update_recursive(cfg, cfg_special)\n\n return cfg" }, { "identifier": "ICLDataset", "path": "datasets/gradslam_datasets/icl.py", "snippet": "class ICLDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict: Dict,\n basedir: Union[Path, str],\n sequence: Union[Path, str],\n stride: Optional[int] = 1,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[Union[Path, str]] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n embedding_file_extension: Optional[str] = \"pt\",\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n # Attempt to find pose file (*.gt.sim)\n self.pose_path = glob.glob(os.path.join(self.input_folder, \"*.gt.sim\"))\n if self.pose_path == 0:\n raise ValueError(\"Need pose file ending in extension `*.gt.sim`\")\n self.pose_path = self.pose_path[0]\n self.embedding_file_extension = embedding_file_extension\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/rgb/*.png\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(\n glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.{self.embedding_file_extension}\")\n )\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n\n lines = []\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n\n _posearr = []\n for line in lines:\n line = line.strip().split()\n if len(line) == 0:\n continue\n _npvec = np.asarray([float(line[0]), float(line[1]), float(line[2]), float(line[3])])\n _posearr.append(_npvec)\n _posearr = np.stack(_posearr)\n\n for pose_line_idx in range(0, _posearr.shape[0], 3):\n _curpose = np.zeros((4, 4))\n _curpose[3, 3] = 3\n _curpose[0] = _posearr[pose_line_idx]\n _curpose[1] = _posearr[pose_line_idx + 1]\n _curpose[2] = _posearr[pose_line_idx + 2]\n poses.append(torch.from_numpy(_curpose).float())\n\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "ReplicaDataset", "path": "datasets/gradslam_datasets/replica.py", "snippet": "class ReplicaDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = os.path.join(self.input_folder, \"traj.txt\")\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/results/frame*.jpg\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/results/depth*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n with open(self.pose_path, \"r\") as f:\n lines = f.readlines()\n for i in range(self.num_imgs):\n line = lines[i]\n c2w = np.array(list(map(float, line.split()))).reshape(4, 4)\n # c2w[:3, 1] *= -1\n # c2w[:3, 2] *= -1\n c2w = torch.from_numpy(c2w).float()\n poses.append(c2w)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "ScannetDataset", "path": "datasets/gradslam_datasets/scannet.py", "snippet": "class ScannetDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 968,\n desired_width: Optional[int] = 1296,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = None\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/color/*.jpg\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n posefiles = natsorted(glob.glob(f\"{self.input_folder}/pose/*.txt\"))\n for posefile in posefiles:\n _pose = torch.from_numpy(np.loadtxt(posefile))\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n print(embedding_file_path)\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "Ai2thorDataset", "path": "datasets/gradslam_datasets/ai2thor.py", "snippet": "class Ai2thorDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 968,\n desired_width: Optional[int] = 1296,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(f\"{self.input_folder}/color/*.png\"))\n depth_paths = natsorted(glob.glob(f\"{self.input_folder}/depth/*.png\"))\n embedding_paths = None\n if self.load_embeddings:\n if self.embedding_dir == \"embed_semseg\":\n # embed_semseg is stored as uint16 pngs\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.png\"))\n else:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n poses = []\n posefiles = natsorted(glob.glob(f\"{self.input_folder}/pose/*.txt\"))\n for posefile in posefiles:\n _pose = torch.from_numpy(np.loadtxt(posefile))\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n if self.embedding_dir == \"embed_semseg\":\n embedding = imageio.imread(embedding_file_path) # (H, W)\n embedding = cv2.resize(\n embedding, (self.desired_width, self.desired_height), interpolation=cv2.INTER_NEAREST\n )\n embedding = torch.from_numpy(embedding).long() # (H, W)\n embedding = F.one_hot(embedding, num_classes=self.embedding_dim) # (H, W, C)\n embedding = embedding.half() # (H, W, C)\n embedding = embedding.permute(2, 0, 1) # (C, H, W)\n embedding = embedding.unsqueeze(0) # (1, C, H, W)\n else:\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "RealsenseDataset", "path": "datasets/gradslam_datasets/realsense.py", "snippet": "class RealsenseDataset(GradSLAMDataset):\n \"\"\"\n Dataset class to process depth images captured by realsense camera on the tabletop manipulator\n \"\"\"\n\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n # only poses/images/depth corresponding to the realsense_camera_order are read/used\n self.pose_path = os.path.join(self.input_folder, \"poses\")\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"rgb\", \"*.jpg\")))\n depth_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"depth\", \"*.png\")))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n posefiles = natsorted(glob.glob(os.path.join(self.pose_path, \"*.npy\")))\n poses = []\n P = torch.tensor([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]).float()\n for posefile in posefiles:\n c2w = torch.from_numpy(np.load(posefile)).float()\n _R = c2w[:3, :3]\n _t = c2w[:3, 3]\n _pose = P @ c2w @ P.T\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "Record3DDataset", "path": "datasets/gradslam_datasets/record3d.py", "snippet": "class Record3DDataset(GradSLAMDataset):\n \"\"\"\n Dataset class to read in saved files from the structure created by our\n `save_record3d_stream.py` script\n \"\"\"\n\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = os.path.join(self.input_folder, \"poses\")\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def get_filepaths(self):\n color_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"rgb\", \"*.png\")))\n depth_paths = natsorted(glob.glob(os.path.join(self.input_folder, \"depth\", \"*.png\")))\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{self.input_folder}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n posefiles = natsorted(glob.glob(os.path.join(self.pose_path, \"*.npy\")))\n poses = []\n P = torch.tensor([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]).float()\n for posefile in posefiles:\n c2w = torch.from_numpy(np.load(posefile)).float()\n _R = c2w[:3, :3]\n _t = c2w[:3, 3]\n _pose = P @ c2w @ P.T\n poses.append(_pose)\n return poses\n\n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path)\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "TUMDataset", "path": "datasets/gradslam_datasets/tum.py", "snippet": "class TUMDataset(GradSLAMDataset):\n def __init__(\n self,\n config_dict,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 480,\n desired_width: Optional[int] = 640,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n self.pose_path = None\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n )\n\n def parse_list(self, filepath, skiprows=0):\n \"\"\" read list data \"\"\"\n data = np.loadtxt(filepath, delimiter=' ',\n dtype=np.unicode_, skiprows=skiprows)\n return data\n\n def associate_frames(self, tstamp_image, tstamp_depth, tstamp_pose, max_dt=0.08):\n \"\"\" pair images, depths, and poses \"\"\"\n associations = []\n for i, t in enumerate(tstamp_image):\n if tstamp_pose is None:\n j = np.argmin(np.abs(tstamp_depth - t))\n if (np.abs(tstamp_depth[j] - t) < max_dt):\n associations.append((i, j))\n\n else:\n j = np.argmin(np.abs(tstamp_depth - t))\n k = np.argmin(np.abs(tstamp_pose - t))\n\n if (np.abs(tstamp_depth[j] - t) < max_dt) and \\\n (np.abs(tstamp_pose[k] - t) < max_dt):\n associations.append((i, j, k))\n\n return associations\n\n def pose_matrix_from_quaternion(self, pvec):\n \"\"\" convert 4x4 pose matrix to (t, q) \"\"\"\n from scipy.spatial.transform import Rotation\n\n pose = np.eye(4)\n pose[:3, :3] = Rotation.from_quat(pvec[3:]).as_matrix()\n pose[:3, 3] = pvec[:3]\n return pose\n\n def get_filepaths(self):\n\n frame_rate = 32\n \"\"\" read video data in tum-rgbd format \"\"\"\n if os.path.isfile(os.path.join(self.input_folder, 'groundtruth.txt')):\n pose_list = os.path.join(self.input_folder, 'groundtruth.txt')\n elif os.path.isfile(os.path.join(self.input_folder, 'pose.txt')):\n pose_list = os.path.join(self.input_folder, 'pose.txt')\n\n image_list = os.path.join(self.input_folder, 'rgb.txt')\n depth_list = os.path.join(self.input_folder, 'depth.txt')\n\n image_data = self.parse_list(image_list)\n depth_data = self.parse_list(depth_list)\n pose_data = self.parse_list(pose_list, skiprows=1)\n pose_vecs = pose_data[:, 1:].astype(np.float64)\n\n tstamp_image = image_data[:, 0].astype(np.float64)\n tstamp_depth = depth_data[:, 0].astype(np.float64)\n tstamp_pose = pose_data[:, 0].astype(np.float64)\n associations = self.associate_frames(\n tstamp_image, tstamp_depth, tstamp_pose)\n\n indicies = [0]\n for i in range(1, len(associations)):\n t0 = tstamp_image[associations[indicies[-1]][0]]\n t1 = tstamp_image[associations[i][0]]\n if t1 - t0 > 1.0 / frame_rate:\n indicies += [i]\n\n color_paths, depth_paths = [], []\n for ix in indicies:\n (i, j, k) = associations[ix]\n color_paths += [os.path.join(self.input_folder, image_data[i, 1])]\n depth_paths += [os.path.join(self.input_folder, depth_data[j, 1])]\n\n embedding_paths = None\n\n return color_paths, depth_paths, embedding_paths\n \n def load_poses(self):\n \n frame_rate = 32\n \"\"\" read video data in tum-rgbd format \"\"\"\n if os.path.isfile(os.path.join(self.input_folder, 'groundtruth.txt')):\n pose_list = os.path.join(self.input_folder, 'groundtruth.txt')\n elif os.path.isfile(os.path.join(self.input_folder, 'pose.txt')):\n pose_list = os.path.join(self.input_folder, 'pose.txt')\n\n image_list = os.path.join(self.input_folder, 'rgb.txt')\n depth_list = os.path.join(self.input_folder, 'depth.txt')\n\n image_data = self.parse_list(image_list)\n depth_data = self.parse_list(depth_list)\n pose_data = self.parse_list(pose_list, skiprows=1)\n pose_vecs = pose_data[:, 1:].astype(np.float64)\n\n tstamp_image = image_data[:, 0].astype(np.float64)\n tstamp_depth = depth_data[:, 0].astype(np.float64)\n tstamp_pose = pose_data[:, 0].astype(np.float64)\n associations = self.associate_frames(\n tstamp_image, tstamp_depth, tstamp_pose)\n\n indicies = [0]\n for i in range(1, len(associations)):\n t0 = tstamp_image[associations[indicies[-1]][0]]\n t1 = tstamp_image[associations[i][0]]\n if t1 - t0 > 1.0 / frame_rate:\n indicies += [i]\n\n color_paths, poses, depth_paths, intrinsics = [], [], [], []\n inv_pose = None\n for ix in indicies:\n (i, j, k) = associations[ix]\n color_paths += [os.path.join(self.input_folder, image_data[i, 1])]\n depth_paths += [os.path.join(self.input_folder, depth_data[j, 1])]\n c2w = self.pose_matrix_from_quaternion(pose_vecs[k])\n c2w = torch.from_numpy(c2w).float()\n poses += [c2w]\n\n return poses\n \n def read_embedding_from_file(self, embedding_file_path):\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1)" }, { "identifier": "ScannetPPDataset", "path": "datasets/gradslam_datasets/scannetpp.py", "snippet": "class ScannetPPDataset(GradSLAMDataset):\n def __init__(\n self,\n basedir,\n sequence,\n ignore_bad: Optional[bool] = False,\n use_train_split: Optional[bool] = True,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 1168,\n desired_width: Optional[int] = 1752,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n config_dict = {}\n config_dict[\"dataset_name\"] = \"scannetpp\"\n self.pose_path = None\n self.ignore_bad = ignore_bad\n self.use_train_split = use_train_split\n\n # Load Train & Test Split\n self.train_test_split = json.load(open(f\"{self.input_folder}/dslr/train_test_lists.json\", \"r\"))\n if self.use_train_split:\n self.image_names = self.train_test_split[\"train\"]\n else:\n self.image_names = self.train_test_split[\"test\"]\n self.train_image_names = self.train_test_split[\"train\"]\n \n # Load NeRFStudio format camera & poses data\n self.cams_metadata = self.load_cams_metadata()\n if self.use_train_split:\n self.frames_metadata = self.cams_metadata[\"frames\"]\n self.filepath_index_mapping = create_filepath_index_mapping(self.frames_metadata)\n else:\n self.frames_metadata = self.cams_metadata[\"test_frames\"]\n self.train_frames_metadata = self.cams_metadata[\"frames\"]\n self.filepath_index_mapping = create_filepath_index_mapping(self.frames_metadata)\n self.train_filepath_index_mapping = create_filepath_index_mapping(self.train_frames_metadata) \n\n # Init Intrinsics\n config_dict[\"camera_params\"] = {}\n config_dict[\"camera_params\"][\"png_depth_scale\"] = 1000.0 # Depth is in mm\n config_dict[\"camera_params\"][\"image_height\"] = self.cams_metadata[\"h\"]\n config_dict[\"camera_params\"][\"image_width\"] = self.cams_metadata[\"w\"]\n config_dict[\"camera_params\"][\"fx\"] = self.cams_metadata[\"fl_x\"]\n config_dict[\"camera_params\"][\"fy\"] = self.cams_metadata[\"fl_y\"]\n config_dict[\"camera_params\"][\"cx\"] = self.cams_metadata[\"cx\"]\n config_dict[\"camera_params\"][\"cy\"] = self.cams_metadata[\"cy\"]\n\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n ) \n\n def load_cams_metadata(self):\n cams_metadata_path = f\"{self.input_folder}/dslr/nerfstudio/transforms_undistorted.json\"\n cams_metadata = json.load(open(cams_metadata_path, \"r\"))\n return cams_metadata\n \n def get_filepaths(self):\n base_path = f\"{self.input_folder}/dslr\"\n color_paths = []\n depth_paths = []\n self.tmp_poses = []\n P = torch.tensor(\n [\n [1, 0, 0, 0],\n [0, -1, 0, 0],\n [0, 0, -1, 0],\n [0, 0, 0, 1]\n ]\n ).float()\n if not self.use_train_split:\n self.first_train_image_name = self.train_image_names[0]\n self.first_train_image_index = self.train_filepath_index_mapping.get(self.first_train_image_name)\n self.first_train_frame_metadata = self.train_frames_metadata[self.first_train_image_index]\n # Get path of undistorted image and depth\n color_path = f\"{base_path}/undistorted_images/{self.first_train_image_name}\"\n depth_path = f\"{base_path}/undistorted_depths/{self.first_train_image_name.replace('.JPG', '.png')}\"\n color_paths.append(color_path)\n depth_paths.append(depth_path)\n # Get pose of first train frame in GradSLAM format\n c2w = torch.from_numpy(np.array(self.first_train_frame_metadata[\"transform_matrix\"])).float()\n _pose = P @ c2w @ P.T\n self.tmp_poses.append(_pose)\n for image_name in self.image_names:\n # Search for image name in frames_metadata\n frame_metadata = self.frames_metadata[self.filepath_index_mapping.get(image_name)]\n # Check if frame is blurry and if it needs to be ignored\n if self.ignore_bad and frame_metadata['is_bad']:\n continue\n # Get path of undistorted image and depth\n color_path = f\"{base_path}/undistorted_images/{image_name}\"\n depth_path = f\"{base_path}/undistorted_depths/{image_name.replace('.JPG', '.png')}\"\n color_paths.append(color_path)\n depth_paths.append(depth_path)\n # Get pose of undistorted image in GradSLAM format\n c2w = torch.from_numpy(np.array(frame_metadata[\"transform_matrix\"])).float()\n _pose = P @ c2w @ P.T\n self.tmp_poses.append(_pose)\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{base_path}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n return self.tmp_poses\n\n def read_embedding_from_file(self, embedding_file_path):\n print(embedding_file_path)\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "NeRFCaptureDataset", "path": "datasets/gradslam_datasets/nerfcapture.py", "snippet": "class NeRFCaptureDataset(GradSLAMDataset):\n def __init__(\n self,\n basedir,\n sequence,\n stride: Optional[int] = None,\n start: Optional[int] = 0,\n end: Optional[int] = -1,\n desired_height: Optional[int] = 1440,\n desired_width: Optional[int] = 1920,\n load_embeddings: Optional[bool] = False,\n embedding_dir: Optional[str] = \"embeddings\",\n embedding_dim: Optional[int] = 512,\n **kwargs,\n ):\n self.input_folder = os.path.join(basedir, sequence)\n config_dict = {}\n config_dict[\"dataset_name\"] = \"nerfcapture\"\n self.pose_path = None\n \n # Load NeRFStudio format camera & poses data\n self.cams_metadata = self.load_cams_metadata()\n self.frames_metadata = self.cams_metadata[\"frames\"]\n self.filepath_index_mapping = create_filepath_index_mapping(self.frames_metadata)\n\n # Load RGB & Depth filepaths\n self.image_names = natsorted(os.listdir(f\"{self.input_folder}/rgb\"))\n self.image_names = [f'rgb/{image_name}' for image_name in self.image_names]\n\n # Init Intrinsics\n config_dict[\"camera_params\"] = {}\n config_dict[\"camera_params\"][\"png_depth_scale\"] = 6553.5 # Depth is in mm\n config_dict[\"camera_params\"][\"image_height\"] = self.cams_metadata[\"h\"]\n config_dict[\"camera_params\"][\"image_width\"] = self.cams_metadata[\"w\"]\n config_dict[\"camera_params\"][\"fx\"] = self.cams_metadata[\"fl_x\"]\n config_dict[\"camera_params\"][\"fy\"] = self.cams_metadata[\"fl_y\"]\n config_dict[\"camera_params\"][\"cx\"] = self.cams_metadata[\"cx\"]\n config_dict[\"camera_params\"][\"cy\"] = self.cams_metadata[\"cy\"]\n\n super().__init__(\n config_dict,\n stride=stride,\n start=start,\n end=end,\n desired_height=desired_height,\n desired_width=desired_width,\n load_embeddings=load_embeddings,\n embedding_dir=embedding_dir,\n embedding_dim=embedding_dim,\n **kwargs,\n ) \n\n def load_cams_metadata(self):\n cams_metadata_path = f\"{self.input_folder}/transforms.json\"\n cams_metadata = json.load(open(cams_metadata_path, \"r\"))\n return cams_metadata\n \n def get_filepaths(self):\n base_path = f\"{self.input_folder}\"\n color_paths = []\n depth_paths = []\n self.tmp_poses = []\n P = torch.tensor(\n [\n [1, 0, 0, 0],\n [0, -1, 0, 0],\n [0, 0, -1, 0],\n [0, 0, 0, 1]\n ]\n ).float()\n for image_name in self.image_names:\n # Search for image name in frames_metadata\n frame_metadata = self.frames_metadata[self.filepath_index_mapping.get(image_name)]\n # Get path of image and depth\n color_path = f\"{base_path}/{image_name}\"\n depth_path = f\"{base_path}/{image_name.replace('rgb', 'depth')}\"\n color_paths.append(color_path)\n depth_paths.append(depth_path)\n # Get pose of image in GradSLAM format\n c2w = torch.from_numpy(np.array(frame_metadata[\"transform_matrix\"])).float()\n _pose = P @ c2w @ P.T\n self.tmp_poses.append(_pose)\n embedding_paths = None\n if self.load_embeddings:\n embedding_paths = natsorted(glob.glob(f\"{base_path}/{self.embedding_dir}/*.pt\"))\n return color_paths, depth_paths, embedding_paths\n\n def load_poses(self):\n return self.tmp_poses\n\n def read_embedding_from_file(self, embedding_file_path):\n print(embedding_file_path)\n embedding = torch.load(embedding_file_path, map_location=\"cpu\")\n return embedding.permute(0, 2, 3, 1) # (1, H, W, embedding_dim)" }, { "identifier": "seed_everything", "path": "utils/common_utils.py", "snippet": "def seed_everything(seed=42):\n \"\"\"\n Set the `seed` value for torch and numpy seeds. Also turns on\n deterministic execution for cudnn.\n \n Parameters:\n - seed: A hashable seed value\n \"\"\"\n random.seed(seed)\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n print(f\"Seed set to: {seed} (type: {type(seed)})\")" }, { "identifier": "save_seq_params", "path": "utils/common_utils.py", "snippet": "def save_seq_params(all_params, output_dir):\n params_to_save = {}\n for frame_idx, params in enumerate(all_params):\n params_to_save[f\"frame_{frame_idx}\"] = params2cpu(params)\n # Save the Parameters containing the Sequence of Gaussians\n os.makedirs(output_dir, exist_ok=True)\n print(f\"Saving parameters to: {output_dir}\")\n save_path = os.path.join(output_dir, \"params.npz\")\n np.savez(save_path, **params_to_save)" }, { "identifier": "setup_camera", "path": "utils/recon_helpers.py", "snippet": "def setup_camera(w, h, k, w2c, near=0.01, far=100):\n fx, fy, cx, cy = k[0][0], k[1][1], k[0][2], k[1][2]\n w2c = torch.tensor(w2c).cuda().float()\n cam_center = torch.inverse(w2c)[:3, 3]\n w2c = w2c.unsqueeze(0).transpose(1, 2)\n opengl_proj = torch.tensor([[2 * fx / w, 0.0, -(w - 2 * cx) / w, 0.0],\n [0.0, 2 * fy / h, -(h - 2 * cy) / h, 0.0],\n [0.0, 0.0, far / (far - near), -(far * near) / (far - near)],\n [0.0, 0.0, 1.0, 0.0]]).cuda().float().unsqueeze(0).transpose(1, 2)\n full_proj = w2c.bmm(opengl_proj)\n cam = Camera(\n image_height=h,\n image_width=w,\n tanfovx=w / (2 * fx),\n tanfovy=h / (2 * fy),\n bg=torch.tensor([0, 0, 0], dtype=torch.float32, device=\"cuda\"),\n scale_modifier=1.0,\n viewmatrix=w2c,\n projmatrix=full_proj,\n sh_degree=0,\n campos=cam_center,\n prefiltered=False\n )\n return cam" }, { "identifier": "params2rendervar", "path": "utils/gs_helpers.py", "snippet": "def params2rendervar(params):\n rendervar = {\n 'means3D': params['means3D'],\n 'colors_precomp': params['rgb_colors'],\n 'rotations': F.normalize(params['unnorm_rotations']),\n 'opacities': torch.sigmoid(params['logit_opacities']),\n 'scales': torch.exp(torch.tile(params['log_scales'], (1, 3))),\n 'means2D': torch.zeros_like(params['means3D'], requires_grad=True, device=\"cuda\") + 0\n }\n return rendervar" }, { "identifier": "params2depthplussilhouette", "path": "utils/gs_helpers.py", "snippet": "def params2depthplussilhouette(params, w2c):\n rendervar = {\n 'means3D': params['means3D'],\n 'colors_precomp': get_depth_and_silhouette(params['means3D'], w2c),\n 'rotations': F.normalize(params['unnorm_rotations']),\n 'opacities': torch.sigmoid(params['logit_opacities']),\n 'scales': torch.exp(torch.tile(params['log_scales'], (1, 3))),\n 'means2D': torch.zeros_like(params['means3D'], requires_grad=True, device=\"cuda\") + 0\n }\n return rendervar" }, { "identifier": "transformed_params2depthplussilhouette", "path": "utils/gs_helpers.py", "snippet": "def transformed_params2depthplussilhouette(params, w2c, transformed_pts):\n rendervar = {\n 'means3D': transformed_pts,\n 'colors_precomp': get_depth_and_silhouette(transformed_pts, w2c),\n 'rotations': F.normalize(params['unnorm_rotations']),\n 'opacities': torch.sigmoid(params['logit_opacities']),\n 'scales': torch.exp(torch.tile(params['log_scales'], (1, 3))),\n 'means2D': torch.zeros_like(params['means3D'], requires_grad=True, device=\"cuda\") + 0\n }\n return rendervar" }, { "identifier": "transform_to_frame", "path": "utils/gs_helpers.py", "snippet": "def transform_to_frame(params, time_idx, gaussians_grad, camera_grad):\n \"\"\"\n Function to transform Isotropic Gaussians from world frame to camera frame.\n \n Args:\n params: dict of parameters\n time_idx: time index to transform to\n gaussians_grad: enable gradients for Gaussians\n camera_grad: enable gradients for camera pose\n \n Returns:\n transformed_pts: Transformed Centers of Gaussians\n \"\"\"\n # Get Frame Camera Pose\n if camera_grad:\n cam_rot = F.normalize(params['cam_unnorm_rots'][..., time_idx])\n cam_tran = params['cam_trans'][..., time_idx]\n else:\n cam_rot = F.normalize(params['cam_unnorm_rots'][..., time_idx].detach())\n cam_tran = params['cam_trans'][..., time_idx].detach()\n rel_w2c = torch.eye(4).cuda().float()\n rel_w2c[:3, :3] = build_rotation(cam_rot)\n rel_w2c[:3, 3] = cam_tran\n\n # Get Centers and norm Rots of Gaussians in World Frame\n if gaussians_grad:\n pts = params['means3D']\n else:\n pts = params['means3D'].detach()\n \n # Transform Centers and Unnorm Rots of Gaussians to Camera Frame\n pts_ones = torch.ones(pts.shape[0], 1).cuda().float()\n pts4 = torch.cat((pts, pts_ones), dim=1)\n transformed_pts = (rel_w2c @ pts4.T).T[:, :3]\n\n return transformed_pts" }, { "identifier": "report_progress", "path": "utils/gs_helpers.py", "snippet": "def report_progress(params, data, i, progress_bar, iter_time_idx, sil_thres, every_i=1, qual_every_i=1, \n tracking=False, mapping=False, wandb_run=None, wandb_step=None, wandb_save_qual=False, online_time_idx=None):\n if i % every_i == 0 or i == 1:\n if wandb_run is not None:\n if tracking:\n stage = \"Tracking\"\n elif mapping:\n stage = \"Mapping\"\n else:\n stage = \"Current Frame Optimization\"\n\n # Initialize Render Variables\n rendervar = params2rendervar(params)\n depth_sil_rendervar = params2depthplussilhouette(params, data['w2c'])\n\n # Initialize Render Variables\n depth_sil, _, _, = Renderer(raster_settings=data['cam'])(**depth_sil_rendervar)\n rastered_depth = depth_sil[0, :, :].unsqueeze(0)\n valid_depth_mask = (data['depth'] > 0)\n silhouette = depth_sil[1, :, :]\n presence_sil_mask = (silhouette > sil_thres)\n\n im, _, _, = Renderer(raster_settings=data['cam'])(**rendervar)\n if tracking:\n psnr = calc_psnr(im * presence_sil_mask, data['im'] * presence_sil_mask).mean()\n else:\n psnr = calc_psnr(im, data['im']).mean()\n\n if tracking:\n diff_depth_rmse = torch.sqrt((((rastered_depth - data['depth']) * presence_sil_mask) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n else:\n diff_depth_rmse = torch.sqrt(((rastered_depth - data['depth']) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n\n if not mapping:\n progress_bar.set_postfix({f\"Time-Step: {iter_time_idx} | Frame {data['id']} | PSNR: {psnr:.{7}} | RMSE\": f\"{rmse:.{7}}\"})\n progress_bar.update(every_i)\n else:\n progress_bar.set_postfix({f\"Time-Step: {online_time_idx} | Frame {data['id']} | PSNR: {psnr:.{7}} | RMSE\": f\"{rmse:.{7}}\"})\n progress_bar.update(every_i)\n \n if wandb_run is not None:\n wandb_run.log({f\"{stage} PSNR\": psnr, f\"{stage} RMSE\": rmse}, step=wandb_step)\n \n if wandb_save_qual and (i % qual_every_i == 0 or i == 1):\n # Silhouette Mask\n presence_sil_mask = presence_sil_mask.detach().cpu().numpy()\n\n # Log plot to wandb\n if not mapping:\n fig_title = f\"Time-Step: {iter_time_idx} | Iter: {i} | Frame: {data['id']}\"\n else:\n fig_title = f\"Time-Step: {online_time_idx} | Iter: {i} | Frame: {data['id']}\"\n plot_rgbd_silhouette(data['im'], data['depth'], im, rastered_depth, presence_sil_mask, diff_depth_rmse,\n psnr, rmse, fig_title, wandb_run=wandb_run, wandb_step=wandb_step, \n wandb_title=f\"{stage} Qual Viz\")" }, { "identifier": "eval", "path": "utils/gs_helpers.py", "snippet": "def eval(dataset, final_params, num_frames, eval_dir, sil_thres, mapping_iters, add_new_gaussians, wandb_run=None, wandb_save_qual=False):\n print(\"Evaluating Final Parameters ...\")\n psnr_list = []\n rmse_list = []\n lpips_list = []\n ssim_list = []\n plot_dir = os.path.join(eval_dir, \"plots\")\n os.makedirs(plot_dir, exist_ok=True)\n\n gt_w2c_list = []\n for time_idx in tqdm(range(num_frames)):\n # Get RGB-D Data & Camera Parameters\n color, depth, intrinsics, pose = dataset[time_idx]\n gt_w2c = torch.linalg.inv(pose)\n gt_w2c_list.append(gt_w2c)\n intrinsics = intrinsics[:3, :3]\n\n # Process RGB-D Data\n color = color.permute(2, 0, 1) / 255 # (H, W, C) -> (C, H, W)\n depth = depth.permute(2, 0, 1) # (H, W, C) -> (C, H, W)\n\n # Process Camera Parameters\n w2c = torch.linalg.inv(pose)\n if time_idx == 0:\n first_frame_w2c = w2c\n # Setup Camera\n cam = setup_camera(color.shape[2], color.shape[1], intrinsics.cpu().numpy(), w2c.detach().cpu().numpy())\n \n # Define current frame data\n curr_data = {'cam': cam, 'im': color, 'depth': depth, 'id': time_idx, 'intrinsics': intrinsics, 'w2c': w2c}\n\n # Initialize Render Variables\n rendervar = params2rendervar(final_params)\n depth_sil_rendervar = params2depthplussilhouette(final_params, w2c)\n\n # Render Depth & Silhouette\n depth_sil, _, _, = Renderer(raster_settings=curr_data['cam'])(**depth_sil_rendervar)\n rastered_depth = depth_sil[0, :, :].unsqueeze(0)\n valid_depth_mask = (curr_data['depth'] > 0)\n silhouette = depth_sil[1, :, :]\n presence_sil_mask = (silhouette > sil_thres)\n \n # Render RGB and Calculate PSNR\n im, radius, _, = Renderer(raster_settings=curr_data['cam'])(**rendervar)\n if mapping_iters==0 and not add_new_gaussians:\n weighted_im = im * presence_sil_mask\n weighted_gt_im = curr_data['im'] * presence_sil_mask\n psnr = calc_psnr(weighted_im, weighted_gt_im).mean()\n ssim = ms_ssim(weighted_im.unsqueeze(0).cpu(), weighted_gt_im.unsqueeze(0).cpu(), \n data_range=1.0, size_average=True)\n lpips_score = loss_fn_alex(torch.clamp(weighted_im.unsqueeze(0), 0.0, 1.0),\n torch.clamp(weighted_gt_im.unsqueeze(0), 0.0, 1.0)).item()\n else:\n psnr = calc_psnr(im, curr_data['im']).mean()\n ssim = ms_ssim(im.unsqueeze(0).cpu(), curr_data['im'].unsqueeze(0).cpu(), \n data_range=1.0, size_average=True)\n lpips_score = loss_fn_alex(torch.clamp(im.unsqueeze(0), 0.0, 1.0),\n torch.clamp(curr_data['im'].unsqueeze(0), 0.0, 1.0)).item()\n\n psnr_list.append(psnr.cpu().numpy())\n ssim_list.append(ssim.cpu().numpy())\n lpips_list.append(lpips_score)\n\n # Compute Depth RMSE\n if mapping_iters==0 and not add_new_gaussians:\n diff_depth_rmse = torch.sqrt((((rastered_depth - curr_data['depth']) * presence_sil_mask) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n else:\n diff_depth_rmse = torch.sqrt(((rastered_depth - curr_data['depth']) ** 2))\n diff_depth_rmse = diff_depth_rmse * valid_depth_mask\n rmse = diff_depth_rmse.sum() / valid_depth_mask.sum()\n rmse_list.append(rmse.cpu().numpy())\n\n # Plot the Ground Truth and Rasterized RGB & Depth, along with Silhouette\n fig_title = \"Time Step: {}\".format(time_idx)\n plot_name = \"%04d\" % time_idx\n presence_sil_mask = presence_sil_mask.detach().cpu().numpy()\n if wandb_run is None:\n plot_rgbd_silhouette(color, depth, im, rastered_depth, presence_sil_mask, diff_depth_rmse,\n psnr, rmse, fig_title, plot_dir, \n plot_name=plot_name, save_plot=True)\n elif wandb_save_qual:\n plot_rgbd_silhouette(color, depth, im, rastered_depth, presence_sil_mask, diff_depth_rmse,\n psnr, rmse, fig_title, plot_dir, \n plot_name=plot_name, save_plot=True,\n wandb_run=wandb_run, wandb_step=None, \n wandb_title=\"Eval Qual Viz\")\n\n # Compute Average Metrics\n psnr_list = np.array(psnr_list)\n rmse_list = np.array(rmse_list)\n ssim_list = np.array(ssim_list)\n lpips_list = np.array(lpips_list)\n avg_psnr = psnr_list.mean()\n avg_rmse = rmse_list.mean()\n avg_ssim = ssim_list.mean()\n avg_lpips = lpips_list.mean()\n print(\"Average PSNR: {:.2f}\".format(avg_psnr))\n print(\"Average Depth RMSE: {:.2f}\".format(avg_rmse))\n print(\"Average MS-SSIM: {:.2f}\".format(avg_ssim))\n print(\"Average LPIPS: {:.2f}\".format(avg_lpips))\n\n if wandb_run is not None:\n wandb_run.log({\"Average PSNR\": avg_psnr, \"Average Depth RMSE\": avg_rmse, \"Average MS-SSIM\": avg_ssim, \"Average LPIPS\": avg_lpips})\n\n # # Save metric lists as text files\n # np.savetxt(os.path.join(eval_dir, \"psnr.txt\"), psnr_list)\n # np.savetxt(os.path.join(eval_dir, \"rmse.txt\"), rmse_list)\n # np.savetxt(os.path.join(eval_dir, \"ssim.txt\"), ssim_list)\n # np.savetxt(os.path.join(eval_dir, \"lpips.txt\"), lpips_list)\n\n # # Plot PSNR & RMSE as line plots\n # fig, axs = plt.subplots(1, 2, figsize=(12, 4))\n # axs[0].plot(np.arange(num_frames), psnr_list)\n # axs[0].set_title(\"RGB PSNR\")\n # axs[0].set_xlabel(\"Time Step\")\n # axs[0].set_ylabel(\"PSNR\")\n # axs[1].plot(np.arange(num_frames), rmse_list)\n # axs[1].set_title(\"Depth RMSE\")\n # axs[1].set_xlabel(\"Time Step\")\n # axs[1].set_ylabel(\"RMSE\")\n # fig.suptitle(\"Average PSNR: {:.2f}, Average Depth RMSE: {:.2f}\".format(avg_psnr, avg_rmse), y=1.05, fontsize=16)\n # plt.savefig(os.path.join(eval_dir, \"metrics.png\"), bbox_inches='tight')\n # if wandb_run is not None:\n # wandb_run.log({\"Eval Metrics\": fig})\n # plt.close()" }, { "identifier": "l1_loss_v1", "path": "utils/gs_helpers.py", "snippet": "def l1_loss_v1(x, y):\n return torch.abs((x - y)).mean()" }, { "identifier": "matrix_to_quaternion", "path": "utils/gs_helpers.py", "snippet": "def matrix_to_quaternion(matrix: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Convert rotations given as rotation matrices to quaternions.\n\n Args:\n matrix: Rotation matrices as tensor of shape (..., 3, 3).\n\n Returns:\n quaternions with real part first, as tensor of shape (..., 4).\n Source: https://pytorch3d.readthedocs.io/en/latest/_modules/pytorch3d/transforms/rotation_conversions.html#matrix_to_quaternion\n \"\"\"\n if matrix.size(-1) != 3 or matrix.size(-2) != 3:\n raise ValueError(f\"Invalid rotation matrix shape {matrix.shape}.\")\n\n batch_dim = matrix.shape[:-2]\n m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(\n matrix.reshape(batch_dim + (9,)), dim=-1\n )\n\n q_abs = _sqrt_positive_part(\n torch.stack(\n [\n 1.0 + m00 + m11 + m22,\n 1.0 + m00 - m11 - m22,\n 1.0 - m00 + m11 - m22,\n 1.0 - m00 - m11 + m22,\n ],\n dim=-1,\n )\n )\n\n # we produce the desired quaternion multiplied by each of r, i, j, k\n quat_by_rijk = torch.stack(\n [\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1),\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1),\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1),\n # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and\n # `int`.\n torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1),\n ],\n dim=-2,\n )\n\n # We floor here at 0.1 but the exact level is not important; if q_abs is small,\n # the candidate won't be picked.\n flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device)\n quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr))\n\n # if not for numerical problems, quat_candidates[i] should be same (up to a sign),\n # forall i; we pick the best-conditioned one (with the largest denominator)\n\n return quat_candidates[\n F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :\n ].reshape(batch_dim + (4,))" }, { "identifier": "calc_ssim", "path": "utils/gs_external.py", "snippet": "def calc_ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)" }, { "identifier": "build_rotation", "path": "utils/gs_external.py", "snippet": "def build_rotation(q):\n norm = torch.sqrt(q[:, 0] * q[:, 0] + q[:, 1] * q[:, 1] + q[:, 2] * q[:, 2] + q[:, 3] * q[:, 3])\n q = q / norm[:, None]\n rot = torch.zeros((q.size(0), 3, 3), device='cuda')\n r = q[:, 0]\n x = q[:, 1]\n y = q[:, 2]\n z = q[:, 3]\n rot[:, 0, 0] = 1 - 2 * (y * y + z * z)\n rot[:, 0, 1] = 2 * (x * y - r * z)\n rot[:, 0, 2] = 2 * (x * z + r * y)\n rot[:, 1, 0] = 2 * (x * y + r * z)\n rot[:, 1, 1] = 1 - 2 * (x * x + z * z)\n rot[:, 1, 2] = 2 * (y * z - r * x)\n rot[:, 2, 0] = 2 * (x * z - r * y)\n rot[:, 2, 1] = 2 * (y * z + r * x)\n rot[:, 2, 2] = 1 - 2 * (x * x + y * y)\n return rot" }, { "identifier": "densify", "path": "utils/gs_external.py", "snippet": "def densify(params, variables, optimizer, iter, densify_dict):\n if iter <= densify_dict['stop_after']:\n variables = accumulate_mean2d_gradient(variables)\n grad_thresh = densify_dict['grad_thresh']\n if (iter >= densify_dict['start_after']) and (iter % densify_dict['densify_every'] == 0):\n grads = variables['means2D_gradient_accum'] / variables['denom']\n grads[grads.isnan()] = 0.0\n to_clone = torch.logical_and(grads >= grad_thresh, (\n torch.max(torch.exp(params['log_scales']), dim=1).values <= 0.01 * variables['scene_radius']))\n new_params = {k: v[to_clone] for k, v in params.items() if k not in ['cam_unnorm_rots', 'cam_trans']}\n\n new_timestep_vars = torch.zeros(new_params['means3D'].shape[0], device=\"cuda\")\n new_timestep_vars = variables['timestep'][to_clone] \n variables['timestep'] = torch.cat((variables['timestep'], new_timestep_vars), dim=0)\n params = cat_params_to_optimizer(new_params, params, optimizer)\n num_pts = params['means3D'].shape[0]\n\n padded_grad = torch.zeros(num_pts, device=\"cuda\")\n padded_grad[:grads.shape[0]] = grads\n to_split = torch.logical_and(padded_grad >= grad_thresh,\n torch.max(torch.exp(params['log_scales']), dim=1).values > 0.01 * variables[\n 'scene_radius'])\n n = densify_dict['num_to_split_into'] # number to split into\n new_params = {k: v[to_split].repeat(n, 1) for k, v in params.items() if k not in ['cam_unnorm_rots', 'cam_trans']}\n #track new variables for new formed points\n new_timestep_vars = torch.zeros(new_params['means3D'].shape[0], device=\"cuda\")\n new_timestep_vars = variables['timestep'][to_split].repeat(n)\n variables['timestep'] = torch.cat((variables['timestep'], new_timestep_vars), dim=0)\n\n stds = torch.exp(params['log_scales'])[to_split].repeat(n, 3)\n means = torch.zeros((stds.size(0), 3), device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = build_rotation(params['unnorm_rotations'][to_split]).repeat(n, 1, 1)\n new_params['means3D'] += torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1)\n new_params['log_scales'] = torch.log(torch.exp(new_params['log_scales']) / (0.8 * n))\n params = cat_params_to_optimizer(new_params, params, optimizer)\n num_pts = params['means3D'].shape[0]\n \n variables['means2D_gradient_accum'] = torch.zeros(num_pts, device=\"cuda\")\n variables['denom'] = torch.zeros(num_pts, device=\"cuda\")\n variables['max_2D_radius'] = torch.zeros(num_pts, device=\"cuda\")\n\n to_remove = torch.cat((to_split, torch.zeros(n * to_split.sum(), dtype=torch.bool, device=\"cuda\")))\n params, variables = remove_points(to_remove, params, variables, optimizer)\n\n if iter == densify_dict['stop_after']:\n remove_threshold = densify_dict['final_removal_opacity_threshold']\n else:\n remove_threshold = densify_dict['removal_opacity_threshold']\n to_remove = (torch.sigmoid(params['logit_opacities']) < remove_threshold).squeeze()\n if iter >= densify_dict['remove_big_after']:\n big_points_ws = torch.exp(params['log_scales']).max(dim=1).values > 0.1 * variables['scene_radius']\n to_remove = torch.logical_or(to_remove, big_points_ws)\n params, variables = remove_points(to_remove, params, variables, optimizer)\n\n torch.cuda.empty_cache()\n\n # Reset Opacities for all Gaussians (This is not desired for mapping on only current frame)\n if iter > 0 and iter % densify_dict['reset_opacities_every'] == 0 and densify_dict['reset_opacities']:\n new_params = {'logit_opacities': inverse_sigmoid(torch.ones_like(params['logit_opacities']) * 0.01)}\n params = update_params_and_optimizer(new_params, params, optimizer)\n\n return params, variables" }, { "identifier": "get_expon_lr_func", "path": "utils/gs_external.py", "snippet": "def get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n \"\"\"\n Copied from Plenoxels\n\n Continuous learning rate decay function. Adapted from JaxNeRF\n The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n is log-linearly interpolated elsewhere (equivalent to exponential decay).\n If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n function of lr_delay_mult, such that the initial learning rate is\n lr_init*lr_delay_mult at the beginning of optimization but will be eased back\n to the normal learning rate when steps>lr_delay_steps.\n :param conf: config subtree 'lr' or similar\n :param max_steps: int, the number of steps during optimization.\n :return HoF which takes step as input\n \"\"\"\n\n def helper(step):\n if step < 0 or (lr_init == 0.0 and lr_final == 0.0):\n # Disable this parameter\n return 0.0\n if lr_delay_steps > 0:\n # A kind of reverse cosine decay.\n delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(\n 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)\n )\n else:\n delay_rate = 1.0\n t = np.clip(step / max_steps, 0, 1)\n log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n return delay_rate * log_lerp\n\n return helper" }, { "identifier": "update_learning_rate", "path": "utils/gs_external.py", "snippet": "def update_learning_rate(optimizer, means3D_scheduler, iteration):\n ''' Learning rate scheduling per step '''\n for param_group in optimizer.param_groups:\n if param_group[\"name\"] == \"means3D\":\n lr = means3D_scheduler(iteration)\n param_group['lr'] = lr\n return lr" } ]
import argparse import os import random import sys import shutil import cv2 import numpy as np import torch import wandb from importlib.machinery import SourceFileLoader from tqdm import tqdm from datasets.gradslam_datasets import ( load_dataset_config, ICLDataset, ReplicaDataset, AzureKinectDataset, ScannetDataset, Ai2thorDataset, Record3DDataset, RealsenseDataset, TUMDataset, ScannetPPDataset, NeRFCaptureDataset ) from utils.common_utils import seed_everything, save_seq_params from utils.recon_helpers import setup_camera from utils.gs_helpers import ( params2rendervar, params2depthplussilhouette, transformed_params2depthplussilhouette, transform_to_frame, report_progress, eval, l1_loss_v1, matrix_to_quaternion ) from utils.gs_external import ( calc_ssim, build_rotation, densify, get_expon_lr_func, update_learning_rate ) from diff_gaussian_rasterization import GaussianRasterizer as Renderer
16,618
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _BASE_DIR) print("System Paths:") for p in sys.path: print(p) def get_dataset(config_dict, basedir, sequence, **kwargs): if config_dict["dataset_name"].lower() in ["icl"]: return ICLDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["replica"]: return ReplicaDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["azure", "azurekinect"]: return AzureKinectDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["scannet"]:
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, _BASE_DIR) print("System Paths:") for p in sys.path: print(p) def get_dataset(config_dict, basedir, sequence, **kwargs): if config_dict["dataset_name"].lower() in ["icl"]: return ICLDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["replica"]: return ReplicaDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["azure", "azurekinect"]: return AzureKinectDataset(config_dict, basedir, sequence, **kwargs) elif config_dict["dataset_name"].lower() in ["scannet"]:
return ScannetDataset(config_dict, basedir, sequence, **kwargs)
4
2023-11-30 20:26:47+00:00
24k
zhyever/PatchFusion
zoedepth/models/zoedepth_custom/patchfusion.py
[ { "identifier": "DepthModel", "path": "zoedepth/models/depth_model.py", "snippet": "class DepthModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.device = 'cpu'\n \n def to(self, device) -> nn.Module:\n self.device = device\n return super().to(device)\n \n def forward(self, x, *args, **kwargs):\n raise NotImplementedError\n \n def _infer(self, x: torch.Tensor):\n \"\"\"\n Inference interface for the model\n Args:\n x (torch.Tensor): input tensor of shape (b, c, h, w)\n Returns:\n torch.Tensor: output tensor of shape (b, 1, h, w)\n \"\"\"\n return self(x)['metric_depth']\n \n def _infer_with_pad_aug(self, x: torch.Tensor, pad_input: bool=True, fh: float=3, fw: float=3, upsampling_mode: str='bicubic', padding_mode=\"reflect\", **kwargs) -> torch.Tensor:\n \"\"\"\n Inference interface for the model with padding augmentation\n Padding augmentation fixes the boundary artifacts in the output depth map.\n Boundary artifacts are sometimes caused by the fact that the model is trained on NYU raw dataset which has a black or white border around the image.\n This augmentation pads the input image and crops the prediction back to the original size / view.\n\n Note: This augmentation is not required for the models trained with 'avoid_boundary'=True.\n Args:\n x (torch.Tensor): input tensor of shape (b, c, h, w)\n pad_input (bool, optional): whether to pad the input or not. Defaults to True.\n fh (float, optional): height padding factor. The padding is calculated as sqrt(h/2) * fh. Defaults to 3.\n fw (float, optional): width padding factor. The padding is calculated as sqrt(w/2) * fw. Defaults to 3.\n upsampling_mode (str, optional): upsampling mode. Defaults to 'bicubic'.\n padding_mode (str, optional): padding mode. Defaults to \"reflect\".\n Returns:\n torch.Tensor: output tensor of shape (b, 1, h, w)\n \"\"\"\n # assert x is nchw and c = 3\n assert x.dim() == 4, \"x must be 4 dimensional, got {}\".format(x.dim())\n assert x.shape[1] == 3, \"x must have 3 channels, got {}\".format(x.shape[1])\n\n if pad_input:\n assert fh > 0 or fw > 0, \"atlease one of fh and fw must be greater than 0\"\n pad_h = int(np.sqrt(x.shape[2]/2) * fh)\n pad_w = int(np.sqrt(x.shape[3]/2) * fw)\n padding = [pad_w, pad_w]\n if pad_h > 0:\n padding += [pad_h, pad_h]\n \n x = F.pad(x, padding, mode=padding_mode, **kwargs)\n out = self._infer(x)\n if out.shape[-2:] != x.shape[-2:]:\n out = F.interpolate(out, size=(x.shape[2], x.shape[3]), mode=upsampling_mode, align_corners=False)\n if pad_input:\n # crop to the original size, handling the case where pad_h and pad_w is 0\n if pad_h > 0:\n out = out[:, :, pad_h:-pad_h,:]\n if pad_w > 0:\n out = out[:, :, :, pad_w:-pad_w]\n return out\n \n def infer_with_flip_aug(self, x, pad_input: bool=True, **kwargs) -> torch.Tensor:\n \"\"\"\n Inference interface for the model with horizontal flip augmentation\n Horizontal flip augmentation improves the accuracy of the model by averaging the output of the model with and without horizontal flip.\n Args:\n x (torch.Tensor): input tensor of shape (b, c, h, w)\n pad_input (bool, optional): whether to use padding augmentation. Defaults to True.\n Returns:\n torch.Tensor: output tensor of shape (b, 1, h, w)\n \"\"\"\n # infer with horizontal flip and average\n out = self._infer_with_pad_aug(x, pad_input=pad_input, **kwargs)\n out_flip = self._infer_with_pad_aug(torch.flip(x, dims=[3]), pad_input=pad_input, **kwargs)\n out = (out + torch.flip(out_flip, dims=[3])) / 2\n return out\n \n def infer(self, x, pad_input: bool=True, with_flip_aug: bool=True, **kwargs) -> torch.Tensor:\n \"\"\"\n Inference interface for the model\n Args:\n x (torch.Tensor): input tensor of shape (b, c, h, w)\n pad_input (bool, optional): whether to use padding augmentation. Defaults to True.\n with_flip_aug (bool, optional): whether to use horizontal flip augmentation. Defaults to True.\n Returns:\n torch.Tensor: output tensor of shape (b, 1, h, w)\n \"\"\"\n if with_flip_aug:\n return self.infer_with_flip_aug(x, pad_input=pad_input, **kwargs)\n else:\n return self._infer_with_pad_aug(x, pad_input=pad_input, **kwargs)\n \n @torch.no_grad()\n def infer_pil(self, pil_img, pad_input: bool=True, with_flip_aug: bool=True, output_type: str=\"numpy\", **kwargs) -> Union[np.ndarray, PIL.Image.Image, torch.Tensor]:\n \"\"\"\n Inference interface for the model for PIL image\n Args:\n pil_img (PIL.Image.Image): input PIL image\n pad_input (bool, optional): whether to use padding augmentation. Defaults to True.\n with_flip_aug (bool, optional): whether to use horizontal flip augmentation. Defaults to True.\n output_type (str, optional): output type. Supported values are 'numpy', 'pil' and 'tensor'. Defaults to \"numpy\".\n \"\"\"\n x = transforms.ToTensor()(pil_img).unsqueeze(0).to(self.device)\n out_tensor = self.infer(x, pad_input=pad_input, with_flip_aug=with_flip_aug, **kwargs)\n if output_type == \"numpy\":\n return out_tensor.squeeze().cpu().numpy()\n elif output_type == \"pil\":\n # uint16 is required for depth pil image\n out_16bit_numpy = (out_tensor.squeeze().cpu().numpy()*256).astype(np.uint16)\n return Image.fromarray(out_16bit_numpy)\n elif output_type == \"tensor\":\n return out_tensor.squeeze().cpu()\n else:\n raise ValueError(f\"output_type {output_type} not supported. Supported values are 'numpy', 'pil' and 'tensor'\")" }, { "identifier": "MidasCore", "path": "zoedepth/models/base_models/midas.py", "snippet": "class MidasCore(nn.Module):\n def __init__(self, midas, trainable=False, fetch_features=True, layer_names=('out_conv', 'l4_rn', 'r4', 'r3', 'r2', 'r1'), freeze_bn=False, keep_aspect_ratio=True,\n img_size=384, **kwargs):\n \"\"\"Midas Base model used for multi-scale feature extraction.\n\n Args:\n midas (torch.nn.Module): Midas model.\n trainable (bool, optional): Train midas model. Defaults to False.\n fetch_features (bool, optional): Extract multi-scale features. Defaults to True.\n layer_names (tuple, optional): Layers used for feature extraction. Order = (head output features, last layer features, ...decoder features). Defaults to ('out_conv', 'l4_rn', 'r4', 'r3', 'r2', 'r1').\n freeze_bn (bool, optional): Freeze BatchNorm. Generally results in better finetuning performance. Defaults to False.\n keep_aspect_ratio (bool, optional): Keep the aspect ratio of input images while resizing. Defaults to True.\n img_size (int, tuple, optional): Input resolution. Defaults to 384.\n \"\"\"\n super().__init__()\n self.core = midas\n self.output_channels = None\n self.core_out = {}\n self.trainable = trainable\n self.fetch_features = fetch_features\n # midas.scratch.output_conv = nn.Identity()\n self.handles = []\n # self.layer_names = ['out_conv','l4_rn', 'r4', 'r3', 'r2', 'r1']\n self.layer_names = layer_names\n\n self.set_trainable(trainable)\n self.set_fetch_features(fetch_features)\n\n self.prep = PrepForMidas(keep_aspect_ratio=keep_aspect_ratio,\n img_size=img_size, do_resize=kwargs.get('do_resize', True))\n\n if freeze_bn:\n self.freeze_bn()\n\n def set_trainable(self, trainable):\n self.trainable = trainable\n if trainable:\n self.unfreeze()\n else:\n self.freeze()\n return self\n\n def set_fetch_features(self, fetch_features):\n self.fetch_features = fetch_features\n if fetch_features:\n if len(self.handles) == 0:\n self.attach_hooks(self.core)\n else:\n self.remove_hooks()\n return self\n\n def freeze(self):\n for p in self.parameters():\n p.requires_grad = False\n self.trainable = False\n return self\n\n def unfreeze(self):\n for p in self.parameters():\n p.requires_grad = True\n self.trainable = True\n return self\n\n def freeze_bn(self):\n for m in self.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.eval()\n return self\n\n def forward(self, x, denorm=False, return_rel_depth=False):\n with torch.no_grad():\n if denorm:\n x = denormalize(x)\n x = self.prep(x)\n # print(\"Shape after prep: \", x.shape)\n\n with torch.set_grad_enabled(self.trainable):\n\n # print(\"Input size to Midascore\", x.shape)\n rel_depth = self.core(x)\n # print(\"Output from midas shape\", rel_depth.shape)\n if not self.fetch_features:\n return rel_depth\n out = [self.core_out[k] for k in self.layer_names]\n\n if return_rel_depth:\n return rel_depth, out\n return out\n\n def get_rel_pos_params(self):\n for name, p in self.core.pretrained.named_parameters():\n if \"relative_position\" in name:\n yield p\n\n def get_enc_params_except_rel_pos(self):\n for name, p in self.core.pretrained.named_parameters():\n if \"relative_position\" not in name:\n yield p\n\n def freeze_encoder(self, freeze_rel_pos=False):\n if freeze_rel_pos:\n for p in self.core.pretrained.parameters():\n p.requires_grad = False\n else:\n for p in self.get_enc_params_except_rel_pos():\n p.requires_grad = False\n return self\n\n def attach_hooks(self, midas):\n if len(self.handles) > 0:\n self.remove_hooks()\n if \"out_conv\" in self.layer_names:\n self.handles.append(list(midas.scratch.output_conv.children())[\n 3].register_forward_hook(get_activation(\"out_conv\", self.core_out)))\n if \"r4\" in self.layer_names:\n self.handles.append(midas.scratch.refinenet4.register_forward_hook(\n get_activation(\"r4\", self.core_out)))\n if \"r3\" in self.layer_names:\n self.handles.append(midas.scratch.refinenet3.register_forward_hook(\n get_activation(\"r3\", self.core_out)))\n if \"r2\" in self.layer_names:\n self.handles.append(midas.scratch.refinenet2.register_forward_hook(\n get_activation(\"r2\", self.core_out)))\n if \"r1\" in self.layer_names:\n self.handles.append(midas.scratch.refinenet1.register_forward_hook(\n get_activation(\"r1\", self.core_out)))\n if \"l4_rn\" in self.layer_names:\n self.handles.append(midas.scratch.layer4_rn.register_forward_hook(\n get_activation(\"l4_rn\", self.core_out)))\n\n return self\n\n def remove_hooks(self):\n for h in self.handles:\n h.remove()\n return self\n\n def __del__(self):\n self.remove_hooks()\n\n def set_output_channels(self, model_type):\n self.output_channels = MIDAS_SETTINGS[model_type]\n\n @staticmethod\n def build(midas_model_type=\"DPT_BEiT_L_384\", train_midas=False, use_pretrained_midas=True, fetch_features=False, freeze_bn=True, force_keep_ar=False, force_reload=False, **kwargs):\n if midas_model_type not in MIDAS_SETTINGS:\n raise ValueError(\n f\"Invalid model type: {midas_model_type}. Must be one of {list(MIDAS_SETTINGS.keys())}\")\n if \"img_size\" in kwargs:\n kwargs = MidasCore.parse_img_size(kwargs)\n img_size = kwargs.pop(\"img_size\", [384, 384])\n print(\"img_size\", img_size)\n midas = torch.hub.load(\"intel-isl/MiDaS\", midas_model_type,\n pretrained=use_pretrained_midas, force_reload=force_reload)\n kwargs.update({'keep_aspect_ratio': force_keep_ar})\n midas_core = MidasCore(midas, trainable=train_midas, fetch_features=fetch_features,\n freeze_bn=freeze_bn, img_size=img_size, **kwargs)\n midas_core.set_output_channels(midas_model_type)\n return midas_core\n\n @staticmethod\n def build_from_config(config):\n return MidasCore.build(**config)\n\n @staticmethod\n def parse_img_size(config):\n assert 'img_size' in config\n if isinstance(config['img_size'], str):\n assert \",\" in config['img_size'], \"img_size should be a string with comma separated img_size=H,W\"\n config['img_size'] = list(map(int, config['img_size'].split(\",\")))\n assert len(\n config['img_size']) == 2, \"img_size should be a string with comma separated img_size=H,W\"\n elif isinstance(config['img_size'], int):\n config['img_size'] = [config['img_size'], config['img_size']]\n else:\n assert isinstance(config['img_size'], list) and len(\n config['img_size']) == 2, \"img_size should be a list of H,W\"\n return config" }, { "identifier": "AttractorLayer", "path": "zoedepth/models/layers/attractor.py", "snippet": "class AttractorLayer(nn.Module):\n def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,\n alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):\n \"\"\"\n Attractor layer for bin centers. Bin centers are bounded on the interval (min_depth, max_depth)\n \"\"\"\n super().__init__()\n\n self.n_attractors = n_attractors\n self.n_bins = n_bins\n self.min_depth = min_depth\n self.max_depth = max_depth\n self.alpha = alpha\n self.gamma = gamma\n self.kind = kind\n self.attractor_type = attractor_type\n self.memory_efficient = memory_efficient\n\n self._net = nn.Sequential(\n nn.Conv2d(in_features, mlp_dim, 1, 1, 0),\n nn.ReLU(inplace=True),\n nn.Conv2d(mlp_dim, n_attractors*2, 1, 1, 0), # x2 for linear norm\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):\n \"\"\"\n Args:\n x (torch.Tensor) : feature block; shape - n, c, h, w\n b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w\n \n Returns:\n tuple(torch.Tensor,torch.Tensor) : new bin centers normed and scaled; shape - n, nbins, h, w\n \"\"\"\n if prev_b_embedding is not None:\n if interpolate:\n prev_b_embedding = nn.functional.interpolate(\n prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)\n x = x + prev_b_embedding\n\n A = self._net(x)\n eps = 1e-3\n A = A + eps\n n, c, h, w = A.shape\n A = A.view(n, self.n_attractors, 2, h, w)\n A_normed = A / A.sum(dim=2, keepdim=True) # n, a, 2, h, w\n A_normed = A[:, :, 0, ...] # n, na, h, w\n\n b_prev = nn.functional.interpolate(\n b_prev, (h, w), mode='bilinear', align_corners=True)\n b_centers = b_prev\n\n if self.attractor_type == 'exp':\n dist = exp_attractor\n else:\n dist = inv_attractor\n\n if not self.memory_efficient:\n func = {'mean': torch.mean, 'sum': torch.sum}[self.kind]\n # .shape N, nbins, h, w\n delta_c = func(dist(A_normed.unsqueeze(\n 2) - b_centers.unsqueeze(1)), dim=1)\n else:\n delta_c = torch.zeros_like(b_centers, device=b_centers.device)\n for i in range(self.n_attractors):\n # .shape N, nbins, h, w\n delta_c += dist(A_normed[:, i, ...].unsqueeze(1) - b_centers)\n\n if self.kind == 'mean':\n delta_c = delta_c / self.n_attractors\n\n b_new_centers = b_centers + delta_c\n B_centers = (self.max_depth - self.min_depth) * \\\n b_new_centers + self.min_depth\n B_centers, _ = torch.sort(B_centers, dim=1)\n B_centers = torch.clip(B_centers, self.min_depth, self.max_depth)\n return b_new_centers, B_centers" }, { "identifier": "AttractorLayerUnnormed", "path": "zoedepth/models/layers/attractor.py", "snippet": "class AttractorLayerUnnormed(nn.Module):\n def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,\n alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):\n \"\"\"\n Attractor layer for bin centers. Bin centers are unbounded\n \"\"\"\n super().__init__()\n\n self.n_attractors = n_attractors\n self.n_bins = n_bins\n self.min_depth = min_depth\n self.max_depth = max_depth\n self.alpha = alpha\n self.gamma = gamma\n self.kind = kind\n self.attractor_type = attractor_type\n self.memory_efficient = memory_efficient\n\n self._net = nn.Sequential(\n nn.Conv2d(in_features, mlp_dim, 1, 1, 0),\n nn.ReLU(inplace=True),\n nn.Conv2d(mlp_dim, n_attractors, 1, 1, 0),\n nn.Softplus()\n )\n\n def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):\n \"\"\"\n Args:\n x (torch.Tensor) : feature block; shape - n, c, h, w\n b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w\n \n Returns:\n tuple(torch.Tensor,torch.Tensor) : new bin centers unbounded; shape - n, nbins, h, w. Two outputs just to keep the API consistent with the normed version\n \"\"\"\n if prev_b_embedding is not None:\n if interpolate:\n prev_b_embedding = nn.functional.interpolate(\n prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)\n x = x + prev_b_embedding\n\n A = self._net(x)\n n, c, h, w = A.shape\n\n b_prev = nn.functional.interpolate(\n b_prev, (h, w), mode='bilinear', align_corners=True)\n b_centers = b_prev\n\n if self.attractor_type == 'exp':\n dist = exp_attractor\n else:\n dist = inv_attractor\n\n if not self.memory_efficient:\n func = {'mean': torch.mean, 'sum': torch.sum}[self.kind]\n # .shape N, nbins, h, w\n delta_c = func(\n dist(A.unsqueeze(2) - b_centers.unsqueeze(1)), dim=1)\n else:\n delta_c = torch.zeros_like(b_centers, device=b_centers.device)\n for i in range(self.n_attractors):\n delta_c += dist(A[:, i, ...].unsqueeze(1) -\n b_centers) # .shape N, nbins, h, w\n\n if self.kind == 'mean':\n delta_c = delta_c / self.n_attractors\n\n b_new_centers = b_centers + delta_c\n B_centers = b_new_centers\n\n return b_new_centers, B_centers" }, { "identifier": "ConditionalLogBinomial", "path": "zoedepth/models/layers/dist_layers.py", "snippet": "class ConditionalLogBinomial(nn.Module):\n def __init__(self, in_features, condition_dim, n_classes=256, bottleneck_factor=2, p_eps=1e-4, max_temp=50, min_temp=1e-7, act=torch.softmax):\n \"\"\"Conditional Log Binomial distribution\n\n Args:\n in_features (int): number of input channels in main feature\n condition_dim (int): number of input channels in condition feature\n n_classes (int, optional): Number of classes. Defaults to 256.\n bottleneck_factor (int, optional): Hidden dim factor. Defaults to 2.\n p_eps (float, optional): small eps value. Defaults to 1e-4.\n max_temp (float, optional): Maximum temperature of output distribution. Defaults to 50.\n min_temp (float, optional): Minimum temperature of output distribution. Defaults to 1e-7.\n \"\"\"\n super().__init__()\n self.p_eps = p_eps\n self.max_temp = max_temp\n self.min_temp = min_temp\n self.log_binomial_transform = LogBinomial(n_classes, act=act)\n bottleneck = (in_features + condition_dim) // bottleneck_factor\n self.mlp = nn.Sequential(\n nn.Conv2d(in_features + condition_dim, bottleneck,\n kernel_size=1, stride=1, padding=0),\n nn.GELU(),\n # 2 for p linear norm, 2 for t linear norm\n nn.Conv2d(bottleneck, 2+2, kernel_size=1, stride=1, padding=0),\n nn.Softplus()\n )\n\n def forward(self, x, cond):\n \"\"\"Forward pass\n\n Args:\n x (torch.Tensor - NCHW): Main feature\n cond (torch.Tensor - NCHW): condition feature\n\n Returns:\n torch.Tensor: Output log binomial distribution\n \"\"\"\n pt = self.mlp(torch.concat((x, cond), dim=1))\n p, t = pt[:, :2, ...], pt[:, 2:, ...]\n\n p = p + self.p_eps\n p = p[:, 0, ...] / (p[:, 0, ...] + p[:, 1, ...])\n\n t = t + self.p_eps\n t = t[:, 0, ...] / (t[:, 0, ...] + t[:, 1, ...])\n t = t.unsqueeze(1)\n t = (self.max_temp - self.min_temp) * t + self.min_temp\n\n return self.log_binomial_transform(p, t)" }, { "identifier": "ConditionalLogBinomialV2", "path": "zoedepth/models/layers/dist_layers.py", "snippet": "class ConditionalLogBinomialV2(nn.Module):\n def __init__(self, in_features, condition_dim, n_classes=256, bottleneck_factor=2, p_eps=1e-4, max_temp=50, min_temp=1e-7, act=torch.softmax):\n \"\"\"Conditional Log Binomial distribution\n\n Args:\n in_features (int): number of input channels in main feature\n condition_dim (int): number of input channels in condition feature\n n_classes (int, optional): Number of classes. Defaults to 256.\n bottleneck_factor (int, optional): Hidden dim factor. Defaults to 2.\n p_eps (float, optional): small eps value. Defaults to 1e-4.\n max_temp (float, optional): Maximum temperature of output distribution. Defaults to 50.\n min_temp (float, optional): Minimum temperature of output distribution. Defaults to 1e-7.\n \"\"\"\n super().__init__()\n self.p_eps = p_eps\n self.max_temp = max_temp\n self.min_temp = min_temp\n self.log_binomial_transform = LogBinomial(n_classes, act=act)\n bottleneck = (in_features + condition_dim) // bottleneck_factor\n self.mlp = nn.Sequential(\n nn.Conv2d(in_features + condition_dim, bottleneck,\n kernel_size=1, stride=1, padding=0),\n nn.GELU(),\n # 2 for p linear norm, 2 for t linear norm\n nn.Conv2d(bottleneck, n_classes*2, kernel_size=1, stride=1, padding=0),\n nn.Sigmoid()\n )\n self.n_classes = n_classes\n\n\n def forward(self, x, cond):\n \"\"\"Forward pass\n\n Args:\n x (torch.Tensor - NCHW): Main feature\n cond (torch.Tensor - NCHW): condition feature\n\n Returns:\n torch.Tensor: Output log binomial distribution\n \"\"\"\n pt = self.mlp(torch.concat((x, cond), dim=1))\n prob, shift = pt[:, :self.n_classes, ...], pt[:, self.n_classes:, ...]\n return prob, shift" }, { "identifier": "Projector", "path": "zoedepth/models/layers/localbins_layers.py", "snippet": "class Projector(nn.Module):\n def __init__(self, in_features, out_features, mlp_dim=128):\n \"\"\"Projector MLP\n\n Args:\n in_features (int): input channels\n out_features (int): output channels\n mlp_dim (int, optional): hidden dimension. Defaults to 128.\n \"\"\"\n super().__init__()\n\n self._net = nn.Sequential(\n nn.Conv2d(in_features, mlp_dim, 1, 1, 0),\n nn.ReLU(inplace=True),\n nn.Conv2d(mlp_dim, out_features, 1, 1, 0),\n )\n\n def forward(self, x):\n return self._net(x)" }, { "identifier": "SeedBinRegressor", "path": "zoedepth/models/layers/localbins_layers.py", "snippet": "class SeedBinRegressor(nn.Module):\n def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):\n \"\"\"Bin center regressor network. Bin centers are bounded on (min_depth, max_depth) interval.\n\n Args:\n in_features (int): input channels\n n_bins (int, optional): Number of bin centers. Defaults to 16.\n mlp_dim (int, optional): Hidden dimension. Defaults to 256.\n min_depth (float, optional): Min depth value. Defaults to 1e-3.\n max_depth (float, optional): Max depth value. Defaults to 10.\n \"\"\"\n super().__init__()\n self.version = \"1_1\"\n self.min_depth = min_depth\n self.max_depth = max_depth\n\n self._net = nn.Sequential(\n nn.Conv2d(in_features, mlp_dim, 1, 1, 0),\n nn.ReLU(inplace=True),\n nn.Conv2d(mlp_dim, n_bins, 1, 1, 0),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n \"\"\"\n Returns tensor of bin_width vectors (centers). One vector b for every pixel\n \"\"\"\n B = self._net(x)\n eps = 1e-3\n B = B + eps\n B_widths_normed = B / B.sum(dim=1, keepdim=True)\n B_widths = (self.max_depth - self.min_depth) * \\\n B_widths_normed # .shape NCHW\n # pad has the form (left, right, top, bottom, front, back)\n B_widths = nn.functional.pad(\n B_widths, (0, 0, 0, 0, 1, 0), mode='constant', value=self.min_depth)\n B_edges = torch.cumsum(B_widths, dim=1) # .shape NCHW\n\n B_centers = 0.5 * (B_edges[:, :-1, ...] + B_edges[:, 1:, ...])\n return B_widths_normed, B_centers" }, { "identifier": "SeedBinRegressorUnnormed", "path": "zoedepth/models/layers/localbins_layers.py", "snippet": "class SeedBinRegressorUnnormed(nn.Module):\n def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):\n \"\"\"Bin center regressor network. Bin centers are unbounded\n\n Args:\n in_features (int): input channels\n n_bins (int, optional): Number of bin centers. Defaults to 16.\n mlp_dim (int, optional): Hidden dimension. Defaults to 256.\n min_depth (float, optional): Not used. (for compatibility with SeedBinRegressor)\n max_depth (float, optional): Not used. (for compatibility with SeedBinRegressor)\n \"\"\"\n super().__init__()\n self.version = \"1_1\"\n self._net = nn.Sequential(\n nn.Conv2d(in_features, mlp_dim, 1, 1, 0),\n nn.ReLU(inplace=True),\n nn.Conv2d(mlp_dim, n_bins, 1, 1, 0),\n nn.Softplus()\n )\n\n def forward(self, x):\n \"\"\"\n Returns tensor of bin_width vectors (centers). One vector b for every pixel\n \"\"\"\n B_centers = self._net(x)\n return B_centers, B_centers" }, { "identifier": "load_state_from_resource", "path": "zoedepth/models/model_io.py", "snippet": "def load_state_from_resource(model, resource: str):\n \"\"\"Loads weights to the model from a given resource. A resource can be of following types:\n 1. URL. Prefixed with \"url::\"\n e.g. url::http(s)://url.resource.com/ckpt.pt\n\n 2. Local path. Prefixed with \"local::\"\n e.g. local::/path/to/ckpt.pt\n\n\n Args:\n model (torch.nn.Module): Model\n resource (str): resource string\n\n Returns:\n torch.nn.Module: Model with loaded weights\n \"\"\"\n print(f\"Using pretrained resource {resource}\")\n\n if resource.startswith('url::'):\n url = resource.split('url::')[1]\n return load_state_dict_from_url(model, url, progress=True)\n\n elif resource.startswith('local::'):\n path = resource.split('local::')[1]\n return load_wts(model, path)\n \n else:\n raise ValueError(\"Invalid resource type, only url:: and local:: are supported\")" }, { "identifier": "generatemask", "path": "zoedepth/utils/misc.py", "snippet": "def generatemask(size, k_size=-1, sigma=-1, h_factor=0.03, w_factor=0.02):\n # Generates a Guassian mask\n mask = np.zeros(size, dtype=np.float32)\n if sigma == -1:\n sigma = int(size[0]/16)\n if k_size == -1:\n k_size = int(2 * np.ceil(2 * int(size[0]/16)) + 1)\n # mask[int(0.02*size[0]):size[0] - int(0.02*size[0]), int(0.015*size[1]): size[1] - int(0.015*size[1])] = 1\n mask[int(h_factor*size[0]):size[0] - int(h_factor*size[0]), int(w_factor*size[1]): size[1] - int(w_factor*size[1])] = 1\n mask = cv2.GaussianBlur(mask, (int(k_size), int(k_size)), sigma)\n mask = (mask - mask.min()) / (mask.max() - mask.min())\n mask = mask.astype(np.float32)\n return mask" }, { "identifier": "TransformerDecoderLayer", "path": "zoedepth/models/layers/transformer.py", "snippet": "class TransformerDecoderLayer(nn.Module):\n\n def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,\n activation=\"relu\", normalize_before=False):\n super().__init__()\n self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\n self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\n # Implementation of Feedforward model\n self.linear1 = nn.Linear(d_model, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n self.norm1 = nn.LayerNorm(d_model)\n self.norm2 = nn.LayerNorm(d_model)\n self.norm3 = nn.LayerNorm(d_model)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n self.dropout3 = nn.Dropout(dropout)\n\n self.activation = _get_activation_fn(activation)\n self.normalize_before = normalize_before\n\n def with_pos_embed(self, tensor, pos: Optional[Tensor]):\n return tensor if pos is None else tensor + pos\n\n def forward_post(self, tgt, memory,\n tgt_mask: Optional[Tensor] = None,\n memory_mask: Optional[Tensor] = None,\n tgt_key_padding_mask: Optional[Tensor] = None,\n memory_key_padding_mask: Optional[Tensor] = None,\n pos: Optional[Tensor] = None,\n query_pos: Optional[Tensor] = None):\n q = k = self.with_pos_embed(tgt, query_pos)\n tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask,\n key_padding_mask=tgt_key_padding_mask)[0]\n tgt = tgt + self.dropout1(tgt2)\n tgt = self.norm1(tgt)\n tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),\n key=self.with_pos_embed(memory, pos),\n value=memory, attn_mask=memory_mask,\n key_padding_mask=memory_key_padding_mask)[0]\n tgt = tgt + self.dropout2(tgt2)\n tgt = self.norm2(tgt)\n tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))\n tgt = tgt + self.dropout3(tgt2)\n tgt = self.norm3(tgt)\n return tgt\n\n def forward_pre(self, tgt, memory,\n tgt_mask: Optional[Tensor] = None,\n memory_mask: Optional[Tensor] = None,\n tgt_key_padding_mask: Optional[Tensor] = None,\n memory_key_padding_mask: Optional[Tensor] = None,\n pos: Optional[Tensor] = None,\n query_pos: Optional[Tensor] = None):\n tgt2 = self.norm1(tgt)\n q = k = self.with_pos_embed(tgt2, query_pos)\n tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask,\n key_padding_mask=tgt_key_padding_mask)[0]\n tgt = tgt + self.dropout1(tgt2)\n tgt2 = self.norm2(tgt)\n tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),\n key=self.with_pos_embed(memory, pos),\n value=memory, attn_mask=memory_mask,\n key_padding_mask=memory_key_padding_mask)[0]\n tgt = tgt + self.dropout2(tgt2)\n tgt2 = self.norm3(tgt)\n tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))\n tgt = tgt + self.dropout3(tgt2)\n return tgt\n\n def forward(self, tgt, memory,\n tgt_mask: Optional[Tensor] = None,\n memory_mask: Optional[Tensor] = None,\n tgt_key_padding_mask: Optional[Tensor] = None,\n memory_key_padding_mask: Optional[Tensor] = None,\n pos: Optional[Tensor] = None,\n query_pos: Optional[Tensor] = None):\n if self.normalize_before:\n return self.forward_pre(tgt, memory, tgt_mask, memory_mask,\n tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)\n return self.forward_post(tgt, memory, tgt_mask, memory_mask,\n tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)" }, { "identifier": "TransformerEncoderLayer", "path": "zoedepth/models/layers/transformer.py", "snippet": "class TransformerEncoderLayer(nn.Module):\n\n def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.0,\n activation=\"gelu\", normalize_before=False):\n super().__init__()\n self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\n # Implementation of Feedforward model\n self.linear1 = nn.Linear(d_model, dim_feedforward)\n self.dropout = nn.Dropout(dropout)\n self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n self.norm1 = nn.LayerNorm(d_model)\n self.norm2 = nn.LayerNorm(d_model)\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n\n self.activation = _get_activation_fn(activation)\n self.normalize_before = normalize_before\n\n def with_pos_embed(self, tensor, pos: Optional[Tensor]):\n return tensor if pos is None else tensor + pos\n\n def forward_post(self,\n src,\n src_mask: Optional[Tensor] = None,\n src_key_padding_mask: Optional[Tensor] = None,\n pos: Optional[Tensor] = None):\n q = k = self.with_pos_embed(src, pos)\n src2 = self.self_attn(q, k, value=src, attn_mask=src_mask,\n key_padding_mask=src_key_padding_mask)[0]\n src = src + self.dropout1(src2)\n src = self.norm1(src)\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))\n src = src + self.dropout2(src2)\n src = self.norm2(src)\n return src\n\n def forward_pre(self, src,\n src_mask: Optional[Tensor] = None,\n src_key_padding_mask: Optional[Tensor] = None,\n pos: Optional[Tensor] = None):\n src2 = self.norm1(src)\n q = k = self.with_pos_embed(src2, pos)\n src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask,\n key_padding_mask=src_key_padding_mask)[0]\n src = src + self.dropout1(src2)\n src2 = self.norm2(src)\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))\n src = src + self.dropout2(src2)\n return src\n\n def forward(self, src,\n src_mask: Optional[Tensor] = None,\n src_key_padding_mask: Optional[Tensor] = None,\n pos: Optional[Tensor] = None):\n if self.normalize_before:\n return self.forward_pre(src, src_mask, src_key_padding_mask, pos)\n return self.forward_post(src, src_mask, src_key_padding_mask, pos)" }, { "identifier": "TransformerEncoder", "path": "zoedepth/models/layers/transformer.py", "snippet": "class TransformerEncoder(nn.Module):\n\n def __init__(self, encoder_layer, num_layers, norm=None, num_patches=None, ape=True, embed_dim=None, input_dim=None):\n super().__init__()\n self.layers = _get_clones(encoder_layer, num_layers)\n self.num_layers = num_layers\n self.norm = norm\n\n self.embed_dim = embed_dim\n if input_dim != embed_dim:\n self.proj_x = nn.Conv2d(input_dim, embed_dim, 3, padding=1)\n else:\n self.proj_x = None\n\n self.embed_proj = nn.Conv2d(1, embed_dim, 1, 1, 0) # learnable\n self.ape = ape\n if self.ape:\n self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim), requires_grad=True)\n trunc_normal_(self.absolute_pos_embed, std=.02)\n\n def forward(self, x,\n mask: Optional[Tensor] = None,\n src_key_padding_mask: Optional[Tensor] = None,\n pos: Optional[Tensor] = None,\n area_prior = None):\n\n if self.proj_x is not None:\n x = self.proj_x(x)\n \n if area_prior is not None:\n prior_embed = self.embed_proj(area_prior)\n x = x + prior_embed\n\n Wh, Ww = x.size(2), x.size(3)\n x = x.flatten(2).transpose(1, 2)\n\n if self.ape:\n x = x + self.absolute_pos_embed # this line is later added\n\n for layer in self.layers:\n x = layer(x, src_mask=None, src_key_padding_mask=None, pos=None)\n\n if self.norm is not None:\n x = self.norm(x)\n\n x = x.view(-1, Wh, Ww, self.embed_dim).permute(0, 3, 1, 2).contiguous()\n return x" }, { "identifier": "colorize", "path": "zoedepth/utils/misc.py", "snippet": "def colorize(value, vmin=None, vmax=None, cmap='turbo_r', invalid_val=-99, invalid_mask=None, background_color=(128, 128, 128, 255), gamma_corrected=False, value_transform=None):\n \"\"\"Converts a depth map to a color image.\n\n Args:\n value (torch.Tensor, numpy.ndarry): Input depth map. Shape: (H, W) or (1, H, W) or (1, 1, H, W). All singular dimensions are squeezed\n vmin (float, optional): vmin-valued entries are mapped to start color of cmap. If None, value.min() is used. Defaults to None.\n vmax (float, optional): vmax-valued entries are mapped to end color of cmap. If None, value.max() is used. Defaults to None.\n cmap (str, optional): matplotlib colormap to use. Defaults to 'magma_r'.\n invalid_val (int, optional): Specifies value of invalid pixels that should be colored as 'background_color'. Defaults to -99.\n invalid_mask (numpy.ndarray, optional): Boolean mask for invalid regions. Defaults to None.\n background_color (tuple[int], optional): 4-tuple RGB color to give to invalid pixels. Defaults to (128, 128, 128, 255).\n gamma_corrected (bool, optional): Apply gamma correction to colored image. Defaults to False.\n value_transform (Callable, optional): Apply transform function to valid pixels before coloring. Defaults to None.\n\n Returns:\n numpy.ndarray, dtype - uint8: Colored depth map. Shape: (H, W, 4)\n \"\"\"\n if isinstance(value, torch.Tensor):\n value = value.detach().cpu().numpy()\n\n value = value.squeeze()\n if invalid_mask is None:\n invalid_mask = value == invalid_val\n mask = np.logical_not(invalid_mask)\n\n # normalize\n vmin = np.percentile(value[mask],2) if vmin is None else vmin\n vmax = np.percentile(value[mask],85) if vmax is None else vmax\n if vmin != vmax:\n value = (value - vmin) / (vmax - vmin) # vmin..vmax\n else:\n # Avoid 0-division\n value = value * 0.\n\n # squeeze last dim if it exists\n # grey out the invalid values\n\n value[invalid_mask] = np.nan\n cmapper = matplotlib.cm.get_cmap(cmap)\n if value_transform:\n value = value_transform(value)\n # value = value / value.max()\n value = cmapper(value, bytes=True) # (nxmx4)\n\n # img = value[:, :, :]\n img = value[...]\n img[invalid_mask] = background_color\n\n # return img.transpose((2, 0, 1))\n if gamma_corrected:\n # gamma correction\n img = img / 255\n img = np.power(img, 2.2)\n img = img * 255\n img = img.astype(np.uint8)\n return img" }, { "identifier": "colors", "path": "zoedepth/utils/misc.py", "snippet": "class colors:\n '''Colors class:\n Reset all colors with colors.reset\n Two subclasses fg for foreground and bg for background.\n Use as colors.subclass.colorname.\n i.e. colors.fg.red or colors.bg.green\n Also, the generic bold, disable, underline, reverse, strikethrough,\n and invisible work with the main class\n i.e. colors.bold\n '''\n reset = '\\033[0m'\n bold = '\\033[01m'\n disable = '\\033[02m'\n underline = '\\033[04m'\n reverse = '\\033[07m'\n strikethrough = '\\033[09m'\n invisible = '\\033[08m'\n\n class fg:\n black = '\\033[30m'\n red = '\\033[31m'\n green = '\\033[32m'\n orange = '\\033[33m'\n blue = '\\033[34m'\n purple = '\\033[35m'\n cyan = '\\033[36m'\n lightgrey = '\\033[37m'\n darkgrey = '\\033[90m'\n lightred = '\\033[91m'\n lightgreen = '\\033[92m'\n yellow = '\\033[93m'\n lightblue = '\\033[94m'\n pink = '\\033[95m'\n lightcyan = '\\033[96m'\n\n class bg:\n black = '\\033[40m'\n red = '\\033[41m'\n green = '\\033[42m'\n orange = '\\033[43m'\n blue = '\\033[44m'\n purple = '\\033[45m'\n cyan = '\\033[46m'\n lightgrey = '\\033[47m'" }, { "identifier": "UNetv1", "path": "zoedepth/models/layers/fusion_network.py", "snippet": "class UNetv1(nn.Module):\n def __init__(self, n_channels, g2l, pos_embed=False, use_area_prior=True):\n super(UNetv1, self).__init__()\n self.n_channels = n_channels\n\n self.inc = DoubleConv(n_channels, 32)\n self.down1 = Down(32, 256)\n self.down2 = Down(256, 256)\n self.down3 = Down(256, 256)\n self.down4 = Down(256, 256)\n self.down5 = Down(256, 256)\n\n self.up1 = Upv1(256+256+256, 256, 384)\n self.up2 = Upv1(256+256+256, 256, 384)\n self.up3 = Upv1(256+256+256, 256, 384)\n self.up4 = Upv1(256+256+256, 256, 384)\n self.up5 = Upv1(256+32+256, 32, 272)\n\n self.g2l = g2l\n \n if self.g2l:\n self.g2l_att = nn.ModuleList()\n win = 12\n in_channels = [32, 256, 256, 256, 256, 256]\n crf_dims = [32, 256, 256, 256, 256, 256]\n\n self.g2l5 = G2LFusion(input_dim=in_channels[5], embed_dim=crf_dims[5], window_size=win, num_heads=32, depth=4, num_patches=12*16)\n self.g2l4 = G2LFusion(input_dim=in_channels[4], embed_dim=crf_dims[4], window_size=win, num_heads=32, depth=4, num_patches=24*32)\n self.g2l3 = G2LFusion(input_dim=in_channels[3], embed_dim=crf_dims[3], window_size=win, num_heads=16, depth=3, num_patches=48*64)\n self.g2l2 = G2LFusion(input_dim=in_channels[2], embed_dim=crf_dims[2], window_size=win, num_heads=16, depth=3, num_patches=96*128)\n self.g2l1 = G2LFusion(input_dim=in_channels[1], embed_dim=crf_dims[1], window_size=win, num_heads=8, depth=2, num_patches=192*256)\n self.g2l0 = G2LFusion(input_dim=in_channels[0], embed_dim=crf_dims[0], window_size=win, num_heads=8, depth=2, num_patches=384*512) \n\n self.conv5 = DoubleConvWOBN(in_channels[4] * 2, in_channels[4], in_channels[4])\n self.conv4 = DoubleConvWOBN(in_channels[4] * 2, in_channels[4], in_channels[4])\n self.conv3 = DoubleConvWOBN(in_channels[3] * 2, in_channels[3], in_channels[3])\n self.conv2 = DoubleConvWOBN(in_channels[2] * 2, in_channels[2], in_channels[2])\n self.conv1 = DoubleConvWOBN(in_channels[1] * 2, in_channels[1], in_channels[1])\n self.conv0 = DoubleConvWOBN(in_channels[0] * 2, in_channels[0], in_channels[0])\n \n def forward(self, \n input_tensor, \n guide_plus, \n guide_cat, \n crop_area_resize=None, \n bbox=None, \n fine_feat_crop=None, \n coarse_feat_whole=None, \n coarse_feat_whole_hack=None, \n coarse_feat_crop=None):\n\n # apply unscaled feat to swin\n if coarse_feat_whole_hack is not None:\n coarse_feat_whole = coarse_feat_whole_hack\n\n if crop_area_resize is None:\n not_use_prior = True\n else:\n not_use_prior = False\n \n x1 = self.inc(input_tensor)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3) \n x5 = self.down4(x4)\n x6 = self.down5(x5)\n if self.g2l:\n g2l_feat5 = self.g2l5(coarse_feat_whole[0], crop_area_resize[0])\n g2l_feat5 = torch_roi_align(g2l_feat5, bbox, (12, 16), 12/384, aligned=True)\n x6 = self.conv5(torch.cat([x6, g2l_feat5], dim=1))\n \n x5 = self.up1(torch.cat([x6, guide_cat[0]], dim=1), x5)\n if self.g2l:\n g2l_feat4 = self.g2l4(coarse_feat_whole[1], crop_area_resize[1])\n g2l_feat4 = torch_roi_align(g2l_feat4, bbox, (24, 32), 24/384, aligned=True)\n x5 = self.conv4(torch.cat([x5, g2l_feat4], dim=1)) \n\n x4 = self.up2(torch.cat([x5, guide_cat[1]], dim=1), x4)\n if self.g2l:\n g2l_feat3 = self.g2l3(coarse_feat_whole[2], crop_area_resize[2])\n g2l_feat3 = torch_roi_align(g2l_feat3, bbox, (48, 64), 48/384, aligned=True)\n x4 = self.conv3(torch.cat([x4, g2l_feat3], dim=1))\n\n x3 = self.up3(torch.cat([x4, guide_cat[2]], dim=1), x3)\n if self.g2l:\n g2l_feat2 = self.g2l2(coarse_feat_whole[3], crop_area_resize[3])\n g2l_feat2 = torch_roi_align(g2l_feat2, bbox, (96, 128), 96/384, aligned=True)\n x3 = self.conv2(torch.cat([x3, g2l_feat2], dim=1))\n\n x2 = self.up4(torch.cat([x3, guide_cat[3]], dim=1), x2)\n if self.g2l:\n g2l_feat1 = self.g2l1(coarse_feat_whole[4], crop_area_resize[4])\n g2l_feat1 = torch_roi_align(g2l_feat1, bbox, (192, 256), 192/384, aligned=True)\n x2 = self.conv1(torch.cat([x2, g2l_feat1], dim=1))\n\n x1 = self.up5(torch.cat([x2, guide_cat[4]], dim=1), x1)\n if self.g2l:\n g2l_feat0 = self.g2l0(coarse_feat_whole[5], crop_area_resize[5])\n g2l_feat0 = torch_roi_align(g2l_feat0, bbox, (384, 512), 384/384, aligned=True)\n x1 = self.conv0(torch.cat([x1, g2l_feat0], dim=1))\n\n output = [x1, x2, x3, x4, x5, x6]\n return output" } ]
import itertools import math import copy import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt import os import torch.distributed as dist import torch.nn.functional as F from zoedepth.models.depth_model import DepthModel from zoedepth.models.base_models.midas import MidasCore from zoedepth.models.layers.attractor import AttractorLayer, AttractorLayerUnnormed from zoedepth.models.layers.dist_layers import ConditionalLogBinomial, ConditionalLogBinomialV2 from zoedepth.models.layers.localbins_layers import (Projector, SeedBinRegressor, SeedBinRegressorUnnormed) from zoedepth.models.model_io import load_state_from_resource from torchvision.transforms import Normalize from torchvision.ops import roi_align as torch_roi_align from zoedepth.utils.misc import generatemask from zoedepth.models.layers.transformer import TransformerDecoderLayer, TransformerEncoderLayer, TransformerEncoder from zoedepth.utils.misc import colorize, colors from zoedepth.models.layers.fusion_network import UNetv1 from zoedepth.models.zoedepth_custom.zoedepth_custom import ZoeDepthCustom
14,571
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # File author: Zhenyu Li def check_keywords_in_name(name, keywords=()): isin = False for keyword in keywords: if keyword in name: isin = True return isin def get_activation(name, bank): # input of forward_hook will be a function of model/inp/oup def hook(module, input, output): bank[name] = output return hook def get_input(name, bank): # input of forward_hook will be a function of model/inp/oup def hook(module, input, output): bank[name] = input return hook class AttributeDict(dict): def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError: raise AttributeError(key) class PatchFusion(DepthModel): def __init__(self, coarse_model, fine_model, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10, n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True, midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, sr_ratio=1, raw_depth_shape=(2160, 3840), transform_sample_gt_size=(2160, 3840), representation='', fetch_features=True, sample_feat_level=3, use_hr=False, deform=False, wo_bins=False, baseline=False, condition=True, freeze=False, g2l=False, use_fusion_network=False, use_area_prior=False, unet_version='v1', consistency_training=False, consistency_target='unet_feat', pos_embed=False, **kwargs): """ZoeDepth model. This is the version of ZoeDepth that has a single metric head Args: core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features n_bins (int, optional): Number of bin centers. Defaults to 64. bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded. Defaults to "softplus". bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3. max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10. n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1]. attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300. attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2. attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'. attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'. min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5. max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50. train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True. midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10. encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10. pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10. sr_ratio: sr ratio during infer raw_depth_shape: raw depth shape during infer. times sr_ratio will be the target resolution. Used to sample points during training transform_sample_gt_size: training depth shape # influenced by crop shape which is not included in this pipeline right now representation: I use it to test the "bilap head" and a discarded idea fetch_features: if fetch feats. Default=True """ super().__init__() self.coarse_model = coarse_model self.fine_model = fine_model self.max_depth = max_depth self.min_depth = min_depth self.min_temp = min_temp self.bin_centers_type = bin_centers_type self.midas_lr_factor = midas_lr_factor self.encoder_lr_factor = encoder_lr_factor self.pos_enc_lr_factor = pos_enc_lr_factor self.train_midas = train_midas self.inverse_midas = inverse_midas if bin_centers_type == "normed": SeedBinRegressorLayer = SeedBinRegressor
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # File author: Zhenyu Li def check_keywords_in_name(name, keywords=()): isin = False for keyword in keywords: if keyword in name: isin = True return isin def get_activation(name, bank): # input of forward_hook will be a function of model/inp/oup def hook(module, input, output): bank[name] = output return hook def get_input(name, bank): # input of forward_hook will be a function of model/inp/oup def hook(module, input, output): bank[name] = input return hook class AttributeDict(dict): def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError: raise AttributeError(key) class PatchFusion(DepthModel): def __init__(self, coarse_model, fine_model, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10, n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True, midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, sr_ratio=1, raw_depth_shape=(2160, 3840), transform_sample_gt_size=(2160, 3840), representation='', fetch_features=True, sample_feat_level=3, use_hr=False, deform=False, wo_bins=False, baseline=False, condition=True, freeze=False, g2l=False, use_fusion_network=False, use_area_prior=False, unet_version='v1', consistency_training=False, consistency_target='unet_feat', pos_embed=False, **kwargs): """ZoeDepth model. This is the version of ZoeDepth that has a single metric head Args: core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features n_bins (int, optional): Number of bin centers. Defaults to 64. bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded. Defaults to "softplus". bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3. max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10. n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1]. attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300. attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2. attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'. attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'. min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5. max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50. train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True. midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10. encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10. pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10. sr_ratio: sr ratio during infer raw_depth_shape: raw depth shape during infer. times sr_ratio will be the target resolution. Used to sample points during training transform_sample_gt_size: training depth shape # influenced by crop shape which is not included in this pipeline right now representation: I use it to test the "bilap head" and a discarded idea fetch_features: if fetch feats. Default=True """ super().__init__() self.coarse_model = coarse_model self.fine_model = fine_model self.max_depth = max_depth self.min_depth = min_depth self.min_temp = min_temp self.bin_centers_type = bin_centers_type self.midas_lr_factor = midas_lr_factor self.encoder_lr_factor = encoder_lr_factor self.pos_enc_lr_factor = pos_enc_lr_factor self.train_midas = train_midas self.inverse_midas = inverse_midas if bin_centers_type == "normed": SeedBinRegressorLayer = SeedBinRegressor
Attractor = AttractorLayer
2
2023-12-04 08:43:15+00:00
24k
alvinliu0/HumanGaussian
threestudio/models/geometry/tetrahedra_sdf_grid.py
[ { "identifier": "BaseExplicitGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseExplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n\n cfg: Config\n\n def configure(self) -> None:\n self.bbox: Float[Tensor, \"2 3\"]\n self.register_buffer(\n \"bbox\",\n torch.as_tensor(\n [\n [-self.cfg.radius, -self.cfg.radius, -self.cfg.radius],\n [self.cfg.radius, self.cfg.radius, self.cfg.radius],\n ],\n dtype=torch.float32,\n ),\n )" }, { "identifier": "BaseGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseGeometry(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n @staticmethod\n def create_from(\n other: \"BaseGeometry\", cfg: Optional[Union[dict, DictConfig]] = None, **kwargs\n ) -> \"BaseGeometry\":\n raise TypeError(\n f\"Cannot create {BaseGeometry.__name__} from {other.__class__.__name__}\"\n )\n\n def export(self, *args, **kwargs) -> Dict[str, Any]:\n return {}" }, { "identifier": "contract_to_unisphere", "path": "threestudio/models/geometry/base.py", "snippet": "def contract_to_unisphere(\n x: Float[Tensor, \"... 3\"], bbox: Float[Tensor, \"2 3\"], unbounded: bool = False\n) -> Float[Tensor, \"... 3\"]:\n if unbounded:\n x = scale_tensor(x, bbox, (0, 1))\n x = x * 2 - 1 # aabb is at [-1, 1]\n mag = x.norm(dim=-1, keepdim=True)\n mask = mag.squeeze(-1) > 1\n x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask])\n x = x / 4 + 0.5 # [-inf, inf] is at [0, 1]\n else:\n x = scale_tensor(x, bbox, (0, 1))\n return x" }, { "identifier": "ImplicitSDF", "path": "threestudio/models/geometry/implicit_sdf.py", "snippet": "class ImplicitSDF(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: Union[\n float, str\n ] = 0.01 # in [float, \"progressive\"]\n shape_init: Optional[str] = None\n shape_init_params: Optional[Any] = None\n shape_init_mesh_up: str = \"+z\"\n shape_init_mesh_front: str = \"+x\"\n force_shape_init: bool = False\n sdf_bias: Union[float, str] = 0.0\n sdf_bias_params: Optional[Any] = None\n\n # no need to removal outlier for SDF\n isosurface_remove_outliers: bool = False\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.sdf_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n if self.cfg.isosurface_deformable_grid:\n assert (\n self.cfg.isosurface_method == \"mt\"\n ), \"isosurface_deformable_grid only works with mt\"\n self.deformation_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n self.finite_difference_normal_eps: Optional[float] = None\n\n def initialize_shape(self) -> None:\n if self.cfg.shape_init is None and not self.cfg.force_shape_init:\n return\n\n # do not initialize shape if weights are provided\n if self.cfg.weights is not None and not self.cfg.force_shape_init:\n return\n\n if self.cfg.sdf_bias != 0.0:\n threestudio.warn(\n \"shape_init and sdf_bias are both specified, which may lead to unexpected results.\"\n )\n\n get_gt_sdf: Callable[[Float[Tensor, \"N 3\"]], Float[Tensor, \"N 1\"]]\n assert isinstance(self.cfg.shape_init, str)\n if self.cfg.shape_init == \"ellipsoid\":\n assert (\n isinstance(self.cfg.shape_init_params, Sized)\n and len(self.cfg.shape_init_params) == 3\n )\n size = torch.as_tensor(self.cfg.shape_init_params).to(self.device)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return ((points_rand / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n\n get_gt_sdf = func\n elif self.cfg.shape_init == \"sphere\":\n assert isinstance(self.cfg.shape_init_params, float)\n radius = self.cfg.shape_init_params\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius\n\n get_gt_sdf = func\n elif self.cfg.shape_init.startswith(\"mesh:\"):\n assert isinstance(self.cfg.shape_init_params, float)\n mesh_path = self.cfg.shape_init[5:]\n if not os.path.exists(mesh_path):\n raise ValueError(f\"Mesh file {mesh_path} does not exist.\")\n\n import trimesh\n\n scene = trimesh.load(mesh_path)\n if isinstance(scene, trimesh.Trimesh):\n mesh = scene\n elif isinstance(scene, trimesh.scene.Scene):\n mesh = trimesh.Trimesh()\n for obj in scene.geometry.values():\n mesh = trimesh.util.concatenate([mesh, obj])\n else:\n raise ValueError(f\"Unknown mesh type at {mesh_path}.\")\n\n # move to center\n centroid = mesh.vertices.mean(0)\n mesh.vertices = mesh.vertices - centroid\n\n # align to up-z and front-x\n dirs = [\"+x\", \"+y\", \"+z\", \"-x\", \"-y\", \"-z\"]\n dir2vec = {\n \"+x\": np.array([1, 0, 0]),\n \"+y\": np.array([0, 1, 0]),\n \"+z\": np.array([0, 0, 1]),\n \"-x\": np.array([-1, 0, 0]),\n \"-y\": np.array([0, -1, 0]),\n \"-z\": np.array([0, 0, -1]),\n }\n if (\n self.cfg.shape_init_mesh_up not in dirs\n or self.cfg.shape_init_mesh_front not in dirs\n ):\n raise ValueError(\n f\"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}.\"\n )\n if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]:\n raise ValueError(\n \"shape_init_mesh_up and shape_init_mesh_front must be orthogonal.\"\n )\n z_, x_ = (\n dir2vec[self.cfg.shape_init_mesh_up],\n dir2vec[self.cfg.shape_init_mesh_front],\n )\n y_ = np.cross(z_, x_)\n std2mesh = np.stack([x_, y_, z_], axis=0).T\n mesh2std = np.linalg.inv(std2mesh)\n\n # scaling\n scale = np.abs(mesh.vertices).max()\n mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params\n mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T\n\n from pysdf import SDF\n\n sdf = SDF(mesh.vertices, mesh.faces)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n # add a negative signed here\n # as in pysdf the inside of the shape has positive signed distance\n return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to(\n points_rand\n )[..., None]\n\n get_gt_sdf = func\n\n else:\n raise ValueError(\n f\"Unknown shape initialization type: {self.cfg.shape_init}\"\n )\n\n # Initialize SDF to a given shape when no weights are provided or force_shape_init is True\n optim = torch.optim.Adam(self.parameters(), lr=1e-3)\n from tqdm import tqdm\n\n for _ in tqdm(\n range(1000),\n desc=f\"Initializing SDF to a(n) {self.cfg.shape_init}:\",\n disable=get_rank() != 0,\n ):\n points_rand = (\n torch.rand((10000, 3), dtype=torch.float32).to(self.device) * 2.0 - 1.0\n )\n sdf_gt = get_gt_sdf(points_rand)\n sdf_pred = self.forward_sdf(points_rand)\n loss = F.mse_loss(sdf_pred, sdf_gt)\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n # explicit broadcast to ensure param consistency across ranks\n for param in self.parameters():\n broadcast(param, src=0)\n\n def get_shifted_sdf(\n self, points: Float[Tensor, \"*N Di\"], sdf: Float[Tensor, \"*N 1\"]\n ) -> Float[Tensor, \"*N 1\"]:\n sdf_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.sdf_bias == \"ellipsoid\":\n assert (\n isinstance(self.cfg.sdf_bias_params, Sized)\n and len(self.cfg.sdf_bias_params) == 3\n )\n size = torch.as_tensor(self.cfg.sdf_bias_params).to(points)\n sdf_bias = ((points / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n elif self.cfg.sdf_bias == \"sphere\":\n assert isinstance(self.cfg.sdf_bias_params, float)\n radius = self.cfg.sdf_bias_params\n sdf_bias = (points**2).sum(dim=-1, keepdim=True).sqrt() - radius\n elif isinstance(self.cfg.sdf_bias, float):\n sdf_bias = self.cfg.sdf_bias\n else:\n raise ValueError(f\"Unknown sdf bias {self.cfg.sdf_bias}\")\n return sdf + sdf_bias\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).view(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n output = {\"sdf\": sdf}\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n assert self.finite_difference_normal_eps is not None\n eps: float = self.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 6 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (\n 0.5\n * (sdf_offset[..., 0::2, 0] - sdf_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 3 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (sdf_offset[..., 0::1, 0] - sdf) / eps\n normal = F.normalize(sdf_grad, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n sdf_grad = normal\n elif self.cfg.normal_type == \"analytic\":\n sdf_grad = -torch.autograd.grad(\n sdf,\n points_unscaled,\n grad_outputs=torch.ones_like(sdf),\n create_graph=True,\n )[0]\n normal = F.normalize(sdf_grad, dim=-1)\n if not grad_enabled:\n sdf_grad = sdf_grad.detach()\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update(\n {\"normal\": normal, \"shading_normal\": normal, \"sdf_grad\": sdf_grad}\n )\n return output\n\n def forward_sdf(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n sdf = self.sdf_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n return sdf\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n deformation: Optional[Float[Tensor, \"*N 3\"]] = None\n if self.cfg.isosurface_deformable_grid:\n deformation = self.deformation_network(enc).reshape(*points.shape[:-1], 3)\n return sdf, deformation\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return field - threshold\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n if isinstance(self.cfg.finite_difference_normal_eps, float):\n self.finite_difference_normal_eps = (\n self.cfg.finite_difference_normal_eps\n )\n elif self.cfg.finite_difference_normal_eps == \"progressive\":\n # progressive finite difference eps from Neuralangelo\n # https://arxiv.org/abs/2306.03092\n hg_conf: Any = self.cfg.pos_encoding_config\n assert (\n hg_conf.otype == \"ProgressiveBandHashGrid\"\n ), \"finite_difference_normal_eps=progressive only works with ProgressiveBandHashGrid\"\n current_level = min(\n hg_conf.start_level\n + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps,\n hg_conf.n_levels,\n )\n grid_res = hg_conf.base_resolution * hg_conf.per_level_scale ** (\n current_level - 1\n )\n grid_size = 2 * self.cfg.radius / grid_res\n if grid_size != self.finite_difference_normal_eps:\n threestudio.info(\n f\"Update finite_difference_normal_eps to {grid_size}\"\n )\n self.finite_difference_normal_eps = grid_size\n else:\n raise ValueError(\n f\"Unknown finite_difference_normal_eps={self.cfg.finite_difference_normal_eps}\"\n )" }, { "identifier": "ImplicitVolume", "path": "threestudio/models/geometry/implicit_volume.py", "snippet": "class ImplicitVolume(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n density_activation: Optional[str] = \"softplus\"\n density_bias: Union[float, str] = \"blob_magic3d\"\n density_blob_scale: float = 10.0\n density_blob_std: float = 0.5\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: float = 0.01\n\n # automatically determine the threshold\n isosurface_threshold: Union[float, str] = 25.0\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.density_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n def get_activated_density(\n self, points: Float[Tensor, \"*N Di\"], density: Float[Tensor, \"*N 1\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Float[Tensor, \"*N 1\"]]:\n density_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.density_bias == \"blob_dreamfusion\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * torch.exp(\n -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2\n )[..., None]\n )\n elif self.cfg.density_bias == \"blob_magic3d\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * (\n 1\n - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std\n )[..., None]\n )\n elif isinstance(self.cfg.density_bias, float):\n density_bias = self.cfg.density_bias\n else:\n raise ValueError(f\"Unknown density bias {self.cfg.density_bias}\")\n raw_density: Float[Tensor, \"*N 1\"] = density + density_bias\n density = get_activation(self.cfg.density_activation)(raw_density)\n return raw_density, density\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n density = self.density_network(enc).view(*points.shape[:-1], 1)\n raw_density, density = self.get_activated_density(points_unscaled, density)\n\n output = {\n \"density\": density,\n }\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n # TODO: use raw density\n eps = self.cfg.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 6 1\"] = self.forward_density(\n points_offset\n )\n normal = (\n -0.5\n * (density_offset[..., 0::2, 0] - density_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 3 1\"] = self.forward_density(\n points_offset\n )\n normal = -(density_offset[..., 0::1, 0] - density) / eps\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"analytic\":\n normal = -torch.autograd.grad(\n density,\n points_unscaled,\n grad_outputs=torch.ones_like(density),\n create_graph=True,\n )[0]\n normal = F.normalize(normal, dim=-1)\n if not grad_enabled:\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update({\"normal\": normal, \"shading_normal\": normal})\n\n torch.set_grad_enabled(grad_enabled)\n return output\n\n def forward_density(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n density = self.density_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n\n _, density = self.get_activated_density(points_unscaled, density)\n return density\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n if self.cfg.isosurface_deformable_grid:\n threestudio.warn(\n f\"{self.__class__.__name__} does not support isosurface_deformable_grid. Ignoring.\"\n )\n density = self.forward_density(points)\n return density, None\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return -(field - threshold)\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n @staticmethod\n @torch.no_grad()\n def create_from(\n other: BaseGeometry,\n cfg: Optional[Union[dict, DictConfig]] = None,\n copy_net: bool = True,\n **kwargs,\n ) -> \"ImplicitVolume\":\n if isinstance(other, ImplicitVolume):\n instance = ImplicitVolume(cfg, **kwargs)\n instance.encoding.load_state_dict(other.encoding.state_dict())\n instance.density_network.load_state_dict(other.density_network.state_dict())\n if copy_net:\n if (\n instance.cfg.n_feature_dims > 0\n and other.cfg.n_feature_dims == instance.cfg.n_feature_dims\n ):\n instance.feature_network.load_state_dict(\n other.feature_network.state_dict()\n )\n if (\n instance.cfg.normal_type == \"pred\"\n and other.cfg.normal_type == \"pred\"\n ):\n instance.normal_network.load_state_dict(\n other.normal_network.state_dict()\n )\n return instance\n else:\n raise TypeError(\n f\"Cannot create {ImplicitVolume.__name__} from {other.__class__.__name__}\"\n )" }, { "identifier": "MarchingTetrahedraHelper", "path": "threestudio/models/isosurface.py", "snippet": "class MarchingTetrahedraHelper(IsosurfaceHelper):\n def __init__(self, resolution: int, tets_path: str):\n super().__init__()\n self.resolution = resolution\n self.tets_path = tets_path\n\n self.triangle_table: Float[Tensor, \"...\"]\n self.register_buffer(\n \"triangle_table\",\n torch.as_tensor(\n [\n [-1, -1, -1, -1, -1, -1],\n [1, 0, 2, -1, -1, -1],\n [4, 0, 3, -1, -1, -1],\n [1, 4, 2, 1, 3, 4],\n [3, 1, 5, -1, -1, -1],\n [2, 3, 0, 2, 5, 3],\n [1, 4, 0, 1, 5, 4],\n [4, 2, 5, -1, -1, -1],\n [4, 5, 2, -1, -1, -1],\n [4, 1, 0, 4, 5, 1],\n [3, 2, 0, 3, 5, 2],\n [1, 3, 5, -1, -1, -1],\n [4, 1, 2, 4, 3, 1],\n [3, 0, 4, -1, -1, -1],\n [2, 0, 1, -1, -1, -1],\n [-1, -1, -1, -1, -1, -1],\n ],\n dtype=torch.long,\n ),\n persistent=False,\n )\n self.num_triangles_table: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"num_triangles_table\",\n torch.as_tensor(\n [0, 1, 1, 2, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 0], dtype=torch.long\n ),\n persistent=False,\n )\n self.base_tet_edges: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"base_tet_edges\",\n torch.as_tensor([0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3], dtype=torch.long),\n persistent=False,\n )\n\n tets = np.load(self.tets_path)\n self._grid_vertices: Float[Tensor, \"...\"]\n self.register_buffer(\n \"_grid_vertices\",\n torch.from_numpy(tets[\"vertices\"]).float(),\n persistent=False,\n )\n self.indices: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"indices\", torch.from_numpy(tets[\"indices\"]).long(), persistent=False\n )\n\n self._all_edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n\n def normalize_grid_deformation(\n self, grid_vertex_offsets: Float[Tensor, \"Nv 3\"]\n ) -> Float[Tensor, \"Nv 3\"]:\n return (\n (self.points_range[1] - self.points_range[0])\n / (self.resolution) # half tet size is approximately 1 / self.resolution\n * torch.tanh(grid_vertex_offsets)\n ) # FIXME: hard-coded activation\n\n @property\n def grid_vertices(self) -> Float[Tensor, \"Nv 3\"]:\n return self._grid_vertices\n\n @property\n def all_edges(self) -> Integer[Tensor, \"Ne 2\"]:\n if self._all_edges is None:\n # compute edges on GPU, or it would be VERY SLOW (basically due to the unique operation)\n edges = torch.tensor(\n [0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],\n dtype=torch.long,\n device=self.indices.device,\n )\n _all_edges = self.indices[:, edges].reshape(-1, 2)\n _all_edges_sorted = torch.sort(_all_edges, dim=1)[0]\n _all_edges = torch.unique(_all_edges_sorted, dim=0)\n self._all_edges = _all_edges\n return self._all_edges\n\n def sort_edges(self, edges_ex2):\n with torch.no_grad():\n order = (edges_ex2[:, 0] > edges_ex2[:, 1]).long()\n order = order.unsqueeze(dim=1)\n\n a = torch.gather(input=edges_ex2, index=order, dim=1)\n b = torch.gather(input=edges_ex2, index=1 - order, dim=1)\n\n return torch.stack([a, b], -1)\n\n def _forward(self, pos_nx3, sdf_n, tet_fx4):\n with torch.no_grad():\n occ_n = sdf_n > 0\n occ_fx4 = occ_n[tet_fx4.reshape(-1)].reshape(-1, 4)\n occ_sum = torch.sum(occ_fx4, -1)\n valid_tets = (occ_sum > 0) & (occ_sum < 4)\n occ_sum = occ_sum[valid_tets]\n\n # find all vertices\n all_edges = tet_fx4[valid_tets][:, self.base_tet_edges].reshape(-1, 2)\n all_edges = self.sort_edges(all_edges)\n unique_edges, idx_map = torch.unique(all_edges, dim=0, return_inverse=True)\n\n unique_edges = unique_edges.long()\n mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1\n mapping = (\n torch.ones(\n (unique_edges.shape[0]), dtype=torch.long, device=pos_nx3.device\n )\n * -1\n )\n mapping[mask_edges] = torch.arange(\n mask_edges.sum(), dtype=torch.long, device=pos_nx3.device\n )\n idx_map = mapping[idx_map] # map edges to verts\n\n interp_v = unique_edges[mask_edges]\n edges_to_interp = pos_nx3[interp_v.reshape(-1)].reshape(-1, 2, 3)\n edges_to_interp_sdf = sdf_n[interp_v.reshape(-1)].reshape(-1, 2, 1)\n edges_to_interp_sdf[:, -1] *= -1\n\n denominator = edges_to_interp_sdf.sum(1, keepdim=True)\n\n edges_to_interp_sdf = torch.flip(edges_to_interp_sdf, [1]) / denominator\n verts = (edges_to_interp * edges_to_interp_sdf).sum(1)\n\n idx_map = idx_map.reshape(-1, 6)\n\n v_id = torch.pow(2, torch.arange(4, dtype=torch.long, device=pos_nx3.device))\n tetindex = (occ_fx4[valid_tets] * v_id.unsqueeze(0)).sum(-1)\n num_triangles = self.num_triangles_table[tetindex]\n\n # Generate triangle indices\n faces = torch.cat(\n (\n torch.gather(\n input=idx_map[num_triangles == 1],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 1]][:, :3],\n ).reshape(-1, 3),\n torch.gather(\n input=idx_map[num_triangles == 2],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 2]][:, :6],\n ).reshape(-1, 3),\n ),\n dim=0,\n )\n\n return verts, faces\n\n def forward(\n self,\n level: Float[Tensor, \"N3 1\"],\n deformation: Optional[Float[Tensor, \"N3 3\"]] = None,\n ) -> Mesh:\n if deformation is not None:\n grid_vertices = self.grid_vertices + self.normalize_grid_deformation(\n deformation\n )\n else:\n grid_vertices = self.grid_vertices\n\n v_pos, t_pos_idx = self._forward(grid_vertices, level, self.indices)\n\n mesh = Mesh(\n v_pos=v_pos,\n t_pos_idx=t_pos_idx,\n # extras\n grid_vertices=grid_vertices,\n tet_edges=self.all_edges,\n grid_level=level,\n grid_deformation=deformation,\n )\n\n return mesh" }, { "identifier": "Mesh", "path": "threestudio/models/mesh.py", "snippet": "class Mesh:\n def __init__(\n self, v_pos: Float[Tensor, \"Nv 3\"], t_pos_idx: Integer[Tensor, \"Nf 3\"], **kwargs\n ) -> None:\n self.v_pos: Float[Tensor, \"Nv 3\"] = v_pos\n self.t_pos_idx: Integer[Tensor, \"Nf 3\"] = t_pos_idx\n self._v_nrm: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tng: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tex: Optional[Float[Tensor, \"Nt 3\"]] = None\n self._t_tex_idx: Optional[Float[Tensor, \"Nf 3\"]] = None\n self._v_rgb: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n self.extras: Dict[str, Any] = {}\n for k, v in kwargs.items():\n self.add_extra(k, v)\n\n def add_extra(self, k, v) -> None:\n self.extras[k] = v\n\n def remove_outlier(self, outlier_n_faces_threshold: Union[int, float]) -> Mesh:\n if self.requires_grad:\n threestudio.debug(\"Mesh is differentiable, not removing outliers\")\n return self\n\n # use trimesh to first split the mesh into connected components\n # then remove the components with less than n_face_threshold faces\n import trimesh\n\n # construct a trimesh object\n mesh = trimesh.Trimesh(\n vertices=self.v_pos.detach().cpu().numpy(),\n faces=self.t_pos_idx.detach().cpu().numpy(),\n )\n\n # split the mesh into connected components\n components = mesh.split(only_watertight=False)\n # log the number of faces in each component\n threestudio.debug(\n \"Mesh has {} components, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n\n n_faces_threshold: int\n if isinstance(outlier_n_faces_threshold, float):\n # set the threshold to the number of faces in the largest component multiplied by outlier_n_faces_threshold\n n_faces_threshold = int(\n max([c.faces.shape[0] for c in components]) * outlier_n_faces_threshold\n )\n else:\n # set the threshold directly to outlier_n_faces_threshold\n n_faces_threshold = outlier_n_faces_threshold\n\n # log the threshold\n threestudio.debug(\n \"Removing components with less than {} faces\".format(n_faces_threshold)\n )\n\n # remove the components with less than n_face_threshold faces\n components = [c for c in components if c.faces.shape[0] >= n_faces_threshold]\n\n # log the number of faces in each component after removing outliers\n threestudio.debug(\n \"Mesh has {} components after removing outliers, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n # merge the components\n mesh = trimesh.util.concatenate(components)\n\n # convert back to our mesh format\n v_pos = torch.from_numpy(mesh.vertices).to(self.v_pos)\n t_pos_idx = torch.from_numpy(mesh.faces).to(self.t_pos_idx)\n\n clean_mesh = Mesh(v_pos, t_pos_idx)\n # keep the extras unchanged\n\n if len(self.extras) > 0:\n clean_mesh.extras = self.extras\n threestudio.debug(\n f\"The following extra attributes are inherited from the original mesh unchanged: {list(self.extras.keys())}\"\n )\n return clean_mesh\n\n @property\n def requires_grad(self):\n return self.v_pos.requires_grad\n\n @property\n def v_nrm(self):\n if self._v_nrm is None:\n self._v_nrm = self._compute_vertex_normal()\n return self._v_nrm\n\n @property\n def v_tng(self):\n if self._v_tng is None:\n self._v_tng = self._compute_vertex_tangent()\n return self._v_tng\n\n @property\n def v_tex(self):\n if self._v_tex is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._v_tex\n\n @property\n def t_tex_idx(self):\n if self._t_tex_idx is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._t_tex_idx\n\n @property\n def v_rgb(self):\n return self._v_rgb\n\n @property\n def edges(self):\n if self._edges is None:\n self._edges = self._compute_edges()\n return self._edges\n\n def _compute_vertex_normal(self):\n i0 = self.t_pos_idx[:, 0]\n i1 = self.t_pos_idx[:, 1]\n i2 = self.t_pos_idx[:, 2]\n\n v0 = self.v_pos[i0, :]\n v1 = self.v_pos[i1, :]\n v2 = self.v_pos[i2, :]\n\n face_normals = torch.cross(v1 - v0, v2 - v0)\n\n # Splat face normals to vertices\n v_nrm = torch.zeros_like(self.v_pos)\n v_nrm.scatter_add_(0, i0[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i1[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i2[:, None].repeat(1, 3), face_normals)\n\n # Normalize, replace zero (degenerated) normals with some default value\n v_nrm = torch.where(\n dot(v_nrm, v_nrm) > 1e-20, v_nrm, torch.as_tensor([0.0, 0.0, 1.0]).to(v_nrm)\n )\n v_nrm = F.normalize(v_nrm, dim=1)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(v_nrm))\n\n return v_nrm\n\n def _compute_vertex_tangent(self):\n vn_idx = [None] * 3\n pos = [None] * 3\n tex = [None] * 3\n for i in range(0, 3):\n pos[i] = self.v_pos[self.t_pos_idx[:, i]]\n tex[i] = self.v_tex[self.t_tex_idx[:, i]]\n # t_nrm_idx is always the same as t_pos_idx\n vn_idx[i] = self.t_pos_idx[:, i]\n\n tangents = torch.zeros_like(self.v_nrm)\n tansum = torch.zeros_like(self.v_nrm)\n\n # Compute tangent space for each triangle\n uve1 = tex[1] - tex[0]\n uve2 = tex[2] - tex[0]\n pe1 = pos[1] - pos[0]\n pe2 = pos[2] - pos[0]\n\n nom = pe1 * uve2[..., 1:2] - pe2 * uve1[..., 1:2]\n denom = uve1[..., 0:1] * uve2[..., 1:2] - uve1[..., 1:2] * uve2[..., 0:1]\n\n # Avoid division by zero for degenerated texture coordinates\n tang = nom / torch.where(\n denom > 0.0, torch.clamp(denom, min=1e-6), torch.clamp(denom, max=-1e-6)\n )\n\n # Update all 3 vertices\n for i in range(0, 3):\n idx = vn_idx[i][:, None].repeat(1, 3)\n tangents.scatter_add_(0, idx, tang) # tangents[n_i] = tangents[n_i] + tang\n tansum.scatter_add_(\n 0, idx, torch.ones_like(tang)\n ) # tansum[n_i] = tansum[n_i] + 1\n tangents = tangents / tansum\n\n # Normalize and make sure tangent is perpendicular to normal\n tangents = F.normalize(tangents, dim=1)\n tangents = F.normalize(tangents - dot(tangents, self.v_nrm) * self.v_nrm)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(tangents))\n\n return tangents\n\n def _unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n threestudio.info(\"Using xatlas to perform UV unwrapping, may take a while ...\")\n\n import xatlas\n\n atlas = xatlas.Atlas()\n atlas.add_mesh(\n self.v_pos.detach().cpu().numpy(),\n self.t_pos_idx.cpu().numpy(),\n )\n co = xatlas.ChartOptions()\n po = xatlas.PackOptions()\n for k, v in xatlas_chart_options.items():\n setattr(co, k, v)\n for k, v in xatlas_pack_options.items():\n setattr(po, k, v)\n atlas.generate(co, po)\n vmapping, indices, uvs = atlas.get_mesh(0)\n vmapping = (\n torch.from_numpy(\n vmapping.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n uvs = torch.from_numpy(uvs).to(self.v_pos.device).float()\n indices = (\n torch.from_numpy(\n indices.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n return uvs, indices\n\n def unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n self._v_tex, self._t_tex_idx = self._unwrap_uv(\n xatlas_chart_options, xatlas_pack_options\n )\n\n def set_vertex_color(self, v_rgb):\n assert v_rgb.shape[0] == self.v_pos.shape[0]\n self._v_rgb = v_rgb\n\n def _compute_edges(self):\n # Compute edges\n edges = torch.cat(\n [\n self.t_pos_idx[:, [0, 1]],\n self.t_pos_idx[:, [1, 2]],\n self.t_pos_idx[:, [2, 0]],\n ],\n dim=0,\n )\n edges = edges.sort()[0]\n edges = torch.unique(edges, dim=0)\n return edges\n\n def normal_consistency(self) -> Float[Tensor, \"\"]:\n edge_nrm: Float[Tensor, \"Ne 2 3\"] = self.v_nrm[self.edges]\n nc = (\n 1.0 - torch.cosine_similarity(edge_nrm[:, 0], edge_nrm[:, 1], dim=-1)\n ).mean()\n return nc\n\n def _laplacian_uniform(self):\n # from stable-dreamfusion\n # https://github.com/ashawkey/stable-dreamfusion/blob/8fb3613e9e4cd1ded1066b46e80ca801dfb9fd06/nerf/renderer.py#L224\n verts, faces = self.v_pos, self.t_pos_idx\n\n V = verts.shape[0]\n F = faces.shape[0]\n\n # Neighbor indices\n ii = faces[:, [1, 2, 0]].flatten()\n jj = faces[:, [2, 0, 1]].flatten()\n adj = torch.stack([torch.cat([ii, jj]), torch.cat([jj, ii])], dim=0).unique(\n dim=1\n )\n adj_values = torch.ones(adj.shape[1]).to(verts)\n\n # Diagonal indices\n diag_idx = adj[0]\n\n # Build the sparse matrix\n idx = torch.cat((adj, torch.stack((diag_idx, diag_idx), dim=0)), dim=1)\n values = torch.cat((-adj_values, adj_values))\n\n # The coalesce operation sums the duplicate indices, resulting in the\n # correct diagonal\n return torch.sparse_coo_tensor(idx, values, (V, V)).coalesce()\n\n def laplacian(self) -> Float[Tensor, \"\"]:\n with torch.no_grad():\n L = self._laplacian_uniform()\n loss = L.mm(self.v_pos)\n loss = loss.norm(dim=1)\n loss = loss.mean()\n return loss" }, { "identifier": "get_encoding", "path": "threestudio/models/networks.py", "snippet": "def get_encoding(n_input_dims: int, config) -> nn.Module:\n # input suppose to be range [0, 1]\n encoding: nn.Module\n if config.otype == \"ProgressiveBandFrequency\":\n encoding = ProgressiveBandFrequency(n_input_dims, config_to_primitive(config))\n elif config.otype == \"ProgressiveBandHashGrid\":\n encoding = ProgressiveBandHashGrid(n_input_dims, config_to_primitive(config))\n else:\n encoding = TCNNEncoding(n_input_dims, config_to_primitive(config))\n encoding = CompositeEncoding(\n encoding,\n include_xyz=config.get(\"include_xyz\", False),\n xyz_scale=2.0,\n xyz_offset=-1.0,\n ) # FIXME: hard coded\n return encoding" }, { "identifier": "get_mlp", "path": "threestudio/models/networks.py", "snippet": "def get_mlp(n_input_dims, n_output_dims, config) -> nn.Module:\n network: nn.Module\n if config.otype == \"VanillaMLP\":\n network = VanillaMLP(n_input_dims, n_output_dims, config_to_primitive(config))\n elif config.otype == \"SphereInitVanillaMLP\":\n network = SphereInitVanillaMLP(\n n_input_dims, n_output_dims, config_to_primitive(config)\n )\n else:\n assert (\n config.get(\"sphere_init\", False) is False\n ), \"sphere_init=True only supported by VanillaMLP\"\n network = TCNNNetwork(n_input_dims, n_output_dims, config_to_primitive(config))\n return network" }, { "identifier": "broadcast", "path": "threestudio/utils/misc.py", "snippet": "def broadcast(tensor, src=0):\n if not _distributed_available():\n return tensor\n else:\n torch.distributed.broadcast(tensor, src=src)\n return tensor" }, { "identifier": "scale_tensor", "path": "threestudio/utils/ops.py", "snippet": "def scale_tensor(\n dat: Num[Tensor, \"... D\"], inp_scale: ValidScale, tgt_scale: ValidScale\n):\n if inp_scale is None:\n inp_scale = (0, 1)\n if tgt_scale is None:\n tgt_scale = (0, 1)\n if isinstance(tgt_scale, Tensor):\n assert dat.shape[-1] == tgt_scale.shape[-1]\n dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0])\n dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0]\n return dat" } ]
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio import trimesh from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseExplicitGeometry, BaseGeometry, contract_to_unisphere, ) from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.models.geometry.implicit_volume import ImplicitVolume from threestudio.models.isosurface import MarchingTetrahedraHelper from threestudio.models.mesh import Mesh from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.misc import broadcast from threestudio.utils.ops import scale_tensor from threestudio.utils.typing import * from pysdf import SDF
15,478
mesh2std = np.linalg.inv(std2mesh) # scaling scale = np.abs(mesh.vertices).max() mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T sdf = SDF(mesh.vertices, mesh.faces) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: # add a negative signed here # as in pysdf the inside of the shape has positive signed distance return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to( points_rand )[..., None] get_gt_sdf = func else: raise ValueError( f"Unknown shape initialization type: {self.cfg.shape_init}" ) sdf_gt = get_gt_sdf( scale_tensor( self.isosurface_helper.grid_vertices, self.isosurface_helper.points_range, self.isosurface_bbox, ) ) self.sdf.data = sdf_gt # explicit broadcast to ensure param consistency across ranks for param in self.parameters(): broadcast(param, src=0) def isosurface(self) -> Mesh: # return cached mesh if fix_geometry is True to save computation if self.cfg.fix_geometry and self.mesh is not None: return self.mesh mesh = self.isosurface_helper(self.sdf, self.deformation) mesh.v_pos = scale_tensor( mesh.v_pos, self.isosurface_helper.points_range, self.isosurface_bbox ) if self.cfg.isosurface_remove_outliers: mesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold) self.mesh = mesh return mesh def forward( self, points: Float[Tensor, "*N Di"], output_normal: bool = False ) -> Dict[str, Float[Tensor, "..."]]: if self.cfg.geometry_only: return {} assert ( output_normal == False ), f"Normal output is not supported for {self.__class__.__name__}" points_unscaled = points # points in the original scale points = contract_to_unisphere(points, self.bbox) # points normalized to (0, 1) enc = self.encoding(points.view(-1, self.cfg.n_input_dims)) features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) return {"features": features} @staticmethod @torch.no_grad() def create_from( other: BaseGeometry, cfg: Optional[Union[dict, DictConfig]] = None, copy_net: bool = True, **kwargs, ) -> "TetrahedraSDFGrid": if isinstance(other, TetrahedraSDFGrid): instance = TetrahedraSDFGrid(cfg, **kwargs) assert instance.cfg.isosurface_resolution == other.cfg.isosurface_resolution instance.isosurface_bbox = other.isosurface_bbox.clone() instance.sdf.data = other.sdf.data.clone() if ( instance.cfg.isosurface_deformable_grid and other.cfg.isosurface_deformable_grid ): assert ( instance.deformation is not None and other.deformation is not None ) instance.deformation.data = other.deformation.data.clone() if ( not instance.cfg.geometry_only and not other.cfg.geometry_only and copy_net ): instance.encoding.load_state_dict(other.encoding.state_dict()) instance.feature_network.load_state_dict( other.feature_network.state_dict() ) return instance elif isinstance(other, ImplicitVolume): instance = TetrahedraSDFGrid(cfg, **kwargs) if other.cfg.isosurface_method != "mt": other.cfg.isosurface_method = "mt" threestudio.warn( f"Override isosurface_method of the source geometry to 'mt'" ) if other.cfg.isosurface_resolution != instance.cfg.isosurface_resolution: other.cfg.isosurface_resolution = instance.cfg.isosurface_resolution threestudio.warn( f"Override isosurface_resolution of the source geometry to {instance.cfg.isosurface_resolution}" ) mesh = other.isosurface() instance.isosurface_bbox = mesh.extras["bbox"] instance.sdf.data = ( mesh.extras["grid_level"].to(instance.sdf.data).clamp(-1, 1) ) if not instance.cfg.geometry_only and copy_net: instance.encoding.load_state_dict(other.encoding.state_dict()) instance.feature_network.load_state_dict( other.feature_network.state_dict() ) return instance
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None shape_init_mesh_up: str = "+z" shape_init_mesh_front: str = "+x" force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone()) self.isosurface_helper = MarchingTetrahedraHelper( self.cfg.isosurface_resolution, f"load/tets/{self.cfg.isosurface_resolution}_tets.npz", ) self.sdf: Float[Tensor, "Nv 1"] self.deformation: Optional[Float[Tensor, "Nv 3"]] if not self.cfg.fix_geometry: self.register_parameter( "sdf", nn.Parameter( torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ) ), ) if self.cfg.isosurface_deformable_grid: self.register_parameter( "deformation", nn.Parameter( torch.zeros_like(self.isosurface_helper.grid_vertices) ), ) else: self.deformation = None else: self.register_buffer( "sdf", torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ), ) if self.cfg.isosurface_deformable_grid: self.register_buffer( "deformation", torch.zeros_like(self.isosurface_helper.grid_vertices), ) else: self.deformation = None if not self.cfg.geometry_only: self.encoding = get_encoding( self.cfg.n_input_dims, self.cfg.pos_encoding_config ) self.feature_network = get_mlp( self.encoding.n_output_dims, self.cfg.n_feature_dims, self.cfg.mlp_network_config, ) self.mesh: Optional[Mesh] = None def initialize_shape(self) -> None: if self.cfg.shape_init is None and not self.cfg.force_shape_init: return # do not initialize shape if weights are provided if self.cfg.weights is not None and not self.cfg.force_shape_init: return get_gt_sdf: Callable[[Float[Tensor, "N 3"]], Float[Tensor, "N 1"]] assert isinstance(self.cfg.shape_init, str) if self.cfg.shape_init == "ellipsoid": assert ( isinstance(self.cfg.shape_init_params, Sized) and len(self.cfg.shape_init_params) == 3 ) size = torch.as_tensor(self.cfg.shape_init_params).to(self.device) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return ((points_rand / size) ** 2).sum( dim=-1, keepdim=True ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid get_gt_sdf = func elif self.cfg.shape_init == "sphere": assert isinstance(self.cfg.shape_init_params, float) radius = self.cfg.shape_init_params def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius get_gt_sdf = func elif self.cfg.shape_init.startswith("mesh:"): assert isinstance(self.cfg.shape_init_params, float) mesh_path = self.cfg.shape_init[5:] if not os.path.exists(mesh_path): raise ValueError(f"Mesh file {mesh_path} does not exist.") mesh = trimesh.load(mesh_path) # move to center centroid = mesh.vertices.mean(0) mesh.vertices = mesh.vertices - centroid # align to up-z and front-x dirs = ["+x", "+y", "+z", "-x", "-y", "-z"] dir2vec = { "+x": np.array([1, 0, 0]), "+y": np.array([0, 1, 0]), "+z": np.array([0, 0, 1]), "-x": np.array([-1, 0, 0]), "-y": np.array([0, -1, 0]), "-z": np.array([0, 0, -1]), } if ( self.cfg.shape_init_mesh_up not in dirs or self.cfg.shape_init_mesh_front not in dirs ): raise ValueError( f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}." ) if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]: raise ValueError( "shape_init_mesh_up and shape_init_mesh_front must be orthogonal." ) z_, x_ = ( dir2vec[self.cfg.shape_init_mesh_up], dir2vec[self.cfg.shape_init_mesh_front], ) y_ = np.cross(z_, x_) std2mesh = np.stack([x_, y_, z_], axis=0).T mesh2std = np.linalg.inv(std2mesh) # scaling scale = np.abs(mesh.vertices).max() mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T sdf = SDF(mesh.vertices, mesh.faces) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: # add a negative signed here # as in pysdf the inside of the shape has positive signed distance return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to( points_rand )[..., None] get_gt_sdf = func else: raise ValueError( f"Unknown shape initialization type: {self.cfg.shape_init}" ) sdf_gt = get_gt_sdf( scale_tensor( self.isosurface_helper.grid_vertices, self.isosurface_helper.points_range, self.isosurface_bbox, ) ) self.sdf.data = sdf_gt # explicit broadcast to ensure param consistency across ranks for param in self.parameters(): broadcast(param, src=0) def isosurface(self) -> Mesh: # return cached mesh if fix_geometry is True to save computation if self.cfg.fix_geometry and self.mesh is not None: return self.mesh mesh = self.isosurface_helper(self.sdf, self.deformation) mesh.v_pos = scale_tensor( mesh.v_pos, self.isosurface_helper.points_range, self.isosurface_bbox ) if self.cfg.isosurface_remove_outliers: mesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold) self.mesh = mesh return mesh def forward( self, points: Float[Tensor, "*N Di"], output_normal: bool = False ) -> Dict[str, Float[Tensor, "..."]]: if self.cfg.geometry_only: return {} assert ( output_normal == False ), f"Normal output is not supported for {self.__class__.__name__}" points_unscaled = points # points in the original scale points = contract_to_unisphere(points, self.bbox) # points normalized to (0, 1) enc = self.encoding(points.view(-1, self.cfg.n_input_dims)) features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) return {"features": features} @staticmethod @torch.no_grad() def create_from( other: BaseGeometry, cfg: Optional[Union[dict, DictConfig]] = None, copy_net: bool = True, **kwargs, ) -> "TetrahedraSDFGrid": if isinstance(other, TetrahedraSDFGrid): instance = TetrahedraSDFGrid(cfg, **kwargs) assert instance.cfg.isosurface_resolution == other.cfg.isosurface_resolution instance.isosurface_bbox = other.isosurface_bbox.clone() instance.sdf.data = other.sdf.data.clone() if ( instance.cfg.isosurface_deformable_grid and other.cfg.isosurface_deformable_grid ): assert ( instance.deformation is not None and other.deformation is not None ) instance.deformation.data = other.deformation.data.clone() if ( not instance.cfg.geometry_only and not other.cfg.geometry_only and copy_net ): instance.encoding.load_state_dict(other.encoding.state_dict()) instance.feature_network.load_state_dict( other.feature_network.state_dict() ) return instance elif isinstance(other, ImplicitVolume): instance = TetrahedraSDFGrid(cfg, **kwargs) if other.cfg.isosurface_method != "mt": other.cfg.isosurface_method = "mt" threestudio.warn( f"Override isosurface_method of the source geometry to 'mt'" ) if other.cfg.isosurface_resolution != instance.cfg.isosurface_resolution: other.cfg.isosurface_resolution = instance.cfg.isosurface_resolution threestudio.warn( f"Override isosurface_resolution of the source geometry to {instance.cfg.isosurface_resolution}" ) mesh = other.isosurface() instance.isosurface_bbox = mesh.extras["bbox"] instance.sdf.data = ( mesh.extras["grid_level"].to(instance.sdf.data).clamp(-1, 1) ) if not instance.cfg.geometry_only and copy_net: instance.encoding.load_state_dict(other.encoding.state_dict()) instance.feature_network.load_state_dict( other.feature_network.state_dict() ) return instance
elif isinstance(other, ImplicitSDF):
3
2023-11-27 02:39:39+00:00
24k
EricGuo5513/momask-codes
edit_t2m.py
[ { "identifier": "MaskTransformer", "path": "models/mask_transformer/transformer.py", "snippet": "class MaskTransformer(nn.Module):\n def __init__(self, code_dim, cond_mode, latent_dim=256, ff_size=1024, num_layers=8,\n num_heads=4, dropout=0.1, clip_dim=512, cond_drop_prob=0.1,\n clip_version=None, opt=None, **kargs):\n super(MaskTransformer, self).__init__()\n print(f'latent_dim: {latent_dim}, ff_size: {ff_size}, nlayers: {num_layers}, nheads: {num_heads}, dropout: {dropout}')\n\n self.code_dim = code_dim\n self.latent_dim = latent_dim\n self.clip_dim = clip_dim\n self.dropout = dropout\n self.opt = opt\n\n self.cond_mode = cond_mode\n self.cond_drop_prob = cond_drop_prob\n\n if self.cond_mode == 'action':\n assert 'num_actions' in kargs\n self.num_actions = kargs.get('num_actions', 1)\n\n '''\n Preparing Networks\n '''\n self.input_process = InputProcess(self.code_dim, self.latent_dim)\n self.position_enc = PositionalEncoding(self.latent_dim, self.dropout)\n\n seqTransEncoderLayer = nn.TransformerEncoderLayer(d_model=self.latent_dim,\n nhead=num_heads,\n dim_feedforward=ff_size,\n dropout=dropout,\n activation='gelu')\n\n self.seqTransEncoder = nn.TransformerEncoder(seqTransEncoderLayer,\n num_layers=num_layers)\n\n self.encode_action = partial(F.one_hot, num_classes=self.num_actions)\n\n # if self.cond_mode != 'no_cond':\n if self.cond_mode == 'text':\n self.cond_emb = nn.Linear(self.clip_dim, self.latent_dim)\n elif self.cond_mode == 'action':\n self.cond_emb = nn.Linear(self.num_actions, self.latent_dim)\n elif self.cond_mode == 'uncond':\n self.cond_emb = nn.Identity()\n else:\n raise KeyError(\"Unsupported condition mode!!!\")\n\n\n _num_tokens = opt.num_tokens + 2 # two dummy tokens, one for masking, one for padding\n self.mask_id = opt.num_tokens\n self.pad_id = opt.num_tokens + 1\n\n self.output_process = OutputProcess_Bert(out_feats=opt.num_tokens, latent_dim=latent_dim)\n\n self.token_emb = nn.Embedding(_num_tokens, self.code_dim)\n\n self.apply(self.__init_weights)\n\n '''\n Preparing frozen weights\n '''\n\n if self.cond_mode == 'text':\n print('Loading CLIP...')\n self.clip_version = clip_version\n self.clip_model = self.load_and_freeze_clip(clip_version)\n\n self.noise_schedule = cosine_schedule\n\n def load_and_freeze_token_emb(self, codebook):\n '''\n :param codebook: (c, d)\n :return:\n '''\n assert self.training, 'Only necessary in training mode'\n c, d = codebook.shape\n self.token_emb.weight = nn.Parameter(torch.cat([codebook, torch.zeros(size=(2, d), device=codebook.device)], dim=0)) #add two dummy tokens, 0 vectors\n self.token_emb.requires_grad_(False)\n # self.token_emb.weight.requires_grad = False\n # self.token_emb_ready = True\n print(\"Token embedding initialized!\")\n\n def __init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def parameters_wo_clip(self):\n return [p for name, p in self.named_parameters() if not name.startswith('clip_model.')]\n\n def load_and_freeze_clip(self, clip_version):\n clip_model, clip_preprocess = clip.load(clip_version, device='cpu',\n jit=False) # Must set jit=False for training\n # Cannot run on cpu\n clip.model.convert_weights(\n clip_model) # Actually this line is unnecessary since clip by default already on float16\n # Date 0707: It's necessary, only unecessary when load directly to gpu. Disable if need to run on cpu\n\n # Freeze CLIP weights\n clip_model.eval()\n for p in clip_model.parameters():\n p.requires_grad = False\n\n return clip_model\n\n def encode_text(self, raw_text):\n device = next(self.parameters()).device\n text = clip.tokenize(raw_text, truncate=True).to(device)\n feat_clip_text = self.clip_model.encode_text(text).float()\n return feat_clip_text\n\n def mask_cond(self, cond, force_mask=False):\n bs, d = cond.shape\n if force_mask:\n return torch.zeros_like(cond)\n elif self.training and self.cond_drop_prob > 0.:\n mask = torch.bernoulli(torch.ones(bs, device=cond.device) * self.cond_drop_prob).view(bs, 1)\n return cond * (1. - mask)\n else:\n return cond\n\n def trans_forward(self, motion_ids, cond, padding_mask, force_mask=False):\n '''\n :param motion_ids: (b, seqlen)\n :padding_mask: (b, seqlen), all pad positions are TRUE else FALSE\n :param cond: (b, embed_dim) for text, (b, num_actions) for action\n :param force_mask: boolean\n :return:\n -logits: (b, num_token, seqlen)\n '''\n\n cond = self.mask_cond(cond, force_mask=force_mask)\n\n # print(motion_ids.shape)\n x = self.token_emb(motion_ids)\n # print(x.shape)\n # (b, seqlen, d) -> (seqlen, b, latent_dim)\n x = self.input_process(x)\n\n cond = self.cond_emb(cond).unsqueeze(0) #(1, b, latent_dim)\n\n x = self.position_enc(x)\n xseq = torch.cat([cond, x], dim=0) #(seqlen+1, b, latent_dim)\n\n padding_mask = torch.cat([torch.zeros_like(padding_mask[:, 0:1]), padding_mask], dim=1) #(b, seqlen+1)\n # print(xseq.shape, padding_mask.shape)\n\n # print(padding_mask.shape, xseq.shape)\n\n output = self.seqTransEncoder(xseq, src_key_padding_mask=padding_mask)[1:] #(seqlen, b, e)\n logits = self.output_process(output) #(seqlen, b, e) -> (b, ntoken, seqlen)\n return logits\n\n def forward(self, ids, y, m_lens):\n '''\n :param ids: (b, n)\n :param y: raw text for cond_mode=text, (b, ) for cond_mode=action\n :m_lens: (b,)\n :return:\n '''\n\n bs, ntokens = ids.shape\n device = ids.device\n\n # Positions that are PADDED are ALL FALSE\n non_pad_mask = lengths_to_mask(m_lens, ntokens) #(b, n)\n ids = torch.where(non_pad_mask, ids, self.pad_id)\n\n force_mask = False\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(y)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(y).to(device).float()\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(bs, self.latent_dim).float().to(device)\n force_mask = True\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n\n '''\n Prepare mask\n '''\n rand_time = uniform((bs,), device=device)\n rand_mask_probs = self.noise_schedule(rand_time)\n num_token_masked = (ntokens * rand_mask_probs).round().clamp(min=1)\n\n batch_randperm = torch.rand((bs, ntokens), device=device).argsort(dim=-1)\n # Positions to be MASKED are ALL TRUE\n mask = batch_randperm < num_token_masked.unsqueeze(-1)\n\n # Positions to be MASKED must also be NON-PADDED\n mask &= non_pad_mask\n\n # Note this is our training target, not input\n labels = torch.where(mask, ids, self.mask_id)\n\n x_ids = ids.clone()\n\n # Further Apply Bert Masking Scheme\n # Step 1: 10% replace with an incorrect token\n mask_rid = get_mask_subset_prob(mask, 0.1)\n rand_id = torch.randint_like(x_ids, high=self.opt.num_tokens)\n x_ids = torch.where(mask_rid, rand_id, x_ids)\n # Step 2: 90% x 10% replace with correct token, and 90% x 88% replace with mask token\n mask_mid = get_mask_subset_prob(mask & ~mask_rid, 0.88)\n\n # mask_mid = mask\n\n x_ids = torch.where(mask_mid, self.mask_id, x_ids)\n\n logits = self.trans_forward(x_ids, cond_vector, ~non_pad_mask, force_mask)\n ce_loss, pred_id, acc = cal_performance(logits, labels, ignore_index=self.mask_id)\n\n return ce_loss, pred_id, acc\n\n def forward_with_cond_scale(self,\n motion_ids,\n cond_vector,\n padding_mask,\n cond_scale=3,\n force_mask=False):\n # bs = motion_ids.shape[0]\n # if cond_scale == 1:\n if force_mask:\n return self.trans_forward(motion_ids, cond_vector, padding_mask, force_mask=True)\n\n logits = self.trans_forward(motion_ids, cond_vector, padding_mask)\n if cond_scale == 1:\n return logits\n\n aux_logits = self.trans_forward(motion_ids, cond_vector, padding_mask, force_mask=True)\n\n scaled_logits = aux_logits + (logits - aux_logits) * cond_scale\n return scaled_logits\n\n @torch.no_grad()\n @eval_decorator\n def generate(self,\n conds,\n m_lens,\n timesteps: int,\n cond_scale: int,\n temperature=1,\n topk_filter_thres=0.9,\n gsample=False,\n force_mask=False\n ):\n # print(self.opt.num_quantizers)\n # assert len(timesteps) >= len(cond_scales) == self.opt.num_quantizers\n\n device = next(self.parameters()).device\n seq_len = max(m_lens)\n batch_size = len(m_lens)\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(batch_size, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n # print(padding_mask.shape, )\n\n # Start from all tokens being masked\n ids = torch.where(padding_mask, self.pad_id, self.mask_id)\n scores = torch.where(padding_mask, 1e5, 0.)\n starting_temperature = temperature\n\n for timestep, steps_until_x0 in zip(torch.linspace(0, 1, timesteps, device=device), reversed(range(timesteps))):\n # 0 < timestep < 1\n rand_mask_prob = self.noise_schedule(timestep) # Tensor\n\n '''\n Maskout, and cope with variable length\n '''\n # fix: the ratio regarding lengths, instead of seq_len\n num_token_masked = torch.round(rand_mask_prob * m_lens).clamp(min=1) # (b, )\n\n # select num_token_masked tokens with lowest scores to be masked\n sorted_indices = scores.argsort(\n dim=1) # (b, k), sorted_indices[i, j] = the index of j-th lowest element in scores on dim=1\n ranks = sorted_indices.argsort(dim=1) # (b, k), rank[i, j] = the rank (0: lowest) of scores[i, j] on dim=1\n is_mask = (ranks < num_token_masked.unsqueeze(-1))\n ids = torch.where(is_mask, self.mask_id, ids)\n\n '''\n Preparing input\n '''\n # (b, num_token, seqlen)\n logits = self.forward_with_cond_scale(ids, cond_vector=cond_vector,\n padding_mask=padding_mask,\n cond_scale=cond_scale,\n force_mask=force_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # print(logits.shape, self.opt.num_tokens)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n '''\n Update ids\n '''\n # if force_mask:\n temperature = starting_temperature\n # else:\n # temperature = starting_temperature * (steps_until_x0 / timesteps)\n # temperature = max(temperature, 1e-4)\n # print(filtered_logits.shape)\n # temperature is annealed, gradually reducing temperature as well as randomness\n if gsample: # use gumbel_softmax sampling\n # print(\"1111\")\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n else: # use multinomial sampling\n # print(\"2222\")\n probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # print(probs / temperature)\n pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n # print(pred_ids.max(), pred_ids.min())\n # if pred_ids.\n ids = torch.where(is_mask, pred_ids, ids)\n\n '''\n Updating scores\n '''\n probs_without_temperature = logits.softmax(dim=-1) # (b, seqlen, ntoken)\n scores = probs_without_temperature.gather(2, pred_ids.unsqueeze(dim=-1)) # (b, seqlen, 1)\n scores = scores.squeeze(-1) # (b, seqlen)\n\n # We do not want to re-mask the previously kept tokens, or pad tokens\n scores = scores.masked_fill(~is_mask, 1e5)\n\n ids = torch.where(padding_mask, -1, ids)\n # print(\"Final\", ids.max(), ids.min())\n return ids\n\n\n @torch.no_grad()\n @eval_decorator\n def edit(self,\n conds,\n tokens,\n m_lens,\n timesteps: int,\n cond_scale: int,\n temperature=1,\n topk_filter_thres=0.9,\n gsample=False,\n force_mask=False,\n edit_mask=None,\n padding_mask=None,\n ):\n\n assert edit_mask.shape == tokens.shape if edit_mask is not None else True\n device = next(self.parameters()).device\n seq_len = tokens.shape[1]\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(1, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n if padding_mask == None:\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n\n # Start from all tokens being masked\n if edit_mask == None:\n mask_free = True\n ids = torch.where(padding_mask, self.pad_id, tokens)\n edit_mask = torch.ones_like(padding_mask)\n edit_mask = edit_mask & ~padding_mask\n edit_len = edit_mask.sum(dim=-1)\n scores = torch.where(edit_mask, 0., 1e5)\n else:\n mask_free = False\n edit_mask = edit_mask & ~padding_mask\n edit_len = edit_mask.sum(dim=-1)\n ids = torch.where(edit_mask, self.mask_id, tokens)\n scores = torch.where(edit_mask, 0., 1e5)\n starting_temperature = temperature\n\n for timestep, steps_until_x0 in zip(torch.linspace(0, 1, timesteps, device=device), reversed(range(timesteps))):\n # 0 < timestep < 1\n rand_mask_prob = 0.16 if mask_free else self.noise_schedule(timestep) # Tensor\n\n '''\n Maskout, and cope with variable length\n '''\n # fix: the ratio regarding lengths, instead of seq_len\n num_token_masked = torch.round(rand_mask_prob * edit_len).clamp(min=1) # (b, )\n\n # select num_token_masked tokens with lowest scores to be masked\n sorted_indices = scores.argsort(\n dim=1) # (b, k), sorted_indices[i, j] = the index of j-th lowest element in scores on dim=1\n ranks = sorted_indices.argsort(dim=1) # (b, k), rank[i, j] = the rank (0: lowest) of scores[i, j] on dim=1\n is_mask = (ranks < num_token_masked.unsqueeze(-1))\n # is_mask = (torch.rand_like(scores) < 0.8) * ~padding_mask if mask_free else is_mask\n ids = torch.where(is_mask, self.mask_id, ids)\n\n '''\n Preparing input\n '''\n # (b, num_token, seqlen)\n logits = self.forward_with_cond_scale(ids, cond_vector=cond_vector,\n padding_mask=padding_mask,\n cond_scale=cond_scale,\n force_mask=force_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # print(logits.shape, self.opt.num_tokens)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n '''\n Update ids\n '''\n # if force_mask:\n temperature = starting_temperature\n # else:\n # temperature = starting_temperature * (steps_until_x0 / timesteps)\n # temperature = max(temperature, 1e-4)\n # print(filtered_logits.shape)\n # temperature is annealed, gradually reducing temperature as well as randomness\n if gsample: # use gumbel_softmax sampling\n # print(\"1111\")\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n else: # use multinomial sampling\n # print(\"2222\")\n probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # print(probs / temperature)\n pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n # print(pred_ids.max(), pred_ids.min())\n # if pred_ids.\n ids = torch.where(is_mask, pred_ids, ids)\n\n '''\n Updating scores\n '''\n probs_without_temperature = logits.softmax(dim=-1) # (b, seqlen, ntoken)\n scores = probs_without_temperature.gather(2, pred_ids.unsqueeze(dim=-1)) # (b, seqlen, 1)\n scores = scores.squeeze(-1) # (b, seqlen)\n\n # We do not want to re-mask the previously kept tokens, or pad tokens\n scores = scores.masked_fill(~edit_mask, 1e5) if mask_free else scores.masked_fill(~is_mask, 1e5)\n\n ids = torch.where(padding_mask, -1, ids)\n # print(\"Final\", ids.max(), ids.min())\n return ids\n\n @torch.no_grad()\n @eval_decorator\n def edit_beta(self,\n conds,\n conds_og,\n tokens,\n m_lens,\n cond_scale: int,\n force_mask=False,\n ):\n\n device = next(self.parameters()).device\n seq_len = tokens.shape[1]\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n if conds_og is not None:\n cond_vector_og = self.encode_text(conds_og)\n else:\n cond_vector_og = None\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n if conds_og is not None:\n cond_vector_og = self.enc_action(conds_og).to(device)\n else:\n cond_vector_og = None\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n\n # Start from all tokens being masked\n ids = torch.where(padding_mask, self.pad_id, tokens) # Do not mask anything\n\n '''\n Preparing input\n '''\n # (b, num_token, seqlen)\n logits = self.forward_with_cond_scale(ids,\n cond_vector=cond_vector,\n cond_vector_neg=cond_vector_og,\n padding_mask=padding_mask,\n cond_scale=cond_scale,\n force_mask=force_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n\n '''\n Updating scores\n '''\n probs_without_temperature = logits.softmax(dim=-1) # (b, seqlen, ntoken)\n tokens[tokens == -1] = 0 # just to get through an error when index = -1 using gather\n og_tokens_scores = probs_without_temperature.gather(2, tokens.unsqueeze(dim=-1)) # (b, seqlen, 1)\n og_tokens_scores = og_tokens_scores.squeeze(-1) # (b, seqlen)\n\n return og_tokens_scores" }, { "identifier": "ResidualTransformer", "path": "models/mask_transformer/transformer.py", "snippet": "class ResidualTransformer(nn.Module):\n def __init__(self, code_dim, cond_mode, latent_dim=256, ff_size=1024, num_layers=8, cond_drop_prob=0.1,\n num_heads=4, dropout=0.1, clip_dim=512, shared_codebook=False, share_weight=False,\n clip_version=None, opt=None, **kargs):\n super(ResidualTransformer, self).__init__()\n print(f'latent_dim: {latent_dim}, ff_size: {ff_size}, nlayers: {num_layers}, nheads: {num_heads}, dropout: {dropout}')\n\n # assert shared_codebook == True, \"Only support shared codebook right now!\"\n\n self.code_dim = code_dim\n self.latent_dim = latent_dim\n self.clip_dim = clip_dim\n self.dropout = dropout\n self.opt = opt\n\n self.cond_mode = cond_mode\n # self.cond_drop_prob = cond_drop_prob\n\n if self.cond_mode == 'action':\n assert 'num_actions' in kargs\n self.num_actions = kargs.get('num_actions', 1)\n self.cond_drop_prob = cond_drop_prob\n\n '''\n Preparing Networks\n '''\n self.input_process = InputProcess(self.code_dim, self.latent_dim)\n self.position_enc = PositionalEncoding(self.latent_dim, self.dropout)\n\n seqTransEncoderLayer = nn.TransformerEncoderLayer(d_model=self.latent_dim,\n nhead=num_heads,\n dim_feedforward=ff_size,\n dropout=dropout,\n activation='gelu')\n\n self.seqTransEncoder = nn.TransformerEncoder(seqTransEncoderLayer,\n num_layers=num_layers)\n\n self.encode_quant = partial(F.one_hot, num_classes=self.opt.num_quantizers)\n self.encode_action = partial(F.one_hot, num_classes=self.num_actions)\n\n self.quant_emb = nn.Linear(self.opt.num_quantizers, self.latent_dim)\n # if self.cond_mode != 'no_cond':\n if self.cond_mode == 'text':\n self.cond_emb = nn.Linear(self.clip_dim, self.latent_dim)\n elif self.cond_mode == 'action':\n self.cond_emb = nn.Linear(self.num_actions, self.latent_dim)\n else:\n raise KeyError(\"Unsupported condition mode!!!\")\n\n\n _num_tokens = opt.num_tokens + 1 # one dummy tokens for padding\n self.pad_id = opt.num_tokens\n\n # self.output_process = OutputProcess_Bert(out_feats=opt.num_tokens, latent_dim=latent_dim)\n self.output_process = OutputProcess(out_feats=code_dim, latent_dim=latent_dim)\n\n if shared_codebook:\n token_embed = nn.Parameter(torch.normal(mean=0, std=0.02, size=(_num_tokens, code_dim)))\n self.token_embed_weight = token_embed.expand(opt.num_quantizers-1, _num_tokens, code_dim)\n if share_weight:\n self.output_proj_weight = self.token_embed_weight\n self.output_proj_bias = None\n else:\n output_proj = nn.Parameter(torch.normal(mean=0, std=0.02, size=(_num_tokens, code_dim)))\n output_bias = nn.Parameter(torch.zeros(size=(_num_tokens,)))\n # self.output_proj_bias = 0\n self.output_proj_weight = output_proj.expand(opt.num_quantizers-1, _num_tokens, code_dim)\n self.output_proj_bias = output_bias.expand(opt.num_quantizers-1, _num_tokens)\n\n else:\n if share_weight:\n self.embed_proj_shared_weight = nn.Parameter(torch.normal(mean=0, std=0.02, size=(opt.num_quantizers - 2, _num_tokens, code_dim)))\n self.token_embed_weight_ = nn.Parameter(torch.normal(mean=0, std=0.02, size=(1, _num_tokens, code_dim)))\n self.output_proj_weight_ = nn.Parameter(torch.normal(mean=0, std=0.02, size=(1, _num_tokens, code_dim)))\n self.output_proj_bias = None\n self.registered = False\n else:\n output_proj_weight = torch.normal(mean=0, std=0.02,\n size=(opt.num_quantizers - 1, _num_tokens, code_dim))\n\n self.output_proj_weight = nn.Parameter(output_proj_weight)\n self.output_proj_bias = nn.Parameter(torch.zeros(size=(opt.num_quantizers, _num_tokens)))\n token_embed_weight = torch.normal(mean=0, std=0.02,\n size=(opt.num_quantizers - 1, _num_tokens, code_dim))\n self.token_embed_weight = nn.Parameter(token_embed_weight)\n\n self.apply(self.__init_weights)\n self.shared_codebook = shared_codebook\n self.share_weight = share_weight\n\n if self.cond_mode == 'text':\n print('Loading CLIP...')\n self.clip_version = clip_version\n self.clip_model = self.load_and_freeze_clip(clip_version)\n\n # def\n\n def mask_cond(self, cond, force_mask=False):\n bs, d = cond.shape\n if force_mask:\n return torch.zeros_like(cond)\n elif self.training and self.cond_drop_prob > 0.:\n mask = torch.bernoulli(torch.ones(bs, device=cond.device) * self.cond_drop_prob).view(bs, 1)\n return cond * (1. - mask)\n else:\n return cond\n\n def __init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def parameters_wo_clip(self):\n return [p for name, p in self.named_parameters() if not name.startswith('clip_model.')]\n\n def load_and_freeze_clip(self, clip_version):\n clip_model, clip_preprocess = clip.load(clip_version, device='cpu',\n jit=False) # Must set jit=False for training\n # Cannot run on cpu\n clip.model.convert_weights(\n clip_model) # Actually this line is unnecessary since clip by default already on float16\n # Date 0707: It's necessary, only unecessary when load directly to gpu. Disable if need to run on cpu\n\n # Freeze CLIP weights\n clip_model.eval()\n for p in clip_model.parameters():\n p.requires_grad = False\n\n return clip_model\n\n def encode_text(self, raw_text):\n device = next(self.parameters()).device\n text = clip.tokenize(raw_text, truncate=True).to(device)\n feat_clip_text = self.clip_model.encode_text(text).float()\n return feat_clip_text\n\n\n def q_schedule(self, bs, low, high):\n noise = uniform((bs,), device=self.opt.device)\n schedule = 1 - cosine_schedule(noise)\n return torch.round(schedule * (high - low)) + low\n\n def process_embed_proj_weight(self):\n if self.share_weight and (not self.shared_codebook):\n # if not self.registered:\n self.output_proj_weight = torch.cat([self.embed_proj_shared_weight, self.output_proj_weight_], dim=0)\n self.token_embed_weight = torch.cat([self.token_embed_weight_, self.embed_proj_shared_weight], dim=0)\n # self.registered = True\n\n def output_project(self, logits, qids):\n '''\n :logits: (bs, code_dim, seqlen)\n :qids: (bs)\n\n :return:\n -logits (bs, ntoken, seqlen)\n '''\n # (num_qlayers-1, num_token, code_dim) -> (bs, ntoken, code_dim)\n output_proj_weight = self.output_proj_weight[qids]\n # (num_qlayers, ntoken) -> (bs, ntoken)\n output_proj_bias = None if self.output_proj_bias is None else self.output_proj_bias[qids]\n\n output = torch.einsum('bnc, bcs->bns', output_proj_weight, logits)\n if output_proj_bias is not None:\n output += output + output_proj_bias.unsqueeze(-1)\n return output\n\n\n\n def trans_forward(self, motion_codes, qids, cond, padding_mask, force_mask=False):\n '''\n :param motion_codes: (b, seqlen, d)\n :padding_mask: (b, seqlen), all pad positions are TRUE else FALSE\n :param qids: (b), quantizer layer ids\n :param cond: (b, embed_dim) for text, (b, num_actions) for action\n :return:\n -logits: (b, num_token, seqlen)\n '''\n cond = self.mask_cond(cond, force_mask=force_mask)\n\n # (b, seqlen, d) -> (seqlen, b, latent_dim)\n x = self.input_process(motion_codes)\n\n # (b, num_quantizer)\n q_onehot = self.encode_quant(qids).float().to(x.device)\n\n q_emb = self.quant_emb(q_onehot).unsqueeze(0) # (1, b, latent_dim)\n cond = self.cond_emb(cond).unsqueeze(0) # (1, b, latent_dim)\n\n x = self.position_enc(x)\n xseq = torch.cat([cond, q_emb, x], dim=0) # (seqlen+2, b, latent_dim)\n\n padding_mask = torch.cat([torch.zeros_like(padding_mask[:, 0:2]), padding_mask], dim=1) # (b, seqlen+2)\n output = self.seqTransEncoder(xseq, src_key_padding_mask=padding_mask)[2:] # (seqlen, b, e)\n logits = self.output_process(output)\n return logits\n\n def forward_with_cond_scale(self,\n motion_codes,\n q_id,\n cond_vector,\n padding_mask,\n cond_scale=3,\n force_mask=False):\n bs = motion_codes.shape[0]\n # if cond_scale == 1:\n qids = torch.full((bs,), q_id, dtype=torch.long, device=motion_codes.device)\n if force_mask:\n logits = self.trans_forward(motion_codes, qids, cond_vector, padding_mask, force_mask=True)\n logits = self.output_project(logits, qids-1)\n return logits\n\n logits = self.trans_forward(motion_codes, qids, cond_vector, padding_mask)\n logits = self.output_project(logits, qids-1)\n if cond_scale == 1:\n return logits\n\n aux_logits = self.trans_forward(motion_codes, qids, cond_vector, padding_mask, force_mask=True)\n aux_logits = self.output_project(aux_logits, qids-1)\n\n scaled_logits = aux_logits + (logits - aux_logits) * cond_scale\n return scaled_logits\n\n def forward(self, all_indices, y, m_lens):\n '''\n :param all_indices: (b, n, q)\n :param y: raw text for cond_mode=text, (b, ) for cond_mode=action\n :m_lens: (b,)\n :return:\n '''\n\n self.process_embed_proj_weight()\n\n bs, ntokens, num_quant_layers = all_indices.shape\n device = all_indices.device\n\n # Positions that are PADDED are ALL FALSE\n non_pad_mask = lengths_to_mask(m_lens, ntokens) # (b, n)\n\n q_non_pad_mask = repeat(non_pad_mask, 'b n -> b n q', q=num_quant_layers)\n all_indices = torch.where(q_non_pad_mask, all_indices, self.pad_id) #(b, n, q)\n\n # randomly sample quantization layers to work on, [1, num_q)\n active_q_layers = q_schedule(bs, low=1, high=num_quant_layers, device=device)\n\n # print(self.token_embed_weight.shape, all_indices.shape)\n token_embed = repeat(self.token_embed_weight, 'q c d-> b c d q', b=bs)\n gather_indices = repeat(all_indices[..., :-1], 'b n q -> b n d q', d=token_embed.shape[2])\n # print(token_embed.shape, gather_indices.shape)\n all_codes = token_embed.gather(1, gather_indices) # (b, n, d, q-1)\n\n cumsum_codes = torch.cumsum(all_codes, dim=-1) #(b, n, d, q-1)\n\n active_indices = all_indices[torch.arange(bs), :, active_q_layers] # (b, n)\n history_sum = cumsum_codes[torch.arange(bs), :, :, active_q_layers - 1]\n\n force_mask = False\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(y)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(y).to(device).float()\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(bs, self.latent_dim).float().to(device)\n force_mask = True\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n logits = self.trans_forward(history_sum, active_q_layers, cond_vector, ~non_pad_mask, force_mask)\n logits = self.output_project(logits, active_q_layers-1)\n ce_loss, pred_id, acc = cal_performance(logits, active_indices, ignore_index=self.pad_id)\n\n return ce_loss, pred_id, acc\n\n @torch.no_grad()\n @eval_decorator\n def generate(self,\n motion_ids,\n conds,\n m_lens,\n temperature=1,\n topk_filter_thres=0.9,\n cond_scale=2,\n num_res_layers=-1, # If it's -1, use all.\n ):\n\n # print(self.opt.num_quantizers)\n # assert len(timesteps) >= len(cond_scales) == self.opt.num_quantizers\n self.process_embed_proj_weight()\n\n device = next(self.parameters()).device\n seq_len = motion_ids.shape[1]\n batch_size = len(conds)\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(batch_size, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n # token_embed = repeat(self.token_embed_weight, 'c d -> b c d', b=batch_size)\n # gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n # history_sum = token_embed.gather(1, gathered_ids)\n\n # print(pa, seq_len)\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n # print(padding_mask.shape, motion_ids.shape)\n motion_ids = torch.where(padding_mask, self.pad_id, motion_ids)\n all_indices = [motion_ids]\n history_sum = 0\n num_quant_layers = self.opt.num_quantizers if num_res_layers==-1 else num_res_layers+1\n\n for i in range(1, num_quant_layers):\n # print(f\"--> Working on {i}-th quantizer\")\n # Start from all tokens being masked\n # qids = torch.full((batch_size,), i, dtype=torch.long, device=motion_ids.device)\n token_embed = self.token_embed_weight[i-1]\n token_embed = repeat(token_embed, 'c d -> b c d', b=batch_size)\n gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n history_sum += token_embed.gather(1, gathered_ids)\n\n logits = self.forward_with_cond_scale(history_sum, i, cond_vector, padding_mask, cond_scale=cond_scale)\n # logits = self.trans_forward(history_sum, qids, cond_vector, padding_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n\n # probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # # print(probs / temperature)\n # pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n ids = torch.where(padding_mask, self.pad_id, pred_ids)\n\n motion_ids = ids\n all_indices.append(ids)\n\n all_indices = torch.stack(all_indices, dim=-1)\n # padding_mask = repeat(padding_mask, 'b n -> b n q', q=all_indices.shape[-1])\n # all_indices = torch.where(padding_mask, -1, all_indices)\n all_indices = torch.where(all_indices==self.pad_id, -1, all_indices)\n # all_indices = all_indices.masked_fill()\n return all_indices\n\n @torch.no_grad()\n @eval_decorator\n def edit(self,\n motion_ids,\n conds,\n m_lens,\n temperature=1,\n topk_filter_thres=0.9,\n cond_scale=2\n ):\n\n # print(self.opt.num_quantizers)\n # assert len(timesteps) >= len(cond_scales) == self.opt.num_quantizers\n self.process_embed_proj_weight()\n\n device = next(self.parameters()).device\n seq_len = motion_ids.shape[1]\n batch_size = len(conds)\n\n if self.cond_mode == 'text':\n with torch.no_grad():\n cond_vector = self.encode_text(conds)\n elif self.cond_mode == 'action':\n cond_vector = self.enc_action(conds).to(device)\n elif self.cond_mode == 'uncond':\n cond_vector = torch.zeros(batch_size, self.latent_dim).float().to(device)\n else:\n raise NotImplementedError(\"Unsupported condition mode!!!\")\n\n # token_embed = repeat(self.token_embed_weight, 'c d -> b c d', b=batch_size)\n # gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n # history_sum = token_embed.gather(1, gathered_ids)\n\n # print(pa, seq_len)\n padding_mask = ~lengths_to_mask(m_lens, seq_len)\n # print(padding_mask.shape, motion_ids.shape)\n motion_ids = torch.where(padding_mask, self.pad_id, motion_ids)\n all_indices = [motion_ids]\n history_sum = 0\n\n for i in range(1, self.opt.num_quantizers):\n # print(f\"--> Working on {i}-th quantizer\")\n # Start from all tokens being masked\n # qids = torch.full((batch_size,), i, dtype=torch.long, device=motion_ids.device)\n token_embed = self.token_embed_weight[i-1]\n token_embed = repeat(token_embed, 'c d -> b c d', b=batch_size)\n gathered_ids = repeat(motion_ids, 'b n -> b n d', d=token_embed.shape[-1])\n history_sum += token_embed.gather(1, gathered_ids)\n\n logits = self.forward_with_cond_scale(history_sum, i, cond_vector, padding_mask, cond_scale=cond_scale)\n # logits = self.trans_forward(history_sum, qids, cond_vector, padding_mask)\n\n logits = logits.permute(0, 2, 1) # (b, seqlen, ntoken)\n # clean low prob token\n filtered_logits = top_k(logits, topk_filter_thres, dim=-1)\n\n pred_ids = gumbel_sample(filtered_logits, temperature=temperature, dim=-1) # (b, seqlen)\n\n # probs = F.softmax(filtered_logits, dim=-1) # (b, seqlen, ntoken)\n # # print(temperature, starting_temperature, steps_until_x0, timesteps)\n # # print(probs / temperature)\n # pred_ids = Categorical(probs / temperature).sample() # (b, seqlen)\n\n ids = torch.where(padding_mask, self.pad_id, pred_ids)\n\n motion_ids = ids\n all_indices.append(ids)\n\n all_indices = torch.stack(all_indices, dim=-1)\n # padding_mask = repeat(padding_mask, 'b n -> b n q', q=all_indices.shape[-1])\n # all_indices = torch.where(padding_mask, -1, all_indices)\n all_indices = torch.where(all_indices==self.pad_id, -1, all_indices)\n # all_indices = all_indices.masked_fill()\n return all_indices" }, { "identifier": "RVQVAE", "path": "models/vq/model.py", "snippet": "class RVQVAE(nn.Module):\n def __init__(self,\n args,\n input_width=263,\n nb_code=1024,\n code_dim=512,\n output_emb_width=512,\n down_t=3,\n stride_t=2,\n width=512,\n depth=3,\n dilation_growth_rate=3,\n activation='relu',\n norm=None):\n\n super().__init__()\n assert output_emb_width == code_dim\n self.code_dim = code_dim\n self.num_code = nb_code\n # self.quant = args.quantizer\n self.encoder = Encoder(input_width, output_emb_width, down_t, stride_t, width, depth,\n dilation_growth_rate, activation=activation, norm=norm)\n self.decoder = Decoder(input_width, output_emb_width, down_t, stride_t, width, depth,\n dilation_growth_rate, activation=activation, norm=norm)\n rvqvae_config = {\n 'num_quantizers': args.num_quantizers,\n 'shared_codebook': args.shared_codebook,\n 'quantize_dropout_prob': args.quantize_dropout_prob,\n 'quantize_dropout_cutoff_index': 0,\n 'nb_code': nb_code,\n 'code_dim':code_dim, \n 'args': args,\n }\n self.quantizer = ResidualVQ(**rvqvae_config)\n\n def preprocess(self, x):\n # (bs, T, Jx3) -> (bs, Jx3, T)\n x = x.permute(0, 2, 1).float()\n return x\n\n def postprocess(self, x):\n # (bs, Jx3, T) -> (bs, T, Jx3)\n x = x.permute(0, 2, 1)\n return x\n\n def encode(self, x):\n N, T, _ = x.shape\n x_in = self.preprocess(x)\n x_encoder = self.encoder(x_in)\n # print(x_encoder.shape)\n code_idx, all_codes = self.quantizer.quantize(x_encoder, return_latent=True)\n # print(code_idx.shape)\n # code_idx = code_idx.view(N, -1)\n # (N, T, Q)\n # print()\n return code_idx, all_codes\n\n def forward(self, x):\n x_in = self.preprocess(x)\n # Encode\n x_encoder = self.encoder(x_in)\n\n ## quantization\n # x_quantized, code_idx, commit_loss, perplexity = self.quantizer(x_encoder, sample_codebook_temp=0.5,\n # force_dropout_index=0) #TODO hardcode\n x_quantized, code_idx, commit_loss, perplexity = self.quantizer(x_encoder, sample_codebook_temp=0.5)\n\n # print(code_idx[0, :, 1])\n ## decoder\n x_out = self.decoder(x_quantized)\n # x_out = self.postprocess(x_decoder)\n return x_out, commit_loss, perplexity\n\n def forward_decoder(self, x):\n x_d = self.quantizer.get_codes_from_indices(x)\n # x_d = x_d.view(1, -1, self.code_dim).permute(0, 2, 1).contiguous()\n x = x_d.sum(dim=0).permute(0, 2, 1)\n\n # decoder\n x_out = self.decoder(x)\n # x_out = self.postprocess(x_decoder)\n return x_out" }, { "identifier": "LengthEstimator", "path": "models/vq/model.py", "snippet": "class LengthEstimator(nn.Module):\n def __init__(self, input_size, output_size):\n super(LengthEstimator, self).__init__()\n nd = 512\n self.output = nn.Sequential(\n nn.Linear(input_size, nd),\n nn.LayerNorm(nd),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Dropout(0.2),\n nn.Linear(nd, nd // 2),\n nn.LayerNorm(nd // 2),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Dropout(0.2),\n nn.Linear(nd // 2, nd // 4),\n nn.LayerNorm(nd // 4),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Linear(nd // 4, output_size)\n )\n\n self.output.apply(self.__init_weights)\n\n def __init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def forward(self, text_emb):\n return self.output(text_emb)" }, { "identifier": "EvalT2MOptions", "path": "options/eval_option.py", "snippet": "class EvalT2MOptions(BaseOptions):\n def initialize(self):\n BaseOptions.initialize(self)\n self.parser.add_argument('--which_epoch', type=str, default=\"latest\", help='Checkpoint you want to use, {latest, net_best_fid, etc}')\n self.parser.add_argument('--batch_size', type=int, default=32, help='Batch size')\n\n self.parser.add_argument('--ext', type=str, default='text2motion', help='Extension of the result file or folder')\n self.parser.add_argument(\"--num_batch\", default=2, type=int,\n help=\"Number of batch for generation\")\n self.parser.add_argument(\"--repeat_times\", default=1, type=int,\n help=\"Number of repetitions, per sample text prompt\")\n self.parser.add_argument(\"--cond_scale\", default=4, type=float,\n help=\"For classifier-free sampling - specifies the s parameter, as defined in the paper.\")\n self.parser.add_argument(\"--temperature\", default=1., type=float,\n help=\"Sampling Temperature.\")\n self.parser.add_argument(\"--topkr\", default=0.9, type=float,\n help=\"Filter out percentil low prop entries.\")\n self.parser.add_argument(\"--time_steps\", default=18, type=int,\n help=\"Mask Generate steps.\")\n self.parser.add_argument(\"--seed\", default=10107, type=int)\n\n self.parser.add_argument('--gumbel_sample', action=\"store_true\", help='True: gumbel sampling, False: categorical sampling.')\n self.parser.add_argument('--use_res_model', action=\"store_true\", help='Whether to use residual transformer.')\n # self.parser.add_argument('--est_length', action=\"store_true\", help='Training iterations')\n\n self.parser.add_argument('--res_name', type=str, default='tres_nlayer8_ld384_ff1024_rvq6ns_cdp0.2_sw', help='Model name of residual transformer')\n self.parser.add_argument('--text_path', type=str, default=\"\", help='Text prompt file')\n\n\n self.parser.add_argument('-msec', '--mask_edit_section', nargs='*', type=str, help='Indicate sections for editing, use comma to separate the start and end of a section'\n 'type int will specify the token frame, type float will specify the ratio of seq_len')\n self.parser.add_argument('--text_prompt', default='', type=str, help=\"A text prompt to be generated. If empty, will take text prompts from dataset.\")\n self.parser.add_argument('--source_motion', default='example_data/000612.npy', type=str, help=\"Source motion path for editing. (new_joint_vecs format .npy file)\")\n self.parser.add_argument(\"--motion_length\", default=0, type=int,\n help=\"Motion length for generation, only applicable with single text prompt.\")\n self.is_train = False" }, { "identifier": "get_opt", "path": "utils/get_opt.py", "snippet": "def get_opt(opt_path, device, **kwargs):\n opt = Namespace()\n opt_dict = vars(opt)\n\n skip = ('-------------- End ----------------',\n '------------ Options -------------',\n '\\n')\n print('Reading', opt_path)\n with open(opt_path, 'r') as f:\n for line in f:\n if line.strip() not in skip:\n # print(line.strip())\n key, value = line.strip('\\n').split(': ')\n if value in ('True', 'False'):\n opt_dict[key] = (value == 'True')\n # print(key, value)\n elif is_float(value):\n opt_dict[key] = float(value)\n elif is_number(value):\n opt_dict[key] = int(value)\n else:\n opt_dict[key] = str(value)\n\n # print(opt)\n opt_dict['which_epoch'] = 'finest'\n opt.save_root = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.name)\n opt.model_dir = pjoin(opt.save_root, 'model')\n opt.meta_dir = pjoin(opt.save_root, 'meta')\n\n if opt.dataset_name == 't2m':\n opt.data_root = './dataset/HumanML3D/'\n opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs')\n opt.text_dir = pjoin(opt.data_root, 'texts')\n opt.joints_num = 22\n opt.dim_pose = 263\n opt.max_motion_length = 196\n opt.max_motion_frame = 196\n opt.max_motion_token = 55\n elif opt.dataset_name == 'kit':\n opt.data_root = './dataset/KIT-ML/'\n opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs')\n opt.text_dir = pjoin(opt.data_root, 'texts')\n opt.joints_num = 21\n opt.dim_pose = 251\n opt.max_motion_length = 196\n opt.max_motion_frame = 196\n opt.max_motion_token = 55\n else:\n raise KeyError('Dataset not recognized')\n if not hasattr(opt, 'unit_length'):\n opt.unit_length = 4\n opt.dim_word = 300\n opt.num_classes = 200 // opt.unit_length\n opt.dim_pos_ohot = len(POS_enumerator)\n opt.is_train = False\n opt.is_continue = False\n opt.device = device\n\n opt_dict.update(kwargs) # Overwrite with kwargs params\n\n return opt" }, { "identifier": "fixseed", "path": "utils/fixseed.py", "snippet": "def fixseed(seed):\n torch.backends.cudnn.benchmark = False\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)" }, { "identifier": "Joint2BVHConvertor", "path": "visualization/joints2bvh.py", "snippet": "class Joint2BVHConvertor:\n def __init__(self):\n self.template = BVH.load('./visualization/data/template.bvh', need_quater=True)\n self.re_order = [0, 1, 4, 7, 10, 2, 5, 8, 11, 3, 6, 9, 12, 15, 13, 16, 18, 20, 14, 17, 19, 21]\n\n self.re_order_inv = [0, 1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12, 14, 18, 13, 15, 19, 16, 20, 17, 21]\n self.end_points = [4, 8, 13, 17, 21]\n\n self.template_offset = self.template.offsets.copy()\n self.parents = [-1, 0, 1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 12, 11, 14, 15, 16, 11, 18, 19, 20]\n\n def convert(self, positions, filename, iterations=10, foot_ik=True):\n '''\n Convert the SMPL joint positions to Mocap BVH\n :param positions: (N, 22, 3)\n :param filename: Save path for resulting BVH\n :param iterations: iterations for optimizing rotations, 10 is usually enough\n :param foot_ik: whether to enfore foot inverse kinematics, removing foot slide issue.\n :return:\n '''\n positions = positions[:, self.re_order]\n new_anim = self.template.copy()\n new_anim.rotations = Quaternions.id(positions.shape[:-1])\n new_anim.positions = new_anim.positions[0:1].repeat(positions.shape[0], axis=-0)\n new_anim.positions[:, 0] = positions[:, 0]\n\n if foot_ik:\n positions = remove_fs(positions, None, fid_l=(3, 4), fid_r=(7, 8), interp_length=5,\n force_on_floor=True)\n ik_solver = BasicInverseKinematics(new_anim, positions, iterations=iterations, silent=True)\n new_anim = ik_solver()\n\n # BVH.save(filename, new_anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n glb = Animation.positions_global(new_anim)[:, self.re_order_inv]\n if filename is not None:\n BVH.save(filename, new_anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n return new_anim, glb\n\n def convert_sgd(self, positions, filename, iterations=100, foot_ik=True):\n '''\n Convert the SMPL joint positions to Mocap BVH\n\n :param positions: (N, 22, 3)\n :param filename: Save path for resulting BVH\n :param iterations: iterations for optimizing rotations, 10 is usually enough\n :param foot_ik: whether to enfore foot inverse kinematics, removing foot slide issue.\n :return:\n '''\n\n ## Positional Foot locking ##\n glb = positions[:, self.re_order]\n\n if foot_ik:\n glb = remove_fs(glb, None, fid_l=(3, 4), fid_r=(7, 8), interp_length=2,\n force_on_floor=True)\n\n ## Fit BVH ##\n new_anim = self.template.copy()\n new_anim.rotations = Quaternions.id(glb.shape[:-1])\n new_anim.positions = new_anim.positions[0:1].repeat(glb.shape[0], axis=-0)\n new_anim.positions[:, 0] = glb[:, 0]\n anim = new_anim.copy()\n\n rot = torch.tensor(anim.rotations.qs, dtype=torch.float)\n pos = torch.tensor(anim.positions[:, 0, :], dtype=torch.float)\n offset = torch.tensor(anim.offsets, dtype=torch.float)\n\n glb = torch.tensor(glb, dtype=torch.float)\n ik_solver = InverseKinematics(rot, pos, offset, anim.parents, glb)\n print('Fixing foot contact using IK...')\n for i in tqdm(range(iterations)):\n mse = ik_solver.step()\n # print(i, mse)\n\n rotations = ik_solver.rotations.detach().cpu()\n norm = torch.norm(rotations, dim=-1, keepdim=True)\n rotations /= norm\n\n anim.rotations = Quaternions(rotations.numpy())\n anim.rotations[:, self.end_points] = Quaternions.id((anim.rotations.shape[0], len(self.end_points)))\n anim.positions[:, 0, :] = ik_solver.position.detach().cpu().numpy()\n if filename is not None:\n BVH.save(filename, anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n # BVH.save(filename[:-3] + 'bvh', anim, names=new_anim.names, frametime=1 / 20, order='zyx', quater=True)\n glb = Animation.positions_global(anim)[:, self.re_order_inv]\n return anim, glb" }, { "identifier": "recover_from_ric", "path": "utils/motion_process.py", "snippet": "def recover_from_ric(data, joints_num):\n r_rot_quat, r_pos = recover_root_rot_pos(data)\n positions = data[..., 4:(joints_num - 1) * 3 + 4]\n positions = positions.view(positions.shape[:-1] + (-1, 3))\n\n '''Add Y-axis rotation to local joints'''\n positions = qrot(qinv(r_rot_quat[..., None, :]).expand(positions.shape[:-1] + (4,)), positions)\n\n '''Add root XZ to joints'''\n positions[..., 0] += r_pos[..., 0:1]\n positions[..., 2] += r_pos[..., 2:3]\n\n '''Concate root and joints'''\n positions = torch.cat([r_pos.unsqueeze(-2), positions], dim=-2)\n\n return positions" }, { "identifier": "plot_3d_motion", "path": "utils/plot_script.py", "snippet": "def plot_3d_motion(save_path, kinematic_tree, joints, title, figsize=(10, 10), fps=120, radius=4):\n matplotlib.use('Agg')\n\n title_sp = title.split(' ')\n if len(title_sp) > 20:\n title = '\\n'.join([' '.join(title_sp[:10]), ' '.join(title_sp[10:20]), ' '.join(title_sp[20:])])\n elif len(title_sp) > 10:\n title = '\\n'.join([' '.join(title_sp[:10]), ' '.join(title_sp[10:])])\n\n def init():\n ax.set_xlim3d([-radius / 2, radius / 2])\n ax.set_ylim3d([0, radius])\n ax.set_zlim3d([0, radius])\n # print(title)\n fig.suptitle(title, fontsize=20)\n ax.grid(b=False)\n\n def plot_xzPlane(minx, maxx, miny, minz, maxz):\n ## Plot a plane XZ\n verts = [\n [minx, miny, minz],\n [minx, miny, maxz],\n [maxx, miny, maxz],\n [maxx, miny, minz]\n ]\n xz_plane = Poly3DCollection([verts])\n xz_plane.set_facecolor((0.5, 0.5, 0.5, 0.5))\n ax.add_collection3d(xz_plane)\n\n # return ax\n\n # (seq_len, joints_num, 3)\n data = joints.copy().reshape(len(joints), -1, 3)\n fig = plt.figure(figsize=figsize)\n ax = p3.Axes3D(fig)\n init()\n MINS = data.min(axis=0).min(axis=0)\n MAXS = data.max(axis=0).max(axis=0)\n colors = ['red', 'blue', 'black', 'red', 'blue',\n 'darkblue', 'darkblue', 'darkblue', 'darkblue', 'darkblue',\n 'darkred', 'darkred', 'darkred', 'darkred', 'darkred']\n frame_number = data.shape[0]\n # print(data.shape)\n\n height_offset = MINS[1]\n data[:, :, 1] -= height_offset\n trajec = data[:, 0, [0, 2]]\n\n data[..., 0] -= data[:, 0:1, 0]\n data[..., 2] -= data[:, 0:1, 2]\n\n # print(trajec.shape)\n\n def update(index):\n # print(index)\n ax.lines = []\n ax.collections = []\n ax.view_init(elev=120, azim=-90)\n ax.dist = 7.5\n # ax =\n plot_xzPlane(MINS[0] - trajec[index, 0], MAXS[0] - trajec[index, 0], 0, MINS[2] - trajec[index, 1],\n MAXS[2] - trajec[index, 1])\n # ax.scatter(data[index, :22, 0], data[index, :22, 1], data[index, :22, 2], color='black', s=3)\n\n if index > 1:\n ax.plot3D(trajec[:index, 0] - trajec[index, 0], np.zeros_like(trajec[:index, 0]),\n trajec[:index, 1] - trajec[index, 1], linewidth=1.0,\n color='blue')\n # ax = plot_xzPlane(ax, MINS[0], MAXS[0], 0, MINS[2], MAXS[2])\n\n for i, (chain, color) in enumerate(zip(kinematic_tree, colors)):\n # print(color)\n if i < 5:\n linewidth = 4.0\n else:\n linewidth = 2.0\n ax.plot3D(data[index, chain, 0], data[index, chain, 1], data[index, chain, 2], linewidth=linewidth,\n color=color)\n # print(trajec[:index, 0].shape)\n\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_zticklabels([])\n\n ani = FuncAnimation(fig, update, frames=frame_number, interval=1000 / fps, repeat=False)\n\n # writer = FFMpegFileWriter(fps=fps)\n ani.save(save_path, fps=fps)\n plt.close()" }, { "identifier": "t2m_kinematic_chain", "path": "utils/paramUtil.py", "snippet": "" }, { "identifier": "load_vq_model", "path": "gen_t2m.py", "snippet": "def load_vq_model(vq_opt):\n # opt_path = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.vq_name, 'opt.txt')\n vq_model = RVQVAE(vq_opt,\n vq_opt.dim_pose,\n vq_opt.nb_code,\n vq_opt.code_dim,\n vq_opt.output_emb_width,\n vq_opt.down_t,\n vq_opt.stride_t,\n vq_opt.width,\n vq_opt.depth,\n vq_opt.dilation_growth_rate,\n vq_opt.vq_act,\n vq_opt.vq_norm)\n ckpt = torch.load(pjoin(vq_opt.checkpoints_dir, vq_opt.dataset_name, vq_opt.name, 'model', 'net_best_fid.tar'),\n map_location='cpu')\n model_key = 'vq_model' if 'vq_model' in ckpt else 'net'\n vq_model.load_state_dict(ckpt[model_key])\n print(f'Loading VQ Model {vq_opt.name} Completed!')\n return vq_model, vq_opt" }, { "identifier": "load_res_model", "path": "gen_t2m.py", "snippet": "def load_res_model(res_opt, vq_opt, opt):\n res_opt.num_quantizers = vq_opt.num_quantizers\n res_opt.num_tokens = vq_opt.nb_code\n res_transformer = ResidualTransformer(code_dim=vq_opt.code_dim,\n cond_mode='text',\n latent_dim=res_opt.latent_dim,\n ff_size=res_opt.ff_size,\n num_layers=res_opt.n_layers,\n num_heads=res_opt.n_heads,\n dropout=res_opt.dropout,\n clip_dim=512,\n shared_codebook=vq_opt.shared_codebook,\n cond_drop_prob=res_opt.cond_drop_prob,\n # codebook=vq_model.quantizer.codebooks[0] if opt.fix_token_emb else None,\n share_weight=res_opt.share_weight,\n clip_version=clip_version,\n opt=res_opt)\n\n ckpt = torch.load(pjoin(res_opt.checkpoints_dir, res_opt.dataset_name, res_opt.name, 'model', 'net_best_fid.tar'),\n map_location=opt.device)\n missing_keys, unexpected_keys = res_transformer.load_state_dict(ckpt['res_transformer'], strict=False)\n assert len(unexpected_keys) == 0\n assert all([k.startswith('clip_model.') for k in missing_keys])\n print(f'Loading Residual Transformer {res_opt.name} from epoch {ckpt[\"ep\"]}!')\n return res_transformer" }, { "identifier": "load_trans_model", "path": "gen_t2m.py", "snippet": "def load_trans_model(model_opt, opt, which_model):\n t2m_transformer = MaskTransformer(code_dim=model_opt.code_dim,\n cond_mode='text',\n latent_dim=model_opt.latent_dim,\n ff_size=model_opt.ff_size,\n num_layers=model_opt.n_layers,\n num_heads=model_opt.n_heads,\n dropout=model_opt.dropout,\n clip_dim=512,\n cond_drop_prob=model_opt.cond_drop_prob,\n clip_version=clip_version,\n opt=model_opt)\n ckpt = torch.load(pjoin(model_opt.checkpoints_dir, model_opt.dataset_name, model_opt.name, 'model', which_model),\n map_location='cpu')\n model_key = 't2m_transformer' if 't2m_transformer' in ckpt else 'trans'\n # print(ckpt.keys())\n missing_keys, unexpected_keys = t2m_transformer.load_state_dict(ckpt[model_key], strict=False)\n assert len(unexpected_keys) == 0\n assert all([k.startswith('clip_model.') for k in missing_keys])\n print(f'Loading Transformer {opt.name} from epoch {ckpt[\"ep\"]}!')\n return t2m_transformer" } ]
import os import torch import torch.nn.functional as F import numpy as np from os.path import join as pjoin from models.mask_transformer.transformer import MaskTransformer, ResidualTransformer from models.vq.model import RVQVAE, LengthEstimator from options.eval_option import EvalT2MOptions from utils.get_opt import get_opt from utils.fixseed import fixseed from visualization.joints2bvh import Joint2BVHConvertor from utils.motion_process import recover_from_ric from utils.plot_script import plot_3d_motion from utils.paramUtil import t2m_kinematic_chain from gen_t2m import load_vq_model, load_res_model, load_trans_model
16,505
if __name__ == '__main__': parser = EvalT2MOptions() opt = parser.parse()
if __name__ == '__main__': parser = EvalT2MOptions() opt = parser.parse()
fixseed(opt.seed)
6
2023-11-29 19:21:27+00:00
24k
dvlab-research/LLMGA
llmga/diffusers/src/diffusers/models/controlnet_flax.py
[ { "identifier": "ConfigMixin", "path": "llmga/diffusers/src/diffusers/configuration_utils.py", "snippet": "class ConfigMixin:\n r\"\"\"\n Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also\n provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and\n saving classes that inherit from [`ConfigMixin`].\n\n Class attributes:\n - **config_name** (`str`) -- A filename under which the config should stored when calling\n [`~ConfigMixin.save_config`] (should be overridden by parent class).\n - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be\n overridden by subclass).\n - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).\n - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function\n should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by\n subclass).\n \"\"\"\n config_name = None\n ignore_for_config = []\n has_compatibles = False\n\n _deprecated_kwargs = []\n\n def register_to_config(self, **kwargs):\n if self.config_name is None:\n raise NotImplementedError(f\"Make sure that {self.__class__} has defined a class name `config_name`\")\n # Special case for `kwargs` used in deprecation warning added to schedulers\n # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,\n # or solve in a more general way.\n kwargs.pop(\"kwargs\", None)\n\n if not hasattr(self, \"_internal_dict\"):\n internal_dict = kwargs\n else:\n previous_dict = dict(self._internal_dict)\n internal_dict = {**self._internal_dict, **kwargs}\n logger.debug(f\"Updating config from {previous_dict} to {internal_dict}\")\n\n self._internal_dict = FrozenDict(internal_dict)\n\n def __getattr__(self, name: str) -> Any:\n \"\"\"The only reason we overwrite `getattr` here is to gracefully deprecate accessing\n config attributes directly. See https://github.com/huggingface/diffusers/pull/3129\n\n Tihs funtion is mostly copied from PyTorch's __getattr__ overwrite:\n https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module\n \"\"\"\n\n is_in_config = \"_internal_dict\" in self.__dict__ and hasattr(self.__dict__[\"_internal_dict\"], name)\n is_attribute = name in self.__dict__\n\n if is_in_config and not is_attribute:\n deprecation_message = f\"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'.\"\n deprecate(\"direct config name access\", \"1.0.0\", deprecation_message, standard_warn=False)\n return self._internal_dict[name]\n\n raise AttributeError(f\"'{type(self).__name__}' object has no attribute '{name}'\")\n\n def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):\n \"\"\"\n Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the\n [`~ConfigMixin.from_config`] class method.\n\n Args:\n save_directory (`str` or `os.PathLike`):\n Directory where the configuration JSON file is saved (will be created if it does not exist).\n push_to_hub (`bool`, *optional*, defaults to `False`):\n Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the\n repository you want to push to with `repo_id` (will default to the name of `save_directory` in your\n namespace).\n kwargs (`Dict[str, Any]`, *optional*):\n Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.\n \"\"\"\n if os.path.isfile(save_directory):\n raise AssertionError(f\"Provided path ({save_directory}) should be a directory, not a file\")\n\n os.makedirs(save_directory, exist_ok=True)\n\n # If we save using the predefined names, we can load using `from_config`\n output_config_file = os.path.join(save_directory, self.config_name)\n\n self.to_json_file(output_config_file)\n logger.info(f\"Configuration saved in {output_config_file}\")\n\n if push_to_hub:\n commit_message = kwargs.pop(\"commit_message\", None)\n private = kwargs.pop(\"private\", False)\n create_pr = kwargs.pop(\"create_pr\", False)\n token = kwargs.pop(\"token\", None)\n repo_id = kwargs.pop(\"repo_id\", save_directory.split(os.path.sep)[-1])\n repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id\n\n self._upload_folder(\n save_directory,\n repo_id,\n token=token,\n commit_message=commit_message,\n create_pr=create_pr,\n )\n\n @classmethod\n def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):\n r\"\"\"\n Instantiate a Python class from a config dictionary.\n\n Parameters:\n config (`Dict[str, Any]`):\n A config dictionary from which the Python class is instantiated. Make sure to only load configuration\n files of compatible classes.\n return_unused_kwargs (`bool`, *optional*, defaults to `False`):\n Whether kwargs that are not consumed by the Python class should be returned or not.\n kwargs (remaining dictionary of keyword arguments, *optional*):\n Can be used to update the configuration object (after it is loaded) and initiate the Python class.\n `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually\n overwrite the same named arguments in `config`.\n\n Returns:\n [`ModelMixin`] or [`SchedulerMixin`]:\n A model or scheduler object instantiated from a config dictionary.\n\n Examples:\n\n ```python\n >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler\n\n >>> # Download scheduler from huggingface.co and cache.\n >>> scheduler = DDPMScheduler.from_pretrained(\"google/ddpm-cifar10-32\")\n\n >>> # Instantiate DDIM scheduler class with same config as DDPM\n >>> scheduler = DDIMScheduler.from_config(scheduler.config)\n\n >>> # Instantiate PNDM scheduler class with same config as DDPM\n >>> scheduler = PNDMScheduler.from_config(scheduler.config)\n ```\n \"\"\"\n # <===== TO BE REMOVED WITH DEPRECATION\n # TODO(Patrick) - make sure to remove the following lines when config==\"model_path\" is deprecated\n if \"pretrained_model_name_or_path\" in kwargs:\n config = kwargs.pop(\"pretrained_model_name_or_path\")\n\n if config is None:\n raise ValueError(\"Please make sure to provide a config as the first positional argument.\")\n # ======>\n\n if not isinstance(config, dict):\n deprecation_message = \"It is deprecated to pass a pretrained model name or path to `from_config`.\"\n if \"Scheduler\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead.\"\n \" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will\"\n \" be removed in v1.0.0.\"\n )\n elif \"Model\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a model, please use {cls}.load_config(...) followed by\"\n f\" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary\"\n \" instead. This functionality will be removed in v1.0.0.\"\n )\n deprecate(\"config-passed-as-path\", \"1.0.0\", deprecation_message, standard_warn=False)\n config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)\n\n init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)\n\n # Allow dtype to be specified on initialization\n if \"dtype\" in unused_kwargs:\n init_dict[\"dtype\"] = unused_kwargs.pop(\"dtype\")\n\n # add possible deprecated kwargs\n for deprecated_kwarg in cls._deprecated_kwargs:\n if deprecated_kwarg in unused_kwargs:\n init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)\n\n # Return model and optionally state and/or unused_kwargs\n model = cls(**init_dict)\n\n # make sure to also save config parameters that might be used for compatible classes\n model.register_to_config(**hidden_dict)\n\n # add hidden kwargs of compatible classes to unused_kwargs\n unused_kwargs = {**unused_kwargs, **hidden_dict}\n\n if return_unused_kwargs:\n return (model, unused_kwargs)\n else:\n return model\n\n @classmethod\n def get_config_dict(cls, *args, **kwargs):\n deprecation_message = (\n f\" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be\"\n \" removed in version v1.0.0\"\n )\n deprecate(\"get_config_dict\", \"1.0.0\", deprecation_message, standard_warn=False)\n return cls.load_config(*args, **kwargs)\n\n @classmethod\n def load_config(\n cls,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n return_unused_kwargs=False,\n return_commit_hash=False,\n **kwargs,\n ) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n r\"\"\"\n Load a model or scheduler configuration.\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):\n Can be either:\n\n - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on\n the Hub.\n - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with\n [`~ConfigMixin.save_config`].\n\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory where a downloaded pretrained model configuration is cached if the standard cache\n is not used.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to resume downloading the model weights and configuration files. If set to `False`, any\n incompletely downloaded files are deleted.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n output_loading_info(`bool`, *optional*, defaults to `False`):\n Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.\n local_files_only (`bool`, *optional*, defaults to `False`):\n Whether to only load local model weights and configuration files or not. If set to `True`, the model\n won't be downloaded from the Hub.\n use_auth_token (`str` or *bool*, *optional*):\n The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from\n `diffusers-cli login` (stored in `~/.huggingface`) is used.\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier\n allowed by Git.\n subfolder (`str`, *optional*, defaults to `\"\"`):\n The subfolder location of a model file within a larger model repository on the Hub or locally.\n return_unused_kwargs (`bool`, *optional*, defaults to `False):\n Whether unused keyword arguments of the config are returned.\n return_commit_hash (`bool`, *optional*, defaults to `False):\n Whether the `commit_hash` of the loaded configuration are returned.\n\n Returns:\n `dict`:\n A dictionary of all the parameters stored in a JSON configuration file.\n\n \"\"\"\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n force_download = kwargs.pop(\"force_download\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n revision = kwargs.pop(\"revision\", None)\n _ = kwargs.pop(\"mirror\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n user_agent = kwargs.pop(\"user_agent\", {})\n\n user_agent = {**user_agent, \"file_type\": \"config\"}\n user_agent = http_user_agent(user_agent)\n\n pretrained_model_name_or_path = str(pretrained_model_name_or_path)\n\n if cls.config_name is None:\n raise ValueError(\n \"`self.config_name` is not defined. Note that one should not load a config from \"\n \"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`\"\n )\n\n if os.path.isfile(pretrained_model_name_or_path):\n config_file = pretrained_model_name_or_path\n elif os.path.isdir(pretrained_model_name_or_path):\n if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):\n # Load from a PyTorch checkpoint\n config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)\n elif subfolder is not None and os.path.isfile(\n os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n ):\n config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n else:\n raise EnvironmentError(\n f\"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}.\"\n )\n else:\n try:\n # Load from URL or cache if already cached\n config_file = hf_hub_download(\n pretrained_model_name_or_path,\n filename=cls.config_name,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n user_agent=user_agent,\n subfolder=subfolder,\n revision=revision,\n )\n except RepositoryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier\"\n \" listed on 'https://huggingface.co/models'\\nIf this is a private repository, make sure to pass a\"\n \" token having permission to this repo with `use_auth_token` or log in with `huggingface-cli\"\n \" login`.\"\n )\n except RevisionNotFoundError:\n raise EnvironmentError(\n f\"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for\"\n \" this model name. Check the model page at\"\n f\" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.\"\n )\n except EntryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}.\"\n )\n except HTTPError as err:\n raise EnvironmentError(\n \"There was a specific connection error when trying to load\"\n f\" {pretrained_model_name_or_path}:\\n{err}\"\n )\n except ValueError:\n raise EnvironmentError(\n f\"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it\"\n f\" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a\"\n f\" directory containing a {cls.config_name} file.\\nCheckout your internet connection or see how to\"\n \" run the library in offline mode at\"\n \" 'https://huggingface.co/docs/diffusers/installation#offline-mode'.\"\n )\n except EnvironmentError:\n raise EnvironmentError(\n f\"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from \"\n \"'https://huggingface.co/models', make sure you don't have a local directory with the same name. \"\n f\"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory \"\n f\"containing a {cls.config_name} file\"\n )\n\n try:\n # Load config dict\n config_dict = cls._dict_from_json_file(config_file)\n\n commit_hash = extract_commit_hash(config_file)\n except (json.JSONDecodeError, UnicodeDecodeError):\n raise EnvironmentError(f\"It looks like the config file at '{config_file}' is not a valid JSON file.\")\n\n if not (return_unused_kwargs or return_commit_hash):\n return config_dict\n\n outputs = (config_dict,)\n\n if return_unused_kwargs:\n outputs += (kwargs,)\n\n if return_commit_hash:\n outputs += (commit_hash,)\n\n return outputs\n\n @staticmethod\n def _get_init_keys(cls):\n return set(dict(inspect.signature(cls.__init__).parameters).keys())\n\n @classmethod\n def extract_init_dict(cls, config_dict, **kwargs):\n # Skip keys that were not present in the original config, so default __init__ values were used\n used_defaults = config_dict.get(\"_use_default_values\", [])\n config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != \"_use_default_values\"}\n\n # 0. Copy origin config dict\n original_dict = dict(config_dict.items())\n\n # 1. Retrieve expected config attributes from __init__ signature\n expected_keys = cls._get_init_keys(cls)\n expected_keys.remove(\"self\")\n # remove general kwargs if present in dict\n if \"kwargs\" in expected_keys:\n expected_keys.remove(\"kwargs\")\n # remove flax internal keys\n if hasattr(cls, \"_flax_internal_args\"):\n for arg in cls._flax_internal_args:\n expected_keys.remove(arg)\n\n # 2. Remove attributes that cannot be expected from expected config attributes\n # remove keys to be ignored\n if len(cls.ignore_for_config) > 0:\n expected_keys = expected_keys - set(cls.ignore_for_config)\n\n # load diffusers library to import compatible and original scheduler\n diffusers_library = importlib.import_module(__name__.split(\".\")[0])\n\n if cls.has_compatibles:\n compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]\n else:\n compatible_classes = []\n\n expected_keys_comp_cls = set()\n for c in compatible_classes:\n expected_keys_c = cls._get_init_keys(c)\n expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)\n expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)\n config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}\n\n # remove attributes from orig class that cannot be expected\n orig_cls_name = config_dict.pop(\"_class_name\", cls.__name__)\n if orig_cls_name != cls.__name__ and hasattr(diffusers_library, orig_cls_name):\n orig_cls = getattr(diffusers_library, orig_cls_name)\n unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys\n config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}\n\n # remove private attributes\n config_dict = {k: v for k, v in config_dict.items() if not k.startswith(\"_\")}\n\n # 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments\n init_dict = {}\n for key in expected_keys:\n # if config param is passed to kwarg and is present in config dict\n # it should overwrite existing config dict key\n if key in kwargs and key in config_dict:\n config_dict[key] = kwargs.pop(key)\n\n if key in kwargs:\n # overwrite key\n init_dict[key] = kwargs.pop(key)\n elif key in config_dict:\n # use value from config dict\n init_dict[key] = config_dict.pop(key)\n\n # 4. Give nice warning if unexpected values have been passed\n if len(config_dict) > 0:\n logger.warning(\n f\"The config attributes {config_dict} were passed to {cls.__name__}, \"\n \"but are not expected and will be ignored. Please verify your \"\n f\"{cls.config_name} configuration file.\"\n )\n\n # 5. Give nice info if config attributes are initiliazed to default because they have not been passed\n passed_keys = set(init_dict.keys())\n if len(expected_keys - passed_keys) > 0:\n logger.info(\n f\"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values.\"\n )\n\n # 6. Define unused keyword arguments\n unused_kwargs = {**config_dict, **kwargs}\n\n # 7. Define \"hidden\" config parameters that were saved for compatible classes\n hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}\n\n return init_dict, unused_kwargs, hidden_config_dict\n\n @classmethod\n def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):\n with open(json_file, \"r\", encoding=\"utf-8\") as reader:\n text = reader.read()\n return json.loads(text)\n\n def __repr__(self):\n return f\"{self.__class__.__name__} {self.to_json_string()}\"\n\n @property\n def config(self) -> Dict[str, Any]:\n \"\"\"\n Returns the config of the class as a frozen dictionary\n\n Returns:\n `Dict[str, Any]`: Config of the class.\n \"\"\"\n return self._internal_dict\n\n def to_json_string(self) -> str:\n \"\"\"\n Serializes the configuration instance to a JSON string.\n\n Returns:\n `str`:\n String containing all the attributes that make up the configuration instance in JSON format.\n \"\"\"\n config_dict = self._internal_dict if hasattr(self, \"_internal_dict\") else {}\n config_dict[\"_class_name\"] = self.__class__.__name__\n config_dict[\"_diffusers_version\"] = __version__\n\n def to_json_saveable(value):\n if isinstance(value, np.ndarray):\n value = value.tolist()\n elif isinstance(value, PosixPath):\n value = str(value)\n return value\n\n config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}\n # Don't save \"_ignore_files\" or \"_use_default_values\"\n config_dict.pop(\"_ignore_files\", None)\n config_dict.pop(\"_use_default_values\", None)\n\n return json.dumps(config_dict, indent=2, sort_keys=True) + \"\\n\"\n\n def to_json_file(self, json_file_path: Union[str, os.PathLike]):\n \"\"\"\n Save the configuration instance's parameters to a JSON file.\n\n Args:\n json_file_path (`str` or `os.PathLike`):\n Path to the JSON file to save a configuration instance's parameters.\n \"\"\"\n with open(json_file_path, \"w\", encoding=\"utf-8\") as writer:\n writer.write(self.to_json_string())" }, { "identifier": "flax_register_to_config", "path": "llmga/diffusers/src/diffusers/configuration_utils.py", "snippet": "def flax_register_to_config(cls):\n original_init = cls.__init__\n\n @functools.wraps(original_init)\n def init(self, *args, **kwargs):\n if not isinstance(self, ConfigMixin):\n raise RuntimeError(\n f\"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does \"\n \"not inherit from `ConfigMixin`.\"\n )\n\n # Ignore private kwargs in the init. Retrieve all passed attributes\n init_kwargs = dict(kwargs.items())\n\n # Retrieve default values\n fields = dataclasses.fields(self)\n default_kwargs = {}\n for field in fields:\n # ignore flax specific attributes\n if field.name in self._flax_internal_args:\n continue\n if type(field.default) == dataclasses._MISSING_TYPE:\n default_kwargs[field.name] = None\n else:\n default_kwargs[field.name] = getattr(self, field.name)\n\n # Make sure init_kwargs override default kwargs\n new_kwargs = {**default_kwargs, **init_kwargs}\n # dtype should be part of `init_kwargs`, but not `new_kwargs`\n if \"dtype\" in new_kwargs:\n new_kwargs.pop(\"dtype\")\n\n # Get positional arguments aligned with kwargs\n for i, arg in enumerate(args):\n name = fields[i].name\n new_kwargs[name] = arg\n\n # Take note of the parameters that were not present in the loaded config\n if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:\n new_kwargs[\"_use_default_values\"] = list(set(new_kwargs.keys()) - set(init_kwargs))\n\n getattr(self, \"register_to_config\")(**new_kwargs)\n original_init(self, *args, **kwargs)\n\n cls.__init__ = init\n return cls" }, { "identifier": "BaseOutput", "path": "llmga/diffusers/src/diffusers/utils/outputs.py", "snippet": "class BaseOutput(OrderedDict):\n \"\"\"\n Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a\n tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular\n Python dictionary.\n\n <Tip warning={true}>\n\n You can't unpack a [`BaseOutput`] directly. Use the [`~utils.BaseOutput.to_tuple`] method to convert it to a tuple\n first.\n\n </Tip>\n \"\"\"\n\n def __post_init__(self):\n class_fields = fields(self)\n\n # Safety and consistency checks\n if not len(class_fields):\n raise ValueError(f\"{self.__class__.__name__} has no fields.\")\n\n first_field = getattr(self, class_fields[0].name)\n other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])\n\n if other_fields_are_none and isinstance(first_field, dict):\n for key, value in first_field.items():\n self[key] = value\n else:\n for field in class_fields:\n v = getattr(self, field.name)\n if v is not None:\n self[field.name] = v\n\n def __delitem__(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.\")\n\n def setdefault(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.\")\n\n def pop(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``pop`` on a {self.__class__.__name__} instance.\")\n\n def update(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``update`` on a {self.__class__.__name__} instance.\")\n\n def __getitem__(self, k):\n if isinstance(k, str):\n inner_dict = dict(self.items())\n return inner_dict[k]\n else:\n return self.to_tuple()[k]\n\n def __setattr__(self, name, value):\n if name in self.keys() and value is not None:\n # Don't call self.__setitem__ to avoid recursion errors\n super().__setitem__(name, value)\n super().__setattr__(name, value)\n\n def __setitem__(self, key, value):\n # Will raise a KeyException if needed\n super().__setitem__(key, value)\n # Don't call self.__setattr__ to avoid recursion errors\n super().__setattr__(key, value)\n\n def __reduce__(self):\n if not is_dataclass(self):\n return super().__reduce__()\n callable, _args, *remaining = super().__reduce__()\n args = tuple(getattr(self, field.name) for field in fields(self))\n return callable, args, *remaining\n\n def to_tuple(self) -> Tuple[Any]:\n \"\"\"\n Convert self to a tuple containing all the attributes/keys that are not `None`.\n \"\"\"\n return tuple(self[k] for k in self.keys())" }, { "identifier": "FlaxTimestepEmbedding", "path": "llmga/diffusers/src/diffusers/models/embeddings_flax.py", "snippet": "class FlaxTimestepEmbedding(nn.Module):\n r\"\"\"\n Time step Embedding Module. Learns embeddings for input time steps.\n\n Args:\n time_embed_dim (`int`, *optional*, defaults to `32`):\n Time step embedding dimension\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n time_embed_dim: int = 32\n dtype: jnp.dtype = jnp.float32\n\n @nn.compact\n def __call__(self, temb):\n temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name=\"linear_1\")(temb)\n temb = nn.silu(temb)\n temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name=\"linear_2\")(temb)\n return temb" }, { "identifier": "FlaxTimesteps", "path": "llmga/diffusers/src/diffusers/models/embeddings_flax.py", "snippet": "class FlaxTimesteps(nn.Module):\n r\"\"\"\n Wrapper Module for sinusoidal Time step Embeddings as described in https://arxiv.org/abs/2006.11239\n\n Args:\n dim (`int`, *optional*, defaults to `32`):\n Time step embedding dimension\n \"\"\"\n dim: int = 32\n flip_sin_to_cos: bool = False\n freq_shift: float = 1\n\n @nn.compact\n def __call__(self, timesteps):\n return get_sinusoidal_embeddings(\n timesteps, embedding_dim=self.dim, flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.freq_shift\n )" }, { "identifier": "FlaxModelMixin", "path": "llmga/diffusers/src/diffusers/models/modeling_flax_utils.py", "snippet": "class FlaxModelMixin(PushToHubMixin):\n r\"\"\"\n Base class for all Flax models.\n\n [`FlaxModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and\n saving models.\n\n - **config_name** ([`str`]) -- Filename to save a model to when calling [`~FlaxModelMixin.save_pretrained`].\n \"\"\"\n config_name = CONFIG_NAME\n _automatically_saved_args = [\"_diffusers_version\", \"_class_name\", \"_name_or_path\"]\n _flax_internal_args = [\"name\", \"parent\", \"dtype\"]\n\n @classmethod\n def _from_config(cls, config, **kwargs):\n \"\"\"\n All context managers that the model should be initialized under go here.\n \"\"\"\n return cls(config, **kwargs)\n\n def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:\n \"\"\"\n Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.\n \"\"\"\n\n # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27\n def conditional_cast(param):\n if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):\n param = param.astype(dtype)\n return param\n\n if mask is None:\n return jax.tree_map(conditional_cast, params)\n\n flat_params = flatten_dict(params)\n flat_mask, _ = jax.tree_flatten(mask)\n\n for masked, key in zip(flat_mask, flat_params.keys()):\n if masked:\n param = flat_params[key]\n flat_params[key] = conditional_cast(param)\n\n return unflatten_dict(flat_params)\n\n def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast\n the `params` in place.\n\n This method can be used on a TPU to explicitly convert the model parameters to bfloat16 precision to do full\n half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`\n for params you want to cast, and `False` for those you want to skip.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # load model\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision\n >>> params = model.to_bf16(params)\n >>> # If you don't want to cast certain parameters (for example layer norm bias and scale)\n >>> # then pass the mask as follows\n >>> from flax import traverse_util\n\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> flat_params = traverse_util.flatten_dict(params)\n >>> mask = {\n ... path: (path[-2] != (\"LayerNorm\", \"bias\") and path[-2:] != (\"LayerNorm\", \"scale\"))\n ... for path in flat_params\n ... }\n >>> mask = traverse_util.unflatten_dict(mask)\n >>> params = model.to_bf16(params, mask)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.bfloat16, mask)\n\n def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the\n model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`\n for params you want to cast, and `False` for those you want to skip.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # Download model and configuration from huggingface.co\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model params will be in fp32, to illustrate the use of this method,\n >>> # we'll first cast to fp16 and back to fp32\n >>> params = model.to_f16(params)\n >>> # now cast back to fp32\n >>> params = model.to_fp32(params)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.float32, mask)\n\n def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the\n `params` in place.\n\n This method can be used on a GPU to explicitly convert the model parameters to float16 precision to do full\n half-precision training or to save weights in float16 for inference in order to save memory and improve speed.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`\n for params you want to cast, and `False` for those you want to skip.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # load model\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model params will be in fp32, to cast these to float16\n >>> params = model.to_fp16(params)\n >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)\n >>> # then pass the mask as follows\n >>> from flax import traverse_util\n\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> flat_params = traverse_util.flatten_dict(params)\n >>> mask = {\n ... path: (path[-2] != (\"LayerNorm\", \"bias\") and path[-2:] != (\"LayerNorm\", \"scale\"))\n ... for path in flat_params\n ... }\n >>> mask = traverse_util.unflatten_dict(mask)\n >>> params = model.to_fp16(params, mask)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.float16, mask)\n\n def init_weights(self, rng: jax.Array) -> Dict:\n raise NotImplementedError(f\"init_weights method has to be implemented for {self}\")\n\n @classmethod\n def from_pretrained(\n cls,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n dtype: jnp.dtype = jnp.float32,\n *model_args,\n **kwargs,\n ):\n r\"\"\"\n Instantiate a pretrained Flax model from a pretrained model configuration.\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`):\n Can be either:\n\n - A string, the *model id* (for example `runwayml/stable-diffusion-v1-5`) of a pretrained model\n hosted on the Hub.\n - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved\n using [`~FlaxModelMixin.save_pretrained`].\n dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):\n The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and\n `jax.numpy.bfloat16` (on TPUs).\n\n This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If\n specified, all the computation will be performed with the given `dtype`.\n\n <Tip>\n\n This only specifies the dtype of the *computation* and does not influence the dtype of model\n parameters.\n\n If you wish to change the dtype of the model parameters, see [`~FlaxModelMixin.to_fp16`] and\n [`~FlaxModelMixin.to_bf16`].\n\n </Tip>\n\n model_args (sequence of positional arguments, *optional*):\n All remaining positional arguments are passed to the underlying model's `__init__` method.\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory where a downloaded pretrained model configuration is cached if the standard cache\n is not used.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to resume downloading the model weights and configuration files. If set to `False`, any\n incompletely downloaded files are deleted.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n local_files_only(`bool`, *optional*, defaults to `False`):\n Whether to only load local model weights and configuration files or not. If set to `True`, the model\n won't be downloaded from the Hub.\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier\n allowed by Git.\n from_pt (`bool`, *optional*, defaults to `False`):\n Load the model weights from a PyTorch checkpoint save file.\n kwargs (remaining dictionary of keyword arguments, *optional*):\n Can be used to update the configuration object (after it is loaded) and initiate the model (for\n example, `output_attentions=True`). Behaves differently depending on whether a `config` is provided or\n automatically loaded:\n\n - If a configuration is provided with `config`, `kwargs` are directly passed to the underlying\n model's `__init__` method (we assume all relevant updates to the configuration have already been\n done).\n - If a configuration is not provided, `kwargs` are first passed to the configuration class\n initialization function [`~ConfigMixin.from_config`]. Each key of the `kwargs` that corresponds\n to a configuration attribute is used to override said attribute with the supplied `kwargs` value.\n Remaining keys that do not correspond to any configuration attribute are passed to the underlying\n model's `__init__` function.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # Download model and configuration from huggingface.co and cache.\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"./test/saved_model/\")\n ```\n\n If you get the error message below, you need to finetune the weights for your downstream task:\n\n ```bash\n Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:\n - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated\n You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n ```\n \"\"\"\n config = kwargs.pop(\"config\", None)\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n force_download = kwargs.pop(\"force_download\", False)\n from_pt = kwargs.pop(\"from_pt\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n revision = kwargs.pop(\"revision\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n\n user_agent = {\n \"diffusers\": __version__,\n \"file_type\": \"model\",\n \"framework\": \"flax\",\n }\n\n # Load config if we don't provide one\n if config is None:\n config, unused_kwargs = cls.load_config(\n pretrained_model_name_or_path,\n cache_dir=cache_dir,\n return_unused_kwargs=True,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n revision=revision,\n subfolder=subfolder,\n **kwargs,\n )\n\n model, model_kwargs = cls.from_config(config, dtype=dtype, return_unused_kwargs=True, **unused_kwargs)\n\n # Load model\n pretrained_path_with_subfolder = (\n pretrained_model_name_or_path\n if subfolder is None\n else os.path.join(pretrained_model_name_or_path, subfolder)\n )\n if os.path.isdir(pretrained_path_with_subfolder):\n if from_pt:\n if not os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):\n raise EnvironmentError(\n f\"Error no file named {WEIGHTS_NAME} found in directory {pretrained_path_with_subfolder} \"\n )\n model_file = os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)\n elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)):\n # Load from a Flax checkpoint\n model_file = os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)\n # Check if pytorch weights exist instead\n elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):\n raise EnvironmentError(\n f\"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model\"\n \" using `from_pt=True`.\"\n )\n else:\n raise EnvironmentError(\n f\"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory \"\n f\"{pretrained_path_with_subfolder}.\"\n )\n else:\n try:\n model_file = hf_hub_download(\n pretrained_model_name_or_path,\n filename=FLAX_WEIGHTS_NAME if not from_pt else WEIGHTS_NAME,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n user_agent=user_agent,\n subfolder=subfolder,\n revision=revision,\n )\n\n except RepositoryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier \"\n \"listed on 'https://huggingface.co/models'\\nIf this is a private repository, make sure to pass a \"\n \"token having permission to this repo with `use_auth_token` or log in with `huggingface-cli \"\n \"login`.\"\n )\n except RevisionNotFoundError:\n raise EnvironmentError(\n f\"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for \"\n \"this model name. Check the model page at \"\n f\"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.\"\n )\n except EntryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}.\"\n )\n except HTTPError as err:\n raise EnvironmentError(\n f\"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\\n\"\n f\"{err}\"\n )\n except ValueError:\n raise EnvironmentError(\n f\"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it\"\n f\" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a\"\n f\" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\\nCheckout your\"\n \" internet connection or see how to run the library in offline mode at\"\n \" 'https://huggingface.co/docs/transformers/installation#offline-mode'.\"\n )\n except EnvironmentError:\n raise EnvironmentError(\n f\"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from \"\n \"'https://huggingface.co/models', make sure you don't have a local directory with the same name. \"\n f\"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory \"\n f\"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\"\n )\n\n if from_pt:\n if is_torch_available():\n from .modeling_utils import load_state_dict\n else:\n raise EnvironmentError(\n \"Can't load the model in PyTorch format because PyTorch is not installed. \"\n \"Please, install PyTorch or use native Flax weights.\"\n )\n\n # Step 1: Get the pytorch file\n pytorch_model_file = load_state_dict(model_file)\n\n # Step 2: Convert the weights\n state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)\n else:\n try:\n with open(model_file, \"rb\") as state_f:\n state = from_bytes(cls, state_f.read())\n except (UnpicklingError, msgpack.exceptions.ExtraData) as e:\n try:\n with open(model_file) as f:\n if f.read().startswith(\"version\"):\n raise OSError(\n \"You seem to have cloned a repository without having git-lfs installed. Please\"\n \" install git-lfs and run `git lfs install` followed by `git lfs pull` in the\"\n \" folder you cloned.\"\n )\n else:\n raise ValueError from e\n except (UnicodeDecodeError, ValueError):\n raise EnvironmentError(f\"Unable to convert {model_file} to Flax deserializable object. \")\n # make sure all arrays are stored as jnp.ndarray\n # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:\n # https://github.com/google/flax/issues/1261\n state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.devices(\"cpu\")[0]), state)\n\n # flatten dicts\n state = flatten_dict(state)\n\n params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))\n required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())\n\n shape_state = flatten_dict(unfreeze(params_shape_tree))\n\n missing_keys = required_params - set(state.keys())\n unexpected_keys = set(state.keys()) - required_params\n\n if missing_keys:\n logger.warning(\n f\"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. \"\n \"Make sure to call model.init_weights to initialize the missing weights.\"\n )\n cls._missing_keys = missing_keys\n\n for key in state.keys():\n if key in shape_state and state[key].shape != shape_state[key].shape:\n raise ValueError(\n f\"Trying to load the pretrained weight for {key} failed: checkpoint has shape \"\n f\"{state[key].shape} which is incompatible with the model shape {shape_state[key].shape}. \"\n )\n\n # remove unexpected keys to not be saved again\n for unexpected_key in unexpected_keys:\n del state[unexpected_key]\n\n if len(unexpected_keys) > 0:\n logger.warning(\n f\"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when\"\n f\" initializing {model.__class__.__name__}: {unexpected_keys}\\n- This IS expected if you are\"\n f\" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or\"\n \" with another architecture.\"\n )\n else:\n logger.info(f\"All model checkpoint weights were used when initializing {model.__class__.__name__}.\\n\")\n\n if len(missing_keys) > 0:\n logger.warning(\n f\"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\\nYou should probably\"\n \" TRAIN this model on a down-stream task to be able to use it for predictions and inference.\"\n )\n else:\n logger.info(\n f\"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path}.\\nIf your task is similar to the task the model of the checkpoint\"\n f\" was trained on, you can already use {model.__class__.__name__} for predictions without further\"\n \" training.\"\n )\n\n return model, unflatten_dict(state)\n\n def save_pretrained(\n self,\n save_directory: Union[str, os.PathLike],\n params: Union[Dict, FrozenDict],\n is_main_process: bool = True,\n push_to_hub: bool = False,\n **kwargs,\n ):\n \"\"\"\n Save a model and its configuration file to a directory so that it can be reloaded using the\n [`~FlaxModelMixin.from_pretrained`] class method.\n\n Arguments:\n save_directory (`str` or `os.PathLike`):\n Directory to save a model and its configuration file to. Will be created if it doesn't exist.\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n is_main_process (`bool`, *optional*, defaults to `True`):\n Whether the process calling this is the main process or not. Useful during distributed training and you\n need to call this function on all processes. In this case, set `is_main_process=True` only on the main\n process to avoid race conditions.\n push_to_hub (`bool`, *optional*, defaults to `False`):\n Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the\n repository you want to push to with `repo_id` (will default to the name of `save_directory` in your\n namespace).\n kwargs (`Dict[str, Any]`, *optional*):\n Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.\n \"\"\"\n if os.path.isfile(save_directory):\n logger.error(f\"Provided path ({save_directory}) should be a directory, not a file\")\n return\n\n os.makedirs(save_directory, exist_ok=True)\n\n if push_to_hub:\n commit_message = kwargs.pop(\"commit_message\", None)\n private = kwargs.pop(\"private\", False)\n create_pr = kwargs.pop(\"create_pr\", False)\n token = kwargs.pop(\"token\", None)\n repo_id = kwargs.pop(\"repo_id\", save_directory.split(os.path.sep)[-1])\n repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id\n\n model_to_save = self\n\n # Attach architecture to the config\n # Save the config\n if is_main_process:\n model_to_save.save_config(save_directory)\n\n # save model\n output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)\n with open(output_model_file, \"wb\") as f:\n model_bytes = to_bytes(params)\n f.write(model_bytes)\n\n logger.info(f\"Model weights saved in {output_model_file}\")\n\n if push_to_hub:\n self._upload_folder(\n save_directory,\n repo_id,\n token=token,\n commit_message=commit_message,\n create_pr=create_pr,\n )" }, { "identifier": "FlaxCrossAttnDownBlock2D", "path": "llmga/diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxCrossAttnDownBlock2D(nn.Module):\n r\"\"\"\n Cross Attention 2D Downsizing block - original architecture from Unet transformers:\n https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n num_attention_heads (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):\n enable memory efficient attention https://arxiv.org/abs/2112.05682\n split_head_dim (`bool`, *optional*, defaults to `False`):\n Whether to split the head dimension into a new axis for the self-attention computation. In most cases,\n enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n out_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n num_attention_heads: int = 1\n add_downsample: bool = True\n use_linear_projection: bool = False\n only_cross_attention: bool = False\n use_memory_efficient_attention: bool = False\n split_head_dim: bool = False\n dtype: jnp.dtype = jnp.float32\n transformer_layers_per_block: int = 1\n\n def setup(self):\n resnets = []\n attentions = []\n\n for i in range(self.num_layers):\n in_channels = self.in_channels if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=in_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n attn_block = FlaxTransformer2DModel(\n in_channels=self.out_channels,\n n_heads=self.num_attention_heads,\n d_head=self.out_channels // self.num_attention_heads,\n depth=self.transformer_layers_per_block,\n use_linear_projection=self.use_linear_projection,\n only_cross_attention=self.only_cross_attention,\n use_memory_efficient_attention=self.use_memory_efficient_attention,\n split_head_dim=self.split_head_dim,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n if self.add_downsample:\n self.downsamplers_0 = FlaxDownsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, temb, encoder_hidden_states, deterministic=True):\n output_states = ()\n\n for resnet, attn in zip(self.resnets, self.attentions):\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n output_states += (hidden_states,)\n\n if self.add_downsample:\n hidden_states = self.downsamplers_0(hidden_states)\n output_states += (hidden_states,)\n\n return hidden_states, output_states" }, { "identifier": "FlaxDownBlock2D", "path": "llmga/diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxDownBlock2D(nn.Module):\n r\"\"\"\n Flax 2D downsizing block\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n out_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n add_downsample: bool = True\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n resnets = []\n\n for i in range(self.num_layers):\n in_channels = self.in_channels if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=in_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n self.resnets = resnets\n\n if self.add_downsample:\n self.downsamplers_0 = FlaxDownsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, temb, deterministic=True):\n output_states = ()\n\n for resnet in self.resnets:\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n output_states += (hidden_states,)\n\n if self.add_downsample:\n hidden_states = self.downsamplers_0(hidden_states)\n output_states += (hidden_states,)\n\n return hidden_states, output_states" }, { "identifier": "FlaxUNetMidBlock2DCrossAttn", "path": "llmga/diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxUNetMidBlock2DCrossAttn(nn.Module):\n r\"\"\"\n Cross Attention 2D Mid-level block - original architecture from Unet transformers: https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n num_attention_heads (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):\n enable memory efficient attention https://arxiv.org/abs/2112.05682\n split_head_dim (`bool`, *optional*, defaults to `False`):\n Whether to split the head dimension into a new axis for the self-attention computation. In most cases,\n enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n num_attention_heads: int = 1\n use_linear_projection: bool = False\n use_memory_efficient_attention: bool = False\n split_head_dim: bool = False\n dtype: jnp.dtype = jnp.float32\n transformer_layers_per_block: int = 1\n\n def setup(self):\n # there is always at least one resnet\n resnets = [\n FlaxResnetBlock2D(\n in_channels=self.in_channels,\n out_channels=self.in_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n ]\n\n attentions = []\n\n for _ in range(self.num_layers):\n attn_block = FlaxTransformer2DModel(\n in_channels=self.in_channels,\n n_heads=self.num_attention_heads,\n d_head=self.in_channels // self.num_attention_heads,\n depth=self.transformer_layers_per_block,\n use_linear_projection=self.use_linear_projection,\n use_memory_efficient_attention=self.use_memory_efficient_attention,\n split_head_dim=self.split_head_dim,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n res_block = FlaxResnetBlock2D(\n in_channels=self.in_channels,\n out_channels=self.in_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n def __call__(self, hidden_states, temb, encoder_hidden_states, deterministic=True):\n hidden_states = self.resnets[0](hidden_states, temb)\n for attn, resnet in zip(self.attentions, self.resnets[1:]):\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n\n return hidden_states" } ]
from typing import Optional, Tuple, Union from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_2d_blocks_flax import ( FlaxCrossAttnDownBlock2D, FlaxDownBlock2D, FlaxUNetMidBlock2DCrossAttn, ) import flax import flax.linen as nn import jax import jax.numpy as jnp
16,322
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @flax.struct.dataclass class FlaxControlNetOutput(BaseOutput): """ The output of [`FlaxControlNetModel`]. Args: down_block_res_samples (`jnp.ndarray`): mid_block_res_sample (`jnp.ndarray`): """ down_block_res_samples: jnp.ndarray mid_block_res_sample: jnp.ndarray class FlaxControlNetConditioningEmbedding(nn.Module): conditioning_embedding_channels: int block_out_channels: Tuple[int] = (16, 32, 96, 256) dtype: jnp.dtype = jnp.float32 def setup(self): self.conv_in = nn.Conv( self.block_out_channels[0], kernel_size=(3, 3), padding=((1, 1), (1, 1)), dtype=self.dtype, ) blocks = [] for i in range(len(self.block_out_channels) - 1): channel_in = self.block_out_channels[i] channel_out = self.block_out_channels[i + 1] conv1 = nn.Conv( channel_in, kernel_size=(3, 3), padding=((1, 1), (1, 1)), dtype=self.dtype, ) blocks.append(conv1) conv2 = nn.Conv( channel_out, kernel_size=(3, 3), strides=(2, 2), padding=((1, 1), (1, 1)), dtype=self.dtype, ) blocks.append(conv2) self.blocks = blocks self.conv_out = nn.Conv( self.conditioning_embedding_channels, kernel_size=(3, 3), padding=((1, 1), (1, 1)), kernel_init=nn.initializers.zeros_init(), bias_init=nn.initializers.zeros_init(), dtype=self.dtype, ) def __call__(self, conditioning): embedding = self.conv_in(conditioning) embedding = nn.silu(embedding) for block in self.blocks: embedding = block(embedding) embedding = nn.silu(embedding) embedding = self.conv_out(embedding) return embedding @flax_register_to_config
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @flax.struct.dataclass class FlaxControlNetOutput(BaseOutput): """ The output of [`FlaxControlNetModel`]. Args: down_block_res_samples (`jnp.ndarray`): mid_block_res_sample (`jnp.ndarray`): """ down_block_res_samples: jnp.ndarray mid_block_res_sample: jnp.ndarray class FlaxControlNetConditioningEmbedding(nn.Module): conditioning_embedding_channels: int block_out_channels: Tuple[int] = (16, 32, 96, 256) dtype: jnp.dtype = jnp.float32 def setup(self): self.conv_in = nn.Conv( self.block_out_channels[0], kernel_size=(3, 3), padding=((1, 1), (1, 1)), dtype=self.dtype, ) blocks = [] for i in range(len(self.block_out_channels) - 1): channel_in = self.block_out_channels[i] channel_out = self.block_out_channels[i + 1] conv1 = nn.Conv( channel_in, kernel_size=(3, 3), padding=((1, 1), (1, 1)), dtype=self.dtype, ) blocks.append(conv1) conv2 = nn.Conv( channel_out, kernel_size=(3, 3), strides=(2, 2), padding=((1, 1), (1, 1)), dtype=self.dtype, ) blocks.append(conv2) self.blocks = blocks self.conv_out = nn.Conv( self.conditioning_embedding_channels, kernel_size=(3, 3), padding=((1, 1), (1, 1)), kernel_init=nn.initializers.zeros_init(), bias_init=nn.initializers.zeros_init(), dtype=self.dtype, ) def __call__(self, conditioning): embedding = self.conv_in(conditioning) embedding = nn.silu(embedding) for block in self.blocks: embedding = block(embedding) embedding = nn.silu(embedding) embedding = self.conv_out(embedding) return embedding @flax_register_to_config
class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
0
2023-11-27 18:46:55+00:00
24k
JiahuiLei/GART
solver.py
[ { "identifier": "prepare_real_seq", "path": "lib_data/get_data.py", "snippet": "def prepare_real_seq(\n seq_name,\n dataset_mode,\n split=\"train\",\n image_zoom_ratio=0.5,\n balance=False,\n ins_avt_wild_start_end_skip=None,\n):\n logging.info(\"Prepare real seq: {}\".format(seq_name))\n # * Get dataset\n if dataset_mode == \"ubcfashion\":\n dataset = UBCFasionDataset(\n data_root=\"./data/ubcfashion/\",\n video_list=[seq_name],\n image_zoom_ratio=image_zoom_ratio,\n start_end_skip=ins_avt_wild_start_end_skip,\n )\n elif dataset_mode == \"people_snapshot\":\n dataset = InstantAvatarDataset(\n noisy_flag=False,\n data_root=\"./data/people_snapshot/\",\n video_name=seq_name,\n split=split,\n image_zoom_ratio=image_zoom_ratio,\n )\n print(\"Load Instant Avatar processed PeopleSnapshot\")\n elif dataset_mode == \"zju\":\n dataset = ZJUDataset(\n data_root=\"./data/zju_mocap\",\n video_name=seq_name,\n split=split,\n image_zoom_ratio=image_zoom_ratio,\n )\n elif dataset_mode == \"instant_avatar_wild\":\n # assert image_zoom_ratio == 1.0, \"Check! in the wild data should use 1.0\"\n if image_zoom_ratio != 1.0:\n logging.warning(\n f\"Check! in the wild data should use 1.0, but got {image_zoom_ratio}\"\n )\n dataset = InstantAvatarWildDataset(\n data_root=\"./data/insav_wild\",\n video_name=seq_name,\n split=split,\n image_zoom_ratio=image_zoom_ratio,\n start_end_skip=ins_avt_wild_start_end_skip,\n )\n elif dataset_mode == \"dog_demo\":\n dataset = DogDemoDataset(data_root=\"./data/dog_data_official/\", video_name=seq_name)\n else:\n raise NotImplementedError(\"Unknown mode: {}\".format(dataset_mode))\n\n # prepare an optimizable data provider\n optimizable_data_provider = RealDataOptimizablePoseProviderPose(\n dataset,\n balance=balance,\n )\n return optimizable_data_provider, dataset" }, { "identifier": "DatabasePoseProvider", "path": "lib_data/data_provider.py", "snippet": "class DatabasePoseProvider(nn.Module):\n def __init__(\n self,\n pose_dirs: list,\n da_pose_prob=0.1,\n da_range=[0.0, np.pi / 4],\n device=torch.device(\"cuda\"),\n ) -> None:\n super().__init__()\n self.device = device\n self.base_R = matrix_to_axis_angle(\n torch.as_tensor(euler2mat(np.pi / 2.0, 0, np.pi / 2.0, \"sxyz\"))[None]\n )[0]\n self.base_R = self.base_R.float().to(self.device)\n\n self.da_pose_prob = da_pose_prob\n self.da_range = da_range\n\n self.data = []\n\n # cache the poses\n for d in pose_dirs:\n print(f\"Caching {d} ...\")\n for subject in tqdm(os.listdir(d)):\n sub_dir = os.path.join(d, subject)\n if not os.path.isdir(sub_dir):\n continue\n npz_files = [f for f in os.listdir(sub_dir) if f.endswith(\".npz\")]\n npz_files.sort()\n for fn in npz_files:\n try:\n npz_fn = os.path.join(sub_dir, fn)\n pose_data = np.load(npz_fn)\n amass_len = pose_data[\"poses\"].shape[0]\n smplx_to_smpl = list(range(66)) + [72, 73, 74, 117, 118, 119]\n poses = pose_data[\"poses\"][:, smplx_to_smpl].reshape(\n amass_len, 24, 3\n )\n self.data.append(poses.astype(np.float16))\n except:\n # print(f\"Error in {npz_fn}, skip!\")\n pass\n self.data = np.concatenate(self.data, axis=0)\n print(\n f\"Database has poses {len(self.data)} with DA-pose prob {self.da_pose_prob} and range {self.da_range}\"\n )\n return\n\n def forward(self, N: int):\n pose, trans = self.sample_pose(N)\n return pose, trans\n\n def sample_pose(self, N: int):\n # da pose\n pose_list = []\n for i in range(N):\n seed = np.random.rand()\n if seed > self.da_pose_prob:\n # from database\n idx = np.random.randint(len(self.data))\n pose = torch.from_numpy(self.data[idx]).float().to(self.device)\n else:\n # da pose\n pose = torch.zeros(24, 3).to(self.device)\n da_theta = float(np.random.uniform(*self.da_range))\n pose[1, -1] = da_theta\n pose[2, -1] = -da_theta\n pose[0] = self.base_R\n pose_list.append(pose)\n pose = torch.stack(pose_list, dim=0)\n trans = torch.zeros(N, 3).to(self.device)\n return pose, trans" }, { "identifier": "get_template", "path": "lib_gart/templates.py", "snippet": "def get_template(\n mode, init_beta, cano_pose_type, voxel_deformer_res, template_model_path=None\n):\n if mode == \"human\":\n template = SMPLTemplate(\n smpl_model_path=template_model_path,\n init_beta=init_beta,\n cano_pose_type=cano_pose_type,\n voxel_deformer_res=voxel_deformer_res,\n )\n elif mode == \"dog\":\n template = SMALTemplate(\n init_beta=init_beta,\n cano_pose_type=cano_pose_type,\n voxel_deformer_res=voxel_deformer_res,\n )\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n return template" }, { "identifier": "GaussianTemplateModel", "path": "lib_gart/model.py", "snippet": "class GaussianTemplateModel(nn.Module):\n def __init__(\n self,\n template,\n add_bones: AdditionalBones,\n ##################################\n # attr config\n w_correction_flag=True,\n # w_rest_dim=0, # additional skinnign weight\n f_localcode_dim=0,\n max_sph_order=0,\n w_memory_type=\"point\",\n ##################################\n max_scale=0.1, # use sigmoid activation, can't be too large\n min_scale=0.0,\n # geo init\n init_mode=\"on_mesh\",\n opacity_init_value=0.9, # the init value of opacity\n # on mesh init params\n onmesh_init_subdivide_num=0,\n onmesh_init_scale_factor=1.0,\n onmesh_init_thickness_factor=0.5,\n # near mesh init params\n scale_init_value=0.01, # the init value of scale\n nearmesh_init_num=10000,\n nearmesh_init_std=0.1,\n ##################################\n ) -> None:\n super().__init__()\n\n self.template = template\n self.num_bones = template.voxel_deformer.num_bones\n self.add_bones = add_bones\n self.num_add_bones = add_bones.num_bones\n\n self.max_scale = max_scale\n self.min_scale = min_scale\n self._init_act(self.max_scale, self.min_scale)\n self.opacity_init_logit = self.o_inv_act(opacity_init_value)\n\n # * init geometry\n if init_mode == \"on_mesh\":\n x, q, s, o = get_on_mesh_init_geo_values(\n template,\n on_mesh_subdivide=onmesh_init_subdivide_num,\n scale_init_factor=onmesh_init_scale_factor,\n thickness_init_factor=onmesh_init_thickness_factor,\n max_scale=max_scale,\n min_scale=min_scale,\n s_inv_act=self.s_inv_act,\n opacity_init_logit=self.opacity_init_logit,\n )\n elif init_mode == \"near_mesh\":\n self.scale_init_logit = self.s_inv_act(scale_init_value)\n x, q, s, o = get_near_mesh_init_geo_values(\n template,\n scale_base_logit=self.scale_init_logit,\n opacity_base_logit=self.opacity_init_logit,\n random_init_num=nearmesh_init_num,\n random_init_std=nearmesh_init_std,\n )\n elif init_mode == \"in_mesh\":\n self.scale_init_logit = self.s_inv_act(scale_init_value)\n x, q, s, o = get_inside_mesh_init_geo_values(\n template,\n scale_base_logit=self.scale_init_logit,\n opacity_base_logit=self.opacity_init_logit,\n random_init_num=nearmesh_init_num,\n )\n else:\n raise NotImplementedError(f\"Unknown init_mode {init_mode}\")\n self._xyz = nn.Parameter(x)\n self._rotation = nn.Parameter(q)\n self._scaling = nn.Parameter(s)\n self._opacity = nn.Parameter(o)\n\n # * init attributes\n self.w_memory_type = w_memory_type\n assert self.w_memory_type in [\"point\", \"voxel\"], f\"Unknown {w_memory_type}\"\n\n self.max_sph_order = max_sph_order\n self.w_dc_dim = self.template.dim if w_correction_flag else 0\n self.w_rest_dim = self.add_bones.num_bones\n self.f_localcode_dim = f_localcode_dim\n\n sph_rest_dim = 3 * (sph_order2nfeat(self.max_sph_order) - 1)\n self._features_dc = nn.Parameter(torch.zeros_like(self._xyz))\n self._features_rest = nn.Parameter(torch.zeros(self.N, sph_rest_dim))\n\n # * Different implementation of smoothness\n if self.w_memory_type == \"point\":\n self._w_correction_dc = nn.Parameter(torch.zeros(self.N, self.w_dc_dim))\n self._w_correction_rest = nn.Parameter(\n torch.ones(self.N, self.w_rest_dim) * 1e-4\n )\n elif self.w_memory_type == \"voxel\":\n self._w_correction_dc = nn.Parameter(torch.zeros(self.N, 0))\n self._w_correction_rest = nn.Parameter(torch.zeros(self.N, 0))\n if self.w_dc_dim > 0:\n self.template.voxel_deformer.enable_voxel_correction()\n if self.w_rest_dim > 0:\n self.template.voxel_deformer.enable_additional_correction(\n self.w_rest_dim\n )\n elif self.w_memory_type == \"hash\":\n raise NotImplementedError(\"TODO\")\n else:\n raise NotImplementedError(f\"Unknown {w_memory_type}\")\n\n self._features_localcode = nn.Parameter(\n torch.zeros(self.N, self.f_localcode_dim)\n )\n\n assert self.f_localcode_dim == 0, \"TODO, add local mlp ablation\"\n\n # * States\n # warning, our code use N, instead of (N,1) as in GS code\n self.register_buffer(\"xyz_gradient_accum\", torch.zeros(self.N).float())\n self.register_buffer(\"xyz_gradient_denom\", torch.zeros(self.N).long())\n self.register_buffer(\"max_radii2D\", torch.zeros(self.N).float())\n\n self.op_update_exclude = [\"add_bones\"]\n if self.w_memory_type != \"point\":\n self.op_update_exclude.extend([\"w_dc_vox\", \"w_rest_vox\"])\n # self.summary()\n return\n\n def summary(self):\n # logging.info number of parameters per pytorch sub module\n msg = \"\"\n for name, param in self.named_parameters():\n if name.startswith(\"add_bones\"):\n continue # compact print\n msg = msg + f\"[{name}:{param.numel()/1e3:.1f}K] \" \n # logging.info(f\"{name}, {param.numel()/1e6:.3f}M\")\n logging.info(msg)\n return\n\n def _init_act(self, max_s_value, min_s_value):\n def s_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n return min_s_value + torch.sigmoid(x) * (max_s_value - min_s_value)\n\n def s_inv_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n y = (x - min_s_value) / (max_s_value - min_s_value) + 1e-5\n y = torch.logit(y)\n assert not torch.isnan(\n y\n ).any(), f\"{x.min()}, {x.max()}, {y.min()}, {y.max()}\"\n return y\n\n def o_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n return torch.sigmoid(x)\n\n def o_inv_act(x):\n if isinstance(x, float):\n x = torch.tensor(x).squeeze()\n return torch.logit(x)\n\n self.s_act = s_act\n self.s_inv_act = s_inv_act\n self.o_act = o_act\n self.o_inv_act = o_inv_act\n\n return\n\n @property\n def N(self):\n return len(self._xyz)\n\n @property\n def get_x(self):\n return self._xyz\n\n @property\n def get_R(self):\n return quaternion_to_matrix(self._rotation)\n\n @property\n def get_o(self):\n return self.o_act(self._opacity)\n\n @property\n def get_s(self):\n return self.s_act(self._scaling)\n\n @property\n def get_c(self):\n return torch.cat([self._features_dc, self._features_rest], dim=-1)\n\n def cache_for_fast(self):\n _cached_W, _ = self.template.forward(None, self._xyz)\n self._cached_W = _cached_W.detach().clone()\n return\n\n def forward(\n self, theta, trans, additional_dict={}, active_sph_order=None, fast=False\n ):\n # * fast will use the cached per point attr, no query anymore\n # TODO: the additional dict contain info to do flexible skinning: it can contain the As directly for optimization, or it can contain t index to query some buffers to provide As, or it can contain t along with the input theta to query some MLP;\n\n # TODO: if use vol memory, every forward update self.xxx, and remove them from parameters, pretend that the attributes are per point, but actually they are queried every forward\n\n # theta: B,24,3; trans: B,3\n B = len(theta)\n if active_sph_order is None:\n active_sph_order = self.max_sph_order\n else:\n assert (\n active_sph_order <= self.max_sph_order\n ), \"active_sph_order should be smaller\"\n sph_dim = 3 * sph_order2nfeat(active_sph_order)\n\n xyz = self.get_x\n mu_can = xyz\n frame_can = self.get_R\n s = self.get_s\n o = self.get_o\n sph = self.get_c[:, :sph_dim]\n\n mu_can = mu_can[None].expand(B, -1, -1)\n frame_can = frame_can[None].expand(B, -1, -1, -1)\n\n if fast:\n # only forward skeleton, no query voxel\n _, A = self.template.forward(theta, None)\n W = self._cached_W[None].expand(B, -1, -1)\n else:\n W, A = self.template.forward(theta, mu_can)\n if self._w_correction_dc.shape[-1] > 0:\n W = W + self._w_correction_dc[None]\n T = torch.einsum(\"bnj, bjrc -> bnrc\", W[..., : self.num_bones], A)\n\n # * additional correction here\n if \"pose\" not in additional_dict.keys():\n # maybe later we want to viz the different pose effect in cano\n additional_dict[\"pose\"] = theta.reshape(B, -1)[:, 3:]\n add_A = self.add_bones(**additional_dict)\n if add_A is not None:\n if theta.ndim == 2:\n global_axis_angle = theta[:, :3]\n else:\n global_axis_angle = theta[:, 0]\n global_orient_action = self.template.get_rot_action(global_axis_angle) # B,4,4\n add_A = torch.einsum(\"bij, bnjk -> bnik\", global_orient_action, add_A)\n\n if self.w_memory_type == \"point\":\n assert self._w_correction_rest.shape[-1] > 0\n add_W = self._w_correction_rest[None].expand(B, -1, -1)\n elif self.w_memory_type == \"voxel\":\n add_W = W[..., self.num_bones :]\n\n add_T = torch.einsum(\"bnj, bjrc -> bnrc\", add_W, add_A)\n T = T + add_T # Linear\n additional_dict[\"As\"] = add_A\n\n R, t = T[:, :, :3, :3], T[:, :, :3, 3] # B,N,3,3; B,N,3\n\n mu = torch.einsum(\"bnij,bnj->bni\", R, mu_can) + t # B,N,3\n frame = torch.einsum(\"bnij,bnjk->bnik\", R, frame_can) # B,N,3,3\n\n s = s[None].expand(B, -1, -1) # B,N,1\n o = o[None].expand(B, -1, -1) # B,N,1\n sph = sph[:, :sph_dim][None].expand(B, -1, -1) # B,N,C\n\n mu = mu + trans[:, None, :]\n\n return mu, frame, s, o, sph, additional_dict\n\n def compute_reg(self, K):\n # !can cancel the knn, but the w reg is critical\n if K > 0:\n xyz = self._xyz\n # todo: this can be cached and updated every several steps!!\n dist_sq, nn_ind, _ = knn_points(xyz[None], xyz[None], K=K, return_nn=False)\n nn_ind = nn_ind.squeeze(0)\n # reg the std inside knn\n q = self._rotation[nn_ind, :] # N,K,4\n s = self.get_s[nn_ind, :] # N,K,3\n o = self.get_o[nn_ind, :] # N,K,1\n q_std = q.std(dim=1).mean()\n s_std = s.std(dim=1).mean()\n o_std = o.std(dim=1).mean()\n\n cd = self._features_dc[nn_ind, :] # N,K,3\n ch = self._features_rest[nn_ind, :] # N,K,C\n cd_std = cd.std(dim=1).mean()\n ch_std = ch.std(dim=1).mean()\n if ch.shape[-1] == 0:\n ch_std = torch.zeros_like(ch_std)\n\n w = self._w_correction_dc[nn_ind, :] # N,K,3\n w_rest = self._w_correction_rest[nn_ind, :] # N,K,C\n f = self._features_localcode[nn_ind, :] # N,K,C\n w_std = w.std(dim=1).mean()\n w_rest_std = w_rest.std(dim=1).mean()\n f_std = f.std(dim=1).mean()\n if w.shape[-1] == 0:\n w_std = torch.zeros_like(cd_std)\n if w_rest.shape[-1] == 0:\n w_rest_std = torch.zeros_like(cd_std)\n if f.shape[-1] == 0:\n f_std = torch.zeros_like(cd_std)\n else:\n dummy = torch.zeros(1).to(self._xyz).squeeze()\n q_std, s_std, o_std = dummy, dummy, dummy\n cd_std, ch_std = dummy, dummy\n w_std, w_rest_std, f_std = dummy, dummy, dummy\n dist_sq = dummy\n\n w_norm = self._w_correction_dc.norm(dim=-1).mean() # N\n w_rest_norm = self._w_correction_rest.norm(dim=-1).mean() # N\n\n if self.w_memory_type == \"voxel\":\n # update the w related std and norm\n w_std = self.template.voxel_deformer.get_tv(\"dc\")\n w_rest_std = self.template.voxel_deformer.get_tv(\"rest\")\n w_norm = self.template.voxel_deformer.get_mag(\"dc\")\n w_rest_norm = self.template.voxel_deformer.get_mag(\"rest\")\n\n max_s_square = torch.mean((self.get_s.max(dim=1).values) ** 2)\n\n return (\n q_std,\n s_std,\n o_std,\n cd_std,\n ch_std,\n w_std,\n w_rest_std,\n f_std,\n w_norm,\n w_rest_norm,\n dist_sq.mean(),\n max_s_square,\n )\n\n def get_optimizable_list(\n self,\n lr_p=0.00016,\n lr_q=0.001,\n lr_s=0.005,\n lr_o=0.05,\n lr_sph=0.0025,\n lr_sph_rest=None,\n lr_w=0.001,\n lr_w_rest=0.001,\n lr_f=0.0001,\n ):\n lr_sph_rest = lr_sph / 20 if lr_sph_rest is None else lr_sph_rest\n l = [\n {\"params\": [self._xyz], \"lr\": lr_p, \"name\": \"xyz\"},\n {\"params\": [self._opacity], \"lr\": lr_o, \"name\": \"opacity\"},\n {\"params\": [self._scaling], \"lr\": lr_s, \"name\": \"scaling\"},\n {\"params\": [self._rotation], \"lr\": lr_q, \"name\": \"rotation\"},\n {\"params\": [self._features_dc], \"lr\": lr_sph, \"name\": \"f_dc\"},\n {\"params\": [self._features_rest], \"lr\": lr_sph_rest, \"name\": \"f_rest\"},\n {\"params\": [self._w_correction_dc], \"lr\": lr_w, \"name\": \"w_dc\"},\n {\"params\": [self._w_correction_rest], \"lr\": lr_w_rest, \"name\": \"w_rest\"},\n {\"params\": [self._features_localcode], \"lr\": lr_f, \"name\": \"f_localcode\"},\n ]\n if self.w_memory_type == \"voxel\":\n if self.w_dc_dim > 0:\n l.append(\n {\n \"params\": [self.template.voxel_deformer.voxel_w_correction],\n \"lr\": lr_w,\n \"name\": \"w_dc_vox\",\n }\n )\n if self.w_rest_dim > 0:\n l.append(\n {\n \"params\": [self.template.voxel_deformer.additional_correction],\n \"lr\": lr_w_rest,\n \"name\": \"w_rest_vox\",\n }\n )\n return l\n\n # * Gaussian Control\n def record_xyz_grad_radii(self, viewspace_point_tensor, radii, update_filter):\n # Record the gradient norm, invariant across different poses\n assert len(viewspace_point_tensor) == self.N\n self.xyz_gradient_accum[update_filter] += torch.norm(\n viewspace_point_tensor.grad[update_filter, :2], dim=-1, keepdim=False\n )\n self.xyz_gradient_denom[update_filter] += 1\n self.max_radii2D[update_filter] = torch.max(\n self.max_radii2D[update_filter], radii[update_filter]\n )\n return\n\n def _densification_postprocess(\n self,\n optimizer,\n new_xyz,\n new_r,\n new_s,\n new_o,\n new_sph_dc,\n new_sph_rest,\n new_w_dc,\n new_w_rest,\n new_localcode,\n ):\n d = {\n \"xyz\": new_xyz,\n \"f_dc\": new_sph_dc,\n \"f_rest\": new_sph_rest,\n \"opacity\": new_o,\n \"scaling\": new_s,\n \"rotation\": new_r,\n \"w_dc\": new_w_dc,\n \"w_rest\": new_w_rest,\n \"f_localcode\": new_localcode,\n }\n d = {k: v for k, v in d.items() if v is not None}\n\n # First cat to optimizer and then return to self\n optimizable_tensors = cat_tensors_to_optimizer(optimizer, d)\n\n self._xyz = optimizable_tensors[\"xyz\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._w_correction_dc = optimizable_tensors[\"w_dc\"]\n self._w_correction_rest = optimizable_tensors[\"w_rest\"]\n self._features_localcode = optimizable_tensors[\"f_localcode\"]\n\n self.xyz_gradient_accum = torch.zeros(self._xyz.shape[0], device=\"cuda\")\n self.xyz_gradient_denom = torch.zeros(self._xyz.shape[0], device=\"cuda\")\n self.max_radii2D = torch.cat(\n [self.max_radii2D, torch.zeros_like(new_xyz[:, 0])], dim=0\n )\n return\n\n def _densify_and_clone(self, optimizer, grad_norm, grad_threshold, scale_th):\n # Extract points that satisfy the gradient condition\n # padding for enabling both call of clone and split\n padded_grad = torch.zeros((self.N), device=\"cuda\")\n padded_grad[: grad_norm.shape[0]] = grad_norm.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(\n selected_pts_mask,\n torch.max(self.get_s, dim=1).values <= scale_th,\n )\n if selected_pts_mask.sum() == 0:\n return 0\n\n new_xyz = self._xyz[selected_pts_mask]\n new_rotation = self._rotation[selected_pts_mask]\n new_scaling = self._scaling[selected_pts_mask]\n new_opacities = self._opacity[selected_pts_mask]\n new_features_dc = self._features_dc[selected_pts_mask]\n new_features_rest = self._features_rest[selected_pts_mask]\n new_w_dc = self._w_correction_dc[selected_pts_mask]\n new_w_rest = self._w_correction_rest[selected_pts_mask]\n new_localcode = self._features_localcode[selected_pts_mask]\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz,\n new_r=new_rotation,\n new_s=new_scaling,\n new_o=new_opacities,\n new_sph_dc=new_features_dc,\n new_sph_rest=new_features_rest,\n new_w_dc=new_w_dc,\n new_w_rest=new_w_rest,\n new_localcode=new_localcode,\n )\n\n return len(new_xyz)\n\n def _densify_and_split(\n self,\n optimizer,\n grad_norm,\n grad_threshold,\n scale_th,\n N=2,\n ):\n # Extract points that satisfy the gradient condition\n _scaling = self.get_s\n # padding for enabling both call of clone and split\n padded_grad = torch.zeros((self.N), device=\"cuda\")\n padded_grad[: grad_norm.shape[0]] = grad_norm.squeeze()\n selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n selected_pts_mask = torch.logical_and(\n selected_pts_mask,\n torch.max(_scaling, dim=1).values > scale_th,\n )\n if selected_pts_mask.sum() == 0:\n return 0\n\n stds = _scaling[selected_pts_mask].repeat(N, 1)\n means = torch.zeros((stds.size(0), 3), device=\"cuda\")\n samples = torch.normal(mean=means, std=stds)\n rots = quaternion_to_matrix(self._rotation[selected_pts_mask]).repeat(N, 1, 1)\n new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self._xyz[\n selected_pts_mask\n ].repeat(N, 1)\n new_scaling = _scaling[selected_pts_mask].repeat(N, 1) / (0.8 * N)\n new_scaling = torch.clamp(new_scaling, max=self.max_scale, min=self.min_scale)\n new_scaling = self.s_inv_act(new_scaling)\n new_rotation = self._rotation[selected_pts_mask].repeat(N, 1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(N, 1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(N, 1)\n new_opacities = self._opacity[selected_pts_mask].repeat(N, 1)\n new_w_dc = self._w_correction_dc[selected_pts_mask].repeat(N, 1)\n new_w_rest = self._w_correction_rest[selected_pts_mask].repeat(N, 1)\n new_localcode = self._features_localcode[selected_pts_mask].repeat(N, 1)\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz,\n new_r=new_rotation,\n new_s=new_scaling,\n new_o=new_opacities,\n new_sph_dc=new_features_dc,\n new_sph_rest=new_features_rest,\n new_w_dc=new_w_dc,\n new_w_rest=new_w_rest,\n new_localcode=new_localcode,\n )\n\n prune_filter = torch.cat(\n (\n selected_pts_mask,\n torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool),\n )\n )\n self._prune_points(optimizer, prune_filter)\n return len(new_xyz)\n\n def densify(self, optimizer, max_grad, percent_dense, extent, verbose=True):\n grads = self.xyz_gradient_accum / self.xyz_gradient_denom\n grads[grads.isnan()] = 0.0\n\n # n_clone = self._densify_and_clone(optimizer, grads, max_grad)\n n_clone = self._densify_and_clone(\n optimizer, grads, max_grad, percent_dense * extent\n )\n n_split = self._densify_and_split(\n optimizer, grads, max_grad, percent_dense * extent, N=2\n )\n\n if verbose:\n logging.info(f\"Densify: Clone[+] {n_clone}, Split[+] {n_split}\")\n # logging.info(f\"Densify: Clone[+] {n_clone}\")\n # torch.cuda.empty_cache()\n return\n\n def random_grow(self, optimizer, num_factor=0.05, std=0.1, init_opa_value=0.1):\n # * New operation, randomly add largely disturbed points to the geometry\n ind = torch.randperm(self.N)[: int(self.N * num_factor)]\n selected_pts_mask = torch.zeros(self.N, dtype=bool, device=\"cuda\")\n selected_pts_mask[ind] = True\n\n new_xyz = self._xyz[selected_pts_mask]\n noise = torch.randn_like(new_xyz) * std\n new_xyz = new_xyz + noise\n new_features_dc = self._features_dc[selected_pts_mask]\n new_features_rest = self._features_rest[selected_pts_mask]\n\n new_opacities = torch.ones_like(self._opacity[selected_pts_mask])\n new_opacities = new_opacities * self.o_inv_act(init_opa_value)\n\n new_scaling = self._scaling[selected_pts_mask]\n new_rotation = self._rotation[selected_pts_mask]\n\n new_w_dc = self._w_correction_dc[selected_pts_mask]\n new_w_rest = self._w_correction_rest[selected_pts_mask]\n new_localcode = self._features_localcode[selected_pts_mask]\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz,\n new_r=new_rotation,\n new_s=new_scaling,\n new_o=new_opacities,\n new_sph_dc=new_features_dc,\n new_sph_rest=new_features_rest,\n new_w_dc=new_w_dc,\n new_w_rest=new_w_rest,\n new_localcode=new_localcode,\n )\n logging.info(f\"Random grow: {len(new_xyz)}\")\n return len(new_xyz)\n\n def prune_points(self, optimizer, min_opacity, max_screen_size, verbose=True):\n opacity = self.o_act(self._opacity)\n prune_mask = (opacity < min_opacity).squeeze()\n if max_screen_size: # if a point is too large\n big_points_vs = self.max_radii2D > max_screen_size\n prune_mask = torch.logical_or(prune_mask, big_points_vs)\n # * reset the maxRadii\n self.max_radii2D = torch.zeros_like(self.max_radii2D)\n self._prune_points(optimizer, prune_mask)\n if verbose:\n logging.info(f\"Prune: {prune_mask.sum()}\")\n\n def _prune_points(self, optimizer, mask):\n valid_points_mask = ~mask\n optimizable_tensors = prune_optimizer(\n optimizer,\n valid_points_mask,\n exclude_names=self.op_update_exclude,\n )\n\n self._xyz = optimizable_tensors[\"xyz\"]\n if getattr(self, \"color_memory\", None) is None:\n self._features_dc = optimizable_tensors[\"f_dc\"]\n self._features_rest = optimizable_tensors[\"f_rest\"]\n self._opacity = optimizable_tensors[\"opacity\"]\n self._scaling = optimizable_tensors[\"scaling\"]\n self._rotation = optimizable_tensors[\"rotation\"]\n self._w_correction_dc = optimizable_tensors[\"w_dc\"]\n self._w_correction_rest = optimizable_tensors[\"w_rest\"]\n self._features_localcode = optimizable_tensors[\"f_localcode\"]\n\n self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n self.xyz_gradient_denom = self.xyz_gradient_denom[valid_points_mask]\n self.max_radii2D = self.max_radii2D[valid_points_mask]\n # torch.cuda.empty_cache()\n return\n\n @torch.no_grad()\n def regaussian(self, optimizer, max_scale=0.03):\n # raise NotImplementedError(\"TODO, like split\")\n # * New operation, manually split the large gaussians with smaller ones to approximate\n # * Now, try bi-split\n\n # Extract points that satisfy the gradient condition\n _scaling = self.get_s\n selected_pts_mask = torch.max(_scaling, dim=1).values > max_scale\n\n step = 0\n before_num = self.N\n while selected_pts_mask.any():\n # This can be done more than 3 times, becuase there may be huge gaussians, which should be devided several times\n fg_xyz = self._xyz[selected_pts_mask]\n fg_scale = _scaling[selected_pts_mask]\n fg_frame = quaternion_to_matrix(self._rotation[selected_pts_mask])\n # each column is the direction of axis in global frame\n axis_ind = torch.argmax(fg_scale, dim=1)\n axis_scale = fg_scale.max(dim=1).values\n # select column\n axis_dir = torch.gather(\n fg_frame, dim=2, index=axis_ind[:, None, None].expand(-1, 3, -1)\n ).squeeze(\n -1\n ) # N,3\n new_x1 = fg_xyz + axis_dir.squeeze() * axis_scale[:, None] / 2.0\n new_x2 = fg_xyz - axis_dir.squeeze() * axis_scale[:, None] / 2.0\n # Repeat will change [1,2,3...] to [1,2,3..., 1,2,3...]\n new_xyz = torch.cat([new_x1, new_x2], dim=0).reshape(-1, 3)\n new_scaling = _scaling[selected_pts_mask]\n new_scaling = torch.scatter(\n new_scaling,\n dim=1,\n index=axis_ind[:, None],\n src=axis_scale[:, None] / 2.0,\n ).repeat(2, 1)\n new_scaling = torch.clamp(\n new_scaling, max=self.max_scale, min=self.min_scale\n )\n new_scaling = self.s_inv_act(new_scaling)\n new_rotation = self._rotation[selected_pts_mask].repeat(2, 1)\n new_features_dc = self._features_dc[selected_pts_mask].repeat(2, 1)\n new_features_rest = self._features_rest[selected_pts_mask].repeat(2, 1)\n new_opacities = self._opacity[selected_pts_mask].repeat(2, 1)\n new_w_dc = self._w_correction_dc[selected_pts_mask].repeat(2, 1)\n new_w_rest = self._w_correction_rest[selected_pts_mask].repeat(2, 1)\n new_localcode = self._features_localcode[selected_pts_mask].repeat(2, 1)\n\n self._densification_postprocess(\n optimizer,\n new_xyz=new_xyz.float(),\n new_r=new_rotation.float(),\n new_s=new_scaling.float(),\n new_o=new_opacities.float(),\n new_sph_dc=new_features_dc.float(),\n new_sph_rest=new_features_rest.float(),\n new_w_dc=new_w_dc.float(),\n new_w_rest=new_w_rest.float(),\n new_localcode=new_localcode.float(),\n )\n\n prune_filter = torch.cat(\n (\n selected_pts_mask,\n torch.zeros(2 * selected_pts_mask.sum(), device=\"cuda\", dtype=bool),\n )\n )\n self._prune_points(optimizer, prune_filter)\n\n step += 1\n logging.info(\n f\"Regaussian-[{step}], {selected_pts_mask.sum()} ({selected_pts_mask.float().mean()*100}% pts-scale>{max_scale})\"\n )\n\n _scaling = self.get_s\n selected_pts_mask = torch.max(_scaling, dim=1).values > max_scale\n logging.info(f\"Re-gaussian: {before_num} -> {self.N}\")\n return\n\n def reset_opacity(self, optimizer, value=0.01, verbose=True):\n opacities_new = self.o_inv_act(\n torch.min(self.o_act(self._opacity), torch.ones_like(self._opacity) * value)\n )\n optimizable_tensors = replace_tensor_to_optimizer(\n optimizer, opacities_new, \"opacity\"\n )\n if verbose:\n logging.info(f\"Reset opacity to {value}\")\n self._opacity = optimizable_tensors[\"opacity\"]\n\n def load(self, ckpt):\n # because N changed, have to re-init the buffers\n self._xyz = nn.Parameter(torch.as_tensor(ckpt[\"_xyz\"], dtype=torch.float32))\n\n self._features_dc = nn.Parameter(\n torch.as_tensor(ckpt[\"_features_dc\"], dtype=torch.float32)\n )\n self._features_rest = nn.Parameter(\n torch.as_tensor(ckpt[\"_features_rest\"], dtype=torch.float32)\n )\n self._opacity = nn.Parameter(\n torch.as_tensor(ckpt[\"_opacity\"], dtype=torch.float32)\n )\n self._scaling = nn.Parameter(\n torch.as_tensor(ckpt[\"_scaling\"], dtype=torch.float32)\n )\n self._rotation = nn.Parameter(\n torch.as_tensor(ckpt[\"_rotation\"], dtype=torch.float32)\n )\n self._w_correction_dc = nn.Parameter(\n torch.as_tensor(ckpt[\"_w_correction_dc\"], dtype=torch.float32)\n )\n self._w_correction_rest = nn.Parameter(\n torch.as_tensor(ckpt[\"_w_correction_rest\"], dtype=torch.float32)\n )\n self._features_localcode = nn.Parameter(\n torch.as_tensor(ckpt[\"_features_localcode\"], dtype=torch.float32)\n )\n self.xyz_gradient_accum = torch.as_tensor(\n ckpt[\"xyz_gradient_accum\"], dtype=torch.float32\n )\n self.xyz_gradient_denom = torch.as_tensor(\n ckpt[\"xyz_gradient_denom\"], dtype=torch.int64\n )\n self.max_radii2D = torch.as_tensor(ckpt[\"max_radii2D\"], dtype=torch.float32)\n\n # * add bones may have different total_t\n if \"add_bones.dt_list\" in ckpt.keys():\n self.add_bones.total_t = ckpt[\"add_bones.dt_list\"].shape[0]\n self.add_bones.dt_list = nn.Parameter(\n torch.as_tensor(ckpt[\"add_bones.dt_list\"], dtype=torch.float32)\n )\n self.add_bones.dr_list = nn.Parameter(\n torch.as_tensor(ckpt[\"add_bones.dr_list\"], dtype=torch.float32)\n )\n # load others\n self.load_state_dict(ckpt, strict=True)\n # this is critical, reinit the funcs\n self._init_act(self.max_scale, self.min_scale)\n return" }, { "identifier": "AdditionalBones", "path": "lib_gart/model.py", "snippet": "class AdditionalBones(nn.Module):\n def __init__(\n self, # additional bones\n num_bones: int = 0,\n total_t: int = 0, # any usage of time should use this!\n mode=\"pose-mlp\",\n # pose-mlp\n pose_dim=23 * 3,\n mlp_hidden_dims=[256, 256, 256, 256],\n mlp_act=nn.LeakyReLU,\n # pose+t-mlp\n ):\n super().__init__()\n self.num_bones = num_bones\n if self.num_bones == 0:\n return\n self.mode = mode\n assert self.mode in [\"pose-mlp\", \"pose+t-mlp\", \"delta-list\", \"list\"]\n self.total_t = total_t\n\n if self.mode == \"pose-mlp\":\n self.pose_dim = pose_dim\n self.mlp_layers = nn.ModuleList()\n c_in = self.pose_dim\n for c_out in mlp_hidden_dims:\n self.mlp_layers.append(nn.Sequential(nn.Linear(c_in, c_out), mlp_act()))\n c_in = c_out\n self.mlp_output_head = nn.Linear(c_in, 7 * self.num_bones, bias=False)\n with torch.no_grad():\n self.mlp_output_head.weight.data = (\n torch.randn_like(self.mlp_output_head.weight.data) * 1e-3\n )\n elif self.mode == \"delta-list\":\n self.dr_list = nn.Parameter(torch.zeros(self.total_t, num_bones, 3))\n self.dt_list = nn.Parameter(torch.zeros(self.total_t, num_bones, 3))\n else:\n raise NotImplementedError()\n\n return\n\n def forward(self, pose=None, t=None, As=None):\n if self.num_bones == 0:\n # * No additional bones\n return None\n if As is not None:\n # * Directly return if As already provided\n return As\n if self.mode == \"pose-mlp\":\n assert pose is not None\n assert pose.ndim == 2 and pose.shape[1] == self.pose_dim\n B = len(pose)\n x = pose\n for layer in self.mlp_layers:\n x = layer(x)\n x = self.mlp_output_head(x).reshape(B, -1, 7)\n q, t = x[:, :, :4], x[:, :, 4:]\n q[..., 0] = q[..., 0] + 1.0\n q = F.normalize(q, dim=-1)\n R = quaternion_to_matrix(q)\n Rt = torch.cat([R, t[:, :, :, None]], dim=-1)\n bottom = torch.zeros_like(Rt[:, :, 0:1])\n bottom[:, :, :, -1] = 1.0\n As = torch.cat([Rt, bottom], dim=2)\n return As\n elif self.mode == \"delta-list\":\n As = self._roll_out_continuous_T()\n if t is None:\n B = len(pose)\n # # ! If no time is set, now return eye(4)\n # ret = (\n # torch.eye(4)\n # .to(As.device)[None, None]\n # .repeat(B, self.num_bones, 1, 1)\n # )\n # ! If no time is set, now return first frame\n ret = As[0][None].repeat(B, 1, 1, 1)\n else:\n if isinstance(t, int):\n t = torch.tensor([t]).to(As.device)\n ret = As[t]\n return ret\n else:\n raise NotImplementedError()\n\n return # As in canonical frame\n\n def _roll_out_continuous_T(self):\n # ! this assumes continuous frames, single frame!\n R = axis_angle_to_matrix(self.dr_list)\n dT = (\n torch.eye(4).to(R.device)[None, None].repeat(self.total_t, R.shape[1], 1, 1)\n )\n dT[:, :, :3, :3] = dT[:, :, :3, :3] * 0 + R\n dT[:, :, :3, 3] = dT[:, :, :3, 3] * 0 + self.dt_list\n T = [dT[0]]\n for i in range(1, self.total_t):\n T.append(torch.einsum(\"nij, njk->nik\", T[-1], dT[i]))\n T = torch.stack(T, dim=0)\n return T" }, { "identifier": "render_cam_pcl", "path": "lib_render/gauspl_renderer.py", "snippet": "def render_cam_pcl(\n xyz,\n frame,\n scale,\n opacity,\n color_feat,\n H,\n W,\n CAM_K,\n verbose=False,\n active_sph_order=0,\n bg_color=[1.0, 1.0, 1.0],\n):\n # ! Camera is at origin, every input is in camera coordinate space\n\n S = torch.zeros_like(frame)\n S[:, 0, 0] = scale[:, 0]\n S[:, 1, 1] = scale[:, 1]\n S[:, 2, 2] = scale[:, 2]\n actual_covariance = frame @ (S**2) @ frame.permute(0, 2, 1)\n\n # Create zero tensor. We will use it to make pytorch return gradients of the 2D (screen-space) means\n device = xyz.device\n screenspace_points = (\n torch.zeros_like(xyz, dtype=xyz.dtype, requires_grad=True, device=xyz.device) + 0\n )\n # screenspace_points.retain_grad()\n try:\n screenspace_points.retain_grad()\n except:\n pass\n\n # * Specially handle the non-centered camera, using first padding and finally crop\n if abs(H // 2 - CAM_K[1, 2]) > 1.0 or abs(W // 2 - CAM_K[0, 2]) > 1.0:\n center_handling_flag = True\n left_w, right_w = CAM_K[0, 2], W - CAM_K[0, 2]\n top_h, bottom_h = CAM_K[1, 2], H - CAM_K[1, 2]\n new_W = int(2 * max(left_w, right_w))\n new_H = int(2 * max(top_h, bottom_h))\n else:\n center_handling_flag = False\n new_W, new_H = W, H\n\n # Set up rasterization configuration\n FoVx = focal2fov(CAM_K[0, 0], new_W)\n FoVy = focal2fov(CAM_K[1, 1], new_H)\n tanfovx = math.tan(FoVx * 0.5)\n tanfovy = math.tan(FoVy * 0.5)\n\n # TODO: Check dynamic gaussian repos and original gaussian repo, they use projection matrix to handle non-centered K, not using this stupid padding like me\n viewmatrix = torch.from_numpy(getWorld2View2(np.eye(3), np.zeros(3)).transpose(0, 1)).to(device)\n projection_matrix = (\n getProjectionMatrix(znear=0.01, zfar=1.0, fovX=FoVx, fovY=FoVy).transpose(0, 1).to(device)\n )\n full_proj_transform = (viewmatrix.unsqueeze(0).bmm(projection_matrix.unsqueeze(0))).squeeze(0)\n camera_center = viewmatrix.inverse()[3, :3]\n\n raster_settings = GaussianRasterizationSettings(\n image_height=new_H,\n image_width=new_W,\n tanfovx=tanfovx,\n tanfovy=tanfovy,\n bg=torch.tensor(bg_color, dtype=torch.float32, device=device),\n scale_modifier=1.0,\n viewmatrix=viewmatrix,\n projmatrix=full_proj_transform,\n sh_degree=0, # ! use pre-compute color!\n campos=camera_center,\n prefiltered=False,\n debug=False,\n )\n rasterizer = GaussianRasterizer(raster_settings=raster_settings)\n\n means3D = xyz\n means2D = screenspace_points\n # opacity = torch.ones_like(means3D[:, 0]) * sigma\n\n # If precomputed 3d covariance is provided, use it. If not, then it will be computed from\n # scaling / rotation by the rasterizer.\n scales = None\n rotations = None\n # JH\n cov3D_precomp = strip_lowerdiag(actual_covariance)\n\n # If precomputed colors are provided, use them. Otherwise, if it is desired to precompute colors\n # from SHs in Python, do it. If not, then SH -> RGB conversion will be done by rasterizer.\n # xyz are in camera frame, so the dir in camera frame is just their normalized direction\n dir_cam = F.normalize(xyz, dim=-1)\n # P_w = Frame @ P_local\n dir_local = torch.einsum(\"nji,nj->ni\", frame, dir_cam) # note the transpose\n dir_local = F.normalize(\n dir_local, dim=-1\n ) # If frame is not SO(3) but Affinity, have to normalize\n N = len(color_feat)\n shs_view = color_feat.reshape(N, -1, 3) # N, Deg, Channels\n sh2rgb = eval_sh(active_sph_order, shs_view.permute(0, 2, 1), dir_local)\n colors_precomp = torch.clamp_min(sh2rgb + 0.5, 0.0)\n # colors_precomp = color_feat\n\n # Rasterize visible Gaussians to image, obtain their radii (on screen).\n\n start_time = time.time()\n ret = rasterizer(\n means3D=means3D.float(),\n means2D=means2D.float(),\n shs=None,\n colors_precomp=colors_precomp.float(),\n opacities=opacity.float(),\n scales=scales,\n rotations=rotations,\n cov3D_precomp=cov3D_precomp.float(),\n )\n if len(ret) == 2:\n rendered_image, radii = ret\n depth, alpha = None, None\n elif len(ret) == 4:\n rendered_image, radii, depth, alpha = ret\n else:\n raise ValueError(f\"Unexpected return value from rasterizer with len={len(ret)}\")\n if verbose:\n print(\n f\"render time: {(time.time() - start_time)*1000:.3f}ms\",\n )\n ret = {\n \"rgb\": rendered_image,\n \"dep\": depth,\n \"alpha\": alpha,\n \"viewspace_points\": screenspace_points,\n \"visibility_filter\": radii > 0,\n \"radii\": radii,\n }\n if center_handling_flag:\n for k in [\"rgb\", \"dep\", \"alpha\"]:\n if ret[k] is None:\n continue\n if left_w > right_w:\n ret[k] = ret[k][:, :, :W]\n else:\n ret[k] = ret[k][:, :, -W:]\n if top_h > bottom_h:\n ret[k] = ret[k][:, :H, :]\n else:\n ret[k] = ret[k][:, -H:, :]\n return ret" }, { "identifier": "transform_mu_frame", "path": "lib_gart/model_utils.py", "snippet": "def transform_mu_frame(mu, frame, T):\n if len(mu) != len(T):\n assert len(mu) == 1 and len(frame) == 1\n mu = mu.expand(len(T), -1, -1)\n frame = frame.expand(len(T), -1, -1, -1)\n R, t = T[:, :3, :3], T[:, :3, 3]\n new_frame = torch.einsum(\"bij, bnjk->bnik\", R, frame)\n new_mu = torch.einsum(\"bij, bnj->bni\", R, mu) + t[:, None]\n return new_mu, new_frame" }, { "identifier": "viz_render", "path": "utils/viz.py", "snippet": "def viz_render(gt_rgb, gt_mask, pred_pkg, save_path=None):\n pred_rgb = pred_pkg[\"rgb\"].permute(1, 2, 0)\n pred_mask = pred_pkg[\"alpha\"].squeeze(0)\n pred_depth = pred_pkg[\"dep\"].squeeze(0)\n fig = plt.figure(figsize=(20, 5))\n plt.subplot(1, 5, 1)\n plt.imshow(torch.clamp(gt_rgb, 0.0, 1.0).detach().cpu().numpy())\n plt.title(\"GT\"), plt.axis(\"off\")\n plt.subplot(1, 5, 2)\n plt.imshow(torch.clamp(pred_rgb, 0.0, 1.0).detach().cpu().numpy())\n plt.title(\"Pred view\"), plt.axis(\"off\")\n plt.subplot(1, 5, 3)\n error = torch.clamp(abs(pred_rgb - gt_rgb), 0.0, 1.0).detach().cpu().numpy().max(axis=-1)\n cmap = plt.imshow(error)\n plt.title(\"Render Error (max in rgb)\"), plt.axis(\"off\")\n plt.colorbar(cmap, shrink=0.8)\n\n plt.subplot(1, 5, 4)\n error = torch.clamp(pred_mask - gt_mask, -1.0, 1.0).detach().cpu().numpy()\n cmap = plt.imshow(error)\n plt.title(\"(Pr - GT) Mask Error\"), plt.axis(\"off\")\n plt.colorbar(cmap, shrink=0.8)\n \n plt.subplot(1, 5, 5)\n depth = pred_depth.detach().cpu().numpy()\n cmap = plt.imshow(depth)\n plt.title(\"Pred Depth\"), plt.axis(\"off\")\n plt.colorbar(cmap, shrink=0.8)\n\n plt.tight_layout()\n fig.canvas.draw()\n fig_np = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)\n fig_np = fig_np.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n if save_path is not None:\n plt.savefig(save_path)\n plt.close(fig)\n return fig_np" }, { "identifier": "sample_camera", "path": "lib_guidance/camera_sampling.py", "snippet": "def sample_camera(\n global_step=1,\n n_view=4,\n real_batch_size=1,\n random_azimuth_range=[-180.0, 180.0],\n random_elevation_range=[0.0, 30.0],\n eval_elevation_deg=15,\n camera_distance_range=[0.8, 1.0], # relative\n fovy_range=[15, 60],\n zoom_range=[1.0, 1.0],\n progressive_until=0,\n relative_radius=True,\n):\n # camera_perturb = 0.0\n # center_perturb = 0.0\n # up_perturb: 0.0\n\n # ! from uncond.py\n # ThreeStudio has progressive increase of camera poses, from eval to random\n r = min(1.0, global_step / (progressive_until + 1))\n elevation_range = [\n (1 - r) * eval_elevation_deg + r * random_elevation_range[0],\n (1 - r) * eval_elevation_deg + r * random_elevation_range[1],\n ]\n azimuth_range = [\n (1 - r) * 0.0 + r * random_azimuth_range[0],\n (1 - r) * 0.0 + r * random_azimuth_range[1],\n ]\n\n # sample elevation angles\n if random.random() < 0.5:\n # sample elevation angles uniformly with a probability 0.5 (biased towards poles)\n elevation_deg = (\n torch.rand(real_batch_size) * (elevation_range[1] - elevation_range[0])\n + elevation_range[0]\n ).repeat_interleave(n_view, dim=0)\n elevation = elevation_deg * math.pi / 180\n else:\n # otherwise sample uniformly on sphere\n elevation_range_percent = [\n (elevation_range[0] + 90.0) / 180.0,\n (elevation_range[1] + 90.0) / 180.0,\n ]\n # inverse transform sampling\n elevation = torch.asin(\n 2\n * (\n torch.rand(real_batch_size)\n * (elevation_range_percent[1] - elevation_range_percent[0])\n + elevation_range_percent[0]\n )\n - 1.0\n ).repeat_interleave(n_view, dim=0)\n elevation_deg = elevation / math.pi * 180.0\n\n # sample azimuth angles from a uniform distribution bounded by azimuth_range\n # ensures sampled azimuth angles in a batch cover the whole range\n azimuth_deg = (\n torch.rand(real_batch_size).reshape(-1, 1) + torch.arange(n_view).reshape(1, -1)\n ).reshape(-1) / n_view * (azimuth_range[1] - azimuth_range[0]) + azimuth_range[0]\n azimuth = azimuth_deg * math.pi / 180\n\n ######## Different from original ########\n # sample fovs from a uniform distribution bounded by fov_range\n fovy_deg = (\n torch.rand(real_batch_size) * (fovy_range[1] - fovy_range[0]) + fovy_range[0]\n ).repeat_interleave(n_view, dim=0)\n fovy = fovy_deg * math.pi / 180\n\n # sample distances from a uniform distribution bounded by distance_range\n camera_distances = (\n torch.rand(real_batch_size) * (camera_distance_range[1] - camera_distance_range[0])\n + camera_distance_range[0]\n ).repeat_interleave(n_view, dim=0)\n if relative_radius:\n scale = 1 / torch.tan(0.5 * fovy)\n camera_distances = scale * camera_distances\n\n # zoom in by decreasing fov after camera distance is fixed\n zoom = (\n torch.rand(real_batch_size) * (zoom_range[1] - zoom_range[0]) + zoom_range[0]\n ).repeat_interleave(n_view, dim=0)\n fovy = fovy * zoom\n fovy_deg = fovy_deg * zoom\n ###########################################\n\n # convert spherical coordinates to cartesian coordinates\n # right hand coordinate system, x back, y right, z up\n # elevation in (-90, 90), azimuth from +x to +y in (-180, 180)\n camera_positions = torch.stack(\n [\n camera_distances * torch.cos(elevation) * torch.cos(azimuth),\n camera_distances * torch.cos(elevation) * torch.sin(azimuth),\n camera_distances * torch.sin(elevation),\n ],\n dim=-1,\n )\n\n azimuth, elevation\n # build opencv camera\n z = -torch.stack(\n [\n torch.cos(elevation) * torch.cos(azimuth),\n torch.cos(elevation) * torch.sin(azimuth),\n torch.sin(elevation),\n ],\n -1,\n ) # nview, 3\n # up is 0,0,1\n x = torch.cross(z, torch.tensor([0.0, 0.0, 1.0], device=z.device).repeat(n_view, 1), -1)\n y = torch.cross(z, x, -1)\n\n R_wc = torch.stack([x, y, z], dim=2) # nview, 3, 3, col is basis\n t_wc = camera_positions\n\n T_wc = torch.eye(4, device=R_wc.device).repeat(n_view, 1, 1)\n T_wc[:, :3, :3] = R_wc\n T_wc[:, :3, 3] = t_wc\n\n return T_wc, fovy_deg # B,4,4, B" }, { "identifier": "fov2K", "path": "lib_guidance/camera_sampling.py", "snippet": "def fov2K(fov=90, H=256, W=256):\n if isinstance(fov, torch.Tensor):\n f = H / (2 * torch.tan(fov / 2 * np.pi / 180))\n K = torch.eye(3).repeat(fov.shape[0], 1, 1).to(fov)\n K[:, 0, 0], K[:, 0, 2] = f, W / 2.0\n K[:, 1, 1], K[:, 1, 2] = f, H / 2.0\n return K.clone()\n else:\n f = H / (2 * np.tan(fov / 2 * np.pi / 180))\n K = np.eye(3)\n K[0, 0], K[0, 2] = f, W / 2.0\n K[1, 1], K[1, 2] = f, H / 2.0\n return K.copy()" }, { "identifier": "opencv2blender", "path": "lib_guidance/camera_sampling.py", "snippet": "def opencv2blender(T):\n ret = T.clone()\n # y,z are negative\n ret[:, :, 1] *= -1\n ret[:, :, 2] *= -1\n return ret" }, { "identifier": "viz_spinning", "path": "viz_utils.py", "snippet": "@torch.no_grad()\ndef viz_spinning(\n model,\n pose,\n trans,\n H,\n W,\n K,\n save_path,\n time_index=None,\n n_spinning=10,\n model_mask=None,\n active_sph_order=0,\n bg_color=[1.0, 1.0, 1.0],\n):\n device = pose.device\n mu, fr, s, o, sph, additional_ret = model(\n pose, trans, {\"t\": time_index}, active_sph_order=active_sph_order\n )\n if model_mask is not None:\n assert len(model_mask) == mu.shape[1]\n mu = mu[:, model_mask.bool()]\n fr = fr[:, model_mask.bool()]\n s = s[:, model_mask.bool()]\n o = o[:, model_mask.bool()]\n sph = sph[:, model_mask.bool()]\n\n viz_frames = []\n for vid in range(n_spinning):\n spin_R = (\n torch.from_numpy(euler2mat(0, 2 * np.pi * vid / n_spinning, 0, \"sxyz\"))\n .to(device)\n .float()\n )\n spin_t = mu.mean(1)[0]\n spin_t = (torch.eye(3).to(device) - spin_R) @ spin_t[:, None]\n spin_T = torch.eye(4).to(device)\n spin_T[:3, :3] = spin_R\n spin_T[:3, 3] = spin_t.squeeze(-1)\n viz_mu, viz_fr = transform_mu_frame(mu, fr, spin_T[None])\n\n render_pkg = render_cam_pcl(\n viz_mu[0],\n viz_fr[0],\n s[0],\n o[0],\n sph[0],\n H,\n W,\n K,\n False,\n active_sph_order,\n bg_color=bg_color,\n )\n viz_frame = (\n torch.clamp(render_pkg[\"rgb\"], 0.0, 1.0)\n .permute(1, 2, 0)\n .detach()\n .cpu()\n .numpy()\n )\n viz_frame = (viz_frame * 255).astype(np.uint8)\n viz_frames.append(viz_frame)\n imageio.mimsave(save_path, viz_frames)\n return" }, { "identifier": "viz_human_all", "path": "viz_utils.py", "snippet": "@torch.no_grad()\ndef viz_human_all(\n solver,\n data_provider: RealDataOptimizablePoseProviderPose = None,\n ckpt_dir=None,\n training_skip=1,\n n_spinning=40,\n novel_pose_dir=\"novel_poses\",\n novel_skip=2,\n model=None,\n model_mask=None,\n viz_name=\"\",\n export_mesh_flag=False, # remove this from release version\n):\n if model is None:\n model = solver.load_saved_model(ckpt_dir)\n model.eval()\n\n viz_dir = osp.join(solver.log_dir, f\"{viz_name}_human_viz\")\n os.makedirs(viz_dir, exist_ok=True)\n\n active_sph_order = int(model.max_sph_order)\n\n if data_provider is not None:\n # if ckpt_dir is None:\n # ckpt_dir = solver.log_dir\n # pose_path = osp.join(ckpt_dir, \"pose.pth\")\n pose_base_list = data_provider.pose_base_list\n pose_rest_list = data_provider.pose_rest_list\n global_trans_list = data_provider.global_trans_list\n pose_list = torch.cat([pose_base_list, pose_rest_list], 1)\n pose_list, global_trans_list = pose_list.to(\n solver.device\n ), global_trans_list.to(solver.device)\n rgb_list = data_provider.rgb_list\n mask_list = data_provider.mask_list\n K_list = data_provider.K_list\n H, W = rgb_list.shape[1:3]\n else:\n H, W = 512, 512\n K_list = [torch.from_numpy(fov2K(45, H, W)).float().to(solver.device)]\n global_trans_list = torch.zeros(1, 3).to(solver.device)\n global_trans_list[0, -1] = 3.0\n\n # viz training\n if data_provider is not None:\n print(\"Viz training...\")\n viz_frames = []\n for t in range(len(pose_list)):\n if t % training_skip != 0:\n continue\n pose = pose_list[t][None]\n K = K_list[t]\n trans = global_trans_list[t][None]\n time_index = torch.Tensor([t]).long().to(solver.device)\n mu, fr, s, o, sph, _ = model(\n pose,\n trans,\n {\"t\": time_index}, # use time_index from training set\n active_sph_order=active_sph_order,\n )\n if model_mask is not None:\n assert len(model_mask) == mu.shape[1]\n mu = mu[:, model_mask.bool()]\n fr = fr[:, model_mask.bool()]\n s = s[:, model_mask.bool()]\n o = o[:, model_mask.bool()]\n sph = sph[:, model_mask.bool()]\n render_pkg = render_cam_pcl(\n mu[0],\n fr[0],\n s[0],\n o[0],\n sph[0],\n H,\n W,\n K,\n False,\n active_sph_order,\n bg_color=getattr(solver, \"DEFAULT_BG\", [1.0, 1.0, 1.0]),\n )\n viz_frame = viz_render(rgb_list[t], mask_list[t], render_pkg)\n viz_frames.append(viz_frame)\n imageio.mimsave(f\"{viz_dir}/training.gif\", viz_frames)\n\n # viz static spinning\n print(\"Viz spinning...\")\n can_pose = model.template.canonical_pose.detach()\n viz_base_R_opencv = np.asarray(euler2mat(np.pi, 0, 0, \"sxyz\"))\n viz_base_R_opencv = torch.from_numpy(viz_base_R_opencv).float()\n can_pose[0] = viz_base_R_opencv.to(can_pose.device)\n can_pose = matrix_to_axis_angle(can_pose)[None]\n dapose = torch.from_numpy(np.zeros((1, 24, 3))).float().to(solver.device)\n dapose[:, 1, -1] = np.pi / 4\n dapose[:, 2, -1] = -np.pi / 4\n dapose[:, 0] = matrix_to_axis_angle(solver.viz_base_R[None])[0]\n tpose = torch.from_numpy(np.zeros((1, 24, 3))).float().to(solver.device)\n tpose[:, 0] = matrix_to_axis_angle(solver.viz_base_R[None])[0]\n to_viz = {\"cano-pose\": can_pose, \"t-pose\": tpose, \"da-pose\": dapose}\n if data_provider is not None:\n to_viz[\"first-frame\"] = pose_list[0][None]\n\n for name, pose in to_viz.items():\n print(f\"Viz novel {name}...\")\n # if export_mesh_flag:\n # from lib_marchingcubes.gaumesh_utils import MeshExtractor\n # # also extract a mesh\n # mesh = solver.extract_mesh(model, pose)\n # mesh.export(f\"{viz_dir}/mc_{name}.obj\", \"obj\")\n\n # # for making figures, the rotation is in another way\n # viz_spinning_self_rotate(\n # model,\n # solver.viz_base_R.detach(),\n # pose,\n # global_trans_list[0][None],\n # H,\n # W,\n # K_list[0],\n # f\"{viz_dir}/{name}_selfrotate.gif\",\n # time_index=None, # if set to None and use t, the add_bone will hand this\n # n_spinning=n_spinning,\n # active_sph_order=model.max_sph_order,\n # )\n viz_spinning(\n model,\n pose,\n global_trans_list[0][None],\n H,\n W,\n K_list[0],\n f\"{viz_dir}/{name}.gif\",\n time_index=None, # if set to None and use t, the add_bone will hand this\n n_spinning=n_spinning,\n active_sph_order=model.max_sph_order,\n bg_color=getattr(solver, \"DEFAULT_BG\", [1.0, 1.0, 1.0]),\n )\n\n # viz novel pose dynamic spinning\n print(\"Viz novel seq...\")\n novel_pose_names = [\n f[:-4] for f in os.listdir(novel_pose_dir) if f.endswith(\".npy\")\n ]\n seq_viz_todo = {}\n for name in novel_pose_names:\n novel_pose_fn = osp.join(novel_pose_dir, f\"{name}.npy\")\n novel_poses = np.load(novel_pose_fn, allow_pickle=True)\n novel_poses = novel_poses[::novel_skip]\n N_frames = len(novel_poses)\n novel_poses = torch.from_numpy(novel_poses).float().to(solver.device)\n novel_poses = novel_poses.reshape(N_frames, 24, 3)\n\n seq_viz_todo[name] = (novel_poses, N_frames)\n if data_provider is not None:\n seq_viz_todo[\"training\"] = [pose_list, len(pose_list)]\n\n for name, (novel_poses, N_frames) in seq_viz_todo.items():\n base_R = solver.viz_base_R.detach().cpu().numpy()\n viz_frames = []\n K = K_list[0]\n for vid in range(N_frames):\n pose = novel_poses[vid][None]\n # pose = novel_poses[0][None] # debug\n rotation = euler2mat(2 * np.pi * vid / N_frames, 0.0, 0.0, \"syxz\")\n rotation = torch.from_numpy(rotation @ base_R).float().to(solver.device)\n pose[:, 0] = matrix_to_axis_angle(rotation[None])[0]\n trans = global_trans_list[0][None]\n mu, fr, s, o, sph, _ = model(\n pose,\n trans,\n # not pass in {}, so t is auto none\n additional_dict={},\n active_sph_order=active_sph_order,\n )\n if model_mask is not None:\n assert len(model_mask) == mu.shape[1]\n mu = mu[:, model_mask.bool()]\n fr = fr[:, model_mask.bool()]\n s = s[:, model_mask.bool()]\n o = o[:, model_mask.bool()]\n sph = sph[:, model_mask.bool()]\n render_pkg = render_cam_pcl(\n mu[0],\n fr[0],\n s[0],\n o[0],\n sph[0],\n H,\n W,\n K,\n False,\n active_sph_order,\n bg_color=getattr(solver, \"DEFAULT_BG\", [1.0, 1.0, 1.0]),\n # bg_color=[1.0, 1.0, 1.0], # ! use white bg for viz\n )\n viz_frame = (\n torch.clamp(render_pkg[\"rgb\"], 0.0, 1.0)\n .permute(1, 2, 0)\n .detach()\n .cpu()\n .numpy()\n )\n viz_frame = (viz_frame * 255).astype(np.uint8)\n viz_frames.append(viz_frame)\n imageio.mimsave(f\"{viz_dir}/novel_pose_{name}.gif\", viz_frames)\n return" }, { "identifier": "viz_dog_all", "path": "viz_utils.py", "snippet": "@torch.no_grad()\ndef viz_dog_all(solver, data_provider, model=None, ckpt_dir=None, viz_name=\"\"):\n if model is None:\n model = solver.load_saved_model(ckpt_dir)\n model.eval()\n viz_dir = osp.join(solver.log_dir, f\"{viz_name}_dog_viz\")\n os.makedirs(viz_dir, exist_ok=True)\n\n viz_pose = (\n torch.cat([data_provider.pose_base_list, data_provider.pose_rest_list], 1)\n .detach()\n .clone()\n )\n viz_pose = torch.mean(viz_pose, dim=0, keepdim=True) # use mean pose for viz \n limb = viz_pose[:, -7:] \n pose = viz_pose[:, :-7].reshape(-1, 35, 3)\n pose[:, :-3] = 0 # exclude ears and mouth poses\n\n viz_pose = torch.concat([pose.reshape(1, -1), limb], dim=1)\n viz_trans = torch.tensor([[0.0, -0.3, 25.0]], device=\"cuda:0\")\n\n viz_dog_spin(\n model.to(\"cuda\"),\n viz_pose,\n viz_trans,\n data_provider.H,\n data_provider.W,\n data_provider.K_list[0],\n save_path=osp.join(viz_dir, \"spin.gif\"),\n n_spinning=42,\n )\n\n viz_dog_spin2(\n model.to(\"cuda\"),\n viz_pose,\n viz_trans,\n data_provider.H,\n data_provider.W,\n data_provider.K_list[0],\n save_path=osp.join(viz_dir, \"spin2.gif\"),\n n_spinning=20,\n )\n\n ######################################################################\n # Dataset pose seq\n viz_pose = (\n torch.cat([data_provider.pose_base_list, data_provider.pose_rest_list], 1)\n .detach()\n .clone()\n )\n viz_pose = torch.mean(viz_pose, dim=0, keepdim=True)\n pose = viz_pose[:, :-7].reshape(-1, 35, 3)\n limb = viz_pose[:, -7:]\n\n # Animation\n aroot = osp.join(osp.dirname(__file__), \"novel_poses/husky\")\n window = list(range(350, 440)) # Run\n trans = torch.tensor([[0.3, -0.3, 25.0]], device=\"cuda:0\")\n files = [f\"{aroot}/{i:04d}.npz\" for i in window]\n pose_list = [dict(np.load(file))[\"pred_pose\"] for file in files]\n pose_list = np.concatenate(pose_list)\n animation = matrix_to_axis_angle(torch.from_numpy(pose_list)).to(solver.device)\n animation[:, [32, 33, 34]] = pose[:, [32, 33, 34]] \n\n viz_dog_animation(\n model.to(\"cuda\"),\n animation,\n limb,\n trans,\n data_provider.H,\n data_provider.W,\n data_provider.K_list[0],\n save_path=osp.join(viz_dir, \"animation.gif\"),\n fps=12,\n )\n return" }, { "identifier": "ssim", "path": "utils/ssim.py", "snippet": "def ssim(img1, img2, window_size=11, size_average=True):\n channel = img1.size(-3)\n window = create_window(window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n return _ssim(img1, img2, window, window_size, channel, size_average)" }, { "identifier": "test", "path": "test_utils/test_func.py", "snippet": "def test(\n solver,\n seq_name: str,\n tto_flag=True,\n tto_step=300,\n tto_decay=60,\n tto_decay_factor=0.5,\n pose_base_lr=3e-3,\n pose_rest_lr=3e-3,\n trans_lr=3e-3,\n dataset_mode=\"people_snapshot\",\n training_optimized_seq=None,\n):\n device = solver.device\n model = solver.load_saved_model()\n\n assert dataset_mode in [\n \"people_snapshot\",\n \"zju\",\n \"instant_avatar_wild\",\n \"dog_demo\",\n ], f\"Unknown dataset mode {dataset_mode}\"\n\n if dataset_mode == \"people_snapshot\":\n eval_mode = \"avatar\"\n bg = [1.0, 1.0, 1.0]\n test_dataset = InstantAvatarDataset(\n noisy_flag=False,\n data_root=\"./data/people_snapshot/\",\n video_name=seq_name,\n split=\"test\",\n image_zoom_ratio=0.5,\n )\n elif dataset_mode == \"zju\":\n eval_mode = \"nvr\"\n test_dataset = ZJUDataset(\n data_root=\"./data/zju_mocap\",\n video_name=seq_name,\n split=\"test\",\n image_zoom_ratio=0.5,\n )\n bg = [0.0, 0.0, 0.0] # zju use black background\n elif dataset_mode == \"instant_avatar_wild\":\n eval_mode = \"avatar\"\n test_dataset = InstantAvatarWildDataset(\n data_root=\"./data/insav_wild\",\n video_name=seq_name,\n split=\"test\",\n image_zoom_ratio=1.0,\n # ! warning, here follow the `ubc_hard.yaml` in InstAVT setting, use slicing\n start_end_skip=[2, 1000000000, 4],\n )\n bg = [1.0, 1.0, 1.0]\n\n test_len = len(test_dataset)\n assert (training_optimized_seq.total_t == test_len) or (\n training_optimized_seq.total_t == 1 + test_len\n ), \"Now UBC can only support the same length of training and testing or + 1\"\n test_dataset.smpl_params[\"body_pose\"] = (\n training_optimized_seq.pose_rest_list.reshape(-1, 69)[:test_len]\n .detach()\n .cpu()\n .numpy()\n )\n test_dataset.smpl_params[\"global_orient\"] = (\n training_optimized_seq.pose_base_list.reshape(-1, 3)[:test_len]\n .detach()\n .cpu()\n .numpy()\n )\n test_dataset.smpl_params[\"transl\"] = (\n training_optimized_seq.global_trans_list.reshape(-1, 3)[:test_len]\n .detach()\n .cpu()\n .numpy()\n )\n elif dataset_mode == \"dog_demo\":\n eval_mode = \"avatar_brightness\"\n bg = [1.0, 1.0, 1.0]\n test_dataset = DogDemoDataset(\n data_root=\"./data/dog_data_official/\", video_name=seq_name, test=True\n )\n else:\n raise NotImplementedError()\n\n evaluator = get_evaluator(eval_mode, device)\n\n _save_eval_maps(\n solver.log_dir,\n \"test\",\n model,\n solver,\n test_dataset,\n dataset_mode=dataset_mode,\n device=device,\n bg=bg,\n tto_flag=tto_flag,\n tto_step=tto_step,\n tto_decay=tto_decay,\n tto_decay_factor=tto_decay_factor,\n tto_evaluator=evaluator,\n pose_base_lr=pose_base_lr,\n pose_rest_lr=pose_rest_lr,\n trans_lr=trans_lr,\n )\n\n if tto_flag:\n _evaluate_dir(evaluator, solver.log_dir, \"test_tto\")\n else:\n _evaluate_dir(evaluator, solver.log_dir, \"test\")\n\n return" } ]
from matplotlib import pyplot as plt from pytorch3d.transforms import matrix_to_axis_angle from tqdm import tqdm from transforms3d.euler import euler2mat from omegaconf import OmegaConf from lib_data.get_data import prepare_real_seq from lib_data.data_provider import DatabasePoseProvider from lib_gart.templates import get_template from lib_gart.model import GaussianTemplateModel, AdditionalBones from lib_gart.optim_utils import * from lib_render.gauspl_renderer import render_cam_pcl from lib_gart.model_utils import transform_mu_frame from utils.misc import * from utils.viz import viz_render from pytorch3d.transforms import axis_angle_to_matrix, matrix_to_axis_angle from pytorch3d.ops import knn_points from lib_guidance.camera_sampling import sample_camera, fov2K, opencv2blender from viz_utils import viz_spinning, viz_human_all, viz_dog_all from utils.ssim import ssim from datetime import datetime from test_utils import test from lib_guidance.mvdream.mvdream_guidance import MVDream from utils.lpips import LPIPS import imageio import torch import numpy as np import os, os.path as osp, shutil, sys import time import logging import argparse
20,524
# from lib_marchingcubes.gaumesh_utils import MeshExtractor try: # from lib_guidance.sd_utils import StableDiffusion except: logging.warning("No guidance module") class TGFitter: def __init__( self, log_dir, profile_fn, mode, template_model_path="data/smpl_model/SMPL_NEUTRAL.pkl", device=torch.device("cuda:0"), **kwargs, ) -> None: self.log_dir = log_dir os.makedirs(self.log_dir, exist_ok=True) self.profile_fn = profile_fn try: shutil.copy(profile_fn, osp.join(self.log_dir, osp.basename(profile_fn))) except: pass self.mode = mode assert self.mode in ["human", "dog"], "Only support human and dog for now" self.template_model_path = template_model_path self.device = device # * auto set attr cfg = OmegaConf.load(profile_fn) # assign the cfg to self attribute for k, v in cfg.items(): setattr(self, k, v) for k, v in kwargs.items(): setattr(self, k, v) # * explicitly set flags self.FAST_TRAINING = getattr(self, "FAST_TRAINING", False) self.LAMBDA_SSIM = getattr(self, "LAMBDA_SSIM", 0.0) self.LAMBDA_LPIPS = getattr(self, "LAMBDA_LPIPS", 0.0) if self.LAMBDA_LPIPS > 0: self.lpips = LPIPS(net="vgg").to(self.device) for param in self.lpips.parameters(): param.requires_grad = False if isinstance(self.RESET_OPACITY_STEPS, int): self.RESET_OPACITY_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.RESET_OPACITY_STEPS == 0 ] if isinstance(self.REGAUSSIAN_STEPS, int): self.REGAUSSIAN_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.REGAUSSIAN_STEPS == 0 ] # prepare base R if self.mode == "human": viz_base_R_opencv = np.asarray(euler2mat(np.pi, 0, 0, "sxyz")) else: viz_base_R_opencv = np.asarray(euler2mat(np.pi / 2.0, 0, np.pi, "rxyz")) viz_base_R_opencv = torch.from_numpy(viz_base_R_opencv).float() self.viz_base_R = viz_base_R_opencv.to(self.device) if self.mode == "human": self.reg_base_R_global = ( matrix_to_axis_angle( torch.as_tensor(euler2mat(np.pi / 2.0, 0, np.pi / 2.0, "sxyz"))[ None ] )[0] .float() .to(self.device) ) else: # TODO, for generation of dog pass self.writer = create_log( self.log_dir, name=osp.basename(self.profile_fn).split(".")[0], debug=False ) return def prepare_fake_data(self, mode, *args, **kwargs): if mode == "amass": # todo: change to amass provider = DatabasePoseProvider(*args, **kwargs, device=torch.device("cpu")) return provider return provider
# from lib_marchingcubes.gaumesh_utils import MeshExtractor try: # from lib_guidance.sd_utils import StableDiffusion except: logging.warning("No guidance module") class TGFitter: def __init__( self, log_dir, profile_fn, mode, template_model_path="data/smpl_model/SMPL_NEUTRAL.pkl", device=torch.device("cuda:0"), **kwargs, ) -> None: self.log_dir = log_dir os.makedirs(self.log_dir, exist_ok=True) self.profile_fn = profile_fn try: shutil.copy(profile_fn, osp.join(self.log_dir, osp.basename(profile_fn))) except: pass self.mode = mode assert self.mode in ["human", "dog"], "Only support human and dog for now" self.template_model_path = template_model_path self.device = device # * auto set attr cfg = OmegaConf.load(profile_fn) # assign the cfg to self attribute for k, v in cfg.items(): setattr(self, k, v) for k, v in kwargs.items(): setattr(self, k, v) # * explicitly set flags self.FAST_TRAINING = getattr(self, "FAST_TRAINING", False) self.LAMBDA_SSIM = getattr(self, "LAMBDA_SSIM", 0.0) self.LAMBDA_LPIPS = getattr(self, "LAMBDA_LPIPS", 0.0) if self.LAMBDA_LPIPS > 0: self.lpips = LPIPS(net="vgg").to(self.device) for param in self.lpips.parameters(): param.requires_grad = False if isinstance(self.RESET_OPACITY_STEPS, int): self.RESET_OPACITY_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.RESET_OPACITY_STEPS == 0 ] if isinstance(self.REGAUSSIAN_STEPS, int): self.REGAUSSIAN_STEPS = [ i for i in range(1, self.TOTAL_steps) if i % self.REGAUSSIAN_STEPS == 0 ] # prepare base R if self.mode == "human": viz_base_R_opencv = np.asarray(euler2mat(np.pi, 0, 0, "sxyz")) else: viz_base_R_opencv = np.asarray(euler2mat(np.pi / 2.0, 0, np.pi, "rxyz")) viz_base_R_opencv = torch.from_numpy(viz_base_R_opencv).float() self.viz_base_R = viz_base_R_opencv.to(self.device) if self.mode == "human": self.reg_base_R_global = ( matrix_to_axis_angle( torch.as_tensor(euler2mat(np.pi / 2.0, 0, np.pi / 2.0, "sxyz"))[ None ] )[0] .float() .to(self.device) ) else: # TODO, for generation of dog pass self.writer = create_log( self.log_dir, name=osp.basename(self.profile_fn).split(".")[0], debug=False ) return def prepare_fake_data(self, mode, *args, **kwargs): if mode == "amass": # todo: change to amass provider = DatabasePoseProvider(*args, **kwargs, device=torch.device("cpu")) return provider return provider
def prepare_real_seq(
0
2023-11-27 17:30:04+00:00
24k
skhu101/GauHuman
scene/dataset_readers.py
[ { "identifier": "read_extrinsics_text", "path": "scene/colmap_loader.py", "snippet": "def read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n image_id = int(elems[0])\n qvec = np.array(tuple(map(float, elems[1:5])))\n tvec = np.array(tuple(map(float, elems[5:8])))\n camera_id = int(elems[8])\n image_name = elems[9]\n elems = fid.readline().split()\n xys = np.column_stack([tuple(map(float, elems[0::3])),\n tuple(map(float, elems[1::3]))])\n point3D_ids = np.array(tuple(map(int, elems[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images" }, { "identifier": "read_intrinsics_text", "path": "scene/colmap_loader.py", "snippet": "def read_intrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n cameras = {}\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n camera_id = int(elems[0])\n model = elems[1]\n assert model == \"PINHOLE\", \"While the loader support other types, the rest of the code assumes PINHOLE\"\n width = int(elems[2])\n height = int(elems[3])\n params = np.array(tuple(map(float, elems[4:])))\n cameras[camera_id] = Camera(id=camera_id, model=model,\n width=width, height=height,\n params=params)\n return cameras" }, { "identifier": "qvec2rotmat", "path": "scene/colmap_loader.py", "snippet": "def qvec2rotmat(qvec):\n return np.array([\n [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,\n 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],\n 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],\n [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])" }, { "identifier": "read_extrinsics_binary", "path": "scene/colmap_loader.py", "snippet": "def read_extrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadImagesBinary(const std::string& path)\n void Reconstruction::WriteImagesBinary(const std::string& path)\n \"\"\"\n images = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_reg_images = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_reg_images):\n binary_image_properties = read_next_bytes(\n fid, num_bytes=64, format_char_sequence=\"idddddddi\")\n image_id = binary_image_properties[0]\n qvec = np.array(binary_image_properties[1:5])\n tvec = np.array(binary_image_properties[5:8])\n camera_id = binary_image_properties[8]\n image_name = \"\"\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n while current_char != b\"\\x00\": # look for the ASCII 0 entry\n image_name += current_char.decode(\"utf-8\")\n current_char = read_next_bytes(fid, 1, \"c\")[0]\n num_points2D = read_next_bytes(fid, num_bytes=8,\n format_char_sequence=\"Q\")[0]\n x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,\n format_char_sequence=\"ddq\"*num_points2D)\n xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),\n tuple(map(float, x_y_id_s[1::3]))])\n point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))\n images[image_id] = Image(\n id=image_id, qvec=qvec, tvec=tvec,\n camera_id=camera_id, name=image_name,\n xys=xys, point3D_ids=point3D_ids)\n return images" }, { "identifier": "read_intrinsics_binary", "path": "scene/colmap_loader.py", "snippet": "def read_intrinsics_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::WriteCamerasBinary(const std::string& path)\n void Reconstruction::ReadCamerasBinary(const std::string& path)\n \"\"\"\n cameras = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_cameras = read_next_bytes(fid, 8, \"Q\")[0]\n for _ in range(num_cameras):\n camera_properties = read_next_bytes(\n fid, num_bytes=24, format_char_sequence=\"iiQQ\")\n camera_id = camera_properties[0]\n model_id = camera_properties[1]\n model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n width = camera_properties[2]\n height = camera_properties[3]\n num_params = CAMERA_MODEL_IDS[model_id].num_params\n params = read_next_bytes(fid, num_bytes=8*num_params,\n format_char_sequence=\"d\"*num_params)\n cameras[camera_id] = Camera(id=camera_id,\n model=model_name,\n width=width,\n height=height,\n params=np.array(params))\n assert len(cameras) == num_cameras\n return cameras" }, { "identifier": "read_points3D_binary", "path": "scene/colmap_loader.py", "snippet": "def read_points3D_binary(path_to_model_file):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DBinary(const std::string& path)\n void Reconstruction::WritePoints3DBinary(const std::string& path)\n \"\"\"\n\n\n with open(path_to_model_file, \"rb\") as fid:\n num_points = read_next_bytes(fid, 8, \"Q\")[0]\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n\n for p_id in range(num_points):\n binary_point_line_properties = read_next_bytes(\n fid, num_bytes=43, format_char_sequence=\"QdddBBBd\")\n xyz = np.array(binary_point_line_properties[1:4])\n rgb = np.array(binary_point_line_properties[4:7])\n error = np.array(binary_point_line_properties[7])\n track_length = read_next_bytes(\n fid, num_bytes=8, format_char_sequence=\"Q\")[0]\n track_elems = read_next_bytes(\n fid, num_bytes=8*track_length,\n format_char_sequence=\"ii\"*track_length)\n xyzs[p_id] = xyz\n rgbs[p_id] = rgb\n errors[p_id] = error\n return xyzs, rgbs, errors" }, { "identifier": "read_points3D_text", "path": "scene/colmap_loader.py", "snippet": "def read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None\n errors = None\n num_points = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n num_points += 1\n\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n count = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) > 0 and line[0] != \"#\":\n elems = line.split()\n xyz = np.array(tuple(map(float, elems[1:4])))\n rgb = np.array(tuple(map(int, elems[4:7])))\n error = np.array(float(elems[7]))\n xyzs[count] = xyz\n rgbs[count] = rgb\n errors[count] = error\n count += 1\n\n return xyzs, rgbs, errors" }, { "identifier": "getWorld2View2", "path": "utils/graphics_utils.py", "snippet": "def getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n Rt = np.zeros((4, 4))\n Rt[:3, :3] = R.transpose()\n Rt[:3, 3] = t\n Rt[3, 3] = 1.0\n\n C2W = np.linalg.inv(Rt)\n cam_center = C2W[:3, 3]\n cam_center = (cam_center + translate) * scale\n C2W[:3, 3] = cam_center\n Rt = np.linalg.inv(C2W)\n return np.float32(Rt)" }, { "identifier": "focal2fov", "path": "utils/graphics_utils.py", "snippet": "def focal2fov(focal, pixels):\n return 2*math.atan(pixels/(2*focal))" }, { "identifier": "fov2focal", "path": "utils/graphics_utils.py", "snippet": "def fov2focal(fov, pixels):\n return pixels / (2 * math.tan(fov / 2))" }, { "identifier": "SH2RGB", "path": "utils/sh_utils.py", "snippet": "def SH2RGB(sh):\n return sh * C0 + 0.5" }, { "identifier": "BasicPointCloud", "path": "scene/gaussian_model.py", "snippet": "class GaussianModel:\n def setup_functions(self):\n def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation, transform):\n def __init__(self, sh_degree : int, smpl_type : str, motion_offset_flag : bool, actor_gender: str):\n def capture(self):\n def restore(self, model_args, training_args):\n def get_scaling(self):\n def get_rotation(self):\n def get_xyz(self):\n def get_features(self):\n def get_opacity(self):\n def get_covariance(self, scaling_modifier = 1, transform=None):\n def oneupSHdegree(self):\n def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):\n def training_setup(self, training_args):\n def update_learning_rate(self, iteration):\n def construct_list_of_attributes(self):\n def save_ply(self, path):\n def reset_opacity(self):\n def load_ply(self, path):\n def replace_tensor_to_optimizer(self, tensor, name):\n def _prune_optimizer(self, mask):\n def prune_points(self, mask):\n def cat_tensors_to_optimizer(self, tensors_dict):\n def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):\n def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):\n def densify_and_clone(self, grads, grad_threshold, scene_extent):\n def kl_densify_and_clone(self, grads, grad_threshold, scene_extent, kl_threshold=0.4):\n def kl_densify_and_split(self, grads, grad_threshold, scene_extent, kl_threshold=0.4, N=2):\n def kl_merge(self, grads, grad_threshold, scene_extent, kl_threshold=0.1):\n def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size, kl_threshold=0.4, t_vertices=None, iter=None):\n def kl_div(self, mu_0, rotation_0_q, scaling_0_diag, mu_1, rotation_1_q, scaling_1_diag):\n def add_densification_stats(self, viewspace_point_tensor, update_filter):\n def coarse_deform_c2source(self, query_pts, params, t_params, t_vertices, lbs_weights=None, correct_Rs=None, return_transl=False):\ndef read_pickle(pkl_path):\ndef SMPL_to_tensor(params, device):\ndef batch_rodrigues_torch(poses):\ndef get_rigid_transformation_torch(rot_mats, joints, parents):\ndef get_transform_params_torch(smpl, params, rot_mats=None, correct_Rs=None):\ndef batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):\n L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n L_0 = rotation_0 @ scaling_0\n A = torch.matmul(bweights, A.reshape(bs, joints_num, -1))\n A = torch.reshape(A, (bs, -1, 4, 4))\n A = torch.matmul(bweights, self.s_A.reshape(bs, joints_num, -1))\n A = torch.reshape(A, (bs, -1, 4, 4))\n K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1)\n K = K.reshape([batch_size, 3, 3])\n A = get_rigid_transformation_torch(rot_mats, joints, parents)\n R = params['R'] \n K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)\n K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n .view((batch_size, 3, 3))" }, { "identifier": "SMPL", "path": "smpl/smpl_numpy.py", "snippet": "class SMPL():\n def __init__(self, sex, model_dir):\n super(SMPL, self).__init__()\n\n model_paths = {\n 'male': os.path.join(model_dir, MALE_PATH),\n 'female': os.path.join(model_dir, FEMALE_PATH),\n # 'neutral': os.path.join(model_dir, NEUTRAL_PATH)\n 'neutral': os.path.join('assets/SMPL_NEUTRAL.pkl')\n }\n\n with open(model_paths[sex], 'rb') as f:\n smpl_model = pickle.load(f, encoding='latin1')\n self.J_regressor = np.array(smpl_model['J_regressor'].todense()) # (24, 6890)\n self.weights = smpl_model['weights'] # (6890, 24)\n self.posedirs = smpl_model['posedirs'] # (6890, 3, 207)\n self.v_template = smpl_model['v_template'] # (6890, 3)\n self.shapedirs = np.array(smpl_model['shapedirs']) # (6890, 3, 10)\n self.faces = smpl_model['f'].astype('int32') # (13776, 3)\n self.kintree_table = smpl_model['kintree_table'].astype('int64') # (2, 24)\n\n id_to_col = {self.kintree_table[1, i].item(): i for i in range(self.kintree_table.shape[1])}\n self.parent = np.array([id_to_col[self.kintree_table[0, it]] for it in range(1, self.kintree_table.shape[1])])\n\n self.pose_shape = [24, 3]\n self.beta_shape = [10]\n self.pose = np.zeros(self.pose_shape)\n self.beta = np.zeros(self.beta_shape)\n\n self.verts = None\n self.J = None\n self.R = None\n\n def __call__(self, pose, beta):\n\n v_template = self.v_template # (6890, 3)\n shapedirs = self.shapedirs.reshape(-1,10) # (6890*3, 10)\n beta = beta[:, None] # (10, 1)\n\n v_shaped = shapedirs.dot(beta).reshape(6890, 3) + v_template # (6890, 3)\n J = self.J_regressor.dot(v_shaped) # (24, 3)\n\n # input is a rotation matrix: (24,3,3)\n if pose.shape == (24, 3, 3):\n R = pose\n # input is a rotation axis-angle vector: (1, 72), (72, 1) or (72, )\n elif pose.shape == (1, 72) or pose.shape == (72, 1) or pose.shape == (72,):\n pose_vectors = pose.reshape(-1, 3) # (24, 3)\n R = np.array([rodrigues(pose_vectors[p_idx])[0] \n for p_idx in range(pose_vectors.shape[0])\n ], \n dtype='float32') # (24, 3, 3)\n else:\n raise ValueError(\"Unsupported Pose Inputs - the Pose Shape is {}\".format(pose.shape))\n\n Is = np.eye(3, dtype='float32')[None, :] # (1, 3, 3)\n lrotmin = (R[1:,:] - Is).reshape(-1, 1) # (23x3x3, 1)\n posedirs = self.posedirs.reshape(-1,207) # (6890x3, 207)\n v_posed = v_shaped + posedirs.dot(lrotmin).reshape(6890, 3) # (6890, 3)\n\n J_ = J.copy()\n J_[1:, :] = J[1:, :] - J[self.parent, :] # (24, 3)\n G_ = np.concatenate([R, J_[:, :, None]], axis=-1) # (24, 3, 4)\n pad_rows = np.array([[0, 0, 0, 1]], dtype='float32')\n pad_rows = np.repeat(pad_rows, 24, axis=0).reshape(-1, 1, 4)\n G_ = np.concatenate([G_, pad_rows], axis=1) # (24, 4, 4)\n\n G = [G_[0].copy()]\n for i in range(1, 24):\n G.append(G[self.parent[i-1]].dot(G_[i, :, :]))\n G = np.stack(G, axis=0) # (24, 4, 4)\n\n joints = G[:, :3, 3]\n rest_joints = np.concatenate([J, np.zeros((24, 1))], axis=-1)[:, :, None] # (24, 4, 1)\n zeros = np.zeros((24, 4, 3), dtype='float32') # (24, 4, 3)\n rest_joints_mtx = np.concatenate([zeros, rest_joints], axis=-1) # (24, 4, 4) \n # print(\"G1: \", G[0], \"rest_joints_mtx1: \", rest_joints_mtx[0])\n posed_joints_mtx = np.matmul(G, rest_joints_mtx)\n # print(\"rest_joints_mtx2: \", posed_joints_mtx[0])\n G = G - posed_joints_mtx\n # print(G[0]) \n rest_shape_h = np.concatenate([v_posed, np.ones(v_posed.shape[0])[:, None]], axis=-1) #(6890, 4)\n T = self.weights.dot(G.reshape(24, -1)).reshape(6890, 4, 4)\n v = np.matmul(T, rest_shape_h[:, :, None])[:, :3, 0]\n \n return v, joints" }, { "identifier": "SMPLX", "path": "smplx/body_models.py", "snippet": "class SMPLX(SMPLH):\n '''\n SMPL-X (SMPL eXpressive) is a unified body model, with shape parameters\n trained jointly for the face, hands and body.\n SMPL-X uses standard vertex based linear blend skinning with learned\n corrective blend shapes, has N=10475 vertices and K=54 joints,\n which includes joints for the neck, jaw, eyeballs and fingers.\n '''\n\n NUM_BODY_JOINTS = SMPLH.NUM_BODY_JOINTS\n NUM_HAND_JOINTS = 15\n NUM_FACE_JOINTS = 3\n NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS + NUM_FACE_JOINTS\n EXPRESSION_SPACE_DIM = 100\n NECK_IDX = 12\n\n def __init__(\n self, model_path: str,\n kid_template_path: str = '',\n num_expression_coeffs: int = 10,\n create_expression: bool = True,\n expression: Optional[Tensor] = None,\n create_jaw_pose: bool = True,\n jaw_pose: Optional[Tensor] = None,\n create_leye_pose: bool = True,\n leye_pose: Optional[Tensor] = None,\n create_reye_pose=True,\n reye_pose: Optional[Tensor] = None,\n use_face_contour: bool = False,\n batch_size: int = 1,\n gender: str = 'neutral',\n age: str = 'adult',\n dtype=torch.float32,\n ext: str = 'npz',\n **kwargs\n ) -> None:\n ''' SMPLX model constructor\n\n Parameters\n ----------\n model_path: str\n The path to the folder or to the file where the model\n parameters are stored\n num_expression_coeffs: int, optional\n Number of expression components to use\n (default = 10).\n create_expression: bool, optional\n Flag for creating a member variable for the expression space\n (default = True).\n expression: torch.tensor, optional, Bx10\n The default value for the expression member variable.\n (default = None)\n create_jaw_pose: bool, optional\n Flag for creating a member variable for the jaw pose.\n (default = False)\n jaw_pose: torch.tensor, optional, Bx3\n The default value for the jaw pose variable.\n (default = None)\n create_leye_pose: bool, optional\n Flag for creating a member variable for the left eye pose.\n (default = False)\n leye_pose: torch.tensor, optional, Bx10\n The default value for the left eye pose variable.\n (default = None)\n create_reye_pose: bool, optional\n Flag for creating a member variable for the right eye pose.\n (default = False)\n reye_pose: torch.tensor, optional, Bx10\n The default value for the right eye pose variable.\n (default = None)\n use_face_contour: bool, optional\n Whether to compute the keypoints that form the facial contour\n batch_size: int, optional\n The batch size used for creating the member variables\n gender: str, optional\n Which gender to load\n dtype: torch.dtype\n The data type for the created variables\n '''\n\n # Load the model\n if osp.isdir(model_path):\n model_fn = 'SMPLX_{}.{ext}'.format(gender.upper(), ext=ext)\n smplx_path = os.path.join(model_path, model_fn)\n else:\n smplx_path = model_path\n assert osp.exists(smplx_path), 'Path {} does not exist!'.format(\n smplx_path)\n\n if ext == 'pkl':\n with open(smplx_path, 'rb') as smplx_file:\n model_data = pickle.load(smplx_file, encoding='latin1')\n elif ext == 'npz':\n model_data = np.load(smplx_path, allow_pickle=True)\n else:\n raise ValueError('Unknown extension: {}'.format(ext))\n\n data_struct = Struct(**model_data)\n\n super(SMPLX, self).__init__(\n model_path=model_path,\n kid_template_path=kid_template_path,\n data_struct=data_struct,\n dtype=dtype,\n batch_size=batch_size,\n vertex_ids=VERTEX_IDS['smplx'],\n gender=gender, age=age, ext=ext,\n **kwargs)\n\n lmk_faces_idx = data_struct.lmk_faces_idx\n self.register_buffer('lmk_faces_idx',\n torch.tensor(lmk_faces_idx, dtype=torch.long))\n lmk_bary_coords = data_struct.lmk_bary_coords\n self.register_buffer('lmk_bary_coords',\n torch.tensor(lmk_bary_coords, dtype=dtype))\n\n self.use_face_contour = use_face_contour\n if self.use_face_contour:\n dynamic_lmk_faces_idx = data_struct.dynamic_lmk_faces_idx\n dynamic_lmk_faces_idx = torch.tensor(\n dynamic_lmk_faces_idx,\n dtype=torch.long)\n self.register_buffer('dynamic_lmk_faces_idx',\n dynamic_lmk_faces_idx)\n\n dynamic_lmk_bary_coords = data_struct.dynamic_lmk_bary_coords\n dynamic_lmk_bary_coords = torch.tensor(\n dynamic_lmk_bary_coords, dtype=dtype)\n self.register_buffer('dynamic_lmk_bary_coords',\n dynamic_lmk_bary_coords)\n\n neck_kin_chain = find_joint_kin_chain(self.NECK_IDX, self.parents)\n self.register_buffer(\n 'neck_kin_chain',\n torch.tensor(neck_kin_chain, dtype=torch.long))\n\n if create_jaw_pose:\n if jaw_pose is None:\n default_jaw_pose = torch.zeros([batch_size, 3], dtype=dtype)\n else:\n default_jaw_pose = torch.tensor(jaw_pose, dtype=dtype)\n jaw_pose_param = nn.Parameter(default_jaw_pose,\n requires_grad=True)\n self.register_parameter('jaw_pose', jaw_pose_param)\n\n if create_leye_pose:\n if leye_pose is None:\n default_leye_pose = torch.zeros([batch_size, 3], dtype=dtype)\n else:\n default_leye_pose = torch.tensor(leye_pose, dtype=dtype)\n leye_pose_param = nn.Parameter(default_leye_pose,\n requires_grad=True)\n self.register_parameter('leye_pose', leye_pose_param)\n\n if create_reye_pose:\n if reye_pose is None:\n default_reye_pose = torch.zeros([batch_size, 3], dtype=dtype)\n else:\n default_reye_pose = torch.tensor(reye_pose, dtype=dtype)\n reye_pose_param = nn.Parameter(default_reye_pose,\n requires_grad=True)\n self.register_parameter('reye_pose', reye_pose_param)\n\n shapedirs = data_struct.shapedirs\n if len(shapedirs.shape) < 3:\n shapedirs = shapedirs[:, :, None]\n if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM +\n self.EXPRESSION_SPACE_DIM):\n print(f'WARNING: You are using a {self.name()} model, with only'\n ' 10 shape and 10 expression coefficients.')\n expr_start_idx = 10\n expr_end_idx = 20\n num_expression_coeffs = min(num_expression_coeffs, 10)\n else:\n expr_start_idx = self.SHAPE_SPACE_DIM\n expr_end_idx = self.SHAPE_SPACE_DIM + num_expression_coeffs\n num_expression_coeffs = min(\n num_expression_coeffs, self.EXPRESSION_SPACE_DIM)\n\n self._num_expression_coeffs = num_expression_coeffs\n\n expr_dirs = shapedirs[:, :, expr_start_idx:expr_end_idx]\n self.register_buffer(\n 'expr_dirs', to_tensor(to_np(expr_dirs), dtype=dtype))\n\n if create_expression:\n if expression is None:\n default_expression = torch.zeros(\n [batch_size, self.num_expression_coeffs], dtype=dtype)\n else:\n default_expression = torch.tensor(expression, dtype=dtype)\n expression_param = nn.Parameter(default_expression,\n requires_grad=True)\n self.register_parameter('expression', expression_param)\n\n def name(self) -> str:\n return 'SMPL-X'\n\n @property\n def num_expression_coeffs(self):\n return self._num_expression_coeffs\n\n def create_mean_pose(self, data_struct, flat_hand_mean=False):\n # Create the array for the mean pose. If flat_hand is false, then use\n # the mean that is given by the data, rather than the flat open hand\n global_orient_mean = torch.zeros([3], dtype=self.dtype)\n body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3],\n dtype=self.dtype)\n jaw_pose_mean = torch.zeros([3], dtype=self.dtype)\n leye_pose_mean = torch.zeros([3], dtype=self.dtype)\n reye_pose_mean = torch.zeros([3], dtype=self.dtype)\n # pose_mean = np.concatenate([global_orient_mean, body_pose_mean, jaw_pose_mean, leye_pose_mean, reye_pose_mean, self.left_hand_mean, self.right_hand_mean], axis=0)\n pose_mean = torch.cat([global_orient_mean, body_pose_mean, jaw_pose_mean, leye_pose_mean, reye_pose_mean, self.left_hand_mean, self.right_hand_mean], 0)\n\n return pose_mean\n\n def extra_repr(self):\n msg = super(SMPLX, self).extra_repr()\n msg = [\n msg,\n f'Number of Expression Coefficients: {self.num_expression_coeffs}'\n ]\n return '\\n'.join(msg)\n\n def forward(\n self,\n betas: Optional[Tensor] = None,\n global_orient: Optional[Tensor] = None,\n body_pose: Optional[Tensor] = None,\n left_hand_pose: Optional[Tensor] = None,\n right_hand_pose: Optional[Tensor] = None,\n transl: Optional[Tensor] = None,\n expression: Optional[Tensor] = None,\n jaw_pose: Optional[Tensor] = None,\n leye_pose: Optional[Tensor] = None,\n reye_pose: Optional[Tensor] = None,\n return_verts: bool = True,\n return_full_pose: bool = False,\n pose2rot: bool = True,\n return_shaped: bool = True,\n **kwargs\n ) -> TensorOutput:\n '''\n Forward pass for the SMPLX model\n\n Parameters\n ----------\n global_orient: torch.tensor, optional, shape Bx3\n If given, ignore the member variable and use it as the global\n rotation of the body. Useful if someone wishes to predicts this\n with an external model. (default=None)\n betas: torch.tensor, optional, shape BxN_b\n If given, ignore the member variable `betas` and use it\n instead. For example, it can used if shape parameters\n `betas` are predicted from some external model.\n (default=None)\n expression: torch.tensor, optional, shape BxN_e\n If given, ignore the member variable `expression` and use it\n instead. For example, it can used if expression parameters\n `expression` are predicted from some external model.\n body_pose: torch.tensor, optional, shape Bx(J*3)\n If given, ignore the member variable `body_pose` and use it\n instead. For example, it can used if someone predicts the\n pose of the body joints are predicted from some external model.\n It should be a tensor that contains joint rotations in\n axis-angle format. (default=None)\n left_hand_pose: torch.tensor, optional, shape BxP\n If given, ignore the member variable `left_hand_pose` and\n use this instead. It should either contain PCA coefficients or\n joint rotations in axis-angle format.\n right_hand_pose: torch.tensor, optional, shape BxP\n If given, ignore the member variable `right_hand_pose` and\n use this instead. It should either contain PCA coefficients or\n joint rotations in axis-angle format.\n jaw_pose: torch.tensor, optional, shape Bx3\n If given, ignore the member variable `jaw_pose` and\n use this instead. It should either joint rotations in\n axis-angle format.\n transl: torch.tensor, optional, shape Bx3\n If given, ignore the member variable `transl` and use it\n instead. For example, it can used if the translation\n `transl` is predicted from some external model.\n (default=None)\n return_verts: bool, optional\n Return the vertices. (default=True)\n return_full_pose: bool, optional\n Returns the full axis-angle pose vector (default=False)\n\n Returns\n -------\n output: ModelOutput\n A named tuple of type `ModelOutput`\n '''\n\n # If no shape and pose parameters are passed along, then use the\n # ones from the module\n global_orient = (global_orient if global_orient is not None else\n self.global_orient)\n body_pose = body_pose if body_pose is not None else self.body_pose\n betas = betas if betas is not None else self.betas\n\n left_hand_pose = (left_hand_pose if left_hand_pose is not None else\n self.left_hand_pose)\n right_hand_pose = (right_hand_pose if right_hand_pose is not None else\n self.right_hand_pose)\n jaw_pose = jaw_pose if jaw_pose is not None else self.jaw_pose\n leye_pose = leye_pose if leye_pose is not None else self.leye_pose\n reye_pose = reye_pose if reye_pose is not None else self.reye_pose\n expression = expression if expression is not None else self.expression\n\n apply_trans = transl is not None or hasattr(self, 'transl')\n if transl is None:\n if hasattr(self, 'transl'):\n transl = self.transl\n\n if self.use_pca:\n left_hand_pose = torch.einsum(\n 'bi,ij->bj', [left_hand_pose, self.left_hand_components])\n right_hand_pose = torch.einsum(\n 'bi,ij->bj', [right_hand_pose, self.right_hand_components])\n\n full_pose = torch.cat([global_orient.reshape(-1, 1, 3),\n body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3),\n jaw_pose.reshape(-1, 1, 3),\n leye_pose.reshape(-1, 1, 3),\n reye_pose.reshape(-1, 1, 3),\n left_hand_pose.reshape(-1, 15, 3),\n right_hand_pose.reshape(-1, 15, 3)],\n dim=1).reshape(-1, 165).to(self.pose_mean.device)\n\n # Add the mean pose of the model. Does not affect the body, only the\n # hands when flat_hand_mean == False\n full_pose += self.pose_mean\n\n batch_size = max(betas.shape[0], global_orient.shape[0],\n body_pose.shape[0])\n # Concatenate the shape and expression coefficients\n scale = int(batch_size / betas.shape[0])\n if scale > 1:\n betas = betas.expand(scale, -1)\n shape_components = torch.cat([betas, expression], dim=-1).to(self.pose_mean.device)\n\n shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1)\n\n vertices, joints, A, T = lbs(shape_components, full_pose, self.v_template,\n shapedirs, self.posedirs,\n self.J_regressor, self.parents,\n self.lbs_weights, pose2rot=pose2rot,\n )\n\n lmk_faces_idx = self.lmk_faces_idx.unsqueeze(\n dim=0).expand(batch_size, -1).contiguous()\n lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat(\n self.batch_size, 1, 1)\n if self.use_face_contour:\n lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords(\n vertices, full_pose, self.dynamic_lmk_faces_idx,\n self.dynamic_lmk_bary_coords,\n self.neck_kin_chain,\n pose2rot=True,\n )\n dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords\n\n lmk_faces_idx = torch.cat([lmk_faces_idx,\n dyn_lmk_faces_idx], 1)\n lmk_bary_coords = torch.cat(\n [lmk_bary_coords.expand(batch_size, -1, -1),\n dyn_lmk_bary_coords], 1)\n\n landmarks = vertices2landmarks(vertices, self.faces_tensor,\n lmk_faces_idx,\n lmk_bary_coords)\n\n # import matplotlib.pyplot as plt\n # import numpy as np\n # xs = joints[0,:,0]\n # ys = joints[0,:,1]\n # plt.scatter(xs, ys)\n\n # # zip joins x and y coordinates in pairs\n # count = 0\n # for x,y in zip(xs, ys):\n\n # label = \"{:.2f}\".format(count)\n\n # plt.annotate(label, # this is the text\n # (x,y), # these are the coordinates to position the label\n # textcoords=\"offset points\", # how to position the text\n # xytext=(0,10), # distance from text to points (x,y)\n # ha='center') # horizontal alignment can be left, right or center\n # count += 1\n # plt.savefig(\"joints.png\")\n # import pdb; pdb.set_trace()\n\n # Add any extra joints that might be needed\n joints = self.vertex_joint_selector(vertices, joints)\n # Add the landmarks to the joints\n joints = torch.cat([joints, landmarks], dim=1)\n # Map the joints to the current dataset\n\n if self.joint_mapper is not None:\n joints = self.joint_mapper(joints=joints, vertices=vertices)\n\n if apply_trans:\n joints += transl.unsqueeze(dim=1)\n vertices += transl.unsqueeze(dim=1)\n # clone because we are modifying them in-place\n A = A.clone()\n A[..., :3, 3] += transl.unsqueeze(dim=1)\n T = T.clone()\n T[..., :3, 3] += transl.unsqueeze(dim=1)\n\n v_shaped = None\n if return_shaped:\n v_shaped = self.v_template + blend_shapes(betas, self.shapedirs)\n else:\n v_shaped = Tensor(0)\n\n output = TensorOutput(vertices=vertices if return_verts else None,\n joints=joints,\n betas=betas,\n expression=expression,\n global_orient=global_orient,\n body_pose=body_pose,\n left_hand_pose=left_hand_pose,\n right_hand_pose=right_hand_pose,\n jaw_pose=jaw_pose,\n v_shaped=v_shaped,\n full_pose=full_pose if return_full_pose else None,\n A=A,\n T=T,\n f=self.faces)\n return output" }, { "identifier": "SMCReader", "path": "data/dna_rendering/dna_rendering_sample_code/SMCReader.py", "snippet": "class SMCReader:\n\n def __init__(self, file_path):\n \"\"\"Read SenseMocapFile endswith \".smc\".\n\n Args:\n file_path (str):\n Path to an SMC file.\n body_model (nn.Module or dict):\n Only needed for SMPL transformation to device frame\n if nn.Module: a body_model instance\n if dict: a body_model config\n \"\"\"\n self.smc = h5py.File(file_path, 'r')\n self.__calibration_dict__ = None\n self.__kinect_calib_dict__ = None \n self.__available_keys__ = list(self.smc.keys())\n \n self.actor_info = None \n if hasattr(self.smc, 'attrs') and len(self.smc.attrs.keys()) > 0:\n self.actor_info = dict(\n id=self.smc.attrs['actor_id'],\n perf_id=self.smc.attrs['performance_id'],\n age=self.smc.attrs['age'],\n gender=self.smc.attrs['gender'],\n height=self.smc.attrs['height'],\n weight=self.smc.attrs['weight'],\n ethnicity=self.smc.attrs['ethnicity'],\n )\n\n self.Camera_5mp_info = None \n if 'Camera_5mp' in self.smc:\n self.Camera_5mp_info = dict(\n num_device=self.smc['Camera_5mp'].attrs['num_device'],\n num_frame=self.smc['Camera_5mp'].attrs['num_frame'],\n resolution=self.smc['Camera_5mp'].attrs['resolution'],\n )\n self.Camera_12mp_info = None \n if 'Camera_12mp' in self.smc:\n self.Camera_12mp_info = dict(\n num_device=self.smc['Camera_12mp'].attrs['num_device'],\n num_frame=self.smc['Camera_12mp'].attrs['num_frame'],\n resolution=self.smc['Camera_12mp'].attrs['resolution'],\n )\n self.Kinect_info = None\n if 'Kinect' in self.smc:\n self.Kinect_info=dict(\n num_device=self.smc['Kinect'].attrs['num_device'],\n num_frame=self.smc['Kinect'].attrs['num_frame'],\n resolution=self.smc['Kinect'].attrs['resolution'],\n )\n\n def get_available_keys(self):\n return self.__available_keys__ \n\n def get_actor_info(self):\n return self.actor_info\n \n def get_Camera_12mp_info(self):\n return self.Camera_12mp_info\n\n def get_Camera_5mp_info(self):\n return self.Camera_5mp_info\n \n def get_Kinect_info(self):\n return self.Kinect_info\n \n ### RGB Camera Calibration\n def get_Calibration_all(self):\n \"\"\"Get calibration matrix of all cameras and save it in self\n \n Args:\n None\n\n Returns:\n Dictionary of calibration matrixs of all matrixs.\n dict( \n Camera_Parameter: Camera_id : Matrix_type : value\n )\n Notice:\n Camera_id(str) in {'Camera_5mp': '0'~'47', 'Camera_12mp':'48'~'60'}\n Matrix_type in ['D', 'K', 'RT', 'Color_Calibration'] \n \"\"\" \n if not 'Camera_Parameter' in self.smc:\n print(\"=== no key: Camera_Parameter.\\nplease check available keys!\")\n return None \n\n if self.__calibration_dict__ is not None:\n return self.__calibration_dict__\n\n self.__calibration_dict__ = dict()\n for ci in self.smc['Camera_Parameter'].keys():\n self.__calibration_dict__.setdefault(ci,dict())\n for mt in ['D', 'K', 'RT', 'Color_Calibration'] :\n self.__calibration_dict__[ci][mt] = \\\n self.smc['Camera_Parameter'][ci][mt][()]\n return self.__calibration_dict__\n\n def get_Calibration(self, Camera_id):\n \"\"\"Get calibration matrixs of a certain camera by its type and id \n\n Args:\n Camera_id (int/str of a number):\n Camera_id(str) in {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60'}\n Returns:\n Dictionary of calibration matrixs.\n ['D', 'K', 'RT', 'Color_Calibration'] \n \"\"\"\n if not 'Camera_Parameter' in self.smc:\n print(\"=== no key: Camera_Parameter.\\nplease check available keys!\")\n return None \n\n rs = dict()\n for k in ['D', 'K', 'RT', 'Color_Calibration'] :\n rs[k] = self.smc['Camera_Parameter'][f'{int(Camera_id):02d}'][k][()]\n return rs\n\n ### Kinect Camera Calibration\n def get_Kinect_Calibration_all(self):\n \"\"\"Get calibration matrix of all kinect cameras and save it in self\n \n Args:\n None\n\n Returns:\n Dictionary of calibration matrixs of all matrixs.\n dict( \n Camera_group: Camera_id : Matrix_type : value\n )\n Notice:\n Camera_group(str) in ['Kinect']\n Camera_id(str) in {'Kinect': '0'~'7'}\n Matrix_type in ['D', 'K', 'RT'] \n \"\"\" \n if not 'Calibration' in self.smc:\n print(\"=== no key: Calibration.\\nplease check available keys!\")\n return None \n\n if self.__kinect_calib_dict__ is not None:\n return self.__kinect_calib_dict__\n\n self.__kinect_calib_dict__ = dict()\n for cg in ['Kinect']:\n self.__kinect_calib_dict__.setdefault(cg,dict())\n for ci in self.smc['Calibration'][cg].keys():\n self.__kinect_calib_dict__[cg].setdefault(ci,dict())\n for mt in ['D', 'K', 'RT'] :\n self.__kinect_calib_dict__[cg][ci][mt] = \\\n self.smc['Calibration'][cg][ci][mt][()]\n return self.__kinect_calib_dict__\n\n def get_kinect_Calibration(self, Camera_id):\n \"\"\"Get calibration matrixs of a certain kinect camera by its type and id \n\n Args:\n Camera_group (str):\n Camera_group in ['Kinect'].\n Camera_id (int/str of a number):\n CameraID(str) in {'Kinect': '0'~'7'}\n Returns:\n Dictionary of calibration matrixs.\n ['D', 'K', 'RT'] \n \"\"\" \n if not 'Calibration' in self.smc:\n print(\"=== no key: Calibration.\\nplease check available keys!\")\n return None \n\n Camera_id = f'{int(Camera_id):02d}'\n assert(Camera_id in self.smc['Calibration'][\"Kinect\"].keys())\n rs = dict()\n for k in ['D', 'K', 'RT']:\n rs[k] = self.smc['Calibration'][\"Kinect\"][Camera_id][k][()]\n return rs\n\n ### RGB image\n def __read_color_from_bytes__(self, color_array):\n \"\"\"Decode an RGB image from an encoded byte array.\"\"\"\n return cv2.imdecode(color_array, cv2.IMREAD_COLOR)\n\n def get_mask(self, Camera_id, Frame_id=None, disable_tqdm=True):\n \"\"\"Get mask from Camera_id, Frame_id\n\n Args:\n Camera_id (int/str of a number):\n Camera_id (str) in \n {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60',\n 'Kinect': '0'~'7'}\n Frame_id a.(int/str of a number): '0' ~ 'num_frame'\n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n a single img :\n 'color': HWC in bgr (uint8)\n 'mask' : HW (uint8)\n 'depth': HW (uint16)\n \"\"\" \n if not 'Mask' in self.smc:\n print(\"=== no key: Mask.\\nplease check available keys!\")\n return None \n\n Camera_id = str(Camera_id)\n\n assert(isinstance(Frame_id,(list,int, str, type(None))))\n if isinstance(Frame_id, (str,int)):\n Frame_id = str(Frame_id)\n assert(Frame_id in self.smc['Mask'][Camera_id]['mask'].keys())\n img_byte = self.smc['Mask'][Camera_id]['mask'][Frame_id][()]\n img_color = self.__read_color_from_bytes__(img_byte)\n img_color = np.max(img_color,2)\n return img_color \n else:\n if Frame_id is None:\n Frame_id_list =sorted([int(l) for l in self.smc['Mask'][Camera_id]['mask'].keys()])\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm.tqdm(Frame_id_list, disable=disable_tqdm):\n rs.append(self.get_mask(Camera_id,fi))\n return np.stack(rs,axis=0)\n\n def get_img(self, Camera_group, Camera_id, Image_type, Frame_id=None, disable_tqdm=True):\n \"\"\"Get image its Camera_group, Camera_id, Image_type and Frame_id\n\n Args:\n Camera_group (str):\n Camera_group in ['Camera_12mp', 'Camera_5mp','Kinect'].\n Camera_id (int/str of a number):\n CameraID (str) in \n {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60',\n 'Kinect': '0'~'7'}\n Image_type(str) in \n {'Camera_5mp': ['color'], \n 'Camera_12mp': ['color'],\n 'Kinect': ['depth', 'mask']}\n Frame_id a.(int/str of a number): '0' ~ 'num_frame'('149') \n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n a single img :\n 'color': HWC in bgr (uint8)\n 'mask' : HW (uint8)\n 'depth': HW (uint16)\n \"\"\" \n if not Camera_group in self.smc:\n print(\"=== no key: %s.\\nplease check available keys!\" % Camera_group)\n return None\n\n assert(Camera_group in ['Camera_12mp', 'Camera_5mp','Kinect'])\n Camera_id = str(Camera_id)\n assert(Camera_id in self.smc[Camera_group].keys())\n assert(Image_type in self.smc[Camera_group][Camera_id].keys())\n assert(isinstance(Frame_id,(list,int, str, type(None))))\n if isinstance(Frame_id, (str,int)):\n Frame_id = str(Frame_id)\n assert(Frame_id in self.smc[Camera_group][Camera_id][Image_type].keys())\n if Image_type in ['color']:\n img_byte = self.smc[Camera_group][Camera_id][Image_type][Frame_id][()]\n img_color = self.__read_color_from_bytes__(img_byte)\n if Image_type == 'mask':\n img_byte = self.smc[Camera_group][Camera_id][Image_type][Frame_id][()]\n img_color = self.__read_color_from_bytes__(img_byte)\n img_color = np.max(img_color,2)\n if Image_type == 'depth':\n img_color = self.smc[Camera_group][Camera_id][Image_type][Frame_id][()]\n return img_color \n else:\n if Frame_id is None:\n Frame_id_list =sorted([int(l) for l in self.smc[Camera_group][Camera_id][Image_type].keys()])\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm(Frame_id_list, disable=disable_tqdm):\n rs.append(self.get_img(Camera_group, Camera_id, Image_type,fi))\n return np.stack(rs,axis=0)\n \n ###Keypoints2d\n def get_Keypoints2d(self, Camera_id, Frame_id=None):\n \"\"\"Get keypoint2D by its Camera_group, Camera_id and Frame_id\n\n Args:\n Camera_id (int/str of a number):\n CameraID (str) in \n {'Camera_5mp': '0'~'47', \n 'Camera_12mp':'48'~'60',}\n Frame_id a.(int/str of a number): '0' ~ 'num_frame-1'('149') \n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n a single img :\n 'color': HWC in bgr (uint8)\n 'mask' : HW (uint8)\n 'depth': HW (uint16)\n \"\"\" \n if not 'Keypoints_2D' in self.smc:\n print(\"=== no key: Keypoints_2D.\\nplease check available keys!\")\n return None \n\n Camera_id = f'{int(Camera_id):02d}'\n assert(isinstance(Frame_id,(list,int, str, type(None))))\n if isinstance(Frame_id, (str,int)):\n Frame_id = int(Frame_id)\n return self.smc['Keypoints_2D'][Camera_id][()][Frame_id,:]\n else:\n if Frame_id is None:\n return self.smc['Keypoints_2D'][Camera_id][()]\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm.tqdm(Frame_id_list):\n rs.append(self.get_Keypoints2d(Camera_id,fi))\n return np.stack(rs,axis=0)\n\n ###Keypoints3d\n def get_Keypoints3d(self, Frame_id=None):\n \"\"\"Get keypoint3D Frame_id, TODO coordinate\n\n Args:\n Frame_id a.(int/str of a number): '0' ~ 'num_frame-1'('149') \n b.list of numbers (int/str)\n c.None: get batch of all imgs in order of time sequence \n Returns:\n Keypoints3d tensor: np.ndarray of shape ([N], ,3)\n \"\"\" \n if not 'Keypoints_3D' in self.smc:\n print(\"=== no key: Keypoints_3D.\\nplease check available keys!\")\n return None \n\n if isinstance(Frame_id, (str,int)):\n Frame_id = int(Frame_id)\n return self.smc['Keypoints_3D'][\"keypoints3d\"][Frame_id,:]\n else:\n if Frame_id is None:\n return self.smc['Keypoints_3D'][\"keypoints3d\"]\n elif isinstance(Frame_id, list):\n Frame_id_list = Frame_id\n rs = []\n for fi in tqdm.tqdm(Frame_id_list):\n rs.append(self.get_Keypoints3d(fi))\n return np.stack(rs,axis=0)\n\n ###SMPLx\n def get_SMPLx(self, Frame_id=None):\n \"\"\"Get SMPL (world coordinate) computed by mocap processing pipeline.\n\n Args:\n Frame_id (int, list or None, optional):\n int: frame id of one selected frame\n list: a list of frame id\n None: all frames will be returned\n Defaults to None.\n\n Returns:\n dict:\n 'global_orient': np.ndarray of shape (N, 3)\n 'body_pose': np.ndarray of shape (N, 21, 3)\n 'transl': np.ndarray of shape (N, 3)\n 'betas': np.ndarray of shape (1, 10)\n \"\"\"\n if not 'SMPLx' in self.smc:\n print(\"=== no key: SMPLx.\\nplease check available keys!\")\n return None \n\n t_frame = self.smc['SMPLx']['betas'][()].shape[0]\n if Frame_id is None:\n frame_list = range(t_frame)\n elif isinstance(Frame_id, list):\n frame_list = [int(fi) for fi in Frame_id]\n elif isinstance(Frame_id, (int,str)):\n Frame_id = int(Frame_id)\n assert Frame_id < t_frame,\\\n f'Invalid frame_index {Frame_id}'\n frame_list = Frame_id\n else:\n raise TypeError('frame_id should be int, list or None.')\n\n smpl_dict = {}\n for key in ['betas', 'expression', 'fullpose', 'transl']:\n smpl_dict[key] = self.smc['SMPLx'][key][()][frame_list, ...]\n smpl_dict['scale'] = self.smc['SMPLx']['scale'][()]\n\n return smpl_dict\n\n def release(self):\n self.smc = None \n self.__calibration_dict__ = None\n self.__kinect_calib_dict__ = None\n self.__available_keys__ = None\n self.actor_info = None \n self.Camera_5mp_info = None\n self.Camera_12mp_info = None \n self.Kinect_info = None" } ]
import os import sys import numpy as np import torch import json import imageio import cv2 import random from PIL import Image from typing import NamedTuple from scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \ read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text from utils.graphics_utils import getWorld2View2, focal2fov, fov2focal from pathlib import Path from plyfile import PlyData, PlyElement from utils.sh_utils import SH2RGB from scene.gaussian_model import BasicPointCloud from smpl.smpl_numpy import SMPL from smplx.body_models import SMPLX from data.dna_rendering.dna_rendering_sample_code.SMCReader import SMCReader
15,094
K: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str bkgd_mask: np.array bound_mask: np.array width: int height: int smpl_param: dict world_vertex: np.array world_bound: np.array big_pose_smpl_param: dict big_pose_world_vertex: np.array big_pose_world_bound: np.array class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file) except: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt")
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact [email protected] # class CameraInfo(NamedTuple): uid: int pose_id: int R: np.array T: np.array K: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str bkgd_mask: np.array bound_mask: np.array width: int height: int smpl_param: dict world_vertex: np.array world_bound: np.array big_pose_smpl_param: dict big_pose_world_vertex: np.array big_pose_world_bound: np.array class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file) except: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt")
cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file)
0
2023-11-29 07:10:39+00:00
24k
cswry/SeeSR
test_seesr.py
[ { "identifier": "StableDiffusionControlNetPipeline", "path": "pipelines/pipeline_seesr.py", "snippet": "class StableDiffusionControlNetPipeline(DiffusionPipeline, TextualInversionLoaderMixin):\n r\"\"\"\n Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.\n\n This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the\n library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)\n\n In addition the pipeline inherits the following loading methods:\n - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]\n\n Args:\n vae ([`AutoencoderKL`]):\n Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.\n text_encoder ([`CLIPTextModel`]):\n Frozen text-encoder. Stable Diffusion uses the text portion of\n [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically\n the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.\n tokenizer (`CLIPTokenizer`):\n Tokenizer of class\n [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).\n unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.\n controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):\n Provides additional conditioning to the unet during the denoising process. If you set multiple ControlNets\n as a list, the outputs from each ControlNet are added together to create one combined additional\n conditioning.\n scheduler ([`SchedulerMixin`]):\n A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of\n [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].\n safety_checker ([`StableDiffusionSafetyChecker`]):\n Classification module that estimates whether generated images could be considered offensive or harmful.\n Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.\n feature_extractor ([`CLIPImageProcessor`]):\n Model that extracts features from generated images to be used as inputs for the `safety_checker`.\n \"\"\"\n _optional_components = [\"safety_checker\", \"feature_extractor\"]\n\n def __init__(\n self,\n vae: AutoencoderKL,\n text_encoder: CLIPTextModel,\n tokenizer: CLIPTokenizer,\n unet: UNet2DConditionModel,\n controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],\n scheduler: KarrasDiffusionSchedulers,\n safety_checker: StableDiffusionSafetyChecker,\n feature_extractor: CLIPImageProcessor,\n requires_safety_checker: bool = True,\n ):\n super().__init__()\n\n if safety_checker is None and requires_safety_checker:\n logger.warning(\n f\"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure\"\n \" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered\"\n \" results in services or applications open to the public. Both the diffusers team and Hugging Face\"\n \" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling\"\n \" it only for use-cases that involve analyzing network behavior or auditing its results. For more\"\n \" information, please have a look at https://github.com/huggingface/diffusers/pull/254 .\"\n )\n\n if safety_checker is not None and feature_extractor is None:\n raise ValueError(\n \"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety\"\n \" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead.\"\n )\n\n if isinstance(controlnet, (list, tuple)):\n controlnet = MultiControlNetModel(controlnet)\n\n self.register_modules(\n vae=vae,\n text_encoder=text_encoder,\n tokenizer=tokenizer,\n unet=unet,\n controlnet=controlnet,\n scheduler=scheduler,\n safety_checker=safety_checker,\n feature_extractor=feature_extractor,\n )\n self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)\n self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)\n self.register_to_config(requires_safety_checker=requires_safety_checker)\n\n def _init_tiled_vae(self,\n encoder_tile_size = 256,\n decoder_tile_size = 256,\n fast_decoder = False,\n fast_encoder = False,\n color_fix = False,\n vae_to_gpu = True):\n # save original forward (only once)\n if not hasattr(self.vae.encoder, 'original_forward'):\n setattr(self.vae.encoder, 'original_forward', self.vae.encoder.forward)\n if not hasattr(self.vae.decoder, 'original_forward'):\n setattr(self.vae.decoder, 'original_forward', self.vae.decoder.forward)\n\n encoder = self.vae.encoder\n decoder = self.vae.decoder\n\n self.vae.encoder.forward = VAEHook(\n encoder, encoder_tile_size, is_decoder=False, fast_decoder=fast_decoder, fast_encoder=fast_encoder, color_fix=color_fix, to_gpu=vae_to_gpu)\n self.vae.decoder.forward = VAEHook(\n decoder, decoder_tile_size, is_decoder=True, fast_decoder=fast_decoder, fast_encoder=fast_encoder, color_fix=color_fix, to_gpu=vae_to_gpu)\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing\n def enable_vae_slicing(self):\n r\"\"\"\n Enable sliced VAE decoding.\n\n When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several\n steps. This is useful to save some memory and allow larger batch sizes.\n \"\"\"\n self.vae.enable_slicing()\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing\n def disable_vae_slicing(self):\n r\"\"\"\n Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to\n computing decoding in one step.\n \"\"\"\n self.vae.disable_slicing()\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling\n def enable_vae_tiling(self):\n r\"\"\"\n Enable tiled VAE decoding.\n\n When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in\n several steps. This is useful to save a large amount of memory and to allow the processing of larger images.\n \"\"\"\n self.vae.enable_tiling()\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling\n def disable_vae_tiling(self):\n r\"\"\"\n Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to\n computing decoding in one step.\n \"\"\"\n self.vae.disable_tiling()\n\n def enable_sequential_cpu_offload(self, gpu_id=0):\n r\"\"\"\n Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,\n text_encoder, vae, controlnet, and safety checker have their state dicts saved to CPU and then are moved to a\n `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.\n Note that offloading happens on a submodule basis. Memory savings are higher than with\n `enable_model_cpu_offload`, but performance is lower.\n \"\"\"\n if is_accelerate_available():\n from accelerate import cpu_offload\n else:\n raise ImportError(\"Please install accelerate via `pip install accelerate`\")\n\n device = torch.device(f\"cuda:{gpu_id}\")\n\n for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.controlnet]:\n cpu_offload(cpu_offloaded_model, device)\n\n if self.safety_checker is not None:\n cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)\n\n def enable_model_cpu_offload(self, gpu_id=0):\n r\"\"\"\n Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared\n to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`\n method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with\n `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.\n \"\"\"\n if is_accelerate_available() and is_accelerate_version(\">=\", \"0.17.0.dev0\"):\n from accelerate import cpu_offload_with_hook\n else:\n raise ImportError(\"`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.\")\n\n device = torch.device(f\"cuda:{gpu_id}\")\n\n hook = None\n for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:\n _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)\n\n if self.safety_checker is not None:\n # the safety checker can offload the vae again\n _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)\n\n # control net hook has be manually offloaded as it alternates with unet\n cpu_offload_with_hook(self.controlnet, device)\n\n # We'll offload the last model manually.\n self.final_offload_hook = hook\n\n @property\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device\n def _execution_device(self):\n r\"\"\"\n Returns the device on which the pipeline's models will be executed. After calling\n `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module\n hooks.\n \"\"\"\n if not hasattr(self.unet, \"_hf_hook\"):\n return self.device\n for module in self.unet.modules():\n if (\n hasattr(module, \"_hf_hook\")\n and hasattr(module._hf_hook, \"execution_device\")\n and module._hf_hook.execution_device is not None\n ):\n return torch.device(module._hf_hook.execution_device)\n return self.device\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt\n def _encode_prompt(\n self,\n prompt,\n device,\n num_images_per_prompt,\n do_classifier_free_guidance,\n negative_prompt=None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n ram_encoder_hidden_states: Optional[torch.FloatTensor] = None,\n ):\n r\"\"\"\n Encodes the prompt into text encoder hidden states.\n\n Args:\n prompt (`str` or `List[str]`, *optional*):\n prompt to be encoded\n device: (`torch.device`):\n torch device\n num_images_per_prompt (`int`):\n number of images that should be generated per prompt\n do_classifier_free_guidance (`bool`):\n whether to use classifier free guidance or not\n negative_prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts not to guide the image generation. If not defined, one has to pass\n `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is\n less than `1`).\n prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not\n provided, text embeddings will be generated from `prompt` input argument.\n negative_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt\n weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input\n argument.\n \"\"\"\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n if prompt_embeds is None:\n # textual inversion: procecss multi-vector tokens if necessary\n if isinstance(self, TextualInversionLoaderMixin):\n prompt = self.maybe_convert_prompt(prompt, self.tokenizer)\n\n text_inputs = self.tokenizer(\n prompt,\n padding=\"max_length\",\n max_length=self.tokenizer.model_max_length,\n truncation=True,\n return_tensors=\"pt\",\n )\n text_input_ids = text_inputs.input_ids\n untruncated_ids = self.tokenizer(prompt, padding=\"longest\", return_tensors=\"pt\").input_ids\n\n if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(\n text_input_ids, untruncated_ids\n ):\n removed_text = self.tokenizer.batch_decode(\n untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]\n )\n logger.warning(\n \"The following part of your input was truncated because CLIP can only handle sequences up to\"\n f\" {self.tokenizer.model_max_length} tokens: {removed_text}\"\n )\n\n if hasattr(self.text_encoder.config, \"use_attention_mask\") and self.text_encoder.config.use_attention_mask:\n attention_mask = text_inputs.attention_mask.to(device)\n else:\n attention_mask = None\n\n prompt_embeds = self.text_encoder(\n text_input_ids.to(device),\n attention_mask=attention_mask,\n )\n prompt_embeds = prompt_embeds[0]\n\n prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)\n\n bs_embed, seq_len, _ = prompt_embeds.shape\n # duplicate text embeddings for each generation per prompt, using mps friendly method\n prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)\n prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)\n\n # get unconditional embeddings for classifier free guidance\n if do_classifier_free_guidance and negative_prompt_embeds is None:\n uncond_tokens: List[str]\n if negative_prompt is None:\n uncond_tokens = [\"\"] * batch_size\n elif prompt is not None and type(prompt) is not type(negative_prompt):\n raise TypeError(\n f\"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=\"\n f\" {type(prompt)}.\"\n )\n elif isinstance(negative_prompt, str):\n uncond_tokens = [negative_prompt]\n elif batch_size != len(negative_prompt):\n raise ValueError(\n f\"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:\"\n f\" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches\"\n \" the batch size of `prompt`.\"\n )\n else:\n uncond_tokens = negative_prompt\n\n # textual inversion: procecss multi-vector tokens if necessary\n if isinstance(self, TextualInversionLoaderMixin):\n uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)\n\n max_length = prompt_embeds.shape[1]\n uncond_input = self.tokenizer(\n uncond_tokens,\n padding=\"max_length\",\n max_length=max_length,\n truncation=True,\n return_tensors=\"pt\",\n )\n\n if hasattr(self.text_encoder.config, \"use_attention_mask\") and self.text_encoder.config.use_attention_mask:\n attention_mask = uncond_input.attention_mask.to(device)\n else:\n attention_mask = None\n\n negative_prompt_embeds = self.text_encoder(\n uncond_input.input_ids.to(device),\n attention_mask=attention_mask,\n )\n negative_prompt_embeds = negative_prompt_embeds[0]\n\n if do_classifier_free_guidance:\n # duplicate unconditional embeddings for each generation per prompt, using mps friendly method\n seq_len = negative_prompt_embeds.shape[1]\n\n negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)\n\n negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)\n negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)\n\n # For classifier free guidance, we need to do two forward passes.\n # Here we concatenate the unconditional and text embeddings into a single batch\n # to avoid doing two forward passes\n prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])\n ram_encoder_hidden_states = torch.cat([ram_encoder_hidden_states, ram_encoder_hidden_states])\n\n return prompt_embeds, ram_encoder_hidden_states\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker\n def run_safety_checker(self, image, device, dtype):\n if self.safety_checker is None:\n has_nsfw_concept = None\n else:\n if torch.is_tensor(image):\n feature_extractor_input = self.image_processor.postprocess(image, output_type=\"pil\")\n else:\n feature_extractor_input = self.image_processor.numpy_to_pil(image)\n safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors=\"pt\").to(device)\n image, has_nsfw_concept = self.safety_checker(\n images=image, clip_input=safety_checker_input.pixel_values.to(dtype)\n )\n return image, has_nsfw_concept\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents\n def decode_latents(self, latents):\n warnings.warn(\n \"The decode_latents method is deprecated and will be removed in a future version. Please\"\n \" use VaeImageProcessor instead\",\n FutureWarning,\n )\n latents = 1 / self.vae.config.scaling_factor * latents\n image = self.vae.decode(latents, return_dict=False)[0]\n image = (image / 2 + 0.5).clamp(0, 1)\n # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16\n image = image.cpu().permute(0, 2, 3, 1).float().numpy()\n return image\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs\n def prepare_extra_step_kwargs(self, generator, eta):\n # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature\n # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.\n # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502\n # and should be between [0, 1]\n\n accepts_eta = \"eta\" in set(inspect.signature(self.scheduler.step).parameters.keys())\n extra_step_kwargs = {}\n if accepts_eta:\n extra_step_kwargs[\"eta\"] = eta\n\n # check if the scheduler accepts generator\n accepts_generator = \"generator\" in set(inspect.signature(self.scheduler.step).parameters.keys())\n if accepts_generator:\n extra_step_kwargs[\"generator\"] = generator\n #extra_step_kwargs[\"generator\"] = generator\n return extra_step_kwargs\n\n def check_inputs(\n self,\n prompt,\n image,\n height,\n width,\n callback_steps,\n negative_prompt=None,\n prompt_embeds=None,\n negative_prompt_embeds=None,\n controlnet_conditioning_scale=1.0,\n ):\n if height % 8 != 0 or width % 8 != 0:\n raise ValueError(f\"`height` and `width` have to be divisible by 8 but are {height} and {width}.\")\n\n if (callback_steps is None) or (\n callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)\n ):\n raise ValueError(\n f\"`callback_steps` has to be a positive integer but is {callback_steps} of type\"\n f\" {type(callback_steps)}.\"\n )\n\n if prompt is not None and prompt_embeds is not None:\n raise ValueError(\n f\"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to\"\n \" only forward one of the two.\"\n )\n elif prompt is None and prompt_embeds is None:\n raise ValueError(\n \"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.\"\n )\n elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):\n raise ValueError(f\"`prompt` has to be of type `str` or `list` but is {type(prompt)}\")\n\n if negative_prompt is not None and negative_prompt_embeds is not None:\n raise ValueError(\n f\"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:\"\n f\" {negative_prompt_embeds}. Please make sure to only forward one of the two.\"\n )\n\n if prompt_embeds is not None and negative_prompt_embeds is not None:\n if prompt_embeds.shape != negative_prompt_embeds.shape:\n raise ValueError(\n \"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but\"\n f\" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`\"\n f\" {negative_prompt_embeds.shape}.\"\n )\n\n # `prompt` needs more sophisticated handling when there are multiple\n # conditionings.\n if isinstance(self.controlnet, MultiControlNetModel):\n if isinstance(prompt, list):\n logger.warning(\n f\"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}\"\n \" prompts. The conditionings will be fixed across the prompts.\"\n )\n\n # Check `image`\n is_compiled = hasattr(F, \"scaled_dot_product_attention\") and isinstance(\n self.controlnet, torch._dynamo.eval_frame.OptimizedModule\n )\n if (\n isinstance(self.controlnet, ControlNetModel)\n or is_compiled\n and isinstance(self.controlnet._orig_mod, ControlNetModel)\n ):\n self.check_image(image, prompt, prompt_embeds)\n elif (\n isinstance(self.controlnet, MultiControlNetModel)\n or is_compiled\n and isinstance(self.controlnet._orig_mod, MultiControlNetModel)\n ):\n if not isinstance(image, list):\n raise TypeError(\"For multiple controlnets: `image` must be type `list`\")\n\n # When `image` is a nested list:\n # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])\n elif any(isinstance(i, list) for i in image):\n raise ValueError(\"A single batch of multiple conditionings are supported at the moment.\")\n elif len(image) != len(self.controlnet.nets):\n raise ValueError(\n \"For multiple controlnets: `image` must have the same length as the number of controlnets.\"\n )\n\n for image_ in image:\n self.check_image(image_, prompt, prompt_embeds)\n else:\n assert False\n\n # Check `controlnet_conditioning_scale`\n if (\n isinstance(self.controlnet, ControlNetModel)\n or is_compiled\n and isinstance(self.controlnet._orig_mod, ControlNetModel)\n ):\n if not isinstance(controlnet_conditioning_scale, float):\n raise TypeError(\"For single controlnet: `controlnet_conditioning_scale` must be type `float`.\")\n elif (\n isinstance(self.controlnet, MultiControlNetModel)\n or is_compiled\n and isinstance(self.controlnet._orig_mod, MultiControlNetModel)\n ):\n if isinstance(controlnet_conditioning_scale, list):\n if any(isinstance(i, list) for i in controlnet_conditioning_scale):\n raise ValueError(\"A single batch of multiple conditionings are supported at the moment.\")\n elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(\n self.controlnet.nets\n ):\n raise ValueError(\n \"For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have\"\n \" the same length as the number of controlnets\"\n )\n else:\n assert False\n\n def check_image(self, image, prompt, prompt_embeds):\n image_is_pil = isinstance(image, PIL.Image.Image)\n image_is_tensor = isinstance(image, torch.Tensor)\n image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)\n image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)\n\n if not image_is_pil and not image_is_tensor and not image_is_pil_list and not image_is_tensor_list:\n raise TypeError(\n \"image must be passed and be one of PIL image, torch tensor, list of PIL images, or list of torch tensors\"\n )\n\n if image_is_pil:\n image_batch_size = 1\n elif image_is_tensor:\n image_batch_size = image.shape[0]\n elif image_is_pil_list:\n image_batch_size = len(image)\n elif image_is_tensor_list:\n image_batch_size = len(image)\n\n if prompt is not None and isinstance(prompt, str):\n prompt_batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n prompt_batch_size = len(prompt)\n elif prompt_embeds is not None:\n prompt_batch_size = prompt_embeds.shape[0]\n\n if image_batch_size != 1 and image_batch_size != prompt_batch_size:\n raise ValueError(\n f\"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}\"\n )\n\n def prepare_image(\n self,\n image,\n width,\n height,\n batch_size,\n num_images_per_prompt,\n device,\n dtype,\n do_classifier_free_guidance=False,\n guess_mode=False,\n ):\n if not isinstance(image, torch.Tensor):\n if isinstance(image, PIL.Image.Image):\n image = [image]\n\n if isinstance(image[0], PIL.Image.Image):\n images = []\n\n for image_ in image:\n image_ = image_.convert(\"RGB\")\n #image_ = image_.resize((width, height), resample=PIL_INTERPOLATION[\"lanczos\"])\n image_ = np.array(image_)\n image_ = image_[None, :]\n images.append(image_)\n\n image = images\n\n image = np.concatenate(image, axis=0)\n image = np.array(image).astype(np.float32) / 255.0\n image = image.transpose(0, 3, 1, 2)\n image = torch.from_numpy(image)#.flip(1)\n elif isinstance(image[0], torch.Tensor):\n image = torch.cat(image, dim=0)\n\n image_batch_size = image.shape[0]\n\n if image_batch_size == 1:\n repeat_by = batch_size\n else:\n # image batch size is the same as prompt batch size\n repeat_by = num_images_per_prompt\n\n image = image.repeat_interleave(repeat_by, dim=0)\n\n image = image.to(device=device, dtype=dtype)\n\n if do_classifier_free_guidance and not guess_mode:\n image = torch.cat([image] * 2)\n\n return image\n\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents\n def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):\n shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)\n if isinstance(generator, list) and len(generator) != batch_size:\n raise ValueError(\n f\"You have passed a list of generators of length {len(generator)}, but requested an effective batch\"\n f\" size of {batch_size}. Make sure the batch size matches the length of the generators.\"\n )\n\n if latents is None:\n latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)\n #latents = randn_tensor(shape, generator=None, device=device, dtype=dtype)\n #offset_noise = torch.randn(batch_size, num_channels_latents, 1, 1, device=device)\n #latents = latents + 0.1 * offset_noise\n else:\n latents = latents.to(device)\n\n # scale the initial noise by the standard deviation required by the scheduler\n latents = latents * self.scheduler.init_noise_sigma\n return latents\n\n def _default_height_width(self, height, width, image):\n # NOTE: It is possible that a list of images have different\n # dimensions for each image, so just checking the first image\n # is not _exactly_ correct, but it is simple.\n while isinstance(image, list):\n image = image[0]\n\n if height is None:\n if isinstance(image, PIL.Image.Image):\n height = image.height\n elif isinstance(image, torch.Tensor):\n height = image.shape[2]\n\n height = (height // 8) * 8 # round down to nearest multiple of 8\n\n if width is None:\n if isinstance(image, PIL.Image.Image):\n width = image.width\n elif isinstance(image, torch.Tensor):\n width = image.shape[3]\n\n width = (width // 8) * 8 # round down to nearest multiple of 8\n\n return height, width\n\n # override DiffusionPipeline\n def save_pretrained(\n self,\n save_directory: Union[str, os.PathLike],\n safe_serialization: bool = False,\n variant: Optional[str] = None,\n ):\n if isinstance(self.controlnet, ControlNetModel):\n super().save_pretrained(save_directory, safe_serialization, variant)\n else:\n raise NotImplementedError(\"Currently, the `save_pretrained()` is not implemented for Multi-ControlNet.\")\n \n def _gaussian_weights(self, tile_width, tile_height, nbatches):\n \"\"\"Generates a gaussian mask of weights for tile contributions\"\"\"\n from numpy import pi, exp, sqrt\n import numpy as np\n\n latent_width = tile_width\n latent_height = tile_height\n\n var = 0.01\n midpoint = (latent_width - 1) / 2 # -1 because index goes from 0 to latent_width - 1\n x_probs = [exp(-(x-midpoint)*(x-midpoint)/(latent_width*latent_width)/(2*var)) / sqrt(2*pi*var) for x in range(latent_width)]\n midpoint = latent_height / 2\n y_probs = [exp(-(y-midpoint)*(y-midpoint)/(latent_height*latent_height)/(2*var)) / sqrt(2*pi*var) for y in range(latent_height)]\n\n weights = np.outer(y_probs, x_probs)\n return torch.tile(torch.tensor(weights, device=self.device), (nbatches, self.unet.config.in_channels, 1, 1))\n\n @perfcount\n @torch.no_grad()\n @replace_example_docstring(EXAMPLE_DOC_STRING)\n def __call__(\n self,\n prompt: Union[str, List[str]] = None,\n image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] = None,\n height: Optional[int] = None,\n width: Optional[int] = None,\n num_inference_steps: int = 50,\n guidance_scale: float = 7.5,\n negative_prompt: Optional[Union[str, List[str]]] = None,\n num_images_per_prompt: Optional[int] = 1,\n eta: float = 0.0,\n generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,\n latents: Optional[torch.FloatTensor] = None,\n prompt_embeds: Optional[torch.FloatTensor] = None,\n negative_prompt_embeds: Optional[torch.FloatTensor] = None,\n output_type: Optional[str] = \"pil\",\n return_dict: bool = True,\n callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,\n callback_steps: int = 1,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n conditioning_scale: Union[float, List[float]] = 1.0,\n guess_mode: bool = False,\n image_sr = None,\n start_steps = 999,\n start_point = 'noise',\n ram_encoder_hidden_states=None,\n latent_tiled_size=320,\n latent_tiled_overlap=4,\n args=None\n ):\n r\"\"\"\n Function invoked when calling the pipeline for generation.\n\n Args:\n prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.\n instead.\n image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`,\n `List[List[torch.FloatTensor]]`, or `List[List[PIL.Image.Image]]`):\n The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If\n the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can\n also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If\n height and/or width are passed, `image` is resized according to them. If multiple ControlNets are\n specified in init, images must be passed as a list such that each element of the list can be correctly\n batched for input to a single controlnet.\n height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):\n The height in pixels of the generated image.\n width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):\n The width in pixels of the generated image.\n num_inference_steps (`int`, *optional*, defaults to 50):\n The number of denoising steps. More denoising steps usually lead to a higher quality image at the\n expense of slower inference.\n guidance_scale (`float`, *optional*, defaults to 7.5):\n Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).\n `guidance_scale` is defined as `w` of equation 2. of [Imagen\n Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >\n 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,\n usually at the expense of lower image quality.\n negative_prompt (`str` or `List[str]`, *optional*):\n The prompt or prompts not to guide the image generation. If not defined, one has to pass\n `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is\n less than `1`).\n num_images_per_prompt (`int`, *optional*, defaults to 1):\n The number of images to generate per prompt.\n eta (`float`, *optional*, defaults to 0.0):\n Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to\n [`schedulers.DDIMScheduler`], will be ignored for others.\n generator (`torch.Generator` or `List[torch.Generator]`, *optional*):\n One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)\n to make generation deterministic.\n latents (`torch.FloatTensor`, *optional*):\n Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image\n generation. Can be used to tweak the same generation with different prompts. If not provided, a latents\n tensor will ge generated by sampling using the supplied random `generator`.\n prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not\n provided, text embeddings will be generated from `prompt` input argument.\n negative_prompt_embeds (`torch.FloatTensor`, *optional*):\n Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt\n weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input\n argument.\n output_type (`str`, *optional*, defaults to `\"pil\"`):\n The output format of the generate image. Choose between\n [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a\n plain tuple.\n callback (`Callable`, *optional*):\n A function that will be called every `callback_steps` steps during inference. The function will be\n called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.\n callback_steps (`int`, *optional*, defaults to 1):\n The frequency at which the `callback` function will be called. If not specified, the callback will be\n called at every step.\n cross_attention_kwargs (`dict`, *optional*):\n A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under\n `self.processor` in\n [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).\n conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):\n The outputs of the controlnet are multiplied by `conditioning_scale` before they are added\n to the residual in the original unet. If multiple ControlNets are specified in init, you can set the\n corresponding scale as a list.\n guess_mode (`bool`, *optional*, defaults to `False`):\n In this mode, the ControlNet encoder will try best to recognize the content of the input image even if\n you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.\n\n Examples:\n\n Returns:\n [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:\n [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.\n When returning a tuple, the first element is a list with the generated images, and the second element is a\n list of `bool`s denoting whether the corresponding generated image likely represents \"not-safe-for-work\"\n (nsfw) content, according to the `safety_checker`.\n \"\"\"\n # 0. Default height and width to unet\n height, width = self._default_height_width(height, width, image)\n \n # 1. Check inputs. Raise error if not correct\n \"\"\"\n self.check_inputs(\n prompt,\n image,\n height,\n width,\n callback_steps,\n negative_prompt,\n prompt_embeds,\n negative_prompt_embeds,\n conditioning_scale,\n )\n \"\"\"\n\n # 2. Define call parameters\n if prompt is not None and isinstance(prompt, str):\n batch_size = 1\n elif prompt is not None and isinstance(prompt, list):\n batch_size = len(prompt)\n else:\n batch_size = prompt_embeds.shape[0]\n\n device = self._execution_device\n # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)\n # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`\n # corresponds to doing no classifier free guidance.\n do_classifier_free_guidance = guidance_scale > 1.0\n\n controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet\n \"\"\"\n if isinstance(controlnet, MultiControlNetModel) and isinstance(conditioning_scale, float):\n conditioning_scale = [conditioning_scale] * len(controlnet.nets)\n \n global_pool_conditions = (\n controlnet.config.global_pool_conditions\n if isinstance(controlnet, ControlNetModel)\n else controlnet.nets[0].config.global_pool_conditions\n )\n \n guess_mode = guess_mode or global_pool_conditions\n \"\"\"\n\n # 3. Encode input prompt\n prompt_embeds, ram_encoder_hidden_states = self._encode_prompt(\n prompt,\n device,\n num_images_per_prompt,\n do_classifier_free_guidance,\n negative_prompt,\n prompt_embeds=prompt_embeds,\n negative_prompt_embeds=negative_prompt_embeds,\n ram_encoder_hidden_states=ram_encoder_hidden_states\n )\n\n # 4. Prepare image\n image = self.prepare_image(\n image=image,\n width=width,\n height=height,\n batch_size=batch_size * num_images_per_prompt,\n num_images_per_prompt=num_images_per_prompt,\n device=device,\n dtype=controlnet.dtype,\n do_classifier_free_guidance=do_classifier_free_guidance,\n guess_mode=guess_mode,\n )\n\n # 5. Prepare timesteps\n self.scheduler.set_timesteps(num_inference_steps, device=device)\n timesteps = self.scheduler.timesteps\n\n # 6. Prepare latent variables\n num_channels_latents = self.unet.config.in_channels\n latents = self.prepare_latents(\n batch_size * num_images_per_prompt,\n num_channels_latents,\n height,\n width,\n prompt_embeds.dtype,\n device,\n generator,\n latents,\n )\n\n # 6. Prepare the start point\n if start_point == 'noise':\n latents = latents\n elif start_point == 'lr': # LRE Strategy\n latents_condition_image = self.vae.encode(image*2-1).latent_dist.sample()\n latents_condition_image = latents_condition_image * self.vae.config.scaling_factor\n start_steps_tensor = torch.randint(start_steps, start_steps+1, (latents.shape[0],), device=latents.device)\n start_steps_tensor = start_steps_tensor.long()\n latents = self.scheduler.add_noise(latents_condition_image[0:1, ...], latents, start_steps_tensor)\n \n\n # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline\n extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)\n\n # 8. Denoising loop\n num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order\n with self.progress_bar(total=num_inference_steps) as progress_bar:\n \n _, _, h, w = latents.size()\n tile_size, tile_overlap = (latent_tiled_size, latent_tiled_overlap) if args is not None else (256, 8)\n if h*w<=tile_size*tile_size:\n print(f\"[Tiled Latent]: the input size is tiny and unnecessary to tile.\")\n else:\n print(f\"[Tiled Latent]: the input size is {image.shape[-2]}x{image.shape[-1]}, need to tiled\")\n\n for i, t in enumerate(timesteps):\n # pass, if the timestep is larger than start_steps\n if t > start_steps:\n print(f'pass {t} steps.')\n continue\n\n # expand the latents if we are doing classifier free guidance\n latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents\n latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)\n\n # controlnet(s) inference\n if guess_mode and do_classifier_free_guidance:\n # Infer ControlNet only for the conditional batch.\n controlnet_latent_model_input = latents\n controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]\n \n else:\n controlnet_latent_model_input = latent_model_input\n controlnet_prompt_embeds = prompt_embeds\n\n if h*w<=tile_size*tile_size: # tiled latent input\n down_block_res_samples, mid_block_res_sample = [None]*10, None\n down_block_res_samples, mid_block_res_sample = self.controlnet(\n controlnet_latent_model_input,\n t,\n encoder_hidden_states=controlnet_prompt_embeds,\n controlnet_cond=image,\n conditioning_scale=conditioning_scale,\n guess_mode=guess_mode,\n return_dict=False,\n image_encoder_hidden_states = ram_encoder_hidden_states,\n )\n\n\n if guess_mode and do_classifier_free_guidance:\n # Infered ControlNet only for the conditional batch.\n # To apply the output of ControlNet to both the unconditional and conditional batches,\n # add 0 to the unconditional batch to keep it unchanged.\n down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]\n mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])\n\n # predict the noise residual\n noise_pred = self.unet(\n latent_model_input,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n down_block_additional_residuals=down_block_res_samples,\n mid_block_additional_residual=mid_block_res_sample,\n return_dict=False,\n image_encoder_hidden_states = ram_encoder_hidden_states,\n )[0]\n else:\n tile_weights = self._gaussian_weights(tile_size, tile_size, 1)\n tile_size = min(tile_size, min(h, w))\n tile_weights = self._gaussian_weights(tile_size, tile_size, 1)\n\n grid_rows = 0\n cur_x = 0\n while cur_x < latent_model_input.size(-1):\n cur_x = max(grid_rows * tile_size-tile_overlap * grid_rows, 0)+tile_size\n grid_rows += 1\n\n grid_cols = 0\n cur_y = 0\n while cur_y < latent_model_input.size(-2):\n cur_y = max(grid_cols * tile_size-tile_overlap * grid_cols, 0)+tile_size\n grid_cols += 1\n\n input_list = []\n cond_list = []\n img_list = []\n noise_preds = []\n for row in range(grid_rows):\n noise_preds_row = []\n for col in range(grid_cols):\n if col < grid_cols-1 or row < grid_rows-1:\n # extract tile from input image\n ofs_x = max(row * tile_size-tile_overlap * row, 0)\n ofs_y = max(col * tile_size-tile_overlap * col, 0)\n # input tile area on total image\n if row == grid_rows-1:\n ofs_x = w - tile_size\n if col == grid_cols-1:\n ofs_y = h - tile_size\n\n input_start_x = ofs_x\n input_end_x = ofs_x + tile_size\n input_start_y = ofs_y\n input_end_y = ofs_y + tile_size\n\n # input tile dimensions\n input_tile = latent_model_input[:, :, input_start_y:input_end_y, input_start_x:input_end_x]\n input_list.append(input_tile)\n cond_tile = controlnet_latent_model_input[:, :, input_start_y:input_end_y, input_start_x:input_end_x]\n cond_list.append(cond_tile)\n img_tile = image[:, :, input_start_y*8:input_end_y*8, input_start_x*8:input_end_x*8]\n img_list.append(img_tile)\n\n if len(input_list) == batch_size or col == grid_cols-1:\n input_list_t = torch.cat(input_list, dim=0)\n cond_list_t = torch.cat(cond_list, dim=0)\n img_list_t = torch.cat(img_list, dim=0)\n #print(input_list_t.shape, cond_list_t.shape, img_list_t.shape, fg_mask_list_t.shape)\n\n down_block_res_samples, mid_block_res_sample = self.controlnet(\n cond_list_t,\n t,\n encoder_hidden_states=controlnet_prompt_embeds,\n controlnet_cond=img_list_t,\n conditioning_scale=conditioning_scale,\n guess_mode=guess_mode,\n return_dict=False,\n image_encoder_hidden_states = ram_encoder_hidden_states,\n )\n\n if guess_mode and do_classifier_free_guidance:\n # Infered ControlNet only for the conditional batch.\n # To apply the output of ControlNet to both the unconditional and conditional batches,\n # add 0 to the unconditional batch to keep it unchanged.\n down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]\n mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])\n\n # predict the noise residual\n model_out = self.unet(\n input_list_t,\n t,\n encoder_hidden_states=prompt_embeds,\n cross_attention_kwargs=cross_attention_kwargs,\n down_block_additional_residuals=down_block_res_samples,\n mid_block_additional_residual=mid_block_res_sample,\n return_dict=False,\n image_encoder_hidden_states = ram_encoder_hidden_states,\n )[0]\n\n #for sample_i in range(model_out.size(0)):\n # noise_preds_row.append(model_out[sample_i].unsqueeze(0))\n input_list = []\n cond_list = []\n img_list = []\n\n noise_preds.append(model_out)\n\n # Stitch noise predictions for all tiles\n noise_pred = torch.zeros(latent_model_input.shape, device=latent_model_input.device)\n contributors = torch.zeros(latent_model_input.shape, device=latent_model_input.device)\n # Add each tile contribution to overall latents\n for row in range(grid_rows):\n for col in range(grid_cols):\n if col < grid_cols-1 or row < grid_rows-1:\n # extract tile from input image\n ofs_x = max(row * tile_size-tile_overlap * row, 0)\n ofs_y = max(col * tile_size-tile_overlap * col, 0)\n # input tile area on total image\n if row == grid_rows-1:\n ofs_x = w - tile_size\n if col == grid_cols-1:\n ofs_y = h - tile_size\n\n input_start_x = ofs_x\n input_end_x = ofs_x + tile_size\n input_start_y = ofs_y\n input_end_y = ofs_y + tile_size\n \n noise_pred[:, :, input_start_y:input_end_y, input_start_x:input_end_x] += noise_preds[row*grid_cols + col] * tile_weights\n contributors[:, :, input_start_y:input_end_y, input_start_x:input_end_x] += tile_weights\n # Average overlapping areas with more than 1 contributor\n noise_pred /= contributors\n \n \n # perform guidance\n if do_classifier_free_guidance:\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n\n\n\n # compute the previous noisy sample x_t -> x_t-1\n latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]\n\n # call the callback, if provided\n if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):\n progress_bar.update()\n if callback is not None and i % callback_steps == 0:\n callback(i, t, latents)\n\n # If we do sequential model offloading, let's offload unet and controlnet\n # manually for max memory savings\n if hasattr(self, \"final_offload_hook\") and self.final_offload_hook is not None:\n self.unet.to(\"cpu\")\n self.controlnet.to(\"cpu\")\n torch.cuda.empty_cache()\n\n has_nsfw_concept = None\n if not output_type == \"latent\":\n image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]#.flip(1)\n #image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)\n else:\n image = latents\n has_nsfw_concept = None\n\n if has_nsfw_concept is None:\n do_denormalize = [True] * image.shape[0]\n else:\n do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]\n\n image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)\n\n # Offload last model to CPU\n if hasattr(self, \"final_offload_hook\") and self.final_offload_hook is not None:\n self.final_offload_hook.offload()\n\n if not return_dict:\n return (image, has_nsfw_concept)\n\n return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)" }, { "identifier": "load_dreambooth_lora", "path": "utils/misc.py", "snippet": "def load_dreambooth_lora(unet, vae=None, model_path=None, alpha=1.0, model_base=\"\"):\n if model_path is None: return unet\n \n if model_path.endswith(\".ckpt\"):\n base_state_dict = torch.load(model_path)['state_dict']\n elif model_path.endswith(\".safetensors\"):\n state_dict = {}\n with safe_open(model_path, framework=\"pt\", device=\"cpu\") as f:\n for key in f.keys():\n state_dict[key] = f.get_tensor(key)\n \n is_lora = all(\"lora\" in k for k in state_dict.keys())\n if not is_lora:\n base_state_dict = state_dict\n else:\n base_state_dict = {}\n with safe_open(model_base, framework=\"pt\", device=\"cpu\") as f:\n for key in f.keys():\n base_state_dict[key] = f.get_tensor(key)\n \n converted_unet_checkpoint = convert_ldm_unet_checkpoint(base_state_dict, unet.config)\n unet_state_dict = unet.state_dict()\n for key in converted_unet_checkpoint:\n converted_unet_checkpoint[key] = alpha * converted_unet_checkpoint[key] + (1.0-alpha) * unet_state_dict[key]\n unet.load_state_dict(converted_unet_checkpoint, strict=False)\n\n if vae is not None:\n converted_vae_checkpoint = convert_ldm_vae_checkpoint(base_state_dict, vae.config)\n vae.load_state_dict(converted_vae_checkpoint)\n \n return unet, vae" }, { "identifier": "wavelet_color_fix", "path": "utils/wavelet_color_fix.py", "snippet": "def wavelet_color_fix(target: Image, source: Image):\n # Convert images to tensors\n to_tensor = ToTensor()\n target_tensor = to_tensor(target).unsqueeze(0)\n source_tensor = to_tensor(source).unsqueeze(0)\n\n # Apply wavelet reconstruction\n result_tensor = wavelet_reconstruction(target_tensor, source_tensor)\n\n # Convert tensor back to image\n to_image = ToPILImage()\n result_image = to_image(result_tensor.squeeze(0).clamp_(0.0, 1.0))\n\n return result_image" }, { "identifier": "adain_color_fix", "path": "utils/wavelet_color_fix.py", "snippet": "def adain_color_fix(target: Image, source: Image):\n # Convert images to tensors\n to_tensor = ToTensor()\n target_tensor = to_tensor(target).unsqueeze(0)\n source_tensor = to_tensor(source).unsqueeze(0)\n\n # Apply adaptive instance normalization\n result_tensor = adaptive_instance_normalization(target_tensor, source_tensor)\n\n # Convert tensor back to image\n to_image = ToPILImage()\n result_image = to_image(result_tensor.squeeze(0).clamp_(0.0, 1.0))\n\n return result_image" }, { "identifier": "ram", "path": "ram/models/ram_lora.py", "snippet": "def ram(pretrained='', pretrained_condition='', **kwargs):\n model = RAMLora(**kwargs)\n\n if pretrained:\n if kwargs['vit'] == 'swin_b':\n model, msg = load_checkpoint_swinbase(model, pretrained, kwargs)\n elif kwargs['vit'] == 'swin_l':\n model, msg = load_checkpoint_swinlarge(model, pretrained, kwargs)\n else:\n model, msg = load_checkpoint(model, pretrained)\n print('vit:', kwargs['vit'])\n \n if pretrained_condition:\n model.load_state_dict(torch.load(pretrained_condition), strict=False)\n print(f'load lora weights from {pretrained_condition}')\n\n return model" }, { "identifier": "inference_ram", "path": "ram/inference.py", "snippet": "def inference_ram(image, model):\n\n with torch.no_grad():\n tags, tags_chinese = model.generate_tag(image)\n\n return tags[0],tags_chinese[0]" }, { "identifier": "get_transform", "path": "ram/transform.py", "snippet": "def get_transform(image_size=384):\n return Compose([\n convert_to_rgb,\n Resize((image_size, image_size)),\n ToTensor(),\n Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])" } ]
import os import sys import cv2 import glob import argparse import numpy as np import torch import torch.utils.checkpoint import torch.nn as nn import torch.nn.functional as F from PIL import Image from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed from diffusers import AutoencoderKL, DDPMScheduler from diffusers.utils import check_min_version from diffusers.utils.import_utils import is_xformers_available from transformers import CLIPTextModel, CLIPTokenizer, CLIPImageProcessor from pipelines.pipeline_seesr import StableDiffusionControlNetPipeline from utils.misc import load_dreambooth_lora from utils.wavelet_color_fix import wavelet_color_fix, adain_color_fix from ram.models.ram_lora import ram from ram import inference_ram as inference from ram import get_transform from typing import Mapping, Any from torchvision import transforms from torchvision import transforms from models.controlnet import ControlNetModel from models.unet_2d_condition import UNet2DConditionModel
15,168
''' * SeeSR: Towards Semantics-Aware Real-World Image Super-Resolution * Modified from diffusers by Rongyuan Wu * 24/12/2023 ''' sys.path.append(os.getcwd()) logger = get_logger(__name__, log_level="INFO") tensor_transforms = transforms.Compose([ transforms.ToTensor(), ]) ram_transforms = transforms.Compose([ transforms.Resize((384, 384)), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) def load_state_dict_diffbirSwinIR(model: nn.Module, state_dict: Mapping[str, Any], strict: bool=False) -> None: state_dict = state_dict.get("state_dict", state_dict) is_model_key_starts_with_module = list(model.state_dict().keys())[0].startswith("module.") is_state_dict_key_starts_with_module = list(state_dict.keys())[0].startswith("module.") if ( is_model_key_starts_with_module and (not is_state_dict_key_starts_with_module) ): state_dict = {f"module.{key}": value for key, value in state_dict.items()} if ( (not is_model_key_starts_with_module) and is_state_dict_key_starts_with_module ): state_dict = {key[len("module."):]: value for key, value in state_dict.items()} model.load_state_dict(state_dict, strict=strict) def load_seesr_pipeline(args, accelerator, enable_xformers_memory_efficient_attention): # Load scheduler, tokenizer and models. scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_path, subfolder="scheduler") text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_path, subfolder="text_encoder") tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_path, subfolder="tokenizer") vae = AutoencoderKL.from_pretrained(args.pretrained_model_path, subfolder="vae") feature_extractor = CLIPImageProcessor.from_pretrained(f"{args.pretrained_model_path}/feature_extractor") unet = UNet2DConditionModel.from_pretrained(args.seesr_model_path, subfolder="unet") controlnet = ControlNetModel.from_pretrained(args.seesr_model_path, subfolder="controlnet") # Freeze vae and text_encoder vae.requires_grad_(False) text_encoder.requires_grad_(False) unet.requires_grad_(False) controlnet.requires_grad_(False) if enable_xformers_memory_efficient_attention: if is_xformers_available(): unet.enable_xformers_memory_efficient_attention() controlnet.enable_xformers_memory_efficient_attention() else: raise ValueError("xformers is not available. Make sure it is installed correctly") # Get the validation pipeline validation_pipeline = StableDiffusionControlNetPipeline( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, feature_extractor=feature_extractor, unet=unet, controlnet=controlnet, scheduler=scheduler, safety_checker=None, requires_safety_checker=False, ) validation_pipeline._init_tiled_vae(encoder_tile_size=args.vae_encoder_tiled_size, decoder_tile_size=args.vae_decoder_tiled_size) # For mixed precision training we cast the text_encoder and vae weights to half-precision # as these models are only used for inference, keeping weights in full precision is not required. weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 # Move text_encode and vae to gpu and cast to weight_dtype text_encoder.to(accelerator.device, dtype=weight_dtype) vae.to(accelerator.device, dtype=weight_dtype) unet.to(accelerator.device, dtype=weight_dtype) controlnet.to(accelerator.device, dtype=weight_dtype) return validation_pipeline def load_tag_model(args, device='cuda'): model = ram(pretrained='preset/models/ram_swin_large_14m.pth', pretrained_condition=args.ram_ft_path, image_size=384, vit='swin_l') model.eval() model.to(device) return model def get_validation_prompt(args, image, model, device='cuda'): validation_prompt = "" lq = tensor_transforms(image).unsqueeze(0).to(device) lq = ram_transforms(lq)
''' * SeeSR: Towards Semantics-Aware Real-World Image Super-Resolution * Modified from diffusers by Rongyuan Wu * 24/12/2023 ''' sys.path.append(os.getcwd()) logger = get_logger(__name__, log_level="INFO") tensor_transforms = transforms.Compose([ transforms.ToTensor(), ]) ram_transforms = transforms.Compose([ transforms.Resize((384, 384)), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) def load_state_dict_diffbirSwinIR(model: nn.Module, state_dict: Mapping[str, Any], strict: bool=False) -> None: state_dict = state_dict.get("state_dict", state_dict) is_model_key_starts_with_module = list(model.state_dict().keys())[0].startswith("module.") is_state_dict_key_starts_with_module = list(state_dict.keys())[0].startswith("module.") if ( is_model_key_starts_with_module and (not is_state_dict_key_starts_with_module) ): state_dict = {f"module.{key}": value for key, value in state_dict.items()} if ( (not is_model_key_starts_with_module) and is_state_dict_key_starts_with_module ): state_dict = {key[len("module."):]: value for key, value in state_dict.items()} model.load_state_dict(state_dict, strict=strict) def load_seesr_pipeline(args, accelerator, enable_xformers_memory_efficient_attention): # Load scheduler, tokenizer and models. scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_path, subfolder="scheduler") text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_path, subfolder="text_encoder") tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_path, subfolder="tokenizer") vae = AutoencoderKL.from_pretrained(args.pretrained_model_path, subfolder="vae") feature_extractor = CLIPImageProcessor.from_pretrained(f"{args.pretrained_model_path}/feature_extractor") unet = UNet2DConditionModel.from_pretrained(args.seesr_model_path, subfolder="unet") controlnet = ControlNetModel.from_pretrained(args.seesr_model_path, subfolder="controlnet") # Freeze vae and text_encoder vae.requires_grad_(False) text_encoder.requires_grad_(False) unet.requires_grad_(False) controlnet.requires_grad_(False) if enable_xformers_memory_efficient_attention: if is_xformers_available(): unet.enable_xformers_memory_efficient_attention() controlnet.enable_xformers_memory_efficient_attention() else: raise ValueError("xformers is not available. Make sure it is installed correctly") # Get the validation pipeline validation_pipeline = StableDiffusionControlNetPipeline( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, feature_extractor=feature_extractor, unet=unet, controlnet=controlnet, scheduler=scheduler, safety_checker=None, requires_safety_checker=False, ) validation_pipeline._init_tiled_vae(encoder_tile_size=args.vae_encoder_tiled_size, decoder_tile_size=args.vae_decoder_tiled_size) # For mixed precision training we cast the text_encoder and vae weights to half-precision # as these models are only used for inference, keeping weights in full precision is not required. weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 # Move text_encode and vae to gpu and cast to weight_dtype text_encoder.to(accelerator.device, dtype=weight_dtype) vae.to(accelerator.device, dtype=weight_dtype) unet.to(accelerator.device, dtype=weight_dtype) controlnet.to(accelerator.device, dtype=weight_dtype) return validation_pipeline def load_tag_model(args, device='cuda'): model = ram(pretrained='preset/models/ram_swin_large_14m.pth', pretrained_condition=args.ram_ft_path, image_size=384, vit='swin_l') model.eval() model.to(device) return model def get_validation_prompt(args, image, model, device='cuda'): validation_prompt = "" lq = tensor_transforms(image).unsqueeze(0).to(device) lq = ram_transforms(lq)
res = inference(lq, model)
4
2023-11-27 08:50:33+00:00
24k
xmu-xiaoma666/X-Dreamer
train_x_dreamer.py
[ { "identifier": "DatasetMesh", "path": "dataset/dataset_mesh.py", "snippet": "class DatasetMesh(torch.utils.data.Dataset):\n\n\n def __init__(self, glctx, FLAGS, validate=False, gif=False):\n # Init \n self.glctx = glctx\n self.FLAGS = FLAGS\n self.validate = validate\n self.gif = gif\n self.aspect = FLAGS.train_res[1] / FLAGS.train_res[0]\n self.fovy_range_min = np.deg2rad(FLAGS.fovy_range[0])\n self.fovy_range_max = np.deg2rad(FLAGS.fovy_range[1])\n self.elevation_range_min= np.deg2rad(FLAGS.elevation_range[0])\n self.elevation_range_max= np.deg2rad(FLAGS.elevation_range[1])\n self.angle_front = np.deg2rad(FLAGS.front_threshold)\n \n\n def _gif_scene(self, itr):\n fovy = np.deg2rad(45)\n proj_mtx = util.perspective(fovy, self.FLAGS.display_res[1] / self.FLAGS.display_res[0], self.FLAGS.cam_near_far[0], self.FLAGS.cam_near_far[1])\n ang = (itr / 100) * np.pi * 2\n rotate_x = np.deg2rad(20)\n prompt_index = 0\n mv = util.translate(0, 0, -3) @ (util.rotate_x(-rotate_x) @ util.rotate_y(ang ))\n normal_rotate = util.rotate_y_1(0)\n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n\n return mv[None, ...], mvp[None, ...], campos[None, ...], self.FLAGS.display_res, self.FLAGS.spp, normal_rotate[None,...], prompt_index, np.rad2deg(rotate_x), np.rad2deg(ang), torch.tensor([fovy])\n \n \n\n def _validate_scene(self, itr):\n fovy = np.deg2rad(45)\n proj_mtx = util.perspective(fovy, self.FLAGS.train_res[1] / self.FLAGS.train_res[0], self.FLAGS.cam_near_far[0], self.FLAGS.cam_near_far[1])\n ang = (itr / 4) * np.pi * 2\n rotate_x = np.random.uniform(-np.pi/4,np.pi/18)\n prompt_index = 0\n mv = util.translate(0, 0, -3) @ (util.rotate_x(rotate_x) @ util.rotate_y( ang ))\n normal_rotate = util.rotate_y_1(0)\n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n return mv[None, ...], mvp[None, ...], campos[None, ...], self.FLAGS.display_res, self.FLAGS.spp, normal_rotate[None,...], prompt_index, np.rad2deg(rotate_x), np.rad2deg(ang), torch.tensor([fovy])\n\n def _train_scene(self, itr):\n fovy = np.random.uniform(self.fovy_range_min, self.fovy_range_max)\n proj_mtx = util.perspective(fovy, self.FLAGS.train_res[1] / self.FLAGS.train_res[0], self.FLAGS.cam_near_far[0], self.FLAGS.cam_near_far[1])\n if self.FLAGS.gpu_number == 8: # All the results in the paper were generated using 8 3090 GPUs. We cannot guarantee that fewer than 8 GPUs can achieve the same effect.\n if self.FLAGS.local_rank in [0,4]:\n rotate_y = np.random.uniform(np.deg2rad(-45), np.deg2rad(45))\n elif self.FLAGS.local_rank in [1,5]:\n rotate_y = np.random.uniform(np.deg2rad(45), np.deg2rad(135))\n elif self.FLAGS.local_rank in [2,6]:#back\n rotate_y = np.random.uniform( np.deg2rad(135), np.deg2rad(225))\n elif self.FLAGS.local_rank in [3,7]:\n rotate_y = np.random.uniform(np.deg2rad(-135), np.deg2rad(-45)) \n if rotate_y > np.pi:\n rotate_y = rotate_y - np.pi*2\n elif self.FLAGS.gpu_number == 4: #All the results in the paper were generated using 8 3090 GPUs. We cannot guarantee that fewer than 8 GPUs can achieve the same effect.\n if self.FLAGS.local_rank in [0]:\n rotate_y = np.random.uniform(np.deg2rad(-45), np.deg2rad(45))\n elif self.FLAGS.local_rank in [1]:\n rotate_y = np.random.uniform(np.deg2rad(45), np.deg2rad(135))\n elif self.FLAGS.local_rank in [2]:#back\n rotate_y = np.random.uniform( np.deg2rad(135), np.deg2rad(225))\n elif self.FLAGS.local_rank in [3]:\n rotate_y = np.random.uniform(np.deg2rad(-135), np.deg2rad(-45)) \n if rotate_y > np.pi:\n rotate_y = rotate_y - np.pi*2\n else:\n rotate_y = np.random.uniform(np.deg2rad(-180), np.deg2rad(180)) #All the results in the paper were generated using 8 3090 GPUs. We cannot guarantee that fewer than 8 GPUs can achieve the same effect.\n \n rotate_x = -np.random.uniform(self.elevation_range_min, self.elevation_range_max)\n # angle_front = np.deg2rad(45)\n prompt_index = get_view_direction(thetas= rotate_x, phis = rotate_y, front= self.angle_front)\n cam_radius = 3\n x = np.random.uniform(-self.FLAGS.camera_random_jitter, self.FLAGS.camera_random_jitter)\n y = np.random.uniform(-self.FLAGS.camera_random_jitter, self.FLAGS.camera_random_jitter)\n mv = util.translate(x, y, -cam_radius) @ (util.rotate_x(rotate_x) @ util.rotate_y(rotate_y))\n if ((itr+1)/self.FLAGS.batch) <=self.FLAGS.coarse_iter:\n rotate_y1 = np.random.uniform(0,np.pi*2) \n rotate_x1 = np.random.uniform(-np.pi,np.pi)\n normal_rotate = util.rotate_y_1(rotate_y1 )@ util.rotate_x_1(rotate_x1) \n else:\n normal_rotate = util.rotate_y_1(0)@util.rotate_x_1(0)\n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n return mv[None, ...], mvp[None, ...], campos[None, ...], self.FLAGS.display_res, self.FLAGS.spp, normal_rotate[None,...], prompt_index, np.rad2deg(rotate_x), np.rad2deg(rotate_y), torch.tensor([fovy])\n\n def __len__(self):\n if self.gif == True:\n return 100\n else:\n return 4 if self.validate else (self.FLAGS.iter + 1) * self.FLAGS.batch\n\n def __getitem__(self, itr):\n if self.gif:\n mv, mvp, campos, iter_res, iter_spp, normal_rotate, prompt_index, elev, azim, fov = self._gif_scene(itr)\n elif self.validate:\n mv, mvp, campos, iter_res, iter_spp, normal_rotate, prompt_index, elev, azim, fov = self._validate_scene(itr)\n else:\n mv, mvp, campos, iter_res, iter_spp, normal_rotate, prompt_index, elev, azim, fov = self._train_scene(itr)\n\n return {\n 'mv' : mv,\n 'mvp' : mvp,\n 'campos' : campos,\n 'resolution' : iter_res,\n 'spp' : iter_spp,\n 'normal_rotate': normal_rotate,\n 'prompt_index' : prompt_index,\n 'elev': elev,\n 'azim': azim,\n 'fov': fov\n }\n def collate(self, batch):\n iter_res, iter_spp = batch[0]['resolution'], batch[0]['spp']\n return {\n 'mv' : torch.cat(list([item['mv'] for item in batch]), dim=0),\n 'mvp' : torch.cat(list([item['mvp'] for item in batch]), dim=0),\n 'campos' : torch.cat(list([item['campos'] for item in batch]), dim=0),\n 'resolution' : iter_res,\n 'spp' : iter_spp,\n 'normal_rotate' : torch.cat(list([item['normal_rotate'] for item in batch]), dim=0),\n # 'prompt_index' : torch.cat(list([item['prompt_index'] for item in batch]), dim=0),\n 'prompt_index' : np.array([item['prompt_index'] for item in batch], dtype=np.int32),\n 'elev' : np.array([item['elev'] for item in batch], dtype=np.float16),\n 'azim' : np.array([item['azim'] for item in batch], dtype=np.float16),\n 'fov' : torch.cat(list([item['fov'] for item in batch]), dim=0),\n }" }, { "identifier": "get_camera_params", "path": "dataset/dataset_mesh.py", "snippet": "def get_camera_params(resolution= 512, fov=45, elev_angle=-20, azim_angle=0):\n fovy = np.deg2rad(fov) \n elev = np.radians( elev_angle )\n azim = np.radians( azim_angle ) \n proj_mtx = util.perspective(fovy, resolution /resolution, 1, 50)\n mv = util.translate(0, 0, -3) @ (util.rotate_x(elev) @ util.rotate_y(azim))\n normal_rotate = util.rotate_y_1(-azim ) @ util.rotate_x_1(-elev) \n # nomral_rotate = util.rotate_y_1(0) @ util.rotate_x_1(0) \n mvp = proj_mtx @ mv\n campos = torch.linalg.inv(mv)[:3, 3]\n bkgs = torch.ones(1, resolution, resolution, 3, dtype=torch.float32, device='cuda')\n return {\n 'mvp' : mvp[None, ...].cuda(),\n 'mv' : mv[None, ...].cuda(),\n 'campos' : campos[None, ...].cuda(),\n 'resolution' : [resolution, resolution], \n 'spp' : 1,\n 'background' : bkgs,\n 'normal_rotate' : normal_rotate[None,...].cuda(),\n 'elev_angle' : torch.tensor(elev_angle).cuda(),\n 'azim_angle' : torch.tensor(azim_angle).cuda(),\n 'fov' : torch.tensor(fovy).cuda(),\n }" }, { "identifier": "DMTetGeometry", "path": "geometry/dmtet_x_dreamer.py", "snippet": "class DMTetGeometry(torch.nn.Module):\n def __init__(self, grid_res, scale, FLAGS):\n super(DMTetGeometry, self).__init__()\n\n self.FLAGS = FLAGS\n self.grid_res = grid_res\n self.marching_tets = DMTet()\n \n tets = np.load('data/tets/{}_tets.npz'.format(self.grid_res))\n self.verts = torch.tensor(tets['vertices'], dtype=torch.float32, device='cuda') * scale\n print(\"tet grid min/max\", torch.min(self.verts).item(), torch.max(self.verts).item())\n self.decoder = Decoder(multires=0 , AABB= self.getAABB(), mesh_scale= scale)\n self.indices = torch.tensor(tets['indices'], dtype=torch.long, device='cuda')\n self.generate_edges()\n self.pos_encoder = CameraEncoder().to(self.verts.device)\n\n def generate_edges(self):\n with torch.no_grad():\n edges = torch.tensor([0,1,0,2,0,3,1,2,1,3,2,3], dtype = torch.long, device = \"cuda\")\n all_edges = self.indices[:,edges].reshape(-1,2) \n all_edges_sorted = torch.sort(all_edges, dim=1)[0]\n self.all_edges = torch.unique(all_edges_sorted, dim=0)\n\n @torch.no_grad()\n def getAABB(self):\n return torch.min(self.verts, dim=0).values, torch.max(self.verts, dim=0).values\n\n def getMesh(self, material):\n pred= self.decoder(self.verts)\n \n self.sdf , self.deform = pred[:, 0], pred[:, 1:] \n v_deformed = self.verts + 1 / (self.grid_res ) * torch.tanh(self.deform)\n verts, faces = self.marching_tets(v_deformed, self.sdf, self.indices)\n \n imesh = mesh.Mesh(verts, faces, material=material)\n imesh = mesh.auto_normals(imesh)\n return imesh\n\n def render(self, glctx, target, lgt, opt_material, bsdf=None, if_normal=False, mode = 'geometry_modeling', if_flip_the_normal = False, if_use_bump = False):\n opt_mesh = self.getMesh(opt_material) \n return render.render_mesh(glctx, \n opt_mesh, \n target['mvp'], \n target['campos'], \n lgt, \n target['resolution'], \n spp=target['spp'], \n msaa= True,\n background= target['background'],\n bsdf= bsdf,\n if_normal= if_normal,\n normal_rotate= target['normal_rotate'],\n mode = mode,\n if_flip_the_normal = if_flip_the_normal,\n if_use_bump = if_use_bump\n )\n\n \n def tick(self, glctx, target, lgt, opt_material, iteration, if_normal, guidance, mode, if_flip_the_normal, if_use_bump):\n # ==============================================================================================\n # Render optimizable object with identical conditions\n # ==============================================================================================\n buffers= self.render(glctx, target, lgt, opt_material, if_normal= if_normal, mode = mode, if_flip_the_normal = if_flip_the_normal, if_use_bump = if_use_bump)\n if self.FLAGS.add_directional_text:\n text_embeddings = torch.cat([guidance.uncond_z[target['prompt_index']], guidance.text_z[target['prompt_index']]]) # [B*2, 77, 1024]\n indexs = torch.cat([guidance.uncond_index[target['prompt_index']], guidance.index[target['prompt_index']]]) # [B*2, 77, 1024]\n else:\n text_embeddings = torch.cat([guidance.uncond_z, guidance.text_z]) # [B * 2, 77, 1024]\n indexs = torch.cat([guidance.uncond_index, guidance.index]) # [B*2, 77, 1024]\n\n \n if iteration <=self.FLAGS.coarse_iter:\n t = torch.randint( guidance.min_step_early, guidance.max_step_early + 1, [self.FLAGS.batch], dtype=torch.long, device='cuda') # [B]\n pred_rgb_512 = buffers['shaded'][..., 0:4].permute(0, 3, 1, 2).contiguous() # [B, 4, 64, 64]\n latents = F.interpolate(pred_rgb_512, (64, 64), mode='bilinear', align_corners=False)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n \n else:\n t = torch.randint(guidance.min_step_late, guidance.max_step_late + 1, [self.FLAGS.batch], dtype=torch.long, device='cuda')\n srgb = buffers['shaded'][...,0:3] #* buffers['shaded'][..., 3:4] # normal * mask\n # \n pred_rgb_512 = srgb.permute(0, 3, 1, 2).contiguous() # [B, 3, 512, 512]\n latents = guidance.encode_imgs(pred_rgb_512)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n\n ### calculate camera pos feature\n came_pos = torch.cat([target['campos'],torch.from_numpy(target['elev']).unsqueeze(-1).cuda(),torch.from_numpy(target['azim']).cuda().unsqueeze(-1),target['fov'].unsqueeze(-1)],dim=-1)\n came_pos = torch.cat([came_pos,came_pos],dim=0) #bs*2, 5\n came_pos = normalize_camera(came_pos,self.FLAGS)\n came_posfeat = self.pos_encoder(came_pos)\n\n # add noise\n noise = torch.randn_like(latents)\n latents_noisy = guidance.scheduler.add_noise(latents, noise, t)\n # pred noise\n latent_model_input = torch.cat([latents_noisy] * 2)\n tt = torch.cat([t] * 2)\n noise_pred, attention_map = guidance.unet(latent_model_input, tt, encoder_hidden_states=text_embeddings, index=indexs, came_posfeat=came_posfeat)\n noise_pred = noise_pred.sample\n\n attention_map[0] = attention_map[0].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n attention_map[1] = attention_map[1].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[2] = attention_map[2].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[3] = attention_map[3].reshape(self.FLAGS.batch*2, 8 , 8 ).contiguous()\n attention_map[4] = attention_map[4].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[5] = attention_map[5].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[6] = attention_map[6].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred =noise_pred_uncond + guidance.guidance_weight * (noise_pred_text - noise_pred_uncond) # [B, 4, 64, 64]\n if iteration <= self.FLAGS.coarse_iter:\n w = (1 - guidance.alphas[t]) # [B]\n else:\n w = guidance.alphas[t] ** 0.5 * (1 - guidance.alphas[t])\n w = w[:, None, None, None] # [B, 1, 1, 1]\n grad = w * (noise_pred - noise ) #*w1\n grad = torch.nan_to_num(grad)\n \n sds_loss = SpecifyGradient.apply(latents, grad) \n img_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n reg_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n\n attention_loss = 0\n mask_sizes = [(64, 64), (32,32), (16,16), (8,8), (16,16), (32,32), (64,64)]\n for i in range(7):\n _, attention_map_text = attention_map[i].chunk(2)\n if(self.FLAGS.batch==1):\n mask2 = F.interpolate(mask2.unsqueeze(0).unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n else:\n mask2 = F.interpolate(mask2.unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n attention_map_text = (attention_map_text - attention_map_text.min())/(attention_map_text.max() - attention_map_text.min()+1e-6)\n attention_map_text = F.interpolate(attention_map_text.unsqueeze(0), size=mask_sizes[i], mode='bilinear', align_corners=False).squeeze()\n attention_loss = 0.1*F.l1_loss(mask2.float(), attention_map_text.float(), reduction=\"mean\") #0.1 1 10\n attention_loss = attention_loss/7\n \n return sds_loss, img_loss, reg_loss, attention_loss" }, { "identifier": "DLMesh", "path": "geometry/dlmesh_x_dreamer.py", "snippet": "class DLMesh(torch.nn.Module):\n def __init__(self, initial_guess, FLAGS):\n super(DLMesh, self).__init__()\n self.FLAGS = FLAGS\n self.initial_guess = initial_guess\n self.mesh = initial_guess.clone()\n self.pos_encoder = CameraEncoder().cuda()\n print(\"Base mesh has %d triangles and %d vertices.\" % (self.mesh.t_pos_idx.shape[0], self.mesh.v_pos.shape[0]))\n \n @torch.no_grad()\n def getAABB(self):\n return mesh.aabb(self.mesh)\n\n def getMesh(self, material):\n self.mesh.material = material\n\n imesh = mesh.Mesh(base=self.mesh)\n # Compute normals and tangent space\n imesh = mesh.auto_normals(imesh)\n imesh = mesh.compute_tangents(imesh)\n return imesh\n\n def render(self, glctx, target, lgt, opt_material, bsdf=None,if_normal=False, mode = 'appearance_modeling', if_flip_the_normal = False, if_use_bump = False):\n opt_mesh = self.getMesh(opt_material)\n return render.render_mesh(glctx, \n opt_mesh,\n target['mvp'],\n target['campos'],\n lgt,\n target['resolution'], \n spp=target['spp'], \n msaa=True,\n background= target['background'] ,\n bsdf= bsdf,\n if_normal=if_normal,\n normal_rotate=target['normal_rotate'], \n mode = mode,\n if_flip_the_normal = if_flip_the_normal,\n if_use_bump = if_use_bump\n )\n\n def tick(self, glctx, target, lgt, opt_material, iteration, if_normal, guidance, mode, if_flip_the_normal, if_use_bump):\n # ==============================================================================================\n # Render optimizable object with identical conditions\n # ==============================================================================================\n buffers= self.render(glctx, target, lgt, opt_material, if_normal = if_normal, mode = mode, if_flip_the_normal = if_flip_the_normal, if_use_bump = if_use_bump)\n if self.FLAGS.add_directional_text:\n text_embeddings = torch.cat([guidance.uncond_z[target['prompt_index']], guidance.text_z[target['prompt_index']]])\n indexs = torch.cat([guidance.uncond_index[target['prompt_index']], guidance.index[target['prompt_index']]]) # [B*2, 77, 1024]\n else:\n text_embeddings = torch.cat([guidance.uncond_z, guidance.text_z])\n indexs = torch.cat([guidance.uncond_index, guidance.index]) # [B*2, 77, 1024]\n\n\n if iteration <= self.FLAGS.coarse_iter:\n srgb = buffers['shaded'][...,0:3]\n srgb = util.rgb_to_srgb(srgb)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n t = torch.randint( guidance.min_step_early, guidance.max_step_early+1, [self.FLAGS.batch], dtype=torch.long, device='cuda') # [B]\n else:\n srgb = buffers['shaded'][...,0:3]\n srgb = util.rgb_to_srgb(srgb)\n mask = (buffers['shaded'][..., 3:4]).permute(0, 3, 1, 2).contiguous()\n mask2 = mask.squeeze()\n t = torch.randint( guidance.min_step_late, guidance.max_step_late+1, [self.FLAGS.batch], dtype=torch.long, device='cuda') # [B]\n\n pred_rgb_512 = srgb.permute(0, 3, 1, 2).contiguous() # [1, 3, H, W]\n latents = guidance.encode_imgs(pred_rgb_512)\n \n ### calculate camera pos feature\n came_pos = torch.cat([target['campos'],torch.from_numpy(target['elev']).unsqueeze(-1).cuda(),torch.from_numpy(target['azim']).cuda().unsqueeze(-1),target['fov'].unsqueeze(-1)],dim=-1)\n came_pos = torch.cat([came_pos,came_pos],dim=0) #bs*2, 5\n came_pos = normalize_camera(came_pos,self.FLAGS)\n came_posfeat = self.pos_encoder(came_pos)\n\n\n # add noise\n noise = torch.randn_like(latents)\n latents_noisy = guidance.scheduler.add_noise(latents, noise, t)\n # pred noise\n latent_model_input = torch.cat([latents_noisy] * 2)\n tt = torch.cat([t] * 2)\n noise_pred, attention_map = guidance.unet(latent_model_input, tt, encoder_hidden_states= text_embeddings, index=indexs, came_posfeat=came_posfeat)#.sample######################\n noise_pred = noise_pred.sample\n\n attention_map[0] = attention_map[0].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n attention_map[1] = attention_map[1].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[2] = attention_map[2].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[3] = attention_map[3].reshape(self.FLAGS.batch*2, 8 , 8 ).contiguous()\n attention_map[4] = attention_map[4].reshape(self.FLAGS.batch*2, 16, 16).contiguous()\n attention_map[5] = attention_map[5].reshape(self.FLAGS.batch*2, 32, 32).contiguous()\n attention_map[6] = attention_map[6].reshape(self.FLAGS.batch*2, 64, 64).contiguous()\n\n noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n noise_pred = noise_pred_uncond + guidance.guidance_weight * (noise_pred_text - noise_pred_uncond)\n \n if guidance.sds_weight_strategy == 0:\n w = guidance.alphas[t] ** 0.5 * (1 - guidance.alphas[t])\n elif guidance.sds_weight_strategy == 1:\n w = 1 / (1 - guidance.alphas[t])\n elif guidance.sds_weight_strategy == 2:\n if iteration <= self.FLAGS.coarse_iter:\n w = guidance.alphas[t] ** 0.5 * (1 - guidance.alphas[t])\n else:\n w = 1 / (1 - guidance.alphas[t])\n w = w[:, None, None, None] # [B, 1, 1, 1]\n grad = w* (noise_pred -noise) \n grad = torch.nan_to_num(grad)\n sds_loss = SpecifyGradient.apply(latents, grad) \n img_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n reg_loss = torch.tensor([0], dtype=torch.float32, device=\"cuda\")\n \n attention_loss = 0\n mask_sizes = [(64, 64), (32,32), (16,16), (8,8), (16,16), (32,32), (64,64)]\n for i in range(7):\n _, attention_map_text = attention_map[i].chunk(2)\n if(self.FLAGS.batch==1):\n mask2 = F.interpolate(mask2.unsqueeze(0).unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n else:\n mask2 = F.interpolate(mask2.unsqueeze(0), mask_sizes[i], mode='bilinear').squeeze()\n attention_map_text = (attention_map_text - attention_map_text.min())/(attention_map_text.max() - attention_map_text.min()+1e-6)\n attention_map_text = F.interpolate(attention_map_text.unsqueeze(0), size=mask2.shape, mode='bilinear', align_corners=False).squeeze()\n attention_loss = 0.1*F.l1_loss(mask2.float(), attention_map_text.float(), reduction=\"mean\") #0.1 1 10\n attention_loss = attention_loss/7\n \n return sds_loss, img_loss, reg_loss, attention_loss" }, { "identifier": "obj", "path": "render/obj.py", "snippet": "def _find_mat(materials, name):\ndef load_obj(filename, clear_ks=True, mtl_override=None):\ndef write_obj(folder, mesh, save_material=True):" }, { "identifier": "material", "path": "render/material.py", "snippet": "class Material(torch.nn.Module):\n def __init__(self, mat_dict):\n def __contains__(self, key):\n def __getitem__(self, key):\n def __setitem__(self, key, val):\n def __delitem__(self, key):\n def keys(self):\ndef load_mtl(fn, clear_ks=True):\ndef save_mtl(fn, material):\ndef _upscale_replicate(x, full_res):\ndef merge_materials(materials, texcoords, tfaces, mfaces):" }, { "identifier": "util", "path": "render/util.py", "snippet": "def dot(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\ndef reflect(x: torch.Tensor, n: torch.Tensor) -> torch.Tensor:\ndef length(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef safe_normalize(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef to_hvec(x: torch.Tensor, w: float) -> torch.Tensor:\ndef _rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef _srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef reinhard(f: torch.Tensor) -> torch.Tensor:\ndef mse_to_psnr(mse):\ndef psnr_to_mse(psnr):\ndef get_miplevels(texture: np.ndarray) -> float:\ndef tex_2d(tex_map : torch.Tensor, coords : torch.Tensor, filter='nearest') -> torch.Tensor:\ndef cube_to_dir(s, x, y):\ndef latlong_to_cubemap(latlong_map, res):\ndef cubemap_to_latlong(cubemap, res):\ndef scale_img_hwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef scale_img_nhwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef avg_pool_nhwc(x : torch.Tensor, size) -> torch.Tensor:\ndef segment_sum(data: torch.Tensor, segment_ids: torch.Tensor) -> torch.Tensor:\ndef fovx_to_fovy(fovx, aspect):\ndef focal_length_to_fovy(focal_length, sensor_height):\ndef perspective(fovy=0.7854, aspect=1.0, n=0.1, f= 1000.0, device=None):\ndef perspective_offcenter(fovy, fraction, rx, ry, aspect=1.0, n=0.1, f=1000.0, device=None):\ndef translate(x, y, z, device=None):\ndef rotate_x(a, device=None):\ndef rotate_x_1(a, device=None):\ndef rotate_y(a, device=None):\ndef rotate_y_1(a, device=None):\ndef rotate_y_2(a, device=None):\ndef rotate_x_2(a, device=None):\ndef scale(s, device=None):\ndef lookAt(eye, at, up):\ndef random_rotation_translation(t, device=None):\ndef random_rotation(device=None):\ndef lines_focal(o, d):\ndef cosine_sample(N, size=None):\ndef bilinear_downsample(x : torch.tensor) -> torch.Tensor:\ndef bilinear_downsample(x : torch.tensor, spp) -> torch.Tensor:\ndef init_glfw():\ndef save_image(fn, x : np.ndarray):\ndef save_image_raw(fn, x : np.ndarray):\ndef load_image_raw(fn) -> np.ndarray:\ndef load_image(fn) -> np.ndarray:\ndef time_to_text(x):\ndef checkerboard(res, checker_size) -> np.ndarray:\ndef get_random_bg(h, w):\n R, L = aspect*y, -aspect*y\n T, B = y, -y\n I = torch.eye(3, dtype=o.dtype, device=o.device)\n S = torch.sum(d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...], dim=0)\n C = torch.sum((d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...]) @ o[..., None], dim=0).squeeze(1)\n N = N/torch.linalg.norm(N)" }, { "identifier": "mesh", "path": "render/mesh.py", "snippet": "class Mesh:\n def __init__(self, v_pos=None, t_pos_idx=None, v_nrm=None, t_nrm_idx=None, v_tex=None, t_tex_idx=None, v_tng=None, t_tng_idx=None, material=None, base=None):\n def copy_none(self, other):\n def clone(self):\ndef load_mesh(filename, mtl_override=None):\ndef aabb(mesh):\ndef compute_edges(attr_idx, return_inverse=False):\ndef compute_edge_to_face_mapping(attr_idx, return_inverse=False):\ndef unit_size(mesh):\ndef center_by_reference(base_mesh, ref_aabb, scale):\ndef auto_normals(imesh):\ndef compute_tangents(imesh):" }, { "identifier": "texture", "path": "render/texture.py", "snippet": "class texture2d_mip(torch.autograd.Function):\nclass Texture2D(torch.nn.Module):\n def forward(ctx, texture):\n def backward(ctx, dout):\n def __init__(self, init, min_max=None):\n def sample(self, texc, texc_deriv, filter_mode='linear-mipmap-linear'):\n def getRes(self):\n def getChannels(self):\n def getMips(self):\n def clamp_(self):\n def normalize_(self):\ndef create_trainable(init, res=None, auto_mipmaps=True, min_max=None):\ndef srgb_to_rgb(texture):\ndef rgb_to_srgb(texture):\ndef _load_mip2D(fn, lambda_fn=None, channels=None):\ndef load_texture2D(fn, lambda_fn=None, channels=None):\ndef _save_mip2D(fn, mip, mipidx, lambda_fn):\ndef save_texture2D(fn, tex, lambda_fn=None):" }, { "identifier": "mlptexture", "path": "render/mlptexture.py", "snippet": "class _MLP(torch.nn.Module):\nclass MLPTexture3D(torch.nn.Module):\n def __init__(self, cfg, loss_scale=1.0):\n def forward(self, x):\n def _init_weights(m):\n def __init__(self, AABB, channels = 3, internal_dims = 32, hidden = 1, min_max = None):\n def sample(self, texc):\n def clamp_(self):\n def cleanup(self):" }, { "identifier": "light", "path": "render/light.py", "snippet": "class cubemap_mip(torch.autograd.Function):\nclass EnvironmentLight(torch.nn.Module):\n def forward(ctx, cubemap):\n def backward(ctx, dout):\n def __init__(self, base):\n def xfm(self, mtx):\n def clone(self):\n def clamp_(self, min=None, max=None):\n def get_mip(self, roughness):\n def build_mips(self, cutoff=0.99):\n def regularizer(self):\n def shade(self, gb_pos, gb_normal, kd, ks, view_pos, specular=True):\ndef _load_env_hdr(fn, scale=1.0):\ndef load_env(fn, scale=1.0):\ndef save_env_map(fn, light):\ndef create_trainable_env_rnd(base_res, scale=0.5, bias=0.25):\n LIGHT_MIN_RES = 16\n MIN_ROUGHNESS = 0.08\n MAX_ROUGHNESS = 0.5" }, { "identifier": "render", "path": "render/render.py", "snippet": "def interpolate(attr, rast, attr_idx, rast_db=None):\ndef shade(\n gb_pos,\n gb_geometric_normal,\n gb_normal,\n gb_tangent,\n gb_texc,\n gb_texc_deriv,\n view_pos,\n lgt,\n material,\n bsdf,\n if_normal,\n normal_rotate,\n mode,\n if_flip_the_normal,\n if_use_bump\n ):\ndef render_layer(\n rast,\n rast_deriv,\n mesh,\n view_pos,\n lgt,\n resolution,\n spp,\n msaa,\n bsdf,\n if_normal,\n normal_rotate,\n mode,\n if_flip_the_normal,\n if_use_bump\n ):\ndef render_mesh(\n ctx,\n mesh,\n mtx_in,\n view_pos,\n lgt,\n resolution,\n spp = 1,\n num_layers = 1,\n msaa = False,\n background = None, \n bsdf = None,\n if_normal = False,\n normal_rotate = None,\n mode = 'geometry_modeling',\n if_flip_the_normal = False,\n if_use_bump = False\n ):\n def prepare_input_vector(x):\n def composite_buffer(key, layers, background, antialias):\ndef render_uv(ctx, mesh, resolution, mlp_texture):\ndef uv_padding(image, hole_mask, padding = 2, uv_padding_block = 4):\ndef render_uv1(ctx, mesh, resolution, mlp_texture, uv_padding_block):" }, { "identifier": "StableDiffusion", "path": "sd_cglora.py", "snippet": "class StableDiffusion(nn.Module):\n def __init__(self, \n device, \n mode='geometry', \n text= '', \n add_directional_text= False, \n batch = 1, \n guidance_weight = 100, \n sds_weight_strategy = 0,\n early_time_step_range = [0.02, 0.5],\n late_time_step_range = [0.02, 0.5]):\n super().__init__()\n\n self.device = device\n self.mode = mode\n self.text= text\n self.add_directional_text = add_directional_text\n self.batch = batch \n print(f'[INFO] loading stable diffusion...')\n model_key = \"stabilityai/stable-diffusion-2-1-base\"\n self.vae = AutoencoderKL.from_pretrained(model_key, subfolder=\"vae\",torch_dtype=torch.float16).to(self.device)\n self.tokenizer = CLIPTokenizer.from_pretrained(model_key, subfolder=\"tokenizer\",torch_dtype=torch.float16)\n self.text_encoder = CLIPTextModel.from_pretrained(model_key, subfolder=\"text_encoder\",torch_dtype=torch.float16).to(self.device)\n self.unet = UNet2DConditionModel.from_pretrained(model_key, subfolder=\"unet\",torch_dtype=torch.float16).to(self.device)\n if is_xformers_available():\n self.unet.enable_xformers_memory_efficient_attention()\n self.negative_text = ''\n if add_directional_text:\n self.text_z = []\n self.uncond_z = []\n self.index = []\n self.uncond_index = []\n for d in ['front', 'side', 'back', 'side']:\n text = f\"{self.text}, {d} view\"\n # text = f\"{d} view of {self.text}\"\n negative_text = f\"{self.negative_text}\"\n # if d == 'back': negative_text += \"face\"\n text_z, index = self.get_text_embeds([text], batch = 1)\n uncond_z, uncond_index =self.get_uncond_embeds([negative_text], batch = 1)\n self.text_z.append(text_z)\n self.uncond_z.append(uncond_z)\n self.index.append(index)\n self.uncond_index.append(uncond_index)\n self.text_z = torch.cat(self.text_z)\n self.uncond_z = torch.cat(self.uncond_z)\n self.index = torch.cat(self.index)\n self.uncond_index = torch.cat(self.uncond_index)\n else: \n self.text_z, self.index = self.get_text_embeds([self.text], batch = self.batch)\n self.uncond_z =self.get_uncond_embeds([self.negative_text], batch = self.batch)\n # del self.text_encoder\n self.scheduler = DPMSolverMultistepScheduler.from_pretrained(model_key, subfolder=\"scheduler\", torch_dtype=torch.float16)\n self.num_train_timesteps = self.scheduler.config.num_train_timesteps\n self.min_step_early = int(self.num_train_timesteps * early_time_step_range[0])\n self.max_step_early = int(self.num_train_timesteps * early_time_step_range[1])\n self.min_step_late = int(self.num_train_timesteps * late_time_step_range[0])\n self.max_step_late = int(self.num_train_timesteps * late_time_step_range[1])\n self.alphas = self.scheduler.alphas_cumprod.to(self.device) # for convenience\n self.guidance_weight = guidance_weight\n self.sds_weight_strategy = sds_weight_strategy\n print(f'[INFO] loaded stable diffusion!')\n\n for p in self.parameters():\n p.requires_grad_(False)\n self.unet_lora_params, self.names = inject_trainable_cglora(self.unet) # This will\n\n\n def get_text_embeds_global(self, prompt, batch=1):\n text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt')\n with torch.no_grad():\n text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]\n if batch > 1:\n text_embeddings = text_embeddings.repeat(batch, 1, 1)\n \n global_embedding = text_embeddings[:,text_input['input_ids'].argmax(dim=-1),:].squeeze()\n \n return global_embedding\n\n\n def get_text_embeds(self, prompt, batch=1):\n text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt')\n with torch.no_grad():\n text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]\n if batch > 1:\n text_embeddings = text_embeddings.repeat(batch, 1, 1)\n ###################################################################\n index = text_input['input_ids'].argmax(dim=-1)\n #global_embedding = text_embeddings[:, index, :].squeeze()\n ##################################################################\n \n return text_embeddings, index\n \n def get_uncond_embeds(self, negative_prompt, batch):\n uncond_input = self.tokenizer(negative_prompt, padding='max_length', max_length=self.tokenizer.model_max_length, return_tensors='pt')\n with torch.no_grad():\n uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]\n \n if batch > 1:\n uncond_embeddings = uncond_embeddings.repeat(batch, 1, 1)\n ###################################################################\n index = uncond_input['input_ids'].argmax(dim=-1)\n # global_embedding = uncond_embeddings[:, index, :].squeeze()\n ##################################################################\n return uncond_embeddings,index\n\n def encode_imgs(self, imgs):\n # imgs: [B, 3, H, W]\n if self.mode == 'appearance_modeling':\n \n imgs = 2 * imgs - 1\n\n posterior = self.vae.encode(imgs).latent_dist\n latents = posterior.sample() * 0.18215\n\n return latents" }, { "identifier": "util", "path": "render/util.py", "snippet": "def dot(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\ndef reflect(x: torch.Tensor, n: torch.Tensor) -> torch.Tensor:\ndef length(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef safe_normalize(x: torch.Tensor, eps: float =1e-20) -> torch.Tensor:\ndef to_hvec(x: torch.Tensor, w: float) -> torch.Tensor:\ndef _rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef rgb_to_srgb(f: torch.Tensor) -> torch.Tensor:\ndef _srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef srgb_to_rgb(f: torch.Tensor) -> torch.Tensor:\ndef reinhard(f: torch.Tensor) -> torch.Tensor:\ndef mse_to_psnr(mse):\ndef psnr_to_mse(psnr):\ndef get_miplevels(texture: np.ndarray) -> float:\ndef tex_2d(tex_map : torch.Tensor, coords : torch.Tensor, filter='nearest') -> torch.Tensor:\ndef cube_to_dir(s, x, y):\ndef latlong_to_cubemap(latlong_map, res):\ndef cubemap_to_latlong(cubemap, res):\ndef scale_img_hwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef scale_img_nhwc(x : torch.Tensor, size, mag='bilinear', min='area') -> torch.Tensor:\ndef avg_pool_nhwc(x : torch.Tensor, size) -> torch.Tensor:\ndef segment_sum(data: torch.Tensor, segment_ids: torch.Tensor) -> torch.Tensor:\ndef fovx_to_fovy(fovx, aspect):\ndef focal_length_to_fovy(focal_length, sensor_height):\ndef perspective(fovy=0.7854, aspect=1.0, n=0.1, f= 1000.0, device=None):\ndef perspective_offcenter(fovy, fraction, rx, ry, aspect=1.0, n=0.1, f=1000.0, device=None):\ndef translate(x, y, z, device=None):\ndef rotate_x(a, device=None):\ndef rotate_x_1(a, device=None):\ndef rotate_y(a, device=None):\ndef rotate_y_1(a, device=None):\ndef rotate_y_2(a, device=None):\ndef rotate_x_2(a, device=None):\ndef scale(s, device=None):\ndef lookAt(eye, at, up):\ndef random_rotation_translation(t, device=None):\ndef random_rotation(device=None):\ndef lines_focal(o, d):\ndef cosine_sample(N, size=None):\ndef bilinear_downsample(x : torch.tensor) -> torch.Tensor:\ndef bilinear_downsample(x : torch.tensor, spp) -> torch.Tensor:\ndef init_glfw():\ndef save_image(fn, x : np.ndarray):\ndef save_image_raw(fn, x : np.ndarray):\ndef load_image_raw(fn) -> np.ndarray:\ndef load_image(fn) -> np.ndarray:\ndef time_to_text(x):\ndef checkerboard(res, checker_size) -> np.ndarray:\ndef get_random_bg(h, w):\n R, L = aspect*y, -aspect*y\n T, B = y, -y\n I = torch.eye(3, dtype=o.dtype, device=o.device)\n S = torch.sum(d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...], dim=0)\n C = torch.sum((d[..., None] @ torch.transpose(d[..., None], 1, 2) - I[None, ...]) @ o[..., None], dim=0).squeeze(1)\n N = N/torch.linalg.norm(N)" }, { "identifier": "Video", "path": "render/video.py", "snippet": "class Video():\n def __init__(self, path, name='video_log.mp4', mode='I', fps=30, codec='libx264', bitrate='16M') -> None:\n \n if path[-1] != \"/\":\n path += \"/\"\n \n self.writer = imageio.get_writer(path+name, mode=mode, fps=fps, codec=codec, bitrate=bitrate)\n \n def ready_image(self, image, write_video=True):\n # assuming channels last - as renderer returns it\n if len(image.shape) == 4: \n image = image.squeeze(0)[..., :3].detach().cpu().numpy()\n else:\n image = image[..., :3].detach().cpu().numpy()\n\n image = np.clip(np.rint(image*255.0), 0, 255).astype(np.uint8)\n\n if write_video:\n self.writer.append_data(image)\n\n return image\n\n def close(self):\n self.writer.close()" } ]
import os import time import argparse import json import math import numpy as np import torch import nvdiffrast.torch as dr import itertools import xatlas import open3d as o3d import random import imageio import os.path as osp import pickle from dataset.dataset_mesh import DatasetMesh from dataset.dataset_mesh import get_camera_params from geometry.dmtet_x_dreamer import DMTetGeometry from geometry.dlmesh_x_dreamer import DLMesh from render import obj from render import material from render import util from render import mesh from render import texture from render import mlptexture from render import light from render import render from sd_cglora import StableDiffusion from tqdm import tqdm from render import util from render.video import Video
15,042
parser.add_argument('-bm', '--base-mesh', type=str, default=None) parser.add_argument('--validate', type=bool, default=True) parser.add_argument("--local_rank", type=int, default=0, help="For distributed training: local_rank") parser.add_argument("--seed", type=int, default=42, help="A seed for reproducible training.") parser.add_argument("--add_directional_text", action='store_true', default=False) parser.add_argument('--mode', default='geometry_modeling', choices=['geometry_modeling', 'appearance_modeling']) parser.add_argument('--text', default=None, help="text prompt") parser.add_argument('--sdf_init_shape', default='ellipsoid', choices=['ellipsoid', 'cylinder', 'custom_mesh']) parser.add_argument('--camera_random_jitter', type= float, default=0.4, help="A large value is advantageous for the extension of objects such as ears or sharp corners to grow.") parser.add_argument('--fovy_range', nargs=2, type=float, default=[25.71, 45.00]) parser.add_argument('--elevation_range', nargs=2, type=int, default=[-10, 45], help="The elevatioin range must in [-90, 90].") parser.add_argument("--guidance_weight", type=int, default=100, help="The weight of classifier-free guidance") parser.add_argument("--sds_weight_strategy", type=int, nargs=1, default=0, choices=[0, 1, 2], help="The strategy of the sds loss's weight") parser.add_argument("--translation_y", type= float, nargs=1, default= 0 , help="translation of the initial shape on the y-axis") parser.add_argument("--coarse_iter", type= int, nargs=1, default= 1000 , help="The iteration number of the coarse stage.") parser.add_argument('--early_time_step_range', nargs=2, type=float, default=[0.02, 0.5], help="The time step range in early phase") parser.add_argument('--late_time_step_range', nargs=2, type=float, default=[0.02, 0.5], help="The time step range in late phase") parser.add_argument("--sdf_init_shape_rotate_x", type= int, nargs=1, default= 0 , help="rotation of the initial shape on the x-axis") parser.add_argument("--if_flip_the_normal", action='store_true', default=False , help="Flip the x-axis positive half-axis of Normal. We find this process helps to alleviate the Janus problem.") parser.add_argument("--front_threshold", type= int, nargs=1, default= 45 , help="the range of front view would be [-front_threshold, front_threshold") parser.add_argument("--if_use_bump", type=bool, default= True , help="whether to use perturbed normals during appearing modeling") parser.add_argument("--uv_padding_block", type= int, default= 4 , help="The block of uv padding.") FLAGS = parser.parse_args() FLAGS.mtl_override = None # Override material of model FLAGS.dmtet_grid = 64 # Resolution of initial tet grid. We provide 64, 128 and 256 resolution grids. Other resolutions can be generated with https://github.com/crawforddoran/quartet FLAGS.mesh_scale = 2.1 # Scale of tet grid box. Adjust to cover the model FLAGS.env_scale = 1.0 # Env map intensity multiplier FLAGS.envmap = None # HDR environment probe FLAGS.relight = None # HDR environment probe(relight) FLAGS.display = None # Conf validation window/display. E.g. [{"relight" : <path to envlight>}] FLAGS.camera_space_light = False # Fixed light in camera space. This is needed for setups like ethiopian head where the scanned object rotates on a stand. FLAGS.lock_light = False # Disable light optimization in the second pass FLAGS.lock_pos = False # Disable vertex position optimization in the second pass FLAGS.pre_load = True # Pre-load entire dataset into memory for faster training FLAGS.kd_min = [ 0.0, 0.0, 0.0, 0.0] # Limits for kd FLAGS.kd_max = [ 1.0, 1.0, 1.0, 1.0] FLAGS.ks_min = [ 0.0, 0.08, 0.0] # Limits for ks FLAGS.ks_max = [ 1.0, 1.0, 1.0] FLAGS.nrm_min = [-1.0, -1.0, 0.0] # Limits for normal map FLAGS.nrm_max = [ 1.0, 1.0, 1.0] FLAGS.cam_near_far = [1, 50] FLAGS.learn_light = False FLAGS.gpu_number = 1 FLAGS.sdf_init_shape_scale=[1.0, 1.0, 1.0] FLAGS.multi_gpu = "WORLD_SIZE" in os.environ and int(os.environ["WORLD_SIZE"]) > 1 if FLAGS.multi_gpu: FLAGS.gpu_number = int(os.environ["WORLD_SIZE"]) FLAGS.local_rank = int(os.environ["LOCAL_RANK"]) torch.distributed.init_process_group(backend="nccl", world_size = FLAGS.gpu_number, rank = FLAGS.local_rank) torch.cuda.set_device(FLAGS.local_rank) if FLAGS.config is not None: data = json.load(open(FLAGS.config, 'r')) for key in data: FLAGS.__dict__[key] = data[key] if FLAGS.display_res is None: FLAGS.display_res = FLAGS.train_res if FLAGS.local_rank == 0: print("Config / Flags:") print("---------") for key in FLAGS.__dict__.keys(): print(key, FLAGS.__dict__[key]) print("---------") seed_everything(FLAGS.seed, FLAGS.local_rank) os.makedirs(FLAGS.out_dir, exist_ok=True) glctx = dr.RasterizeCudaContext() # ============================================================================================== # Create data pipeline # ============================================================================================== dataset_train = DatasetMesh(glctx, FLAGS, validate=False) dataset_validate = DatasetMesh(glctx, FLAGS, validate=True) dataset_gif = DatasetMesh(glctx, FLAGS, gif=True) # ============================================================================================== # Create env light with trainable parameters # ============================================================================================== if FLAGS.mode == 'appearance_modeling' and FLAGS.base_mesh is not None: if FLAGS.learn_light: lgt = light.create_trainable_env_rnd(512, scale=0.0, bias=1) else: lgt = light.load_env(FLAGS.envmap, scale=FLAGS.env_scale) else: lgt = None if FLAGS.sdf_init_shape in ['ellipsoid', 'cylinder', 'custom_mesh'] and FLAGS.mode == 'geometry_modeling': if FLAGS.sdf_init_shape == 'ellipsoid': init_shape = o3d.geometry.TriangleMesh.create_sphere(1) elif FLAGS.sdf_init_shape == 'cylinder': init_shape = o3d.geometry.TriangleMesh.create_cylinder(radius=0.75, height=1.2, resolution=20, split=4, create_uv_map=False) elif FLAGS.sdf_init_shape == 'custom_mesh': if FLAGS.base_mesh: init_shape = get_normalize_mesh(FLAGS.base_mesh) else: assert False, "[Error] The path of custom mesh is invalid ! (geometry modeling)" else: assert False, "Invalid init type" vertices = np.asarray(init_shape.vertices) vertices[...,0]=vertices[...,0] * FLAGS.sdf_init_shape_scale[0] vertices[...,1]=vertices[...,1] * FLAGS.sdf_init_shape_scale[1] vertices[...,2]=vertices[...,2] * FLAGS.sdf_init_shape_scale[2] vertices = vertices @ util.rotate_x_2(np.deg2rad(FLAGS.sdf_init_shape_rotate_x)) vertices[...,1]=vertices[...,1] + FLAGS.translation_y init_shape.vertices = o3d.cuda.pybind.utility.Vector3dVector(vertices) points_surface = np.asarray(init_shape.sample_points_poisson_disk(5000).points) init_shape = o3d.t.geometry.TriangleMesh.from_legacy(init_shape) scene = o3d.t.geometry.RaycastingScene() scene.add_triangles(init_shape) scene_and_vertices = [scene, points_surface]
############################################################################### # Mix background into a dataset image ############################################################################### @torch.no_grad() def prepare_batch(target, background= 'black'): target['mv'] = target['mv'].cuda() target['mvp'] = target['mvp'].cuda() target['campos'] = target['campos'].cuda() target['fov'] = target['fov'].cuda() target['normal_rotate'] = target['normal_rotate'].cuda() batch_size = target['mv'].shape[0] resolution = target['resolution'] if background == 'white': target['background']= torch.ones(batch_size, resolution[0], resolution[1], 3, dtype=torch.float32, device='cuda') if background == 'black': target['background'] = torch.zeros(batch_size, resolution[0], resolution[1], 3, dtype=torch.float32, device='cuda') return target ############################################################################### # UV - map geometry & convert to a mesh ############################################################################### @torch.no_grad() def xatlas_uvmap(glctx, geometry, mat, FLAGS): eval_mesh = geometry.getMesh(mat) # Create uvs with xatlas v_pos = eval_mesh.v_pos.detach().cpu().numpy() t_pos_idx = eval_mesh.t_pos_idx.detach().cpu().numpy() vmapping, indices, uvs = xatlas.parametrize(v_pos, t_pos_idx) # Convert to tensors indices_int64 = indices.astype(np.uint64, casting='same_kind').view(np.int64) uvs = torch.tensor(uvs, dtype=torch.float32, device='cuda') faces = torch.tensor(indices_int64, dtype=torch.int64, device='cuda') new_mesh = mesh.Mesh(v_tex=uvs, t_tex_idx=faces, base=eval_mesh) mask, kd, ks, normal = render.render_uv(glctx, new_mesh, FLAGS.texture_res, eval_mesh.material['kd_ks_normal']) if FLAGS.layers > 1: kd = torch.cat((kd, torch.rand_like(kd[...,0:1])), dim=-1) kd_min, kd_max = torch.tensor(FLAGS.kd_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.kd_max, dtype=torch.float32, device='cuda') ks_min, ks_max = torch.tensor(FLAGS.ks_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.ks_max, dtype=torch.float32, device='cuda') nrm_min, nrm_max = torch.tensor(FLAGS.nrm_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.nrm_max, dtype=torch.float32, device='cuda') new_mesh.material = material.Material({ 'bsdf' : mat['bsdf'], 'kd' : texture.Texture2D(kd, min_max=[kd_min, kd_max]), 'ks' : texture.Texture2D(ks, min_max=[ks_min, ks_max]), 'normal' : texture.Texture2D(normal, min_max=[nrm_min, nrm_max]) }) return new_mesh @torch.no_grad() def xatlas_uvmap1(glctx, geometry, mat, FLAGS): eval_mesh = geometry.getMesh(mat) new_mesh = mesh.Mesh( base=eval_mesh) mask, kd, ks, normal = render.render_uv1(glctx, new_mesh, FLAGS.texture_res, eval_mesh.material['kd_ks_normal'], FLAGS.uv_padding_block) if FLAGS.layers > 1: kd = torch.cat((kd, torch.rand_like(kd[...,0:1])), dim=-1) kd_min, kd_max = torch.tensor(FLAGS.kd_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.kd_max, dtype=torch.float32, device='cuda') ks_min, ks_max = torch.tensor(FLAGS.ks_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.ks_max, dtype=torch.float32, device='cuda') nrm_min, nrm_max = torch.tensor(FLAGS.nrm_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.nrm_max, dtype=torch.float32, device='cuda') new_mesh.material = material.Material({ 'bsdf' : mat['bsdf'], 'kd' : texture.Texture2D(kd, min_max=[kd_min, kd_max]), 'ks' : texture.Texture2D(ks, min_max=[ks_min, ks_max]), 'normal' : texture.Texture2D(normal, min_max=[nrm_min, nrm_max]) }) return new_mesh ############################################################################### # Utility functions for material ############################################################################### def get_normalize_mesh(pro_path): mesh = o3d.io.read_triangle_mesh(pro_path) vertices = np.asarray(mesh.vertices) shift = np.mean(vertices,axis=0) scale = np.max(np.linalg.norm(vertices-shift, ord=2, axis=1)) vertices = (vertices-shift) / scale mesh.vertices = o3d.cuda.pybind.utility.Vector3dVector(vertices) return mesh def initial_guness_material(geometry, mlp, FLAGS, init_mat=None): # ipdb.set_trace(()) kd_min, kd_max = torch.tensor(FLAGS.kd_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.kd_max, dtype=torch.float32, device='cuda') ks_min, ks_max = torch.tensor(FLAGS.ks_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.ks_max, dtype=torch.float32, device='cuda') nrm_min, nrm_max = torch.tensor(FLAGS.nrm_min, dtype=torch.float32, device='cuda'), torch.tensor(FLAGS.nrm_max, dtype=torch.float32, device='cuda') if mlp: mlp_min = torch.cat((kd_min[0:3], ks_min, nrm_min), dim=0) mlp_max = torch.cat((kd_max[0:3], ks_max, nrm_max), dim=0) mlp_map_opt = mlptexture.MLPTexture3D(geometry.getAABB(), channels=9, min_max=[mlp_min, mlp_max]) mat = material.Material({'kd_ks_normal' : mlp_map_opt}) else: # Setup Kd (albedo) and Ks (x, roughness, metalness) textures if FLAGS.random_textures or init_mat is None: num_channels = 4 if FLAGS.layers > 1 else 3 kd_init = torch.rand(size=FLAGS.texture_res + [num_channels], device='cuda') * (kd_max - kd_min)[None, None, 0:num_channels] + kd_min[None, None, 0:num_channels] kd_map_opt = texture.create_trainable(kd_init , FLAGS.texture_res, not FLAGS.custom_mip, [kd_min, kd_max]) ksR = np.random.uniform(size=FLAGS.texture_res + [1], low=0.0, high=0.01) ksG = np.random.uniform(size=FLAGS.texture_res + [1], low=ks_min[1].cpu(), high=ks_max[1].cpu()) ksB = np.random.uniform(size=FLAGS.texture_res + [1], low=ks_min[2].cpu(), high=ks_max[2].cpu()) ks_map_opt = texture.create_trainable(np.concatenate((ksR, ksG, ksB), axis=2), FLAGS.texture_res, not FLAGS.custom_mip, [ks_min, ks_max]) else: kd_map_opt = texture.create_trainable(init_mat['kd'], FLAGS.texture_res, not FLAGS.custom_mip, [kd_min, kd_max]) ks_map_opt = texture.create_trainable(init_mat['ks'], FLAGS.texture_res, not FLAGS.custom_mip, [ks_min, ks_max]) # Setup normal map if FLAGS.random_textures or init_mat is None or 'normal' not in init_mat: normal_map_opt = texture.create_trainable(np.array([0, 0, 1]), FLAGS.texture_res, not FLAGS.custom_mip, [nrm_min, nrm_max]) else: normal_map_opt = texture.create_trainable(init_mat['normal'], FLAGS.texture_res, not FLAGS.custom_mip, [nrm_min, nrm_max]) mat = material.Material({ 'kd' : kd_map_opt, 'ks' : ks_map_opt, 'normal' : normal_map_opt }) if init_mat is not None: mat['bsdf'] = init_mat['bsdf'] else: mat['bsdf'] = 'pbr' return mat ############################################################################### # Validation & testing ############################################################################### # @torch.no_grad() def validate_itr(glctx, target, geometry, opt_material, lgt, FLAGS, relight = None): result_dict = {} with torch.no_grad(): if FLAGS.mode == 'appearance_modeling': with torch.no_grad(): lgt.build_mips() if FLAGS.camera_space_light: lgt.xfm(target['mv']) if relight != None: relight.build_mips() buffers = geometry.render(glctx, target, lgt, opt_material, if_use_bump = FLAGS.if_use_bump) result_dict['shaded'] = buffers['shaded'][0, ..., 0:3] result_dict['shaded'] = util.rgb_to_srgb(result_dict['shaded']) if relight != None: result_dict['relight'] = geometry.render(glctx, target, relight, opt_material, if_use_bump = FLAGS.if_use_bump)['shaded'][0, ..., 0:3] result_dict['relight'] = util.rgb_to_srgb(result_dict['relight']) result_dict['mask'] = (buffers['shaded'][0, ..., 3:4]) result_image = result_dict['shaded'] if FLAGS.display is not None : # white_bg = torch.ones_like(target['background']) for layer in FLAGS.display: if 'latlong' in layer and layer['latlong']: if isinstance(lgt, light.EnvironmentLight): result_dict['light_image'] = util.cubemap_to_latlong(lgt.base, FLAGS.display_res) result_image = torch.cat([result_image, result_dict['light_image']], axis=1) elif 'bsdf' in layer: buffers = geometry.render(glctx, target, lgt, opt_material, bsdf=layer['bsdf'], if_use_bump = FLAGS.if_use_bump) if layer['bsdf'] == 'kd': result_dict[layer['bsdf']] = util.rgb_to_srgb(buffers['shaded'][0, ..., 0:3]) elif layer['bsdf'] == 'normal': result_dict[layer['bsdf']] = (buffers['shaded'][0, ..., 0:3] + 1) * 0.5 else: result_dict[layer['bsdf']] = buffers['shaded'][0, ..., 0:3] result_image = torch.cat([result_image, result_dict[layer['bsdf']]], axis=1) return result_image, result_dict def save_gif(dir,fps): imgpath = dir frames = [] for idx in sorted(os.listdir(imgpath)): img = osp.join(imgpath,idx) frames.append(imageio.imread(img)) imageio.mimsave(os.path.join(dir, 'eval.gif'),frames,'GIF',duration=1/fps,loop=0) @torch.no_grad() def validate(glctx, geometry, opt_material, lgt, dataset_validate, out_dir, FLAGS, relight= None): # ============================================================================================== # Validation loop # ============================================================================================== mse_values = [] psnr_values = [] dataloader_validate = torch.utils.data.DataLoader(dataset_validate, batch_size=1, collate_fn=dataset_validate.collate) os.makedirs(out_dir, exist_ok=True) shaded_dir = os.path.join(out_dir, "shaded") relight_dir = os.path.join(out_dir, "relight") kd_dir = os.path.join(out_dir, "kd") ks_dir = os.path.join(out_dir, "ks") normal_dir = os.path.join(out_dir, "normal") mask_dir = os.path.join(out_dir, "mask") os.makedirs(shaded_dir, exist_ok=True) os.makedirs(relight_dir, exist_ok=True) os.makedirs(kd_dir, exist_ok=True) os.makedirs(ks_dir, exist_ok=True) os.makedirs(normal_dir, exist_ok=True) os.makedirs(mask_dir, exist_ok=True) print("Running validation") dataloader_validate = tqdm(dataloader_validate) for it, target in enumerate(dataloader_validate): # Mix validation background target = prepare_batch(target, 'white') result_image, result_dict = validate_itr(glctx, target, geometry, opt_material, lgt, FLAGS, relight) for k in result_dict.keys(): np_img = result_dict[k].detach().cpu().numpy() if k == 'shaded': util.save_image(shaded_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'relight': util.save_image(relight_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'kd': util.save_image(kd_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'ks': util.save_image(ks_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'normal': util.save_image(normal_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) elif k == 'mask': util.save_image(mask_dir + '/' + ('val_%06d_%s.png' % (it, k)), np_img) if 'shaded' in result_dict.keys(): save_gif(shaded_dir,30) if 'relight' in result_dict.keys(): save_gif(relight_dir,30) if 'kd' in result_dict.keys(): save_gif(kd_dir,30) if 'ks' in result_dict.keys(): save_gif(ks_dir,30) if 'normal' in result_dict.keys(): save_gif(normal_dir,30) return 0 ############################################################################### # Main shape fitter function / optimization loop ############################################################################### class Trainer(torch.nn.Module): def __init__(self, glctx, geometry, lgt, mat, optimize_geometry, optimize_light, FLAGS, guidance): super(Trainer, self).__init__() self.glctx = glctx self.geometry = geometry self.light = lgt self.material = mat self.optimize_geometry = optimize_geometry self.optimize_light = optimize_light self.FLAGS = FLAGS self.guidance = guidance self.if_flip_the_normal = FLAGS.if_flip_the_normal self.if_use_bump = FLAGS.if_use_bump if self.FLAGS.mode == 'appearance_modeling': if not self.optimize_light: with torch.no_grad(): self.light.build_mips() self.params = list(self.material.parameters()) self.params += list(self.geometry.pos_encoder.parameters()) self.params += list(self.light.parameters()) if optimize_light else [] self.geo_params = list(self.geometry.parameters()) if optimize_geometry else [] def forward(self, target, it, if_normal, if_pretrain, scene_and_vertices ): if self.FLAGS.mode == 'appearance_modeling': if self.optimize_light: self.light.build_mips() if self.FLAGS.camera_space_light: self.light.xfm(target['mv']) if if_pretrain: return self.geometry.decoder.pre_train_ellipsoid(it, scene_and_vertices) else: return self.geometry.tick(glctx, target, self.light, self.material, it , if_normal, self.guidance, self.FLAGS.mode, self.if_flip_the_normal, self.if_use_bump) def optimize_mesh( glctx, geometry, opt_material, lgt, dataset_train, dataset_validate, FLAGS, log_interval=10, optimize_light=True, optimize_geometry=True, guidance = None, scene_and_vertices = None, ): dataloader_train = torch.utils.data.DataLoader(dataset_train, batch_size=FLAGS.batch, collate_fn=dataset_train.collate, shuffle=False) dataloader_validate = torch.utils.data.DataLoader(dataset_validate, batch_size=1, collate_fn=dataset_train.collate) model = Trainer(glctx, geometry, lgt, opt_material, optimize_geometry, optimize_light, FLAGS, guidance) if optimize_geometry: optimizer_mesh = torch.optim.AdamW(model.geo_params, lr=0.001, betas=(0.9, 0.99), eps=1e-15) optimizer = torch.optim.AdamW(model.params, lr=0.01, betas=(0.9, 0.99), eps=1e-15) optimizer_lora = torch.optim.SGD(itertools.chain(*guidance.unet_lora_params), lr=1e-5) if FLAGS.multi_gpu: model = model.cuda() model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[FLAGS.local_rank], find_unused_parameters= True ) img_cnt = 0 img_loss_vec = [] reg_loss_vec = [] iter_dur_vec = [] def cycle(iterable): iterator = iter(iterable) while True: try: yield next(iterator) except StopIteration: iterator = iter(iterable) v_it = cycle(dataloader_validate) scaler = torch.cuda.amp.GradScaler(enabled=True) rot_ang = 0 if FLAGS.local_rank == 0: video = Video(FLAGS.out_dir) if FLAGS.local_rank == 0: dataloader_train = tqdm(dataloader_train) for it, target in enumerate(dataloader_train): # Mix randomized background into dataset image target = prepare_batch(target, FLAGS.train_background) # Show/save image before training step (want to get correct rendering of input) if FLAGS.local_rank == 0: save_image = FLAGS.save_interval and (it % FLAGS.save_interval == 0) save_video = FLAGS.video_interval and (it % FLAGS.video_interval == 0) if save_image: result_image, result_dict = validate_itr(glctx, prepare_batch(next(v_it), FLAGS.train_background), geometry, opt_material, lgt, FLAGS) #prepare_batch(next(v_it), FLAGS.background) np_result_image = result_image.detach().cpu().numpy() util.save_image(FLAGS.out_dir + '/' + ('img_%s_%06d.png' % (FLAGS.mode, img_cnt)), np_result_image) util.save_image(FLAGS.out_dir + '/' + ('mask_%s_%06d.png' % (FLAGS.mode, img_cnt)), result_dict['mask'].detach().cpu().numpy()) img_cnt = img_cnt+1 if save_video: with torch.no_grad(): params = get_camera_params( resolution=512, fov=45, elev_angle=-20, azim_angle =rot_ang, ) rot_ang += 1 if FLAGS.mode =='geometry_modeling': buffers = geometry.render(glctx, params, lgt, opt_material, bsdf='normal', if_use_bump = FLAGS.if_use_bump) video_image = (buffers['shaded'][0, ..., 0:3]+1)/2 else: buffers = geometry.render(glctx, params, lgt, opt_material, bsdf='pbr', if_use_bump = FLAGS.if_use_bump) video_image = util.rgb_to_srgb(buffers['shaded'][0, ..., 0:3]) video_image = video.ready_image(video_image) iter_start_time = time.time() if FLAGS.mode =='geometry_modeling': if it<=400: if_pretrain = True else: if_pretrain = False if_normal =True else: if_pretrain = False if_normal = False with torch.cuda.amp.autocast(enabled= True): if if_pretrain== True: reg_loss = model(target, it, if_normal, if_pretrain= if_pretrain, scene_and_vertices = scene_and_vertices) img_loss = 0 sds_loss = 0 attention_loss = 0 if if_pretrain == False: sds_loss, img_loss, reg_loss, attention_loss = model(target, it, if_normal, if_pretrain= if_pretrain, scene_and_vertices =None) if FLAGS.mode =='geometry_modeling': if(it<1000): attention_loss = 0 else: if(it<500): attention_loss = 0 # ============================================================================================== # Final loss # ============================================================================================== total_loss = img_loss + reg_loss + sds_loss + attention_loss if if_pretrain == True: scaler.scale(total_loss).backward() if if_pretrain == False: scaler.scale(total_loss).backward() img_loss_vec.append(img_loss.item()) reg_loss_vec.append(reg_loss.item()) # ============================================================================================== # Backpropagate # ============================================================================================== if if_normal == False and if_pretrain == False: scaler.step(optimizer) optimizer.zero_grad() if if_normal == True or if_pretrain == True: if optimize_geometry: scaler.step(optimizer_mesh) optimizer_mesh.zero_grad() for param in guidance.parameters(): if param.grad is not None and torch.isnan(param.grad).any(): param.grad = torch.nan_to_num(param.grad, nan=0.0) max_norm = 5.0 torch.nn.utils.clip_grad_norm_(guidance.parameters(), max_norm) if if_pretrain == False: optimizer_lora.step() optimizer_lora.zero_grad() for param in guidance.parameters(): param.data = torch.nan_to_num(param.data, nan=0.0, posinf=None, neginf=None) scaler.update() # ============================================================================================== # Clamp trainables to reasonable range # ============================================================================================== with torch.no_grad(): if 'kd' in opt_material: opt_material['kd'].clamp_() if 'ks' in opt_material: opt_material['ks'].clamp_() if 'normal' in opt_material: opt_material['normal'].clamp_() opt_material['normal'].normalize_() if lgt is not None: lgt.clamp_(min=0.0) torch.cuda.current_stream().synchronize() iter_dur_vec.append(time.time() - iter_start_time) return geometry, opt_material def seed_everything(seed, local_rank): random.seed(seed + local_rank) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed + local_rank) torch.manual_seed(seed) torch.cuda.manual_seed(seed) if __name__ == "__main__": parser = argparse.ArgumentParser(description='nvdiffrec') parser.add_argument('--config', type=str, default='configs_clean3/icecream_geometry_debug.json', help='Config file') parser.add_argument('-i', '--iter', type=int, default=5000) parser.add_argument('-b', '--batch', type=int, default=1) parser.add_argument('-s', '--spp', type=int, default=1) parser.add_argument('-l', '--layers', type=int, default=1) parser.add_argument('-r', '--train-res', nargs=2, type=int, default=[512, 512]) parser.add_argument('-dr', '--display-res', type=int, default=None) parser.add_argument('-tr', '--texture-res', nargs=2, type=int, default=[1024, 1024]) parser.add_argument('-si', '--save-interval', type=int, default=1000, help="The interval of saving an image") parser.add_argument('-vi', '--video_interval', type=int, default=10, help="The interval of saving a frame of the video") parser.add_argument('-mr', '--min-roughness', type=float, default=0.08) parser.add_argument('-mip', '--custom-mip', action='store_true', default=False) parser.add_argument('-rt', '--random-textures', action='store_true', default=False) parser.add_argument('-bg', '--train_background', default='black', choices=['black', 'white', 'checker', 'reference']) parser.add_argument('-o', '--out-dir', type=str, default='results/result_debug/icecream_geometry') parser.add_argument('-rm', '--ref_mesh', type=str) parser.add_argument('-bm', '--base-mesh', type=str, default=None) parser.add_argument('--validate', type=bool, default=True) parser.add_argument("--local_rank", type=int, default=0, help="For distributed training: local_rank") parser.add_argument("--seed", type=int, default=42, help="A seed for reproducible training.") parser.add_argument("--add_directional_text", action='store_true', default=False) parser.add_argument('--mode', default='geometry_modeling', choices=['geometry_modeling', 'appearance_modeling']) parser.add_argument('--text', default=None, help="text prompt") parser.add_argument('--sdf_init_shape', default='ellipsoid', choices=['ellipsoid', 'cylinder', 'custom_mesh']) parser.add_argument('--camera_random_jitter', type= float, default=0.4, help="A large value is advantageous for the extension of objects such as ears or sharp corners to grow.") parser.add_argument('--fovy_range', nargs=2, type=float, default=[25.71, 45.00]) parser.add_argument('--elevation_range', nargs=2, type=int, default=[-10, 45], help="The elevatioin range must in [-90, 90].") parser.add_argument("--guidance_weight", type=int, default=100, help="The weight of classifier-free guidance") parser.add_argument("--sds_weight_strategy", type=int, nargs=1, default=0, choices=[0, 1, 2], help="The strategy of the sds loss's weight") parser.add_argument("--translation_y", type= float, nargs=1, default= 0 , help="translation of the initial shape on the y-axis") parser.add_argument("--coarse_iter", type= int, nargs=1, default= 1000 , help="The iteration number of the coarse stage.") parser.add_argument('--early_time_step_range', nargs=2, type=float, default=[0.02, 0.5], help="The time step range in early phase") parser.add_argument('--late_time_step_range', nargs=2, type=float, default=[0.02, 0.5], help="The time step range in late phase") parser.add_argument("--sdf_init_shape_rotate_x", type= int, nargs=1, default= 0 , help="rotation of the initial shape on the x-axis") parser.add_argument("--if_flip_the_normal", action='store_true', default=False , help="Flip the x-axis positive half-axis of Normal. We find this process helps to alleviate the Janus problem.") parser.add_argument("--front_threshold", type= int, nargs=1, default= 45 , help="the range of front view would be [-front_threshold, front_threshold") parser.add_argument("--if_use_bump", type=bool, default= True , help="whether to use perturbed normals during appearing modeling") parser.add_argument("--uv_padding_block", type= int, default= 4 , help="The block of uv padding.") FLAGS = parser.parse_args() FLAGS.mtl_override = None # Override material of model FLAGS.dmtet_grid = 64 # Resolution of initial tet grid. We provide 64, 128 and 256 resolution grids. Other resolutions can be generated with https://github.com/crawforddoran/quartet FLAGS.mesh_scale = 2.1 # Scale of tet grid box. Adjust to cover the model FLAGS.env_scale = 1.0 # Env map intensity multiplier FLAGS.envmap = None # HDR environment probe FLAGS.relight = None # HDR environment probe(relight) FLAGS.display = None # Conf validation window/display. E.g. [{"relight" : <path to envlight>}] FLAGS.camera_space_light = False # Fixed light in camera space. This is needed for setups like ethiopian head where the scanned object rotates on a stand. FLAGS.lock_light = False # Disable light optimization in the second pass FLAGS.lock_pos = False # Disable vertex position optimization in the second pass FLAGS.pre_load = True # Pre-load entire dataset into memory for faster training FLAGS.kd_min = [ 0.0, 0.0, 0.0, 0.0] # Limits for kd FLAGS.kd_max = [ 1.0, 1.0, 1.0, 1.0] FLAGS.ks_min = [ 0.0, 0.08, 0.0] # Limits for ks FLAGS.ks_max = [ 1.0, 1.0, 1.0] FLAGS.nrm_min = [-1.0, -1.0, 0.0] # Limits for normal map FLAGS.nrm_max = [ 1.0, 1.0, 1.0] FLAGS.cam_near_far = [1, 50] FLAGS.learn_light = False FLAGS.gpu_number = 1 FLAGS.sdf_init_shape_scale=[1.0, 1.0, 1.0] FLAGS.multi_gpu = "WORLD_SIZE" in os.environ and int(os.environ["WORLD_SIZE"]) > 1 if FLAGS.multi_gpu: FLAGS.gpu_number = int(os.environ["WORLD_SIZE"]) FLAGS.local_rank = int(os.environ["LOCAL_RANK"]) torch.distributed.init_process_group(backend="nccl", world_size = FLAGS.gpu_number, rank = FLAGS.local_rank) torch.cuda.set_device(FLAGS.local_rank) if FLAGS.config is not None: data = json.load(open(FLAGS.config, 'r')) for key in data: FLAGS.__dict__[key] = data[key] if FLAGS.display_res is None: FLAGS.display_res = FLAGS.train_res if FLAGS.local_rank == 0: print("Config / Flags:") print("---------") for key in FLAGS.__dict__.keys(): print(key, FLAGS.__dict__[key]) print("---------") seed_everything(FLAGS.seed, FLAGS.local_rank) os.makedirs(FLAGS.out_dir, exist_ok=True) glctx = dr.RasterizeCudaContext() # ============================================================================================== # Create data pipeline # ============================================================================================== dataset_train = DatasetMesh(glctx, FLAGS, validate=False) dataset_validate = DatasetMesh(glctx, FLAGS, validate=True) dataset_gif = DatasetMesh(glctx, FLAGS, gif=True) # ============================================================================================== # Create env light with trainable parameters # ============================================================================================== if FLAGS.mode == 'appearance_modeling' and FLAGS.base_mesh is not None: if FLAGS.learn_light: lgt = light.create_trainable_env_rnd(512, scale=0.0, bias=1) else: lgt = light.load_env(FLAGS.envmap, scale=FLAGS.env_scale) else: lgt = None if FLAGS.sdf_init_shape in ['ellipsoid', 'cylinder', 'custom_mesh'] and FLAGS.mode == 'geometry_modeling': if FLAGS.sdf_init_shape == 'ellipsoid': init_shape = o3d.geometry.TriangleMesh.create_sphere(1) elif FLAGS.sdf_init_shape == 'cylinder': init_shape = o3d.geometry.TriangleMesh.create_cylinder(radius=0.75, height=1.2, resolution=20, split=4, create_uv_map=False) elif FLAGS.sdf_init_shape == 'custom_mesh': if FLAGS.base_mesh: init_shape = get_normalize_mesh(FLAGS.base_mesh) else: assert False, "[Error] The path of custom mesh is invalid ! (geometry modeling)" else: assert False, "Invalid init type" vertices = np.asarray(init_shape.vertices) vertices[...,0]=vertices[...,0] * FLAGS.sdf_init_shape_scale[0] vertices[...,1]=vertices[...,1] * FLAGS.sdf_init_shape_scale[1] vertices[...,2]=vertices[...,2] * FLAGS.sdf_init_shape_scale[2] vertices = vertices @ util.rotate_x_2(np.deg2rad(FLAGS.sdf_init_shape_rotate_x)) vertices[...,1]=vertices[...,1] + FLAGS.translation_y init_shape.vertices = o3d.cuda.pybind.utility.Vector3dVector(vertices) points_surface = np.asarray(init_shape.sample_points_poisson_disk(5000).points) init_shape = o3d.t.geometry.TriangleMesh.from_legacy(init_shape) scene = o3d.t.geometry.RaycastingScene() scene.add_triangles(init_shape) scene_and_vertices = [scene, points_surface]
guidance = StableDiffusion(device = 'cuda',
12
2023-11-27 13:44:01+00:00
24k
camenduru/magicanimate-hf
magicanimate/pipelines/pipeline_animation.py
[ { "identifier": "UNet3DConditionModel", "path": "magicanimate/models/unet_controlnet.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in_channels: int = 4,\n out_channels: int = 4,\n center_input_sample: bool = False,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0, \n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\",\n ),\n mid_block_type: str = \"UNetMidBlock3DCrossAttn\",\n up_block_types: Tuple[str] = (\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: int = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n dual_cross_attention: bool = False,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n \n # Additional\n use_motion_module = False,\n motion_module_resolutions = ( 1,2,4,8 ),\n motion_module_mid_block = False,\n motion_module_decoder_only = False,\n motion_module_type = None,\n motion_module_kwargs = {},\n unet_use_cross_frame_attention = None,\n unet_use_temporal_attention = None,\n ):\n super().__init__()\n\n self.sample_size = sample_size\n time_embed_dim = block_out_channels[0] * 4\n\n # input\n self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))\n\n # time\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n self.down_blocks = nn.ModuleList([])\n self.mid_block = None\n self.up_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n for i, down_block_type in enumerate(down_block_types):\n res = 2 ** i\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n \n use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.down_blocks.append(down_block)\n\n # mid\n if mid_block_type == \"UNetMidBlock3DCrossAttn\":\n self.mid_block = UNetMidBlock3DCrossAttn(\n in_channels=block_out_channels[-1],\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n \n use_motion_module=use_motion_module and motion_module_mid_block,\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n else:\n raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n \n # count how many layers upsample the videos\n self.num_upsamplers = 0\n\n # up\n reversed_block_out_channels = list(reversed(block_out_channels))\n reversed_attention_head_dim = list(reversed(attention_head_dim))\n only_cross_attention = list(reversed(only_cross_attention))\n output_channel = reversed_block_out_channels[0]\n for i, up_block_type in enumerate(up_block_types):\n res = 2 ** (3 - i)\n is_final_block = i == len(block_out_channels) - 1\n\n prev_output_channel = output_channel\n output_channel = reversed_block_out_channels[i]\n input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n # add upsample block for all BUT final layer\n if not is_final_block:\n add_upsample = True\n self.num_upsamplers += 1\n else:\n add_upsample = False\n\n up_block = get_up_block(\n up_block_type,\n num_layers=layers_per_block + 1,\n in_channels=input_channel,\n out_channels=output_channel,\n prev_output_channel=prev_output_channel,\n temb_channels=time_embed_dim,\n add_upsample=add_upsample,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=reversed_attention_head_dim[i],\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n\n use_motion_module=use_motion_module and (res in motion_module_resolutions),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.up_blocks.append(up_block)\n prev_output_channel = output_channel\n\n # out\n self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)\n self.conv_act = nn.SiLU()\n self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1)\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n class_labels: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n # for controlnet\n down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n mid_block_additional_residual: Optional[torch.Tensor] = None,\n return_dict: bool = True,\n ) -> Union[UNet3DConditionOutput, Tuple]:\n r\"\"\"\n Args:\n sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor\n timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps\n encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.\n\n Returns:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When\n returning a tuple, the first element is the sample tensor.\n \"\"\"\n # By default samples have to be AT least a multiple of the overall upsampling factor.\n # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).\n # However, the upsampling interpolation output size can be forced to fit any upsampling size\n # on the fly if necessary.\n default_overall_up_factor = 2**self.num_upsamplers\n\n # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n forward_upsample_size = False\n upsample_size = None\n\n if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):\n logger.info(\"Forward upsample size to force interpolation output size.\")\n forward_upsample_size = True\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # center input if necessary\n if self.config.center_input_sample:\n sample = 2 * sample - 1.0\n\n # time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n emb = self.time_embedding(t_emb)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # pre-process\n sample = self.conv_in(sample)\n\n # down\n is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None\n\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb, encoder_hidden_states=encoder_hidden_states)\n\n down_block_res_samples += res_samples\n\n if is_controlnet:\n new_down_block_res_samples = ()\n\n for down_block_res_sample, down_block_additional_residual in zip(\n down_block_res_samples, down_block_additional_residuals\n ):\n down_block_res_sample = down_block_res_sample + down_block_additional_residual\n new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)\n\n down_block_res_samples = new_down_block_res_samples\n\n # mid\n sample = self.mid_block(\n sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n\n if is_controlnet:\n sample = sample + mid_block_additional_residual\n\n # up\n for i, upsample_block in enumerate(self.up_blocks):\n is_final_block = i == len(self.up_blocks) - 1\n\n res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n # if we have not reached the final block and need to forward the\n # upsample size, we do it here\n if not is_final_block and forward_upsample_size:\n upsample_size = down_block_res_samples[-1].shape[2:]\n\n if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n encoder_hidden_states=encoder_hidden_states,\n upsample_size=upsample_size,\n attention_mask=attention_mask,\n )\n else:\n sample = upsample_block(\n hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size, encoder_hidden_states=encoder_hidden_states,\n )\n\n # post-process\n sample = self.conv_norm_out(sample)\n sample = self.conv_act(sample)\n sample = self.conv_out(sample)\n\n if not return_dict:\n return (sample,)\n\n return UNet3DConditionOutput(sample=sample)\n\n @classmethod\n def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, unet_additional_kwargs=None):\n if subfolder is not None:\n pretrained_model_path = os.path.join(pretrained_model_path, subfolder)\n print(f\"loaded temporal unet's pretrained weights from {pretrained_model_path} ...\")\n\n config_file = os.path.join(pretrained_model_path, 'config.json')\n if not os.path.isfile(config_file):\n raise RuntimeError(f\"{config_file} does not exist\")\n with open(config_file, \"r\") as f:\n config = json.load(f)\n config[\"_class_name\"] = cls.__name__\n config[\"down_block_types\"] = [\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\"\n ]\n config[\"up_block_types\"] = [\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ]\n # config[\"mid_block_type\"] = \"UNetMidBlock3DCrossAttn\"\n\n from diffusers.utils import WEIGHTS_NAME\n model = cls.from_config(config, **unet_additional_kwargs)\n model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)\n if not os.path.isfile(model_file):\n raise RuntimeError(f\"{model_file} does not exist\")\n state_dict = torch.load(model_file, map_location=\"cpu\")\n\n m, u = model.load_state_dict(state_dict, strict=False)\n print(f\"### missing keys: {len(m)}; \\n### unexpected keys: {len(u)};\")\n # print(f\"### missing keys:\\n{m}\\n### unexpected keys:\\n{u}\\n\")\n \n params = [p.numel() if \"temporal\" in n else 0 for n, p in model.named_parameters()]\n print(f\"### Temporal Module Parameters: {sum(params) / 1e6} M\")\n \n return model" }, { "identifier": "ControlNetModel", "path": "magicanimate/models/controlnet.py", "snippet": "class ControlNetModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n in_channels: int = 4,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"DownBlock2D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: Optional[int] = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n projection_class_embeddings_input_dim: Optional[int] = None,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n ):\n super().__init__()\n\n # Check inputs\n if len(block_out_channels) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n )\n\n # input\n conv_in_kernel = 3\n conv_in_padding = (conv_in_kernel - 1) // 2\n self.conv_in = nn.Conv2d(\n in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n\n # time\n time_embed_dim = block_out_channels[0] * 4\n\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(\n timestep_input_dim,\n time_embed_dim,\n act_fn=act_fn,\n )\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n elif class_embed_type == \"projection\":\n if projection_class_embeddings_input_dim is None:\n raise ValueError(\n \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n )\n # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n # 2. it projects from an arbitrary input dimension.\n #\n # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n # control net conditioning embedding\n self.controlnet_cond_embedding = ControlNetConditioningEmbedding(\n conditioning_embedding_channels=block_out_channels[0],\n block_out_channels=conditioning_embedding_out_channels,\n )\n\n self.down_blocks = nn.ModuleList([])\n self.controlnet_down_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[i],\n downsample_padding=downsample_padding,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n )\n self.down_blocks.append(down_block)\n\n for _ in range(layers_per_block):\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n if not is_final_block:\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n # mid\n mid_block_channel = block_out_channels[-1]\n\n controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_mid_block = controlnet_block\n\n self.mid_block = UNetMidBlock2DCrossAttn(\n in_channels=mid_block_channel,\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n )\n\n @classmethod\n def from_unet(\n cls,\n unet: UNet2DConditionModel,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n load_weights_from_unet: bool = True,\n ):\n r\"\"\"\n Instantiate Controlnet class from UNet2DConditionModel.\n\n Parameters:\n unet (`UNet2DConditionModel`):\n UNet model which weights are copied to the ControlNet. Note that all configuration options are also\n copied where applicable.\n \"\"\"\n controlnet = cls(\n in_channels=unet.config.in_channels,\n flip_sin_to_cos=unet.config.flip_sin_to_cos,\n freq_shift=unet.config.freq_shift,\n down_block_types=unet.config.down_block_types,\n only_cross_attention=unet.config.only_cross_attention,\n block_out_channels=unet.config.block_out_channels,\n layers_per_block=unet.config.layers_per_block,\n downsample_padding=unet.config.downsample_padding,\n mid_block_scale_factor=unet.config.mid_block_scale_factor,\n act_fn=unet.config.act_fn,\n norm_num_groups=unet.config.norm_num_groups,\n norm_eps=unet.config.norm_eps,\n cross_attention_dim=unet.config.cross_attention_dim,\n attention_head_dim=unet.config.attention_head_dim,\n use_linear_projection=unet.config.use_linear_projection,\n class_embed_type=unet.config.class_embed_type,\n num_class_embeds=unet.config.num_class_embeds,\n upcast_attention=unet.config.upcast_attention,\n resnet_time_scale_shift=unet.config.resnet_time_scale_shift,\n projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,\n controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,\n conditioning_embedding_out_channels=conditioning_embedding_out_channels,\n )\n\n if load_weights_from_unet:\n controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())\n controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())\n controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())\n\n if controlnet.class_embedding:\n controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())\n\n controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())\n controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())\n\n return controlnet\n\n # @property\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors\n # def attn_processors(self) -> Dict[str, AttentionProcessor]:\n # r\"\"\"\n # Returns:\n # `dict` of attention processors: A dictionary containing all attention processors used in the model with\n # indexed by its weight name.\n # \"\"\"\n # # set recursively\n # processors = {}\n\n # def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):\n # if hasattr(module, \"set_processor\"):\n # processors[f\"{name}.processor\"] = module.processor\n\n # for sub_name, child in module.named_children():\n # fn_recursive_add_processors(f\"{name}.{sub_name}\", child, processors)\n\n # return processors\n\n # for name, module in self.named_children():\n # fn_recursive_add_processors(name, module, processors)\n\n # return processors\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor\n # def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):\n # r\"\"\"\n # Parameters:\n # `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`):\n # The instantiated processor class or a dictionary of processor classes that will be set as the processor\n # of **all** `Attention` layers.\n # In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.:\n\n # \"\"\"\n # count = len(self.attn_processors.keys())\n\n # if isinstance(processor, dict) and len(processor) != count:\n # raise ValueError(\n # f\"A dict of processors was passed, but the number of processors {len(processor)} does not match the\"\n # f\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\n # )\n\n # def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):\n # if hasattr(module, \"set_processor\"):\n # if not isinstance(processor, dict):\n # module.set_processor(processor)\n # else:\n # module.set_processor(processor.pop(f\"{name}.processor\"))\n\n # for sub_name, child in module.named_children():\n # fn_recursive_attn_processor(f\"{name}.{sub_name}\", child, processor)\n\n # for name, module in self.named_children():\n # fn_recursive_attn_processor(name, module, processor)\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor\n # def set_default_attn_processor(self):\n # \"\"\"\n # Disables custom attention processors and sets the default attention implementation.\n # \"\"\"\n # self.set_attn_processor(AttnProcessor())\n\n # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maximum amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_sliceable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_sliceable_dims(module)\n\n num_sliceable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_sliceable_layers * [1]\n\n slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n controlnet_cond: torch.FloatTensor,\n conditioning_scale: float = 1.0,\n class_labels: Optional[torch.Tensor] = None,\n timestep_cond: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n return_dict: bool = True,\n ) -> Union[ControlNetOutput, Tuple]:\n # check channel order\n channel_order = self.config.controlnet_conditioning_channel_order\n\n if channel_order == \"rgb\":\n # in rgb order by default\n ...\n elif channel_order == \"bgr\":\n controlnet_cond = torch.flip(controlnet_cond, dims=[1])\n else:\n raise ValueError(f\"unknown `controlnet_conditioning_channel_order`: {channel_order}\")\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n\n emb = self.time_embedding(t_emb, timestep_cond)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)\n\n sample += controlnet_cond\n\n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n # 4. mid\n if self.mid_block is not None:\n sample = self.mid_block(\n sample,\n emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n\n # 5. Control net blocks\n\n controlnet_down_block_res_samples = ()\n\n for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):\n down_block_res_sample = controlnet_block(down_block_res_sample)\n controlnet_down_block_res_samples += (down_block_res_sample,)\n\n down_block_res_samples = controlnet_down_block_res_samples\n\n mid_block_res_sample = self.controlnet_mid_block(sample)\n\n # 6. scaling\n down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]\n mid_block_res_sample *= conditioning_scale\n\n if not return_dict:\n return (down_block_res_samples, mid_block_res_sample)\n\n return ControlNetOutput(\n down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample\n )" }, { "identifier": "ReferenceAttentionControl", "path": "magicanimate/models/mutual_self_attention.py", "snippet": "class ReferenceAttentionControl():\n \n def __init__(self, \n unet,\n mode=\"write\",\n do_classifier_free_guidance=False,\n attention_auto_machine_weight = float('inf'),\n gn_auto_machine_weight = 1.0,\n style_fidelity = 1.0,\n reference_attn=True,\n reference_adain=False,\n fusion_blocks=\"midup\",\n batch_size=1, \n ) -> None:\n # 10. Modify self attention and group norm\n self.unet = unet\n assert mode in [\"read\", \"write\"]\n assert fusion_blocks in [\"midup\", \"full\"]\n self.reference_attn = reference_attn\n self.reference_adain = reference_adain\n self.fusion_blocks = fusion_blocks\n self.register_reference_hooks(\n mode, \n do_classifier_free_guidance,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n fusion_blocks,\n batch_size=batch_size, \n )\n\n def register_reference_hooks(\n self, \n mode, \n do_classifier_free_guidance,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n dtype=torch.float16,\n batch_size=1, \n num_images_per_prompt=1, \n device=torch.device(\"cpu\"), \n fusion_blocks='midup',\n ):\n MODE = mode\n do_classifier_free_guidance = do_classifier_free_guidance\n attention_auto_machine_weight = attention_auto_machine_weight\n gn_auto_machine_weight = gn_auto_machine_weight\n style_fidelity = style_fidelity\n reference_attn = reference_attn\n reference_adain = reference_adain\n fusion_blocks = fusion_blocks\n num_images_per_prompt = num_images_per_prompt\n dtype=dtype\n if do_classifier_free_guidance:\n uc_mask = (\n torch.Tensor([1] * batch_size * num_images_per_prompt * 16 + [0] * batch_size * num_images_per_prompt * 16)\n .to(device)\n .bool()\n )\n else:\n uc_mask = (\n torch.Tensor([0] * batch_size * num_images_per_prompt * 2)\n .to(device)\n .bool()\n )\n \n def hacked_basic_transformer_inner_forward(\n self,\n hidden_states: torch.FloatTensor,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n timestep: Optional[torch.LongTensor] = None,\n cross_attention_kwargs: Dict[str, Any] = None,\n class_labels: Optional[torch.LongTensor] = None,\n video_length=None,\n ):\n if self.use_ada_layer_norm:\n norm_hidden_states = self.norm1(hidden_states, timestep)\n elif self.use_ada_layer_norm_zero:\n norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(\n hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype\n )\n else:\n norm_hidden_states = self.norm1(hidden_states)\n\n # 1. Self-Attention\n cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}\n if self.only_cross_attention:\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n else:\n if MODE == \"write\":\n self.bank.append(norm_hidden_states.clone())\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n if MODE == \"read\":\n self.bank = [rearrange(d.unsqueeze(1).repeat(1, video_length, 1, 1), \"b t l c -> (b t) l c\")[:hidden_states.shape[0]] for d in self.bank]\n hidden_states_uc = self.attn1(norm_hidden_states, \n encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),\n attention_mask=attention_mask) + hidden_states\n hidden_states_c = hidden_states_uc.clone()\n _uc_mask = uc_mask.clone()\n if do_classifier_free_guidance:\n if hidden_states.shape[0] != _uc_mask.shape[0]:\n _uc_mask = (\n torch.Tensor([1] * (hidden_states.shape[0]//2) + [0] * (hidden_states.shape[0]//2))\n .to(device)\n .bool()\n )\n hidden_states_c[_uc_mask] = self.attn1(\n norm_hidden_states[_uc_mask],\n encoder_hidden_states=norm_hidden_states[_uc_mask],\n attention_mask=attention_mask,\n ) + hidden_states[_uc_mask]\n hidden_states = hidden_states_c.clone()\n \n self.bank.clear()\n if self.attn2 is not None:\n # Cross-Attention\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n hidden_states = (\n self.attn2(\n norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n + hidden_states\n )\n\n # Feed-forward\n hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states\n\n # Temporal-Attention\n if self.unet_use_temporal_attention:\n d = hidden_states.shape[1]\n hidden_states = rearrange(hidden_states, \"(b f) d c -> (b d) f c\", f=video_length)\n norm_hidden_states = (\n self.norm_temp(hidden_states, timestep) if self.use_ada_layer_norm else self.norm_temp(hidden_states)\n )\n hidden_states = self.attn_temp(norm_hidden_states) + hidden_states\n hidden_states = rearrange(hidden_states, \"(b d) f c -> (b f) d c\", d=d)\n\n return hidden_states\n \n if self.use_ada_layer_norm_zero:\n attn_output = gate_msa.unsqueeze(1) * attn_output\n hidden_states = attn_output + hidden_states\n\n if self.attn2 is not None:\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n\n # 2. Cross-Attention\n attn_output = self.attn2(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=encoder_attention_mask,\n **cross_attention_kwargs,\n )\n hidden_states = attn_output + hidden_states\n\n # 3. Feed-forward\n norm_hidden_states = self.norm3(hidden_states)\n\n if self.use_ada_layer_norm_zero:\n norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]\n\n ff_output = self.ff(norm_hidden_states)\n\n if self.use_ada_layer_norm_zero:\n ff_output = gate_mlp.unsqueeze(1) * ff_output\n\n hidden_states = ff_output + hidden_states\n\n return hidden_states\n\n def hacked_mid_forward(self, *args, **kwargs):\n eps = 1e-6\n x = self.original_forward(*args, **kwargs)\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append(mean)\n self.var_bank.append(var)\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))\n var_acc = sum(self.var_bank) / float(len(self.var_bank))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n x_uc = (((x - mean) / std) * std_acc) + mean_acc\n x_c = x_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n x_c[uc_mask] = x[uc_mask]\n x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc\n self.mean_bank = []\n self.var_bank = []\n return x\n\n def hack_CrossAttnDownBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n\n # TODO(Patrick, William) - attention mask is not used\n output_states = ()\n\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_DownBlock2D_forward(self, hidden_states, temb=None):\n eps = 1e-6\n\n output_states = ()\n\n for i, resnet in enumerate(self.resnets):\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_CrossAttnUpBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n upsample_size: Optional[int] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n # TODO(Patrick, William) - attention mask is not used\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):\n eps = 1e-6\n for i, resnet in enumerate(self.resnets):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)] \n attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n\n for i, module in enumerate(attn_modules):\n module._original_inner_forward = module.forward\n module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)\n module.bank = []\n module.attn_weight = float(i) / float(len(attn_modules))\n\n if self.reference_adain:\n gn_modules = [self.unet.mid_block]\n self.unet.mid_block.gn_weight = 0\n\n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n module.gn_weight = 1.0 - float(w) / float(len(down_blocks))\n gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n module.gn_weight = float(w) / float(len(up_blocks))\n gn_modules.append(module)\n\n for i, module in enumerate(gn_modules):\n if getattr(module, \"original_forward\", None) is None:\n module.original_forward = module.forward\n if i == 0:\n # mid_block\n module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)\n elif isinstance(module, CrossAttnDownBlock2D):\n module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)\n elif isinstance(module, DownBlock2D):\n module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)\n elif isinstance(module, CrossAttnUpBlock2D):\n module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)\n elif isinstance(module, UpBlock2D):\n module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)\n module.mean_bank = []\n module.var_bank = []\n module.gn_weight *= 2\n \n def update(self, writer, dtype=torch.float16):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in (torch_dfs(writer.unet.mid_block)+torch_dfs(writer.unet.up_blocks)) if isinstance(module, BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in torch_dfs(writer.unet) if isinstance(module, BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]) \n writer_attn_modules = sorted(writer_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r, w in zip(reader_attn_modules, writer_attn_modules):\n r.bank = [v.clone().to(dtype) for v in w.bank]\n # w.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n writer_gn_modules = [writer.unet.mid_block]\n \n down_blocks = writer.unet.down_blocks\n for w, module in enumerate(down_blocks):\n writer_gn_modules.append(module)\n\n up_blocks = writer.unet.up_blocks\n for w, module in enumerate(up_blocks):\n writer_gn_modules.append(module)\n \n for r, w in zip(reader_gn_modules, writer_gn_modules):\n if len(w.mean_bank) > 0 and isinstance(w.mean_bank[0], list):\n r.mean_bank = [[v.clone().to(dtype) for v in vl] for vl in w.mean_bank]\n r.var_bank = [[v.clone().to(dtype) for v in vl] for vl in w.var_bank]\n else:\n r.mean_bank = [v.clone().to(dtype) for v in w.mean_bank]\n r.var_bank = [v.clone().to(dtype) for v in w.var_bank]\n \n def clear(self):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r in reader_attn_modules:\n r.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n for r in reader_gn_modules:\n r.mean_bank.clear()\n r.var_bank.clear()" }, { "identifier": "get_context_scheduler", "path": "magicanimate/pipelines/context.py", "snippet": "def get_context_scheduler(name: str) -> Callable:\n if name == \"uniform\":\n return uniform\n else:\n raise ValueError(f\"Unknown context_overlap policy {name}\")" }, { "identifier": "get_total_steps", "path": "magicanimate/pipelines/context.py", "snippet": "def get_total_steps(\n scheduler,\n timesteps: List[int],\n num_steps: Optional[int] = None,\n num_frames: int = ...,\n context_size: Optional[int] = None,\n context_stride: int = 3,\n context_overlap: int = 4,\n closed_loop: bool = True,\n):\n return sum(\n len(\n list(\n scheduler(\n i,\n num_steps,\n num_frames,\n context_size,\n context_stride,\n context_overlap,\n )\n )\n )\n for i in range(len(timesteps))\n )" }, { "identifier": "get_tensor_interpolation_method", "path": "magicanimate/utils/util.py", "snippet": "def get_tensor_interpolation_method():\n return tensor_interpolation" } ]
import inspect, math import numpy as np import torch import torch.distributed as dist from typing import Callable, List, Optional, Union from dataclasses import dataclass from PIL import Image from tqdm import tqdm from diffusers.utils import is_accelerate_available from packaging import version from transformers import CLIPTextModel, CLIPTokenizer from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL from diffusers.pipeline_utils import DiffusionPipeline from diffusers.schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from diffusers.utils import deprecate, logging, BaseOutput from einops import rearrange from magicanimate.models.unet_controlnet import UNet3DConditionModel from magicanimate.models.controlnet import ControlNetModel from magicanimate.models.mutual_self_attention import ReferenceAttentionControl from magicanimate.pipelines.context import ( get_context_scheduler, get_total_steps ) from magicanimate.utils.util import get_tensor_interpolation_method from accelerate import cpu_offload
16,739
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TODO: 1. support multi-controlnet 2. [DONE] support DDIM inversion 3. support Prompt-to-prompt """ logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] class AnimationPipeline(DiffusionPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer,
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TODO: 1. support multi-controlnet 2. [DONE] support DDIM inversion 3. support Prompt-to-prompt """ logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] class AnimationPipeline(DiffusionPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer,
unet: UNet3DConditionModel,
0
2023-12-04 20:47:34+00:00
24k
metatube-community/metatube-plex-plugins
MetaTube.bundle/Contents/Libraries/Shared/urllib3/poolmanager.py
[ { "identifier": "HTTPHeaderDict", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/_collections.py", "snippet": "class HTTPHeaderDict(MutableMapping):\n \"\"\"\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-insensitively.\n\n :param kwargs:\n Additional field-value pairs to pass in to ``dict.update``.\n\n A ``dict`` like container for storing HTTP Headers.\n\n Field names are stored and compared case-insensitively in compliance with\n RFC 7230. Iteration provides the first case-sensitive key seen for each\n case-insensitive pair.\n\n Using ``__setitem__`` syntax overwrites fields that compare equal\n case-insensitively in order to maintain ``dict``'s api. For fields that\n compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n in a loop.\n\n If multiple fields that are equal case-insensitively are passed to the\n constructor or ``.update``, the behavior is undefined and some will be\n lost.\n\n >>> headers = HTTPHeaderDict()\n >>> headers.add('Set-Cookie', 'foo=bar')\n >>> headers.add('set-cookie', 'baz=quxx')\n >>> headers['content-length'] = '7'\n >>> headers['SET-cookie']\n 'foo=bar, baz=quxx'\n >>> headers['Content-Length']\n '7'\n \"\"\"\n\n def __init__(self, headers=None, **kwargs):\n super(HTTPHeaderDict, self).__init__()\n self._container = OrderedDict()\n if headers is not None:\n if isinstance(headers, HTTPHeaderDict):\n self._copy_from(headers)\n else:\n self.extend(headers)\n if kwargs:\n self.extend(kwargs)\n\n def __setitem__(self, key, val):\n self._container[key.lower()] = [key, val]\n return self._container[key.lower()]\n\n def __getitem__(self, key):\n val = self._container[key.lower()]\n return \", \".join(val[1:])\n\n def __delitem__(self, key):\n del self._container[key.lower()]\n\n def __contains__(self, key):\n return key.lower() in self._container\n\n def __eq__(self, other):\n if not isinstance(other, Mapping) and not hasattr(other, \"keys\"):\n return False\n if not isinstance(other, type(self)):\n other = type(self)(other)\n return dict((k.lower(), v) for k, v in self.itermerged()) == dict(\n (k.lower(), v) for k, v in other.itermerged()\n )\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n if six.PY2: # Python 2\n iterkeys = MutableMapping.iterkeys\n itervalues = MutableMapping.itervalues\n\n __marker = object()\n\n def __len__(self):\n return len(self._container)\n\n def __iter__(self):\n # Only provide the originally cased names\n for vals in self._container.values():\n yield vals[0]\n\n def pop(self, key, default=__marker):\n \"\"\"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n If key is not found, d is returned if given, otherwise KeyError is raised.\n \"\"\"\n # Using the MutableMapping function directly fails due to the private marker.\n # Using ordinary dict.pop would expose the internal structures.\n # So let's reinvent the wheel.\n try:\n value = self[key]\n except KeyError:\n if default is self.__marker:\n raise\n return default\n else:\n del self[key]\n return value\n\n def discard(self, key):\n try:\n del self[key]\n except KeyError:\n pass\n\n def add(self, key, val):\n \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n \"\"\"\n key_lower = key.lower()\n new_vals = [key, val]\n # Keep the common case aka no item present as fast as possible\n vals = self._container.setdefault(key_lower, new_vals)\n if new_vals is not vals:\n vals.append(val)\n\n def extend(self, *args, **kwargs):\n \"\"\"Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n \"\"\"\n if len(args) > 1:\n raise TypeError(\n \"extend() takes at most 1 positional \"\n \"arguments ({0} given)\".format(len(args))\n )\n other = args[0] if len(args) >= 1 else ()\n\n if isinstance(other, HTTPHeaderDict):\n for key, val in other.iteritems():\n self.add(key, val)\n elif isinstance(other, Mapping):\n for key in other:\n self.add(key, other[key])\n elif hasattr(other, \"keys\"):\n for key in other.keys():\n self.add(key, other[key])\n else:\n for key, value in other:\n self.add(key, value)\n\n for key, value in kwargs.items():\n self.add(key, value)\n\n def getlist(self, key, default=__marker):\n \"\"\"Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist.\"\"\"\n try:\n vals = self._container[key.lower()]\n except KeyError:\n if default is self.__marker:\n return []\n return default\n else:\n return vals[1:]\n\n def _prepare_for_method_change(self):\n \"\"\"\n Remove content-specific header fields before changing the request\n method to GET or HEAD according to RFC 9110, Section 15.4.\n \"\"\"\n content_specific_headers = [\n \"Content-Encoding\",\n \"Content-Language\",\n \"Content-Location\",\n \"Content-Type\",\n \"Content-Length\",\n \"Digest\",\n \"Last-Modified\",\n ]\n for header in content_specific_headers:\n self.discard(header)\n return self\n\n # Backwards compatibility for httplib\n getheaders = getlist\n getallmatchingheaders = getlist\n iget = getlist\n\n # Backwards compatibility for http.cookiejar\n get_all = getlist\n\n def __repr__(self):\n return \"%s(%s)\" % (type(self).__name__, dict(self.itermerged()))\n\n def _copy_from(self, other):\n for key in other:\n val = other.getlist(key)\n if isinstance(val, list):\n # Don't need to convert tuples\n val = list(val)\n self._container[key.lower()] = [key] + val\n\n def copy(self):\n clone = type(self)()\n clone._copy_from(self)\n return clone\n\n def iteritems(self):\n \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n for key in self:\n vals = self._container[key.lower()]\n for val in vals[1:]:\n yield vals[0], val\n\n def itermerged(self):\n \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n for key in self:\n val = self._container[key.lower()]\n yield val[0], \", \".join(val[1:])\n\n def items(self):\n return list(self.iteritems())\n\n @classmethod\n def from_httplib(cls, message): # Python 2\n \"\"\"Read headers from a Python 2 httplib message object.\"\"\"\n # python2.7 does not expose a proper API for exporting multiheaders\n # efficiently. This function re-reads raw lines from the message\n # object and extracts the multiheaders properly.\n obs_fold_continued_leaders = (\" \", \"\\t\")\n headers = []\n\n for line in message.headers:\n if line.startswith(obs_fold_continued_leaders):\n if not headers:\n # We received a header line that starts with OWS as described\n # in RFC-7230 S3.2.4. This indicates a multiline header, but\n # there exists no previous header to which we can attach it.\n raise InvalidHeader(\n \"Header continuation with no previous header: %s\" % line\n )\n else:\n key, value = headers[-1]\n headers[-1] = (key, value + \" \" + line.strip())\n continue\n\n key, value = line.split(\":\", 1)\n headers.append((key, value.strip()))\n\n return cls(headers)" }, { "identifier": "RecentlyUsedContainer", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/_collections.py", "snippet": "class RecentlyUsedContainer(MutableMapping):\n \"\"\"\n Provides a thread-safe dict-like container which maintains up to\n ``maxsize`` keys while throwing away the least-recently-used keys beyond\n ``maxsize``.\n\n :param maxsize:\n Maximum number of recent elements to retain.\n\n :param dispose_func:\n Every time an item is evicted from the container,\n ``dispose_func(value)`` is called. Callback which will get called\n \"\"\"\n\n ContainerCls = OrderedDict\n\n def __init__(self, maxsize=10, dispose_func=None):\n self._maxsize = maxsize\n self.dispose_func = dispose_func\n\n self._container = self.ContainerCls()\n self.lock = RLock()\n\n def __getitem__(self, key):\n # Re-insert the item, moving it to the end of the eviction line.\n with self.lock:\n item = self._container.pop(key)\n self._container[key] = item\n return item\n\n def __setitem__(self, key, value):\n evicted_value = _Null\n with self.lock:\n # Possibly evict the existing value of 'key'\n evicted_value = self._container.get(key, _Null)\n self._container[key] = value\n\n # If we didn't evict an existing value, we might have to evict the\n # least recently used item from the beginning of the container.\n if len(self._container) > self._maxsize:\n _key, evicted_value = self._container.popitem(last=False)\n\n if self.dispose_func and evicted_value is not _Null:\n self.dispose_func(evicted_value)\n\n def __delitem__(self, key):\n with self.lock:\n value = self._container.pop(key)\n\n if self.dispose_func:\n self.dispose_func(value)\n\n def __len__(self):\n with self.lock:\n return len(self._container)\n\n def __iter__(self):\n raise NotImplementedError(\n \"Iteration over this class is unlikely to be threadsafe.\"\n )\n\n def clear(self):\n with self.lock:\n # Copy pointers to all values, then wipe the mapping\n values = list(itervalues(self._container))\n self._container.clear()\n\n if self.dispose_func:\n for value in values:\n self.dispose_func(value)\n\n def keys(self):\n with self.lock:\n return list(iterkeys(self._container))" }, { "identifier": "HTTPConnectionPool", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/connectionpool.py", "snippet": "class ConnectionPool(object):\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\nclass HTTPSConnectionPool(HTTPConnectionPool):\n def __init__(self, host, port=None):\n def __str__(self):\n def __enter__(self):\n def __exit__(self, exc_type, exc_val, exc_tb):\n def close(self):\n def __init__(\n self,\n host,\n port=None,\n strict=False,\n timeout=Timeout.DEFAULT_TIMEOUT,\n maxsize=1,\n block=False,\n headers=None,\n retries=None,\n _proxy=None,\n _proxy_headers=None,\n _proxy_config=None,\n **conn_kw\n ):\n def _new_conn(self):\n def _get_conn(self, timeout=None):\n def _put_conn(self, conn):\n def _validate_conn(self, conn):\n def _prepare_proxy(self, conn):\n def _get_timeout(self, timeout):\n def _raise_timeout(self, err, url, timeout_value):\n def _make_request(\n self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw\n ):\n def _absolute_url(self, path):\n def close(self):\n def is_same_host(self, url):\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n retries=None,\n redirect=True,\n assert_same_host=True,\n timeout=_Default,\n pool_timeout=None,\n release_conn=None,\n chunked=False,\n body_pos=None,\n **response_kw\n ):\n def _is_ssl_error_message_from_http_proxy(ssl_error):\n def __init__(\n self,\n host,\n port=None,\n strict=False,\n timeout=Timeout.DEFAULT_TIMEOUT,\n maxsize=1,\n block=False,\n headers=None,\n retries=None,\n _proxy=None,\n _proxy_headers=None,\n key_file=None,\n cert_file=None,\n cert_reqs=None,\n key_password=None,\n ca_certs=None,\n ssl_version=None,\n assert_hostname=None,\n assert_fingerprint=None,\n ca_cert_dir=None,\n **conn_kw\n ):\n def _prepare_conn(self, conn):\n def _prepare_proxy(self, conn):\n def _new_conn(self):\n def _validate_conn(self, conn):\ndef connection_from_url(url, **kw):\ndef _normalize_host(host, scheme):\ndef _close_pool_connections(pool):" }, { "identifier": "LocationValueError", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class LocationValueError(ValueError, HTTPError):\n \"\"\"Raised when there is something wrong with a given URL input.\"\"\"\n\n pass" }, { "identifier": "MaxRetryError", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class MaxRetryError(RequestError):\n \"\"\"Raised when the maximum number of retries is exceeded.\n\n :param pool: The connection pool\n :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n :param string url: The requested Url\n :param exceptions.Exception reason: The underlying error\n\n \"\"\"\n\n def __init__(self, pool, url, reason=None):\n self.reason = reason\n\n message = \"Max retries exceeded with url: %s (Caused by %r)\" % (url, reason)\n\n RequestError.__init__(self, pool, url, message)" }, { "identifier": "ProxySchemeUnknown", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):\n \"\"\"ProxyManager does not support the supplied scheme\"\"\"\n\n # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.\n\n def __init__(self, scheme):\n # 'localhost' is here because our URL parser parses\n # localhost:8080 -> scheme=localhost, remove if we fix this.\n if scheme == \"localhost\":\n scheme = None\n if scheme is None:\n message = \"Proxy URL had no scheme, should start with http:// or https://\"\n else:\n message = (\n \"Proxy URL had unsupported scheme %s, should use http:// or https://\"\n % scheme\n )\n super(ProxySchemeUnknown, self).__init__(message)" }, { "identifier": "ProxySchemeUnsupported", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class ProxySchemeUnsupported(ValueError):\n \"\"\"Fetching HTTPS resources through HTTPS proxies is unsupported\"\"\"\n\n pass" }, { "identifier": "URLSchemeUnknown", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/exceptions.py", "snippet": "class URLSchemeUnknown(LocationValueError):\n \"\"\"Raised when a URL input has an unsupported scheme.\"\"\"\n\n def __init__(self, scheme):\n message = \"Not supported URL scheme %s\" % scheme\n super(URLSchemeUnknown, self).__init__(message)\n\n self.scheme = scheme" }, { "identifier": "six", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/packages/six.py", "snippet": "PY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\nPY34 = sys.version_info[0:2] >= (3, 4)\n MAXSIZE = sys.maxsize\n MAXSIZE = int((1 << 31) - 1)\n MAXSIZE = int((1 << 31) - 1)\n MAXSIZE = int((1 << 63) - 1)\n class X(object):\nclass _LazyDescr(object):\nclass MovedModule(_LazyDescr):\nclass _LazyModule(types.ModuleType):\nclass MovedAttribute(_LazyDescr):\nclass _SixMetaPathImporter(object):\nclass _MovedItems(_LazyModule):\nclass Module_six_moves_urllib_parse(_LazyModule):\nclass Module_six_moves_urllib_error(_LazyModule):\nclass Module_six_moves_urllib_request(_LazyModule):\nclass Module_six_moves_urllib_response(_LazyModule):\nclass Module_six_moves_urllib_robotparser(_LazyModule):\nclass Module_six_moves_urllib(types.ModuleType):\n class Iterator(object):\n class metaclass(type):\n def __len__(self):\ndef _add_doc(func, doc):\ndef _import_module(name):\n def __init__(self, name):\n def __get__(self, obj, tp):\n def __init__(self, name, old, new=None):\n def _resolve(self):\n def __getattr__(self, attr):\n def __init__(self, name):\n def __dir__(self):\n def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n def _resolve(self):\n def __init__(self, six_module_name):\n def _add_module(self, mod, *fullnames):\n def _get_module(self, fullname):\n def find_module(self, fullname, path=None):\n def find_spec(self, fullname, path, target=None):\n def __get_module(self, fullname):\n def load_module(self, fullname):\n def is_package(self, fullname):\n def get_code(self, fullname):\n def create_module(self, spec):\n def exec_module(self, module):\n def __dir__(self):\ndef add_move(move):\ndef remove_move(name):\n def advance_iterator(it):\n def callable(obj):\n def get_unbound_function(unbound):\n def create_unbound_method(func, cls):\n def get_unbound_function(unbound):\n def create_bound_method(func, obj):\n def create_unbound_method(func, cls):\n def next(self):\n def iterkeys(d, **kw):\n def itervalues(d, **kw):\n def iteritems(d, **kw):\n def iterlists(d, **kw):\n def iterkeys(d, **kw):\n def itervalues(d, **kw):\n def iteritems(d, **kw):\n def iterlists(d, **kw):\n def b(s):\n def u(s):\n def b(s):\n def u(s):\n def byte2int(bs):\n def indexbytes(buf, i):\ndef assertCountEqual(self, *args, **kwargs):\ndef assertRaisesRegex(self, *args, **kwargs):\ndef assertRegex(self, *args, **kwargs):\ndef assertNotRegex(self, *args, **kwargs):\n def reraise(tp, value, tb=None):\n def exec_(_code_, _globs_=None, _locs_=None):\n def raise_from(value, from_value):\n def print_(*args, **kwargs):\n def write(data):\n def print_(*args, **kwargs):\n def _update_wrapper(\n wrapper,\n wrapped,\n assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES,\n ):\n def wraps(\n wrapped,\n assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES,\n ):\ndef with_metaclass(meta, *bases):\n def __new__(cls, name, this_bases, d):\n def __prepare__(cls, name, this_bases):\ndef add_metaclass(metaclass):\n def wrapper(cls):\ndef ensure_binary(s, encoding=\"utf-8\", errors=\"strict\"):\ndef ensure_str(s, encoding=\"utf-8\", errors=\"strict\"):\ndef ensure_text(s, encoding=\"utf-8\", errors=\"strict\"):\ndef python_2_unicode_compatible(klass):" }, { "identifier": "RequestMethods", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/request.py", "snippet": "class RequestMethods(object):\n \"\"\"\n Convenience mixin for classes who implement a :meth:`urlopen` method, such\n as :class:`urllib3.HTTPConnectionPool` and\n :class:`urllib3.PoolManager`.\n\n Provides behavior for making common types of HTTP request methods and\n decides which type of request field encoding to use.\n\n Specifically,\n\n :meth:`.request_encode_url` is for sending requests whose fields are\n encoded in the URL (such as GET, HEAD, DELETE).\n\n :meth:`.request_encode_body` is for sending requests whose fields are\n encoded in the *body* of the request using multipart or www-form-urlencoded\n (such as for POST, PUT, PATCH).\n\n :meth:`.request` is for making any kind of request, it will look up the\n appropriate encoding format and use one of the above two methods to make\n the request.\n\n Initializer parameters:\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n \"\"\"\n\n _encode_url_methods = {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\"}\n\n def __init__(self, headers=None):\n self.headers = headers or {}\n\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n encode_multipart=True,\n multipart_boundary=None,\n **kw\n ): # Abstract\n raise NotImplementedError(\n \"Classes extending RequestMethods must implement \"\n \"their own ``urlopen`` method.\"\n )\n\n def request(self, method, url, fields=None, headers=None, **urlopen_kw):\n \"\"\"\n Make a request using :meth:`urlopen` with the appropriate encoding of\n ``fields`` based on the ``method`` used.\n\n This is a convenience method that requires the least amount of manual\n effort. It can be used in most situations, while still having the\n option to drop down to more specific methods when necessary, such as\n :meth:`request_encode_url`, :meth:`request_encode_body`,\n or even the lowest level :meth:`urlopen`.\n \"\"\"\n method = method.upper()\n\n urlopen_kw[\"request_url\"] = url\n\n if method in self._encode_url_methods:\n return self.request_encode_url(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n else:\n return self.request_encode_body(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n\n def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw):\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw = {\"headers\": headers}\n extra_kw.update(urlopen_kw)\n\n if fields:\n url += \"?\" + urlencode(fields)\n\n return self.urlopen(method, url, **extra_kw)\n\n def request_encode_body(\n self,\n method,\n url,\n fields=None,\n headers=None,\n encode_multipart=True,\n multipart_boundary=None,\n **urlopen_kw\n ):\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :func:`urllib3.encode_multipart_formdata` is used to encode\n the payload with the appropriate content type. Otherwise\n :func:`urllib.parse.urlencode` is used with the\n 'application/x-www-form-urlencoded' content type.\n\n Multipart encoding must be used when posting files, and it's reasonably\n safe to use it in other times too. However, it may break request\n signing, such as with OAuth.\n\n Supports an optional ``fields`` parameter of key/value strings AND\n key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n the MIME type is optional. For example::\n\n fields = {\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(),\n 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n }\n\n When uploading a file, providing a filename (the first parameter of the\n tuple) is optional but recommended to best mimic behavior of browsers.\n\n Note that if ``headers`` are supplied, the 'Content-Type' header will\n be overwritten because it depends on the dynamic random boundary string\n which is used to compose the body of the request. The random boundary\n string can be explicitly set with the ``multipart_boundary`` parameter.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw = {\"headers\": {}}\n\n if fields:\n if \"body\" in urlopen_kw:\n raise TypeError(\n \"request got values for both 'fields' and 'body', can only specify one.\"\n )\n\n if encode_multipart:\n body, content_type = encode_multipart_formdata(\n fields, boundary=multipart_boundary\n )\n else:\n body, content_type = (\n urlencode(fields),\n \"application/x-www-form-urlencoded\",\n )\n\n extra_kw[\"body\"] = body\n extra_kw[\"headers\"] = {\"Content-Type\": content_type}\n\n extra_kw[\"headers\"].update(headers)\n extra_kw.update(urlopen_kw)\n\n return self.urlopen(method, url, **extra_kw)" }, { "identifier": "connection_requires_http_tunnel", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/util/proxy.py", "snippet": "def connection_requires_http_tunnel(\n proxy_url=None, proxy_config=None, destination_scheme=None\n):\n \"\"\"\n Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n :param URL proxy_url:\n URL of the proxy.\n :param ProxyConfig proxy_config:\n Proxy configuration from poolmanager.py\n :param str destination_scheme:\n The scheme of the destination. (i.e https, http, etc)\n \"\"\"\n # If we're not using a proxy, no way to use a tunnel.\n if proxy_url is None:\n return False\n\n # HTTP destinations never require tunneling, we always forward.\n if destination_scheme == \"http\":\n return False\n\n # Support for forwarding with HTTPS proxies and HTTPS destinations.\n if (\n proxy_url.scheme == \"https\"\n and proxy_config\n and proxy_config.use_forwarding_for_https\n ):\n return False\n\n # Otherwise always use a tunnel.\n return True" }, { "identifier": "Retry", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/util/retry.py", "snippet": "class Retry(object):\n \"\"\"Retry configuration.\n\n Each retry attempt will create a new Retry object with updated values, so\n they can be safely reused.\n\n Retries can be defined as a default for a pool::\n\n retries = Retry(connect=5, read=2, redirect=5)\n http = PoolManager(retries=retries)\n response = http.request('GET', 'http://example.com/')\n\n Or per-request (which overrides the default for the pool)::\n\n response = http.request('GET', 'http://example.com/', retries=Retry(10))\n\n Retries can be disabled by passing ``False``::\n\n response = http.request('GET', 'http://example.com/', retries=False)\n\n Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n retries are disabled, in which case the causing exception will be raised.\n\n :param int total:\n Total number of retries to allow. Takes precedence over other counts.\n\n Set to ``None`` to remove this constraint and fall back on other\n counts.\n\n Set to ``0`` to fail on the first retry.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int connect:\n How many connection-related errors to retry on.\n\n These are errors raised before the request is sent to the remote server,\n which we assume has not triggered the server to process the request.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int read:\n How many times to retry on read errors.\n\n These errors are raised after the request was sent to the server, so the\n request may have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int redirect:\n How many redirects to perform. Limit this to avoid infinite redirect\n loops.\n\n A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n 308.\n\n Set to ``0`` to fail on the first retry of this type.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int status:\n How many times to retry on bad status codes.\n\n These are retries made on responses, where status code matches\n ``status_forcelist``.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int other:\n How many times to retry on other errors.\n\n Other errors are errors that are not connect, read, redirect or status errors.\n These errors might be raised after the request was sent to the server, so the\n request might have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n If ``total`` is not set, it's a good idea to set this to 0 to account\n for unexpected edge cases and avoid infinite retry loops.\n\n :param iterable allowed_methods:\n Set of uppercased HTTP method verbs that we should retry on.\n\n By default, we only retry on methods which are considered to be\n idempotent (multiple requests with the same parameters end with the\n same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n Set to a ``False`` value to retry on any verb.\n\n .. warning::\n\n Previously this parameter was named ``method_whitelist``, that\n usage is deprecated in v1.26.0 and will be removed in v2.0.\n\n :param iterable status_forcelist:\n A set of integer HTTP status codes that we should force a retry on.\n A retry is initiated if the request method is in ``allowed_methods``\n and the response status code is in ``status_forcelist``.\n\n By default, this is disabled with ``None``.\n\n :param float backoff_factor:\n A backoff factor to apply between attempts after the second try\n (most errors are resolved immediately by a second try without a\n delay). urllib3 will sleep for::\n\n {backoff factor} * (2 ** ({number of total retries} - 1))\n\n seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep\n for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer\n than :attr:`Retry.DEFAULT_BACKOFF_MAX`.\n\n By default, backoff is disabled (set to 0).\n\n :param bool raise_on_redirect: Whether, if the number of redirects is\n exhausted, to raise a MaxRetryError, or to return a response with a\n response code in the 3xx range.\n\n :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n whether we should raise an exception, or return a response,\n if status falls in ``status_forcelist`` range and retries have\n been exhausted.\n\n :param tuple history: The history of the request encountered during\n each call to :meth:`~Retry.increment`. The list is in the order\n the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n :param bool respect_retry_after_header:\n Whether to respect Retry-After header on status codes defined as\n :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n :param iterable remove_headers_on_redirect:\n Sequence of headers to remove from the request when a response\n indicating a redirect is returned before firing off the redirected\n request.\n \"\"\"\n\n #: Default methods to be used for ``allowed_methods``\n DEFAULT_ALLOWED_METHODS = frozenset(\n [\"HEAD\", \"GET\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"]\n )\n\n #: Default status codes to be used for ``status_forcelist``\n RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n #: Default headers to be used for ``remove_headers_on_redirect``\n DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset([\"Cookie\", \"Authorization\"])\n\n #: Maximum backoff time.\n DEFAULT_BACKOFF_MAX = 120\n\n def __init__(\n self,\n total=10,\n connect=None,\n read=None,\n redirect=None,\n status=None,\n other=None,\n allowed_methods=_Default,\n status_forcelist=None,\n backoff_factor=0,\n raise_on_redirect=True,\n raise_on_status=True,\n history=None,\n respect_retry_after_header=True,\n remove_headers_on_redirect=_Default,\n # TODO: Deprecated, remove in v2.0\n method_whitelist=_Default,\n ):\n\n if method_whitelist is not _Default:\n if allowed_methods is not _Default:\n raise ValueError(\n \"Using both 'allowed_methods' and \"\n \"'method_whitelist' together is not allowed. \"\n \"Instead only use 'allowed_methods'\"\n )\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n stacklevel=2,\n )\n allowed_methods = method_whitelist\n if allowed_methods is _Default:\n allowed_methods = self.DEFAULT_ALLOWED_METHODS\n if remove_headers_on_redirect is _Default:\n remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n self.total = total\n self.connect = connect\n self.read = read\n self.status = status\n self.other = other\n\n if redirect is False or total is False:\n redirect = 0\n raise_on_redirect = False\n\n self.redirect = redirect\n self.status_forcelist = status_forcelist or set()\n self.allowed_methods = allowed_methods\n self.backoff_factor = backoff_factor\n self.raise_on_redirect = raise_on_redirect\n self.raise_on_status = raise_on_status\n self.history = history or tuple()\n self.respect_retry_after_header = respect_retry_after_header\n self.remove_headers_on_redirect = frozenset(\n [h.lower() for h in remove_headers_on_redirect]\n )\n\n def new(self, **kw):\n params = dict(\n total=self.total,\n connect=self.connect,\n read=self.read,\n redirect=self.redirect,\n status=self.status,\n other=self.other,\n status_forcelist=self.status_forcelist,\n backoff_factor=self.backoff_factor,\n raise_on_redirect=self.raise_on_redirect,\n raise_on_status=self.raise_on_status,\n history=self.history,\n remove_headers_on_redirect=self.remove_headers_on_redirect,\n respect_retry_after_header=self.respect_retry_after_header,\n )\n\n # TODO: If already given in **kw we use what's given to us\n # If not given we need to figure out what to pass. We decide\n # based on whether our class has the 'method_whitelist' property\n # and if so we pass the deprecated 'method_whitelist' otherwise\n # we use 'allowed_methods'. Remove in v2.0\n if \"method_whitelist\" not in kw and \"allowed_methods\" not in kw:\n if \"method_whitelist\" in self.__dict__:\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n )\n params[\"method_whitelist\"] = self.allowed_methods\n else:\n params[\"allowed_methods\"] = self.allowed_methods\n\n params.update(kw)\n return type(self)(**params)\n\n @classmethod\n def from_int(cls, retries, redirect=True, default=None):\n \"\"\"Backwards-compatibility for the old retries format.\"\"\"\n if retries is None:\n retries = default if default is not None else cls.DEFAULT\n\n if isinstance(retries, Retry):\n return retries\n\n redirect = bool(redirect) and None\n new_retries = cls(retries, redirect=redirect)\n log.debug(\"Converted retries value: %r -> %r\", retries, new_retries)\n return new_retries\n\n def get_backoff_time(self):\n \"\"\"Formula for computing the current backoff\n\n :rtype: float\n \"\"\"\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n return min(self.DEFAULT_BACKOFF_MAX, backoff_value)\n\n def parse_retry_after(self, retry_after):\n # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n if re.match(r\"^\\s*[0-9]+\\s*$\", retry_after):\n seconds = int(retry_after)\n else:\n retry_date_tuple = email.utils.parsedate_tz(retry_after)\n if retry_date_tuple is None:\n raise InvalidHeader(\"Invalid Retry-After header: %s\" % retry_after)\n if retry_date_tuple[9] is None: # Python 2\n # Assume UTC if no timezone was specified\n # On Python2.7, parsedate_tz returns None for a timezone offset\n # instead of 0 if no timezone is given, where mktime_tz treats\n # a None timezone offset as local time.\n retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]\n\n retry_date = email.utils.mktime_tz(retry_date_tuple)\n seconds = retry_date - time.time()\n\n if seconds < 0:\n seconds = 0\n\n return seconds\n\n def get_retry_after(self, response):\n \"\"\"Get the value of Retry-After in seconds.\"\"\"\n\n retry_after = response.headers.get(\"Retry-After\")\n\n if retry_after is None:\n return None\n\n return self.parse_retry_after(retry_after)\n\n def sleep_for_retry(self, response=None):\n retry_after = self.get_retry_after(response)\n if retry_after:\n time.sleep(retry_after)\n return True\n\n return False\n\n def _sleep_backoff(self):\n backoff = self.get_backoff_time()\n if backoff <= 0:\n return\n time.sleep(backoff)\n\n def sleep(self, response=None):\n \"\"\"Sleep between retry attempts.\n\n This method will respect a server's ``Retry-After`` response header\n and sleep the duration of the time requested. If that is not present, it\n will use an exponential backoff. By default, the backoff factor is 0 and\n this method will return immediately.\n \"\"\"\n\n if self.respect_retry_after_header and response:\n slept = self.sleep_for_retry(response)\n if slept:\n return\n\n self._sleep_backoff()\n\n def _is_connection_error(self, err):\n \"\"\"Errors when we're fairly sure that the server did not receive the\n request, so it should be safe to retry.\n \"\"\"\n if isinstance(err, ProxyError):\n err = err.original_error\n return isinstance(err, ConnectTimeoutError)\n\n def _is_read_error(self, err):\n \"\"\"Errors that occur after the request has been started, so we should\n assume that the server began processing it.\n \"\"\"\n return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n def _is_method_retryable(self, method):\n \"\"\"Checks if a given HTTP method should be retried upon, depending if\n it is included in the allowed_methods\n \"\"\"\n # TODO: For now favor if the Retry implementation sets its own method_whitelist\n # property outside of our constructor to avoid breaking custom implementations.\n if \"method_whitelist\" in self.__dict__:\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n )\n allowed_methods = self.method_whitelist\n else:\n allowed_methods = self.allowed_methods\n\n if allowed_methods and method.upper() not in allowed_methods:\n return False\n return True\n\n def is_retry(self, method, status_code, has_retry_after=False):\n \"\"\"Is this method/status code retryable? (Based on allowlists and control\n variables such as the number of total retries to allow, whether to\n respect the Retry-After header, whether this header is present, and\n whether the returned status code is on the list of status codes to\n be retried upon on the presence of the aforementioned header)\n \"\"\"\n if not self._is_method_retryable(method):\n return False\n\n if self.status_forcelist and status_code in self.status_forcelist:\n return True\n\n return (\n self.total\n and self.respect_retry_after_header\n and has_retry_after\n and (status_code in self.RETRY_AFTER_STATUS_CODES)\n )\n\n def is_exhausted(self):\n \"\"\"Are we out of retries?\"\"\"\n retry_counts = (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n retry_counts = list(filter(None, retry_counts))\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0\n\n def increment(\n self,\n method=None,\n url=None,\n response=None,\n error=None,\n _pool=None,\n _stacktrace=None,\n ):\n \"\"\"Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.HTTPResponse`\n :param Exception error: An error encountered during the request, or\n None if the response was received successfully.\n\n :return: A new ``Retry`` object.\n \"\"\"\n if self.total is False and error:\n # Disabled, indicate to re-raise the error.\n raise six.reraise(type(error), error, _stacktrace)\n\n total = self.total\n if total is not None:\n total -= 1\n\n connect = self.connect\n read = self.read\n redirect = self.redirect\n status_count = self.status\n other = self.other\n cause = \"unknown\"\n status = None\n redirect_location = None\n\n if error and self._is_connection_error(error):\n # Connect retry?\n if connect is False:\n raise six.reraise(type(error), error, _stacktrace)\n elif connect is not None:\n connect -= 1\n\n elif error and self._is_read_error(error):\n # Read retry?\n if read is False or not self._is_method_retryable(method):\n raise six.reraise(type(error), error, _stacktrace)\n elif read is not None:\n read -= 1\n\n elif error:\n # Other retry?\n if other is not None:\n other -= 1\n\n elif response and response.get_redirect_location():\n # Redirect retry?\n if redirect is not None:\n redirect -= 1\n cause = \"too many redirects\"\n redirect_location = response.get_redirect_location()\n status = response.status\n\n else:\n # Incrementing because of a server error like a 500 in\n # status_forcelist and the given method is in the allowed_methods\n cause = ResponseError.GENERIC_ERROR\n if response and response.status:\n if status_count is not None:\n status_count -= 1\n cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n status = response.status\n\n history = self.history + (\n RequestHistory(method, url, error, status, redirect_location),\n )\n\n new_retry = self.new(\n total=total,\n connect=connect,\n read=read,\n redirect=redirect,\n status=status_count,\n other=other,\n history=history,\n )\n\n if new_retry.is_exhausted():\n raise MaxRetryError(_pool, url, error or ResponseError(cause))\n\n log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n return new_retry\n\n def __repr__(self):\n return (\n \"{cls.__name__}(total={self.total}, connect={self.connect}, \"\n \"read={self.read}, redirect={self.redirect}, status={self.status})\"\n ).format(cls=type(self), self=self)\n\n def __getattr__(self, item):\n if item == \"method_whitelist\":\n # TODO: Remove this deprecated alias in v2.0\n warnings.warn(\n \"Using 'method_whitelist' with Retry is deprecated and \"\n \"will be removed in v2.0. Use 'allowed_methods' instead\",\n DeprecationWarning,\n )\n return self.allowed_methods\n try:\n return getattr(super(Retry, self), item)\n except AttributeError:\n return getattr(Retry, item)" }, { "identifier": "parse_url", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/util/url.py", "snippet": "def parse_url(url):\n \"\"\"\n Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n performed to parse incomplete urls. Fields not provided will be None.\n This parser is RFC 3986 and RFC 6874 compliant.\n\n The parser logic and helper functions are based heavily on\n work done in the ``rfc3986`` module.\n\n :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n Partly backwards-compatible with :mod:`urlparse`.\n\n Example::\n\n >>> parse_url('http://google.com/mail/')\n Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n >>> parse_url('google.com:80')\n Url(scheme=None, host='google.com', port=80, path=None, ...)\n >>> parse_url('/foo?bar')\n Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n \"\"\"\n if not url:\n # Empty\n return Url()\n\n source_url = url\n if not SCHEME_RE.search(url):\n url = \"//\" + url\n\n try:\n scheme, authority, path, query, fragment = URI_RE.match(url).groups()\n normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES\n\n if scheme:\n scheme = scheme.lower()\n\n if authority:\n auth, _, host_port = authority.rpartition(\"@\")\n auth = auth or None\n host, port = _HOST_PORT_RE.match(host_port).groups()\n if auth and normalize_uri:\n auth = _encode_invalid_chars(auth, USERINFO_CHARS)\n if port == \"\":\n port = None\n else:\n auth, host, port = None, None, None\n\n if port is not None:\n port = int(port)\n if not (0 <= port <= 65535):\n raise LocationParseError(url)\n\n host = _normalize_host(host, scheme)\n\n if normalize_uri and path:\n path = _remove_path_dot_segments(path)\n path = _encode_invalid_chars(path, PATH_CHARS)\n if normalize_uri and query:\n query = _encode_invalid_chars(query, QUERY_CHARS)\n if normalize_uri and fragment:\n fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)\n\n except (ValueError, AttributeError):\n return six.raise_from(LocationParseError(source_url), None)\n\n # For the sake of backwards compatibility we put empty\n # string values for path if there are any defined values\n # beyond the path in the URL.\n # TODO: Remove this when we break backwards compatibility.\n if not path:\n if query is not None or fragment is not None:\n path = \"\"\n else:\n path = None\n\n # Ensure that each part of the URL is a `str` for\n # backwards compatibility.\n if isinstance(url, six.text_type):\n ensure_func = six.ensure_text\n else:\n ensure_func = six.ensure_str\n\n def ensure_type(x):\n return x if x is None else ensure_func(x)\n\n return Url(\n scheme=ensure_type(scheme),\n auth=ensure_type(auth),\n host=ensure_type(host),\n port=port,\n path=ensure_type(path),\n query=ensure_type(query),\n fragment=ensure_type(fragment),\n )" } ]
import collections import functools import logging from ._collections import HTTPHeaderDict, RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, ProxySchemeUnsupported, URLSchemeUnknown, ) from .packages import six from .packages.six.moves.urllib.parse import urljoin from .request import RequestMethods from .util.proxy import connection_requires_http_tunnel from .util.retry import Retry from .util.url import parse_url
14,652
self.pool_classes_by_scheme = pool_classes_by_scheme self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.clear() # Return False to re-raise any potential exceptions return False def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context["scheme"] = scheme or "http" if not port: port = port_by_scheme.get(request_context["scheme"].lower(), 80) request_context["port"] = port request_context["host"] = host return self.connection_from_context(request_context) def connection_from_context(self, request_context): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. """ scheme = request_context["scheme"].lower() pool_key_constructor = self.key_fn_by_scheme.get(scheme) if not pool_key_constructor: raise URLSchemeUnknown(scheme) pool_key = pool_key_constructor(request_context) return self.connection_from_pool_key(pool_key, request_context=request_context) def connection_from_pool_key(self, pool_key, request_context=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields. """ with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type scheme = request_context["scheme"] host = request_context["host"] port = request_context["port"] pool = self._new_pool(scheme, host, port, request_context=request_context) self.pools[pool_key] = pool return pool def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used instead. Note that if a new pool does not need to be created for the request, the provided ``pool_kwargs`` are not used. """
from __future__ import absolute_import __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ca_cert_dir", "ssl_context", "key_password", "server_hostname", ) # All known keyword arguments that could be provided to the pool manager, its # pools, or the underlying connections. This is used to construct a pool key. _key_fields = ( "key_scheme", # str "key_host", # str "key_port", # int "key_timeout", # int or float or Timeout "key_retries", # int or Retry "key_strict", # bool "key_block", # bool "key_source_address", # str "key_key_file", # str "key_key_password", # str "key_cert_file", # str "key_cert_reqs", # str "key_ca_certs", # str "key_ssl_version", # str "key_ca_cert_dir", # str "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext "key_maxsize", # int "key_headers", # dict "key__proxy", # parsed proxy url "key__proxy_headers", # dict "key__proxy_config", # class "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples "key__socks_options", # dict "key_assert_hostname", # bool or string "key_assert_fingerprint", # str "key_server_hostname", # str ) #: The namedtuple class used to construct keys for the connection pool. #: All custom key schemes should include the fields in this key at a minimum. PoolKey = collections.namedtuple("PoolKey", _key_fields) _proxy_config_fields = ("ssl_context", "use_forwarding_for_https") ProxyConfig = collections.namedtuple("ProxyConfig", _proxy_config_fields) def _default_key_normalizer(key_class, request_context): """ Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param key_class: The class to use when constructing the key. This should be a namedtuple with the ``scheme`` and ``host`` keys at a minimum. :type key_class: namedtuple :param request_context: A dictionary-like object that contain the context for a request. :type request_context: dict :return: A namedtuple that can be used as a connection pool key. :rtype: PoolKey """ # Since we mutate the dictionary, make a copy first context = request_context.copy() context["scheme"] = context["scheme"].lower() context["host"] = context["host"].lower() # These are both dictionaries and need to be transformed into frozensets for key in ("headers", "_proxy_headers", "_socks_options"): if key in context and context[key] is not None: context[key] = frozenset(context[key].items()) # The socket_options key may be a list and needs to be transformed into a # tuple. socket_opts = context.get("socket_options") if socket_opts is not None: context["socket_options"] = tuple(socket_opts) # Map the kwargs to the names in the namedtuple - this is necessary since # namedtuples can't have fields starting with '_'. for key in list(context.keys()): context["key_" + key] = context.pop(key) # Default to ``None`` for keys missing from the context for field in key_class._fields: if field not in context: context[field] = None return key_class(**context) #: A dictionary that maps a scheme to a callable that creates a pool key. #: This can be used to alter the way pool keys are constructed, if desired. #: Each PoolManager makes a copy of this dictionary so they can be configured #: globally here, or individually on the instance. key_fn_by_scheme = { "http": functools.partial(_default_key_normalizer, PoolKey), "https": functools.partial(_default_key_normalizer, PoolKey), } pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} class PoolManager(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param \\**connection_pool_kw: Additional parameters are used to create fresh :class:`urllib3.connectionpool.ConnectionPool` instances. Example:: >>> manager = PoolManager(num_pools=2) >>> r = manager.request('GET', 'http://google.com/') >>> r = manager.request('GET', 'http://google.com/mail') >>> r = manager.request('GET', 'http://yahoo.com/') >>> len(manager.pools) 2 """ proxy = None proxy_config = None def __init__(self, num_pools=10, headers=None, **connection_pool_kw): RequestMethods.__init__(self, headers) self.connection_pool_kw = connection_pool_kw self.pools = RecentlyUsedContainer(num_pools) # Locally set the pool classes and keys so other PoolManagers can # override them. self.pool_classes_by_scheme = pool_classes_by_scheme self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.clear() # Return False to re-raise any potential exceptions return False def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context["scheme"] = scheme or "http" if not port: port = port_by_scheme.get(request_context["scheme"].lower(), 80) request_context["port"] = port request_context["host"] = host return self.connection_from_context(request_context) def connection_from_context(self, request_context): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. """ scheme = request_context["scheme"].lower() pool_key_constructor = self.key_fn_by_scheme.get(scheme) if not pool_key_constructor: raise URLSchemeUnknown(scheme) pool_key = pool_key_constructor(request_context) return self.connection_from_pool_key(pool_key, request_context=request_context) def connection_from_pool_key(self, pool_key, request_context=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields. """ with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type scheme = request_context["scheme"] host = request_context["host"] port = request_context["port"] pool = self._new_pool(scheme, host, port, request_context=request_context) self.pools[pool_key] = pool return pool def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used instead. Note that if a new pool does not need to be created for the request, the provided ``pool_kwargs`` are not used. """
u = parse_url(url)
12
2023-11-27 07:01:39+00:00
24k
NobiDeveloper/Nobita-Filter-Bot
plugins/pm_filter.py
[ { "identifier": "script", "path": "Script.py", "snippet": "class script(object):\n START_TXT = \"\"\"\n<b>{},\n\nɪ ᴄᴀɴ ᴘʀᴏᴠɪᴅᴇ ᴍᴏᴠɪᴇs ᴀɴᴅ sᴇʀɪᴇs,\nᴊᴜsᴛ ᴀᴅᴅ ᴍᴇ ᴛᴏ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴀɴᴅ ᴇɴᴊᴏʏ 😍\n\n💞 ᴍᴀɪɴᴛᴀɪɴᴇᴅ ʙʏ : <a href='https://telegram.me/MovieVillaYT'>ᴍᴏᴠɪᴇ ᴠɪʟʟᴀ</a></b>\n\"\"\"\n\n HELP_TXT = \"\"\"\n<b>{},\n\n/g_info - ᴛᴏ ᴄʜᴇᴄᴋ ʏᴏᴜʀ ᴠᴀʟᴜᴇꜱ\n/set_tutorial - ᴛᴏ ꜱᴇᴛ ᴄᴜꜱᴛᴏᴍ ᴛᴜᴛᴏʀɪᴀʟ\n/set_shortlink - ᴛᴏ ꜱᴇᴛ ᴄᴜꜱᴛᴏᴍ ꜱʜᴏʀᴛᴇɴᴇʀ\n/rem_tutorial - ᴛᴏ ʀᴇᴍᴏᴠᴇ ᴛᴜᴛᴏʀɪᴀʟ ʟɪɴᴋ\n</b>\"\"\"\n\n ABOUT_TXT = \"\"\"<b>➣ ᴍʏ ɴᴀᴍᴇ ⋟</b> {}\n<b>➢ ᴄʀᴇᴀᴛᴏʀ ⋟</b> <a href=https://youtube.com/@NobiDeveloper>𝘔𝘖𝘝𝘐𝘌 𝘝𝘐𝘓𝘓𝘈</a>\n<b>➣ ʟɪʙʀᴀʀʏ ⋟</b> 𝘱𝘺𝘳𝘰𝘨𝘳𝘢𝘮\n<b>➢ ʟᴀɴɢᴜᴀɢᴇ ⋟</b> 𝘱𝘺𝘵𝘩𝘰𝘯 3\n<b>➣ ᴅᴀᴛᴀʙᴀsᴇ ⋟</b> 𝘮𝘰𝘯𝘨𝘰 𝘥𝘣\n<b>➢ ʙᴏᴛ sᴇʀᴠᴇʀ ⋟</b> 𝘩𝘦𝘳𝘰𝘬𝘶\n<b>➣ ʙᴜɪʟᴅ sᴛᴀᴛs ⋟</b> 𝘷2.0.1 ﹝ʙᴇᴛᴀ﹞\"\"\"\n\n SOURCE_TXT = \"\"\"\n<b>ᴛʜɪꜱ ɪꜱ ᴀɴ ᴏᴘᴇɴ ꜱᴏᴜʀᴄᴇ ᴘʀᴏᴊᴇᴄᴛ.</b>\n\nᴀʟʟ ᴛʜᴇ ꜰɪʟᴇꜱ ɪɴ ᴛʜɪꜱ ʙᴏᴛ ᴀʀᴇ ꜰʀᴇᴇʟʏ ᴀᴠᴀɪʟᴀʙʟᴇ ᴏɴ ᴛʜᴇ ɪɴᴛᴇʀɴᴇᴛ ᴏʀ ᴘᴏꜱᴛᴇᴅ ʙʏ ꜱᴏᴍᴇʙᴏᴅʏ ᴇʟꜱᴇ. ᴊᴜꜱᴛ ꜰᴏʀ ᴇᴀꜱʏ ꜱᴇᴀʀᴄʜɪɴɢ ᴛʜɪꜱ ʙᴏᴛ ɪꜱ ɪɴᴅᴇxɪɴɢ ꜰɪʟᴇꜱ ᴡʜɪᴄʜ ᴀʀᴇ ᴀʟʀᴇᴀᴅʏ ᴜᴘʟᴏᴀᴅᴇᴅ ᴏɴ ᴛᴇʟᴇɢʀᴀᴍ. ᴡᴇ ʀᴇꜱᴘᴇᴄᴛ ᴀʟʟ ᴛʜᴇ ᴄᴏᴘʏʀɪɢʜᴛ ʟᴀᴡꜱ ᴀɴᴅ ᴡᴏʀᴋꜱ ɪɴ ᴄᴏᴍᴘʟɪᴀɴᴄᴇ ᴡɪᴛʜ ᴅᴍᴄᴀ ᴀɴᴅ ᴇᴜᴄᴅ. ɪꜰ ᴀɴʏᴛʜɪɴɢ ɪꜱ ᴀɢᴀɪɴꜱᴛ ʟᴀᴡ ᴘʟᴇᴀꜱᴇ ᴄᴏɴᴛᴀᴄᴛ ᴍᴇ ꜱᴏ ᴛʜᴀᴛ ɪᴛ ᴄᴀɴ ʙᴇ ʀᴇᴍᴏᴠᴇᴅ ᴀꜱᴀᴘ. ɪᴛ ɪꜱ ꜰᴏʀʙɪʙʙᴇɴ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ, ꜱᴛʀᴇᴀᴍ, ʀᴇᴘʀᴏᴅᴜᴄᴇ, ᴏʀ ʙʏ ᴀɴʏ ᴍᴇᴀɴꜱ, ꜱʜᴀʀᴇ, ᴏʀ ᴄᴏɴꜱᴜᴍᴇ, ᴄᴏɴᴛᴇɴᴛ ᴡɪᴛʜᴏᴜᴛ ᴇxᴘʟɪᴄɪᴛ ᴘᴇʀᴍɪꜱꜱɪᴏɴ ꜰʀᴏᴍ ᴛʜᴇ ᴄᴏɴᴛᴇɴᴛ ᴄʀᴇᴀᴛᴏʀ ᴏʀ ʟᴇɢᴀʟ ᴄᴏᴘʏʀɪɢʜᴛ ʜᴏʟᴅᴇʀ. ɪꜰ ʏᴏᴜ ʙᴇʟɪᴇᴠᴇ ᴛʜɪꜱ ʙᴏᴛ ɪꜱ ᴠɪᴏʟᴀᴛɪɴɢ ʏᴏᴜʀ ɪɴᴛᴇʟʟᴇᴄᴛᴜᴀʟ ᴘʀᴏᴘᴇʀᴛʏ, ᴄᴏɴᴛᴀᴄᴛ ᴛʜᴇ ʀᴇꜱᴘᴇᴄᴛɪᴠᴇ ᴄʜᴀɴɴᴇʟꜱ ꜰᴏʀ ʀᴇᴍᴏᴠᴀʟ. ᴛʜᴇ ʙᴏᴛ ᴅᴏᴇꜱ ɴᴏᴛ ᴏᴡɴ ᴀɴʏ ᴏꜰ ᴛʜᴇꜱᴇ ᴄᴏɴᴛᴇɴᴛꜱ, ɪᴛ ᴏɴʟʏ ɪɴᴅᴇx ᴛʜᴇ ꜰɪʟᴇꜱ ꜰʀᴏᴍ ᴛᴇʟᴇɢʀᴀᴍ.\n\n<b><a href=https://telegram.me/NobiDeveloper>~ ᴍᴀɪɴᴛᴀɪɴᴇᴅ ʙʏ @MovieVillaYT</a></b>\n\"\"\"\n\n MANUELFILTER_TXT = \"\"\"\n<b>{},\n\n~ ʏᴏᴜ ᴄᴀɴ ᴇᴀsɪʟʏ ᴄᴜsᴛᴏᴍɪᴢᴇ ᴛʜɪs ʙᴏᴛ ꜰᴏʀ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\n\n~ ᴏɴʟʏ ɢʀᴏᴜᴘ ᴀᴅᴍɪɴ ᴄᴀɴ ᴜsᴇ ᴛʜɪs ᴄᴏᴍᴍᴀɴᴅ ᴀɴᴅ ᴄʜᴀɴɢᴇs sᴇᴛᴛɪɴɢs.\n\n~ ɪᴛ ᴡᴏʀᴋs ᴏɴʟʏ ᴡʜᴇɴ ʏᴏᴜ ᴀʟʀᴇᴀᴅʏ ᴄᴏɴɴᴇᴄᴛ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\n\nᴄᴏᴍᴍᴀɴᴅs ᴀɴᴅ ᴜsᴀɢᴇ -\n\n• /settings - ᴄʜᴀɴɢᴇ sᴇᴛᴛɪɴɢs ᴀs ʏᴏᴜʀ ᴡɪsʜ.</b>\n\"\"\"\n\n GROUP_TXT = \"\"\"\n<b>⍟ ᴄʜᴀɴɴᴇʟs ᴀɴᴅ ɢʀᴏᴜᴘs ᴍᴏᴅᴜʟᴇ ⍟</b>\n\n<b>🍿 ᴍᴏᴠɪᴇꜱ ᴄʜᴀɴɴᴇʟ.\n🗣️ ʙᴏᴛ sᴜᴘᴘᴏʀᴛ ɢʀᴏᴜᴘ.\n🚦 ʙᴏᴛ ᴜᴘᴅᴀᴛᴇs ᴄʜᴀɴɴᴇʟ.\n🎬 ᴍᴏᴠɪᴇ ʀᴇǫᴜᴇsᴛɪɴɢ ɢʀᴏᴜᴘ.</b>\"\"\"\n\n BUTTON_TXT = \"\"\"\n<b>💵 ɪ ʀᴇǫᴜᴇsᴛᴇᴅ ᴛᴏ ʏᴏᴜ 💸\n\nᴘʟᴇᴀsᴇ ᴅᴏɴᴀᴛᴇ ᴛʜᴇ ᴅᴇᴠᴇʟᴏᴘᴇʀ ꜰᴏʀ ᴋᴇᴇᴘɪɴɢ ᴛʜᴇ sᴇʀᴠɪᴄᴇ ᴀʟɪᴠᴇ & ᴋᴇᴇᴘ ʙʀɪɴɢɪɴɢ ᴍᴏʀᴇ ɴᴇᴡ ꜰᴇᴀᴛᴜʀᴇs ꜰᴏʀ ʏᴏᴜ....</b>\n\n𝐘𝐨𝐮 𝐂𝐚𝐧 𝐃𝐨𝐧𝐚𝐭𝐞 𝐀𝐧𝐲 𝐀𝐦𝐨𝐮𝐧𝐭 𝐘𝐨𝐮 𝐇𝐚𝐯𝐞 💷\n\n<b>᚜ ᴘᴀʏᴍᴇɴᴛ ᴍᴇᴛʜᴏᴅs ᚛</b>\n\n💵 <a href='https://telegra.ph/SUPPORT-12-22-2'>𝗚𝗼𝗼𝗴𝗹𝗲 𝗣𝗮𝘆</a>\n💸 <a href='https://telegra.ph/SUPPORT-12-22-2'>𝗣𝗮𝘆𝘁𝗺</a>\n💶 <a href='https://telegra.ph/SUPPORT-12-22-2'>𝗣𝗵𝗼𝗻𝗲𝗣𝗲</a>\n\n𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐌𝐞 𝐅𝐨𝐫 𝐊𝐧𝐨𝐰 𝐀𝐛𝐨𝐮𝐭 𝐓𝐡𝐞 𝐏𝐚𝐲𝐦𝐞𝐧𝐭 𝐈𝐧𝐟𝐨\n\n<b>ᴄʟɪᴄᴋ ʜᴇʀᴇ - <a href='https://telegram.me/NobiDeveloperr'>ʙᴏss</a>\nᴄʟɪᴄᴋ ʜᴇʀᴇ - <a href='https://telegram.me/NobiDeveloperr'>ʙᴏss</a></b>\"\"\"\n\n AUTOFILTER_TXT = \"\"\"ʜᴇʟᴘ: <b>ᴀᴜᴛᴏ ꜰɪʟᴛᴇʀ</b>\n<b>ɴᴏᴛᴇ: Fɪʟᴇ Iɴᴅᴇx</b>\n1. ᴍᴀᴋᴇ ᴍᴇ ᴛʜᴇ ᴀᴅᴍɪɴ ᴏꜰ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ɪꜰ ɪᴛ'ꜱ ᴘʀɪᴠᴀᴛᴇ.\n2. ᴍᴀᴋᴇ ꜱᴜʀᴇ ᴛʜᴀᴛ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ᴅᴏᴇꜱ ɴᴏᴛ ᴄᴏɴᴛᴀɪɴꜱ ᴄᴀᴍʀɪᴘꜱ, ᴘᴏʀɴ ᴀɴᴅ ꜰᴀᴋᴇ ꜰɪʟᴇꜱ.\n3. ꜰᴏʀᴡᴀʀᴅ ᴛʜᴇ ʟᴀꜱᴛ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴍᴇ ᴡɪᴛʜ Qᴜᴏᴛᴇꜱ. ɪ'ʟʟ ᴀᴅᴅ ᴀʟʟ ᴛʜᴇ ꜰɪʟᴇꜱ ɪɴ ᴛʜᴀᴛ ᴄʜᴀɴɴᴇʟ ᴛᴏ ᴍʏ ᴅʙ.\n\n<b>Nᴏᴛᴇ: AᴜᴛᴏFɪʟᴛᴇʀ</b>\n1. Aᴅᴅ ᴛʜᴇ ʙᴏᴛ ᴀs ᴀᴅᴍɪɴ ᴏɴ ʏᴏᴜʀ ɢʀᴏᴜᴘ.\n2. Usᴇ /connect ᴀɴᴅ ᴄᴏɴɴᴇᴄᴛ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴛᴏ ᴛʜᴇ ʙᴏᴛ.\n3. Usᴇ /settings ᴏɴ ʙᴏᴛ's PM ᴀɴᴅ ᴛᴜʀɴ ᴏɴ AᴜᴛᴏFɪʟᴛᴇʀ ᴏɴ ᴛʜᴇ sᴇᴛᴛɪɴɢs ᴍᴇɴᴜ.\"\"\"\n\n CONNECTION_TXT = \"\"\"ʜᴇʟᴘ: <b>ᴄᴏɴɴᴇᴄᴛɪᴏɴꜱ</b>\n- ᴜꜱᴇᴅ ᴛᴏ ᴄᴏɴɴᴇᴄᴛ ʙᴏᴛ ᴛᴏ ᴘᴍ ꜰᴏʀ ᴍᴀɴᴀɢɪɴɢ ꜰɪʟᴛᴇʀꜱ \n- ɪᴛ ʜᴇʟᴘꜱ ᴛᴏ ᴀᴠᴏɪᴅ ꜱᴘᴀᴍᴍɪɴɢ ɪɴ ɢʀᴏᴜᴘꜱ.\n<b>ɴᴏᴛᴇ:</b>\n1. ᴏɴʟʏ ᴀᴅᴍɪɴꜱ ᴄᴀɴ ᴀᴅᴅ ᴀ ᴄᴏɴɴᴇᴄᴛɪᴏɴ.\n2. ꜱᴇɴᴅ <code>/ᴄᴏɴɴᴇᴄᴛ</code> ꜰᴏʀ ᴄᴏɴɴᴇᴄᴛɪɴɢ ᴍᴇ ᴛᴏ ʏᴏᴜʀ ᴘᴍ\nCᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ:\n• /connect - <code>ᴄᴏɴɴᴇᴄᴛ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ᴄʜᴀᴛ ᴛᴏ ʏᴏᴜʀ ᴘᴍ</code>\n• /disconnect - <code>ᴅɪꜱᴄᴏɴɴᴇᴄᴛ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ</code>\n• /connections - <code>ʟɪꜱᴛ ᴀʟʟ ʏᴏᴜʀ ᴄᴏɴɴᴇᴄᴛɪᴏɴꜱ</code>\"\"\"\n\n EXTRAMOD_TXT = \"\"\"ʜᴇʟᴘ: Exᴛʀᴀ Mᴏᴅᴜʟᴇs\n<b>ɴᴏᴛᴇ:</b>\nᴛʜᴇꜱᴇ ᴀʀᴇ ᴛʜᴇ ᴇxᴛʀᴀ ꜰᴇᴀᴛᴜʀᴇꜱ ᴏꜰ ᴛʜɪꜱ ʙᴏᴛ\nCᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ:\n• /id - <code>ɢᴇᴛ ɪᴅ ᴏꜰ ᴀ ꜱᴘᴇᴄɪꜰɪᴇᴅ ᴜꜱᴇʀ.</code>\n• /info - <code>ɢᴇᴛ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ᴀʙᴏᴜᴛ ᴀ ᴜꜱᴇʀ.</code>\n• /imdb - <code>ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ɪᴍᴅʙ ꜱᴏᴜʀᴄᴇ.</code>\n• /search - <code>ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ᴠᴀʀɪᴏᴜꜱ ꜱᴏᴜʀᴄᴇꜱ.</code>\"\"\"\n\n ADMIN_TXT = \"\"\"ʜᴇʟᴘ: Aᴅᴍɪɴ Mᴏᴅs\n<b>ɴᴏᴛᴇ:</b>\nTʜɪs Mᴏᴅᴜʟᴇ Oɴʟʏ Wᴏʀᴋs Fᴏʀ Mʏ Aᴅᴍɪɴs\nCᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ:\n• /logs - <code>ᴛᴏ ɢᴇᴛ ᴛʜᴇ ʀᴇᴄᴇɴᴛ ᴇʀʀᴏʀꜱ</code>\n• /stats - <code>ᴛᴏ ɢᴇᴛ ꜱᴛᴀᴛᴜꜱ ᴏꜰ ꜰɪʟᴇꜱ ɪɴ ᴅʙ. [Tʜɪs Cᴏᴍᴍᴀɴᴅ Cᴀɴ Bᴇ Usᴇᴅ Bʏ Aɴʏᴏɴᴇ]</code>\n• /delete - <code>ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ ꜱᴘᴇᴄɪꜰɪᴄ ꜰɪʟᴇ ꜰʀᴏᴍ ᴅʙ.</code>\n• /users - <code>ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴜꜱᴇʀꜱ ᴀɴᴅ ɪᴅꜱ.</code>\n• /chats - <code>ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴄʜᴀᴛꜱ ᴀɴᴅ ɪᴅꜱ</code>\n• /leave - <code>ᴛᴏ ʟᴇᴀᴠᴇ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ.</code>\n• /disable - <code>ᴛᴏ ᴅɪꜱᴀʙʟᴇ ᴀ ᴄʜᴀᴛ.</code>\n• /ban - <code>ᴛᴏ ʙᴀɴ ᴀ ᴜꜱᴇʀ.</code>\n• /unban - <code>ᴛᴏ ᴜɴʙᴀɴ ᴀ ᴜꜱᴇʀ.</code>\n• /channel - <code>ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴛᴏᴛᴀʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ᴄʜᴀɴɴᴇʟꜱ</code>\n• /broadcast - <code>ᴛᴏ ʙʀᴏᴀᴅᴄᴀꜱᴛ ᴀ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴀʟʟ ᴜꜱᴇʀꜱ</code>\n• /grp_broadcast - <code>Tᴏ ʙʀᴏᴀᴅᴄᴀsᴛ ᴀ ᴍᴇssᴀɢᴇ ᴛᴏ ᴀʟʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ɢʀᴏᴜᴘs.</code>\n• /gfilter - <code>ᴛᴏ ᴀᴅᴅ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs</code>\n• /gfilters - <code>ᴛᴏ ᴠɪᴇᴡ ʟɪsᴛ ᴏғ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs</code>\n• /delg - <code>ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ sᴘᴇᴄɪғɪᴄ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ</code>\n• /request - <code>Tᴏ sᴇɴᴅ ᴀ Mᴏᴠɪᴇ/Sᴇʀɪᴇs ʀᴇᴏ̨ᴜᴇsᴛ ᴛᴏ ʙᴏᴛ ᴀᴅᴍɪɴs. Oɴʟʏ ᴡᴏʀᴋs ᴏɴ sᴜᴘᴘᴏʀᴛ ɢʀᴏᴜᴘ. [Tʜɪs Cᴏᴍᴍᴀɴᴅ Cᴀɴ Bᴇ Usᴇᴅ Bʏ Aɴʏᴏɴᴇ]</code>\n• /delallg - <code>Tᴏ ᴅᴇʟᴇᴛᴇ ᴀʟʟ Gғɪʟᴛᴇʀs ғʀᴏᴍ ᴛʜᴇ ʙᴏᴛ's ᴅᴀᴛᴀʙᴀsᴇ.</code>\n• /deletefiles - <code>Tᴏ ᴅᴇʟᴇᴛᴇ CᴀᴍRɪᴘ ᴀɴᴅ PʀᴇDVD Fɪʟᴇs ғʀᴏᴍ ᴛʜᴇ ʙᴏᴛ's ᴅᴀᴛᴀʙᴀsᴇ.</code>\"\"\"\n\n STATUS_TXT = \"\"\"<b>📂 ᴛᴏᴛᴀʟ ꜰɪʟᴇs: <code>{}</code>\n👤 ᴛᴏᴛᴀʟ ᴜsᴇʀs: <code>{}</code>\n♻️ ᴛᴏᴛᴀʟ ᴄʜᴀᴛs: <code>{}</code>\n🗃️ ᴜsᴇᴅ sᴛᴏʀᴀɢᴇ: <code>{}</code>\n🆓 ꜰʀᴇᴇ sᴛᴏʀᴀɢᴇ: <code>{}</code></b>\"\"\"\n\n LOG_TEXT_G = \"\"\"#𝐍𝐞𝐰𝐆𝐫𝐨𝐮𝐩\n\n<b>᚛› 𝐆𝐫𝐨𝐮𝐩 ⪼ {}(<code>{}</code>)</b>\n<b>᚛› 𝐓𝐨𝐭𝐚𝐥 𝐌𝐞𝐦𝐛𝐞𝐫𝐬 ⪼ <code>{}</code></b>\n<b>᚛› 𝐀𝐝𝐝𝐞𝐝 𝐁𝐲 ⪼ {}</b>\n\"\"\"\n\n LOG_TEXT_P = \"\"\"#𝐍𝐞𝐰𝐔𝐬𝐞𝐫\n\n<b>᚛› 𝐈𝐃 - <code>{}</code></b>\n<b>᚛› 𝐍𝐚𝐦𝐞 - {}</b>\n\"\"\"\n\n ALRT_TXT = \"\"\"{},\nᴄʜᴇᴄᴋ ʏᴏᴜʀ ᴏᴡɴ ʀᴇǫᴜᴇ𝗌ᴛ 😤\n\"\"\"\n\n OLD_ALRT_TXT =\"\"\"{},\n\nʏᴏᴜ ᴀʀᴇ ᴜꜱɪɴɢ ᴍʏ ᴏʟᴅ ᴍᴇꜱꜱᴀɢᴇ,\n\nꜱᴇɴᴅ ᴛʜᴇ ʀᴇǫᴜᴇ𝗌ᴛ ᴀɢᴀɪɴ 😊\n\"\"\"\n\n CUDNT_FND = \"\"\"<b>{},</b>\n\n𝗜 𝗰𝗼𝘂𝗹𝗱𝗻'𝘁 𝗳𝗶𝗻𝗱 𝗮𝗻𝘆𝘁𝗵𝗶𝗻𝗴 𝗿𝗲𝗹𝗮𝘁𝗲𝗱 𝘁𝗼 𝘁𝗵𝗮𝘁 𝗱𝗶𝗱 𝘆𝗼𝘂 𝗺𝗲𝗮𝗻 𝗮𝗻𝘆 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 ?? 👇\"\"\"\n\n I_CUDNT = \"\"\"<b>{},</b>\n\n𝗜 𝗰𝗼𝘂𝗹𝗱𝗻'𝘁 𝗳𝗶𝗻𝗱 𝗮𝗻𝘆 𝗺𝗼𝘃𝗶𝗲 𝗼𝗿 𝘀𝗲𝗿𝗶𝗲𝘀 𝗶𝗻 𝘁𝗵𝗮𝘁 𝗻𝗮𝗺𝗲.. 😐\"\"\"\n\n I_CUD_NT = \"\"\"ɪ ᴄᴏᴜʟᴅɴ'ᴛ ꜰɪɴᴅ ᴀɴʏ ᴍᴏᴠɪᴇ ʀᴇʟᴀᴛᴇᴅ ᴛᴏ {}.\nᴘʟᴇᴀꜱᴇ ᴄʜᴇᴄᴋ ᴛʜᴇ ꜱᴘᴇʟʟɪɴɢ ᴏɴ ɢᴏᴏɢʟᴇ ᴏʀ ɪᴍᴅʙ...\"\"\"\n\n MVE_NT_FND = \"\"\"<b>ᴍᴏᴠɪᴇ ɴᴏᴛ ꜰᴏᴜɴᴅ...\n\n<u>ʀᴇᴀꜱᴏɴꜱ:</u></b>\n\n𝟷) ꜱᴘᴇʟʟɪɴɢ ᴍɪꜱᴛᴀᴋᴇ\n\n𝟸) ᴏᴛᴛ ᴏʀ ᴅᴠᴅ ɴᴏᴛ ʀᴇʟᴇᴀꜱᴇᴅ\n\n𝟹) ɴᴏᴛ ᴀᴠᴀɪʟᴀʙʟᴇ ɪɴ ᴅᴀᴛᴀʙᴀꜱᴇ\n\n<b><a href=https://telegram.me/NobiDeveloperr>~ ʀᴇǫᴜᴇ𝗌ᴛ ᴛᴏ ᴏᴡɴᴇʀ</a></b>\n\"\"\"\n\n TOP_ALRT_MSG = \"\"\"ꜱᴇᴀʀᴄʜɪɴɢ ɪɴ ᴅᴀᴛᴀʙᴀꜱᴇ...\"\"\"\n\n MELCOW_ENG = \"\"\"<b>{},\n\n📿 ᴡᴇʟᴄᴏᴍᴇ ᴛᴏ ᴏᴜʀ ɢʀᴏᴜᴘ {}\n\n🚬 ᴛʜɪs ɪs ᴀ ᴍᴏᴠɪᴇ ɢʀᴏᴜᴘ\n\n⏳ ᴀʟʟ ᴄᴀᴛᴇɢᴏʀɪᴇs ᴏꜰ ᴍᴏᴠɪᴇs ᴀᴠᴀɪʟᴀʙʟᴇ ʜᴇʀᴇ\n\n🧨 ᴊᴜsᴛ ᴛʏᴘᴇ ᴛʜᴇ ᴍᴏᴠɪᴇ ɴᴀᴍᴇ\n\n🤖 ʙᴏᴛ ᴡɪʟʟ sᴇɴᴅ ʏᴏᴜʀ ᴍᴏᴠɪᴇ\n\n☎️ ʀᴇᴀᴅ ɢʀᴏᴜᴘ ʀᴜʟᴇs ᴛᴏ ᴋɴᴏᴡ ᴍᴏʀᴇ...</b>\"\"\"\n\n SHORTLINK_INFO = \"\"\"\n<b>──────「 <a href='https://telegram.me/NobiDeveloper'>ᴇᴀʀɴ ᴍᴏɴᴇʏ</a> 」──────\n\n➥ ɴᴏᴡ ʏᴏᴜ ᴄᴀɴ ᴀʟsᴏ ᴇᴀʀɴ ʟᴏᴛs ᴏꜰ ᴍᴏɴᴇʏ ꜰʀᴏᴍ ᴛʜɪꜱ ʙᴏᴛ.\n\n›› sᴛᴇᴘ 𝟷 : ʏᴏᴜ ᴍᴜsᴛ ʜᴀᴠᴇ ᴀᴛʟᴇᴀsᴛ ᴏɴᴇ ɢʀᴏᴜᴘ ᴡɪᴛʜ ᴍɪɴɪᴍᴜᴍ 𝟹𝟶𝟶 ᴍᴇᴍʙᴇʀs.\n\n›› sᴛᴇᴘ 𝟸 : ᴍᴀᴋᴇ ᴀᴄᴄᴏᴜɴᴛ ᴏɴ <a href='https://tnshort.net/ref/devilofficial'>ᴛɴʟɪɴᴋ</a> ᴏʀ <a href='https://onepagelink.in/ref/Nobita'>ᴏɴᴇᴘᴀɢᴇʟɪɴᴋ</a>. [ ʏᴏᴜ ᴄᴀɴ ᴀʟsᴏ ᴜsᴇ ᴏᴛʜᴇʀ sʜᴏʀᴛɴᴇʀ ᴡᴇʙsɪᴛᴇ ]\n\n›› sᴛᴇᴘ 𝟹 : ꜰᴏʟʟᴏᴡ ᴛʜᴇsᴇ <a href='https://telegram.me/NobiDeveloper/1063'>ɪɴꜱᴛʀᴜᴄᴛɪᴏɴꜱ</a>.\n\n➥ ᴛʜɪꜱ ʙᴏᴛ ꜰʀᴇᴇ ꜰᴏʀ ᴀʟʟ ʏᴏᴜ ᴄᴀɴ ᴜꜱᴇ ᴛʜɪꜱ ʙᴏᴛ ɪɴ ʏᴏᴜʀ ɢʀᴏᴜᴘs ꜰʀᴇᴇ ᴏꜰ ᴄᴏꜱᴛ.</b>\"\"\"\n\n REQINFO = \"\"\"\n⚠ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ⚠\n\nᴀꜰᴛᴇʀ 5 ᴍɪɴᴜᴛᴇꜱ ᴛʜɪꜱ ᴍᴇꜱꜱᴀɢᴇ ᴡɪʟʟ ʙᴇ ᴀᴜᴛᴏᴍᴀᴛɪᴄᴀʟʟʏ ᴅᴇʟᴇᴛᴇᴅ\n\nɪꜰ ʏᴏᴜ ᴅᴏ ɴᴏᴛ ꜱᴇᴇ ᴛʜᴇ ʀᴇǫᴜᴇsᴛᴇᴅ ᴍᴏᴠɪᴇ / sᴇʀɪᴇs ꜰɪʟᴇ, ʟᴏᴏᴋ ᴀᴛ ᴛʜᴇ ɴᴇxᴛ ᴘᴀɢᴇ\"\"\"\n\n SELECT = \"\"\"\nMOVIES ➢ Sᴇʟᴇᴄᴛ \"Lᴀɴɢᴜᴀɢᴇs\"\n\nSERIES ➢ Sᴇʟᴇᴄᴛ \"Sᴇᴀsᴏɴs\"\n\nTɪᴘ: Sᴇʟᴇᴄᴛ \"Lᴀɴɢᴜᴀɢᴇs\" ᴏʀ \"Sᴇᴀsᴏɴs\" Bᴜᴛᴛᴏɴ ᴀɴᴅ Cʟɪᴄᴋ \"Sᴇɴᴅ Aʟʟ\" Tᴏ ɢᴇᴛ Aʟʟ Fɪʟᴇ Lɪɴᴋs ɪɴ ᴀ Sɪɴɢʟᴇ ᴄʟɪᴄᴋ\"\"\"\n\n SINFO = \"\"\"\n▣ ᴛɪᴘs ▣\n\n☆ ᴛʏᴘᴇ ᴄᴏʀʀᴇᴄᴛ sᴘᴇʟʟɪɴɢ (ɢᴏᴏɢʟᴇ)\n\n☆ ɪꜰ ʏᴏᴜ ɴᴏᴛ ɢᴇᴛ ʏᴏᴜʀ ꜰɪʟᴇ ɪɴ ᴛʜɪꜱ ᴘᴀɢᴇ ᴛʜᴇɴ ᴄʟɪᴄᴋ ᴏɴ ɴᴇxᴛ ʙᴜᴛᴛᴏɴ\n\n☆ ᴄᴏɴᴛɪɴᴜᴇ ᴛʜɪs ᴍᴇᴛʜᴏᴅ ᴛᴏ ɢᴇᴛᴛɪɴɢ ʏᴏᴜ ꜰɪʟᴇ\n\n❤️‍🔥 ᴘᴏᴡᴇʀᴇᴅ ʙʏ @NobiDeveloper\n\"\"\"\n\n NORSLTS = \"\"\"\n★ #𝗡𝗼𝗥𝗲𝘀𝘂𝗹𝘁𝘀 ★\n\n𝗜𝗗 <b>: {}</b>\n𝗡𝗮𝗺𝗲 <b>: {}</b>\n𝗠𝗲𝘀𝘀𝗮𝗴𝗲 <b>: {}</b>\"\"\"\n\n CAPTION = \"\"\"\n[{file_name}](https://telegram.me/NobiDeveloper)\n\n<b>•────•────────•────•\n📌 ʀᴇǫᴜᴇsᴛ ɢʀᴏᴜᴘ​ : [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://telegram.me/AllRequestGroups)\n🎬 ᴍᴏᴠɪᴇs ᴄʜᴀɴɴᴇʟ​ : [ᴄʟɪᴄᴋ ʜᴇʀᴇ](https://telegram.me/MovieVillaYT)\n•────•────────•────•\n\n©️ ᴘᴏᴡᴇʀᴇᴅ ʙʏ : [ᴍᴏᴠɪᴇ ᴠɪʟʟᴀ](https://youtube.com/@NobiDeveloper)</b>\"\"\"\n\n IMDB_TEMPLATE_TXT = \"\"\"\n<b>{title}</b>\n\n⭐️<b>{rating}</b> | ⏰ <b>{runtime}</b> | 📆 <b>{release_date}</b>\n\n● <b>{genres}</b>\n● <b>{languages}</b>\n\n📖 sᴛᴏʀʏ : <b>{plot}</b> \n\n© {message.chat.title}\n\"\"\"\n \n ALL_FILTERS = \"\"\"\n<b>Hᴇʏ {}, Tʜᴇsᴇ ᴀʀᴇ ᴍʏ ᴛʜʀᴇᴇ ᴛʏᴘᴇs ᴏғ ғɪʟᴛᴇʀs.</b>\"\"\"\n \n GFILTER_TXT = \"\"\"\n<b>Wᴇʟᴄᴏᴍᴇ ᴛᴏ Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs. Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs ᴀʀᴇ ᴛʜᴇ ғɪʟᴛᴇʀs sᴇᴛ ʙʏ ʙᴏᴛ ᴀᴅᴍɪɴs ᴡʜɪᴄʜ ᴡɪʟʟ ᴡᴏʀᴋ ᴏɴ ᴀʟʟ ɢʀᴏᴜᴘs.</b>\n \nAᴠᴀɪʟᴀʙʟᴇ ᴄᴏᴍᴍᴀɴᴅs:\n• /gfilter - <code>Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ.</code>\n• /gfilters - <code>Tᴏ ᴠɪᴇᴡ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs.</code>\n• /delg - <code>Tᴏ ᴅᴇʟᴇᴛᴇ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ.</code>\n• /delallg - <code>ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀʟʟ ɢʟᴏʙᴀʟ ꜰɪʟᴛᴇʀꜱ.</code>\"\"\"\n \n FILE_STORE_TXT = \"\"\"\n<b>Fɪʟᴇ sᴛᴏʀᴇ ɪs ᴛʜᴇ ғᴇᴀᴛᴜʀᴇ ᴡʜɪᴄʜ ᴡɪʟʟ ᴄʀᴇᴀᴛᴇ ᴀ sʜᴀʀᴇᴀʙʟᴇ ʟɪɴᴋ ᴏғ ᴀ sɪɴɢʟᴇ ᴏʀ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs.</b>\n\nAᴠᴀɪʟᴀʙʟᴇ ᴄᴏᴍᴍᴀɴᴅs:\n• /batch - <code>Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ ʙᴀᴛᴄʜ ʟɪɴᴋ ᴏғ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs.</code>\n• /link - <code>Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ sɪɴɢʟᴇ ғɪʟᴇ sᴛᴏʀᴇ ʟɪɴᴋ.</code>\n• /pbatch - <code>Jᴜsᴛ ʟɪᴋᴇ /batch, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇs ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴs.</code>\n• /plink - <code>Jᴜsᴛ ʟɪᴋᴇ /link, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇ ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴ.</code>\"\"\"\n\n RESTART_TXT = \"\"\"\n<b>Bᴏᴛ Rᴇsᴛᴀʀᴛᴇᴅ !\n\n📅 Dᴀᴛᴇ : <code>{}</code>\n⏰ Tɪᴍᴇ : <code>{}</code>\n🌐 Tɪᴍᴇᴢᴏɴᴇ : <code>Asia/Kolkata</code>\n🛠️ Bᴜɪʟᴅ Sᴛᴀᴛᴜs: <code>v2.7.1 [ Sᴛᴀʙʟᴇ ]</code></b>\n\"\"\"\n\n LOGO = \"\"\"\n𝑺𝒕𝒂𝒓𝒕𝒊𝒏𝒈.......🥵\"\"\"" }, { "identifier": "active_connection", "path": "database/connections_mdb.py", "snippet": "async def active_connection(user_id):\n\n query = mycol.find_one(\n { \"_id\": user_id },\n { \"_id\": 0, \"group_details\": 0 }\n )\n if not query:\n return None\n\n group_id = query['active_group']\n return int(group_id) if group_id != None else None" }, { "identifier": "all_connections", "path": "database/connections_mdb.py", "snippet": "async def all_connections(user_id):\n query = mycol.find_one(\n { \"_id\": user_id },\n { \"_id\": 0, \"active_group\": 0 }\n )\n if query is not None:\n return [x[\"group_id\"] for x in query[\"group_details\"]]\n else:\n return None" }, { "identifier": "delete_connection", "path": "database/connections_mdb.py", "snippet": "async def delete_connection(user_id, group_id):\n\n try:\n update = mycol.update_one(\n {\"_id\": user_id},\n {\"$pull\" : { \"group_details\" : {\"group_id\":group_id} } }\n )\n if update.modified_count == 0:\n return False\n query = mycol.find_one(\n { \"_id\": user_id },\n { \"_id\": 0 }\n )\n if len(query[\"group_details\"]) >= 1:\n if query['active_group'] == group_id:\n prvs_group_id = query[\"group_details\"][len(query[\"group_details\"]) - 1][\"group_id\"]\n\n mycol.update_one(\n {'_id': user_id},\n {\"$set\": {\"active_group\" : prvs_group_id}}\n )\n else:\n mycol.update_one(\n {'_id': user_id},\n {\"$set\": {\"active_group\" : None}}\n )\n return True\n except Exception as e:\n logger.exception(f'Some error occurred! {e}', exc_info=True)\n return False" }, { "identifier": "if_active", "path": "database/connections_mdb.py", "snippet": "async def if_active(user_id, group_id):\n query = mycol.find_one(\n { \"_id\": user_id },\n { \"_id\": 0, \"group_details\": 0 }\n )\n return query is not None and query['active_group'] == group_id" }, { "identifier": "make_active", "path": "database/connections_mdb.py", "snippet": "async def make_active(user_id, group_id):\n update = mycol.update_one(\n {'_id': user_id},\n {\"$set\": {\"active_group\" : group_id}}\n )\n return update.modified_count != 0" }, { "identifier": "make_inactive", "path": "database/connections_mdb.py", "snippet": "async def make_inactive(user_id):\n update = mycol.update_one(\n {'_id': user_id},\n {\"$set\": {\"active_group\" : None}}\n )\n return update.modified_count != 0" }, { "identifier": "ADMINS", "path": "info.py", "snippet": "ADMINS = [int(admin) if id_pattern.search(admin) else admin for admin in environ.get('ADMINS', '').split()]" }, { "identifier": "AUTH_CHANNEL", "path": "info.py", "snippet": "AUTH_CHANNEL = int(auth_channel) if auth_channel and id_pattern.search(auth_channel) else None" }, { "identifier": "AUTH_USERS", "path": "info.py", "snippet": "AUTH_USERS = (auth_users + ADMINS) if auth_users else []" }, { "identifier": "SUPPORT_CHAT_ID", "path": "info.py", "snippet": "SUPPORT_CHAT_ID = int(support_chat_id) if support_chat_id and id_pattern.search(support_chat_id) else None" }, { "identifier": "CUSTOM_FILE_CAPTION", "path": "info.py", "snippet": "CUSTOM_FILE_CAPTION = environ.get(\"CUSTOM_FILE_CAPTION\", f\"{script.CAPTION}\")" }, { "identifier": "MSG_ALRT", "path": "info.py", "snippet": "MSG_ALRT = environ.get('MSG_ALRT', 'ꜱʜᴀʀᴇ ᴀɴᴅ ꜱᴜᴘᴘᴏʀᴛ ᴜꜱ')" }, { "identifier": "PICS", "path": "info.py", "snippet": "PICS = (environ.get('PICS', 'https://telegra.ph/file/61ef9818986cef9554017.jpg https://telegra.ph/file/4696ff67a5bae3ea92c14.jpg')).split()" }, { "identifier": "AUTH_GROUPS", "path": "info.py", "snippet": "AUTH_GROUPS = [int(ch) for ch in auth_grp.split()] if auth_grp else None" }, { "identifier": "P_TTI_SHOW_OFF", "path": "info.py", "snippet": "P_TTI_SHOW_OFF = is_enabled((environ.get('P_TTI_SHOW_OFF', \"True\")), True)" }, { "identifier": "GRP_LNK", "path": "info.py", "snippet": "GRP_LNK = environ.get('GRP_LNK', 'https://telegram.me/NobiDeveloperSupport')" }, { "identifier": "CHNL_LNK", "path": "info.py", "snippet": "CHNL_LNK = environ.get('CHNL_LNK', 'https://telegram.me/NobiDeveloper')" }, { "identifier": "NOR_IMG", "path": "info.py", "snippet": "NOR_IMG = environ.get(\"NOR_IMG\", \"https://telegra.ph/file/61ef9818986cef9554017.jpg\")" }, { "identifier": "LOG_CHANNEL", "path": "info.py", "snippet": "LOG_CHANNEL = int(environ.get('LOG_CHANNEL', ''))" }, { "identifier": "SPELL_IMG", "path": "info.py", "snippet": "SPELL_IMG = environ.get(\"SPELL_IMG\", \"https://telegra.ph/file/61ef9818986cef9554017.jpg\")" }, { "identifier": "MAX_B_TN", "path": "info.py", "snippet": "MAX_B_TN = environ.get(\"MAX_B_TN\", \"8\")" }, { "identifier": "IMDB", "path": "info.py", "snippet": "IMDB = is_enabled((environ.get('IMDB', \"False\")), False)" }, { "identifier": "SINGLE_BUTTON", "path": "info.py", "snippet": "SINGLE_BUTTON = is_enabled((environ.get('SINGLE_BUTTON', \"True\")), True)" }, { "identifier": "SPELL_CHECK_REPLY", "path": "info.py", "snippet": "SPELL_CHECK_REPLY = is_enabled(environ.get(\"SPELL_CHECK_REPLY\", \"True\"), True)" }, { "identifier": "IMDB_TEMPLATE", "path": "info.py", "snippet": "IMDB_TEMPLATE = environ.get(\"IMDB_TEMPLATE\", f\"{script.IMDB_TEMPLATE_TXT}\")" }, { "identifier": "NO_RESULTS_MSG", "path": "info.py", "snippet": "NO_RESULTS_MSG = bool(environ.get(\"NO_RESULTS_MSG\", True))" }, { "identifier": "TUTORIAL", "path": "info.py", "snippet": "TUTORIAL = environ.get('TUTORIAL', 'https://youtu.be/0c-i2Lol6LU')" }, { "identifier": "REQST_CHANNEL", "path": "info.py", "snippet": "REQST_CHANNEL = int(reqst_channel) if reqst_channel and id_pattern.search(reqst_channel) else None" }, { "identifier": "IS_TUTORIAL", "path": "info.py", "snippet": "IS_TUTORIAL = bool(environ.get('IS_TUTORIAL', True))" }, { "identifier": "LANGUAGES", "path": "info.py", "snippet": "LANGUAGES = [\"hindi\", \"hin\", \"tamil\", \"tam\", \"telugu\", \"tel\", \"english\", \"eng\", \"kannada\", \"kan\", \"malayalam\", \"mal\"]" }, { "identifier": "SUPPORT_CHAT", "path": "info.py", "snippet": "SUPPORT_CHAT = environ.get('SUPPORT_CHAT', 'NobiDeveloperSupport')" }, { "identifier": "get_size", "path": "utils.py", "snippet": "def get_size(size):\n \"\"\"Get size in readable format\"\"\"\n\n units = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"]\n size = float(size)\n i = 0\n while size >= 1024.0 and i < len(units):\n i += 1\n size /= 1024.0\n return \"%.2f %s\" % (size, units[i])" }, { "identifier": "is_subscribed", "path": "utils.py", "snippet": "async def is_subscribed(bot, query):\n try:\n user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)\n except UserNotParticipant:\n pass\n except Exception as e:\n logger.exception(e)\n else:\n if user.status != enums.ChatMemberStatus.BANNED:\n return True\n\n return False" }, { "identifier": "get_poster", "path": "utils.py", "snippet": "async def get_poster(query, bulk=False, id=False, file=None):\n if not id:\n query = (query.strip()).lower()\n title = query\n year = re.findall(r'[1-2]\\d{3}$', query, re.IGNORECASE)\n if year:\n year = list_to_str(year[:1])\n title = (query.replace(year, \"\")).strip()\n elif file is not None:\n year = re.findall(r'[1-2]\\d{3}', file, re.IGNORECASE)\n if year:\n year = list_to_str(year[:1]) \n else:\n year = None\n movieid = imdb.search_movie(title.lower(), results=10)\n if not movieid:\n return None\n if year:\n filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))\n if not filtered:\n filtered = movieid\n else:\n filtered = movieid\n movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))\n if not movieid:\n movieid = filtered\n if bulk:\n return movieid\n movieid = movieid[0].movieID\n else:\n movieid = query\n movie = imdb.get_movie(movieid)\n if movie.get(\"original air date\"):\n date = movie[\"original air date\"]\n elif movie.get(\"year\"):\n date = movie.get(\"year\")\n else:\n date = \"N/A\"\n plot = \"\"\n if not LONG_IMDB_DESCRIPTION:\n plot = movie.get('plot')\n if plot and len(plot) > 0:\n plot = plot[0]\n else:\n plot = movie.get('plot outline')\n if plot and len(plot) > 800:\n plot = plot[0:800] + \"...\"\n\n return {\n 'title': movie.get('title'),\n 'votes': movie.get('votes'),\n \"aka\": list_to_str(movie.get(\"akas\")),\n \"seasons\": movie.get(\"number of seasons\"),\n \"box_office\": movie.get('box office'),\n 'localized_title': movie.get('localized title'),\n 'kind': movie.get(\"kind\"),\n \"imdb_id\": f\"tt{movie.get('imdbID')}\",\n \"cast\": list_to_str(movie.get(\"cast\")),\n \"runtime\": list_to_str(movie.get(\"runtimes\")),\n \"countries\": list_to_str(movie.get(\"countries\")),\n \"certificates\": list_to_str(movie.get(\"certificates\")),\n \"languages\": list_to_str(movie.get(\"languages\")),\n \"director\": list_to_str(movie.get(\"director\")),\n \"writer\":list_to_str(movie.get(\"writer\")),\n \"producer\":list_to_str(movie.get(\"producer\")),\n \"composer\":list_to_str(movie.get(\"composer\")) ,\n \"cinematographer\":list_to_str(movie.get(\"cinematographer\")),\n \"music_team\": list_to_str(movie.get(\"music department\")),\n \"distributors\": list_to_str(movie.get(\"distributors\")),\n 'release_date': date,\n 'year': movie.get('year'),\n 'genres': list_to_str(movie.get(\"genres\")),\n 'poster': movie.get('full-size cover url'),\n 'plot': plot,\n 'rating': str(movie.get(\"rating\")),\n 'url':f'https://www.imdb.com/title/tt{movieid}'\n }" }, { "identifier": "search_gagala", "path": "utils.py", "snippet": "async def search_gagala(text):\n usr_agent = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/61.0.3163.100 Safari/537.36'\n }\n text = text.replace(\" \", '+')\n url = f'https://www.google.com/search?q={text}'\n response = requests.get(url, headers=usr_agent)\n response.raise_for_status()\n soup = BeautifulSoup(response.text, 'html.parser')\n titles = soup.find_all( 'h3' )\n return [title.getText() for title in titles]" }, { "identifier": "temp", "path": "utils.py", "snippet": "class temp(object):\n BANNED_USERS = []\n BANNED_CHATS = []\n ME = None\n CURRENT=int(os.environ.get(\"SKIP\", 2))\n CANCEL = False\n MELCOW = {}\n U_NAME = None\n B_NAME = None\n GETALL = {}\n SHORT = {}\n SETTINGS = {}" }, { "identifier": "get_settings", "path": "utils.py", "snippet": "async def get_settings(group_id):\n settings = temp.SETTINGS.get(group_id)\n if not settings:\n settings = await db.get_settings(group_id)\n temp.SETTINGS[group_id] = settings\n return settings" }, { "identifier": "save_group_settings", "path": "utils.py", "snippet": "async def save_group_settings(group_id, key, value):\n current = await get_settings(group_id)\n current[key] = value\n temp.SETTINGS[group_id] = current\n await db.update_settings(group_id, current)" }, { "identifier": "get_shortlink", "path": "utils.py", "snippet": "async def get_shortlink(chat_id, link):\n settings = await get_settings(chat_id) #fetching settings for group\n if 'shortlink' in settings.keys():\n URL = settings['shortlink']\n else:\n URL = SHORTLINK_URL\n if 'shortlink_api' in settings.keys():\n API = settings['shortlink_api']\n else:\n API = SHORTLINK_API\n https = link.split(\":\")[0] \n if \"http\" == https: #if https == \"http\":\n https = \"https\"\n link = link.replace(\"http\", https)\n if URL == \"api.shareus.in\":\n url = f'https://{URL}/shortLink'\n params = {\n \"token\": API,\n \"format\": \"json\",\n \"link\": link,\n }\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:\n data = await response.json(content_type=\"text/html\")\n if data[\"status\"] == \"success\":\n return data[\"shortlink\"]\n else:\n logger.error(f\"Error: {data['message']}\")\n return f'https://{URL}/shortLink?token={API}&format=json&link={link}'\n except Exception as e:\n logger.error(e)\n return f'https://{URL}/shortLink?token={API}&format=json&link={link}'\n else:\n url = f'https://{URL}/api'\n params = {\n \"api\": API,\n \"url\": link,\n }\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:\n data = await response.json()\n if data[\"status\"] == \"success\":\n return data[\"shortenedUrl\"]\n else:\n logger.error(f\"Error: {data['message']}\")\n return f'https://{URL}/api?api={API}&link={link}'\n except Exception as e:\n logger.error(e)\n return f'https://{URL}/api?api={API}&link={link}'" }, { "identifier": "get_tutorial", "path": "utils.py", "snippet": "async def get_tutorial(chat_id):\n settings = await get_settings(chat_id) #fetching settings for group\n if 'tutorial' in settings.keys():\n if settings['is_tutorial']:\n TUTORIAL_URL = settings['tutorial']\n else:\n TUTORIAL_URL = TUTORIAL\n else:\n TUTORIAL_URL = TUTORIAL\n return TUTORIAL_URL" }, { "identifier": "send_all", "path": "utils.py", "snippet": "async def send_all(bot, userid, files, ident, chat_id, user_name, query):\n settings = await get_settings(chat_id)\n if 'is_shortlink' in settings.keys():\n ENABLE_SHORTLINK = settings['is_shortlink']\n else:\n await save_group_settings(message.chat.id, 'is_shortlink', False)\n ENABLE_SHORTLINK = False\n try:\n if ENABLE_SHORTLINK:\n for file in files:\n title = file.file_name\n size = get_size(file.file_size)\n await bot.send_message(chat_id=userid, text=f\"<b>Hᴇʏ ᴛʜᴇʀᴇ {user_name} 👋🏽 \\n\\n✅ Sᴇᴄᴜʀᴇ ʟɪɴᴋ ᴛᴏ ʏᴏᴜʀ ғɪʟᴇ ʜᴀs sᴜᴄᴄᴇssғᴜʟʟʏ ʙᴇᴇɴ ɢᴇɴᴇʀᴀᴛᴇᴅ ᴘʟᴇᴀsᴇ ᴄʟɪᴄᴋ ᴅᴏᴡɴʟᴏᴀᴅ ʙᴜᴛᴛᴏɴ\\n\\n🗃️ Fɪʟᴇ Nᴀᴍᴇ : {title}\\n🔖 Fɪʟᴇ Sɪᴢᴇ : {size}</b>\", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\"📤 Dᴏᴡɴʟᴏᴀᴅ 📥\", url=await get_shortlink(chat_id, f\"https://telegram.me/{temp.U_NAME}?start=files_{file.file_id}\"))]]))\n else:\n for file in files:\n f_caption = file.caption\n title = file.file_name\n size = get_size(file.file_size)\n if CUSTOM_FILE_CAPTION:\n try:\n f_caption = CUSTOM_FILE_CAPTION.format(file_name='' if title is None else title,\n file_size='' if size is None else size,\n file_caption='' if f_caption is None else f_caption)\n except Exception as e:\n print(e)\n f_caption = f_caption\n if f_caption is None:\n f_caption = f\"{title}\"\n await bot.send_cached_media(\n chat_id=userid,\n file_id=file.file_id,\n caption=f_caption,\n protect_content=True if ident == \"filep\" else False,\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton('❤️‍🔥 ᴄʜᴀɴɴᴇʟ​ ❤️‍🔥​', url='https://telegram.me/NobiDeveloper')\n ]\n ]\n )\n )\n except UserIsBlocked:\n await query.answer('Uɴʙʟᴏᴄᴋ ᴛʜᴇ ʙᴏᴛ ᴍᴀʜɴ !', show_alert=True)\n except PeerIdInvalid:\n await query.answer('Hᴇʏ, Sᴛᴀʀᴛ Bᴏᴛ Fɪʀsᴛ Aɴᴅ Cʟɪᴄᴋ Sᴇɴᴅ Aʟʟ', show_alert=True)\n except Exception as e:\n await query.answer('Hᴇʏ, Sᴛᴀʀᴛ Bᴏᴛ Fɪʀsᴛ Aɴᴅ Cʟɪᴄᴋ Sᴇɴᴅ Aʟʟ', show_alert=True)" }, { "identifier": "db", "path": "database/users_chats_db.py", "snippet": "class Database:\n def __init__(self, uri, database_name):\n def new_user(self, id, name):\n def new_group(self, id, title):\n async def add_user(self, id, name):\n async def is_user_exist(self, id):\n async def total_users_count(self):\n async def remove_ban(self, id):\n async def ban_user(self, user_id, ban_reason=\"No Reason\"):\n async def get_ban_status(self, id):\n async def get_all_users(self):\n async def delete_user(self, user_id):\n async def get_banned(self):\n async def add_chat(self, chat, title):\n async def get_chat(self, chat):\n async def re_enable_chat(self, id):\n async def update_settings(self, id, settings):\n async def get_settings(self, id):\n async def disable_chat(self, chat, reason=\"No Reason\"):\n async def total_chat_count(self):\n async def get_all_chats(self):\n async def get_db_size(self):" }, { "identifier": "Media", "path": "database/ia_filterdb.py", "snippet": "class Media(Document):\n file_id = fields.StrField(attribute='_id')\n file_ref = fields.StrField(allow_none=True)\n file_name = fields.StrField(required=True)\n file_size = fields.IntField(required=True)\n file_type = fields.StrField(allow_none=True)\n mime_type = fields.StrField(allow_none=True)\n caption = fields.StrField(allow_none=True)\n\n class Meta:\n indexes = ('$file_name', )\n collection_name = COLLECTION_NAME" }, { "identifier": "get_file_details", "path": "database/ia_filterdb.py", "snippet": "async def get_file_details(query):\n filter = {'file_id': query}\n cursor = Media.find(filter)\n filedetails = await cursor.to_list(length=1)\n return filedetails" }, { "identifier": "get_search_results", "path": "database/ia_filterdb.py", "snippet": "async def get_search_results(chat_id, query, file_type=None, max_results=10, offset=0, filter=False):\n \"\"\"For given query return (results, next_offset)\"\"\"\n if chat_id is not None:\n settings = await get_settings(int(chat_id))\n try:\n if settings['max_btn']:\n max_results = 10\n else:\n max_results = int(MAX_B_TN)\n except KeyError:\n await save_group_settings(int(chat_id), 'max_btn', False)\n settings = await get_settings(int(chat_id))\n if settings['max_btn']:\n max_results = 10\n else:\n max_results = int(MAX_B_TN)\n query = query.strip()\n #if filter:\n #better ?\n #query = query.replace(' ', r'(\\s|\\.|\\+|\\-|_)')\n #raw_pattern = r'(\\s|_|\\-|\\.|\\+)' + query + r'(\\s|_|\\-|\\.|\\+)'\n if not query:\n raw_pattern = '.'\n elif ' ' not in query:\n raw_pattern = r'(\\b|[\\.\\+\\-_])' + query + r'(\\b|[\\.\\+\\-_])'\n else:\n raw_pattern = query.replace(' ', r'.*[\\s\\.\\+\\-_]')\n \n try:\n regex = re.compile(raw_pattern, flags=re.IGNORECASE)\n except:\n return []\n\n if USE_CAPTION_FILTER:\n filter = {'$or': [{'file_name': regex}, {'caption': regex}]}\n else:\n filter = {'file_name': regex}\n\n if file_type:\n filter['file_type'] = file_type\n\n total_results = await Media.count_documents(filter)\n next_offset = offset + max_results\n\n if next_offset > total_results:\n next_offset = ''\n\n cursor = Media.find(filter)\n # Sort by recent\n cursor.sort('$natural', -1)\n # Slice files according to offset and max results\n cursor.skip(offset).limit(max_results)\n # Get list of files\n files = await cursor.to_list(length=max_results)\n\n return files, next_offset, total_results" }, { "identifier": "get_bad_files", "path": "database/ia_filterdb.py", "snippet": "async def get_bad_files(query, file_type=None, filter=False):\n \"\"\"For given query return (results, next_offset)\"\"\"\n query = query.strip()\n #if filter:\n #better ?\n #query = query.replace(' ', r'(\\s|\\.|\\+|\\-|_)')\n #raw_pattern = r'(\\s|_|\\-|\\.|\\+)' + query + r'(\\s|_|\\-|\\.|\\+)'\n if not query:\n raw_pattern = '.'\n elif ' ' not in query:\n raw_pattern = r'(\\b|[\\.\\+\\-_])' + query + r'(\\b|[\\.\\+\\-_])'\n else:\n raw_pattern = query.replace(' ', r'.*[\\s\\.\\+\\-_]')\n \n try:\n regex = re.compile(raw_pattern, flags=re.IGNORECASE)\n except:\n return []\n\n if USE_CAPTION_FILTER:\n filter = {'$or': [{'file_name': regex}, {'caption': regex}]}\n else:\n filter = {'file_name': regex}\n\n if file_type:\n filter['file_type'] = file_type\n\n total_results = await Media.count_documents(filter)\n\n cursor = Media.find(filter)\n # Sort by recent\n cursor.sort('$natural', -1)\n # Get list of files\n files = await cursor.to_list(length=total_results)\n\n return files, total_results" }, { "identifier": "del_all", "path": "database/filters_mdb.py", "snippet": "async def del_all(message, group_id, title):\n if str(group_id) not in mydb.list_collection_names():\n await message.edit_text(f\"Nothing to remove in {title}!\")\n return\n\n mycol = mydb[str(group_id)]\n try:\n mycol.drop()\n await message.edit_text(f\"All filters from {title} has been removed\")\n except:\n await message.edit_text(\"Couldn't remove all filters from group!\")\n return" }, { "identifier": "find_filter", "path": "database/filters_mdb.py", "snippet": "async def find_filter(group_id, name):\n mycol = mydb[str(group_id)]\n \n query = mycol.find( {\"text\":name})\n # query = mycol.find( { \"$text\": {\"$search\": name}})\n try:\n for file in query:\n reply_text = file['reply']\n btn = file['btn']\n fileid = file['file']\n try:\n alert = file['alert']\n except:\n alert = None\n return reply_text, btn, alert, fileid\n except:\n return None, None, None, None" }, { "identifier": "get_filters", "path": "database/filters_mdb.py", "snippet": "async def get_filters(group_id):\n mycol = mydb[str(group_id)]\n\n texts = []\n query = mycol.find()\n try:\n for file in query:\n text = file['text']\n texts.append(text)\n except:\n pass\n return texts" }, { "identifier": "find_gfilter", "path": "database/gfilters_mdb.py", "snippet": "async def find_gfilter(gfilters, name):\n mycol = mydb[str(gfilters)]\n \n query = mycol.find( {\"text\":name})\n # query = mycol.find( { \"$text\": {\"$search\": name}})\n try:\n for file in query:\n reply_text = file['reply']\n btn = file['btn']\n fileid = file['file']\n try:\n alert = file['alert']\n except:\n alert = None\n return reply_text, btn, alert, fileid\n except:\n return None, None, None, None" }, { "identifier": "get_gfilters", "path": "database/gfilters_mdb.py", "snippet": "async def get_gfilters(gfilters):\n mycol = mydb[str(gfilters)]\n\n texts = []\n query = mycol.find()\n try:\n for file in query:\n text = file['text']\n texts.append(text)\n except:\n pass\n return texts" }, { "identifier": "del_allg", "path": "database/gfilters_mdb.py", "snippet": "async def del_allg(message, gfilters):\n if str(gfilters) not in mydb.list_collection_names():\n await message.edit_text(\"Nothing to remove !\")\n return\n\n mycol = mydb[str(gfilters)]\n try:\n mycol.drop()\n await message.edit_text(f\"All gfilters has been removed !\")\n except:\n await message.edit_text(\"Couldn't remove all gfilters !\")\n return" } ]
import asyncio import re import ast import math import random import pytz import pyrogram import logging from datetime import datetime, timedelta, date, time from pyrogram.errors.exceptions.bad_request_400 import MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty from Script import script from database.connections_mdb import active_connection, all_connections, delete_connection, if_active, make_active, \ make_inactive from info import ADMINS, AUTH_CHANNEL, AUTH_USERS, SUPPORT_CHAT_ID, CUSTOM_FILE_CAPTION, MSG_ALRT, PICS, AUTH_GROUPS, P_TTI_SHOW_OFF, GRP_LNK, CHNL_LNK, NOR_IMG, LOG_CHANNEL, SPELL_IMG, MAX_B_TN, IMDB, \ SINGLE_BUTTON, SPELL_CHECK_REPLY, IMDB_TEMPLATE, NO_RESULTS_MSG, TUTORIAL, REQST_CHANNEL, IS_TUTORIAL, LANGUAGES, SUPPORT_CHAT from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, InputMediaPhoto from pyrogram import Client, filters, enums from pyrogram.errors import FloodWait, UserIsBlocked, MessageNotModified, PeerIdInvalid from utils import get_size, is_subscribed, get_poster, search_gagala, temp, get_settings, save_group_settings, get_shortlink, get_tutorial, send_all from database.users_chats_db import db from database.ia_filterdb import Media, get_file_details, get_search_results, get_bad_files from database.filters_mdb import ( del_all, find_filter, get_filters, ) from database.gfilters_mdb import ( find_gfilter, get_gfilters, del_allg )
21,360
# ©NobiDeveloper lock = asyncio.Lock() logger = logging.getLogger(__name__) logger.setLevel(logging.ERROR) BUTTON = {} BUTTONS = {} FRESH = {} BUTTONS0 = {} BUTTONS1 = {} BUTTONS2 = {} SPELL_CHECK = {} ENABLE_SHORTLINK = "" @Client.on_message(filters.group & filters.text & filters.incoming) async def give_filter(client, message): if message.chat.id != SUPPORT_CHAT_ID: manual = await manual_filters(client, message) if manual == False: settings = await get_settings(message.chat.id) try: if settings['auto_ffilter']: await auto_filter(client, message) except KeyError: grpid = await active_connection(str(message.from_user.id)) await save_group_settings(grpid, 'auto_ffilter', True) settings = await get_settings(message.chat.id) if settings['auto_ffilter']: await auto_filter(client, message) else: #a better logic to avoid repeated lines of code in auto_filter function search = message.text temp_files, temp_offset, total_results = await get_search_results(chat_id=message.chat.id, query=search.lower(), offset=0, filter=True) if total_results == 0: return else: return await message.reply_text( text=f"<b>{message.from_user.mention},</b>\n\n({str(total_results)}) ʀᴇsᴜʟᴛ ᴀʀᴇ ꜰᴏᴜɴᴅ ɪɴ ᴍʏ ᴅᴀᴛᴀʙᴀsᴇ ꜰᴏʀ ʏᴏᴜʀ sᴇᴀʀᴄʜ [{search}]", parse_mode=enums.ParseMode.HTML, reply_markup=InlineKeyboardMarkup( [[ InlineKeyboardButton('✧ ᴛᴀᴋᴇ ᴍᴏᴠɪᴇ ꜰʀᴏᴍ ʜᴇʀᴇ ✧', url ='https://telegram.me/AllRequestGroups') ]] ) ) @Client.on_message(filters.private & filters.text & filters.incoming) async def pm_text(bot, message): content = message.text user = message.from_user.first_name user_id = message.from_user.id if content.startswith("/") or content.startswith("#"): return # ignore commands and hashtags if user_id in ADMINS: return # ignore admins await message.reply_text( text="<b>ʜʏ,\n\nɪꜰ ʏᴏᴜ ᴡᴀɴᴛ ᴍᴏᴠɪᴇs / sᴇʀɪᴇs ᴛʜᴇɴ ᴄʟɪᴄᴋ ᴏɴ ꜰɪʀsᴛ ʙᴜᴛᴛᴏɴ ᴏʀ ᴀɴʏ ᴘʀᴏʙʟᴇᴍ ɪɴ ʙᴏᴛ ᴛʜᴇɴ ᴄʟɪᴄᴋ ᴏɴ sᴇᴄᴏɴᴅ ʙᴜᴛᴛᴏɴ</b>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("📝 ʀᴇǫᴜᴇsᴛ ʜᴇʀᴇ​ ", url=f"https://telegram.me/AllRequestGroups")]]), disable_web_page_preview=True ) await bot.send_message( chat_id=LOG_CHANNEL, text=f"<b>#𝐌𝐒𝐆\n\nNᴀᴍᴇ : {user}\n\nID : {user_id}\n\nMᴇssᴀɢᴇ : {content}</b>" ) @Client.on_callback_query(filters.regex(r"^next")) async def next_page(bot, query): ident, req, key, offset = query.data.split("_") if int(req) not in [query.from_user.id, 0]:
# ©NobiDeveloper lock = asyncio.Lock() logger = logging.getLogger(__name__) logger.setLevel(logging.ERROR) BUTTON = {} BUTTONS = {} FRESH = {} BUTTONS0 = {} BUTTONS1 = {} BUTTONS2 = {} SPELL_CHECK = {} ENABLE_SHORTLINK = "" @Client.on_message(filters.group & filters.text & filters.incoming) async def give_filter(client, message): if message.chat.id != SUPPORT_CHAT_ID: manual = await manual_filters(client, message) if manual == False: settings = await get_settings(message.chat.id) try: if settings['auto_ffilter']: await auto_filter(client, message) except KeyError: grpid = await active_connection(str(message.from_user.id)) await save_group_settings(grpid, 'auto_ffilter', True) settings = await get_settings(message.chat.id) if settings['auto_ffilter']: await auto_filter(client, message) else: #a better logic to avoid repeated lines of code in auto_filter function search = message.text temp_files, temp_offset, total_results = await get_search_results(chat_id=message.chat.id, query=search.lower(), offset=0, filter=True) if total_results == 0: return else: return await message.reply_text( text=f"<b>{message.from_user.mention},</b>\n\n({str(total_results)}) ʀᴇsᴜʟᴛ ᴀʀᴇ ꜰᴏᴜɴᴅ ɪɴ ᴍʏ ᴅᴀᴛᴀʙᴀsᴇ ꜰᴏʀ ʏᴏᴜʀ sᴇᴀʀᴄʜ [{search}]", parse_mode=enums.ParseMode.HTML, reply_markup=InlineKeyboardMarkup( [[ InlineKeyboardButton('✧ ᴛᴀᴋᴇ ᴍᴏᴠɪᴇ ꜰʀᴏᴍ ʜᴇʀᴇ ✧', url ='https://telegram.me/AllRequestGroups') ]] ) ) @Client.on_message(filters.private & filters.text & filters.incoming) async def pm_text(bot, message): content = message.text user = message.from_user.first_name user_id = message.from_user.id if content.startswith("/") or content.startswith("#"): return # ignore commands and hashtags if user_id in ADMINS: return # ignore admins await message.reply_text( text="<b>ʜʏ,\n\nɪꜰ ʏᴏᴜ ᴡᴀɴᴛ ᴍᴏᴠɪᴇs / sᴇʀɪᴇs ᴛʜᴇɴ ᴄʟɪᴄᴋ ᴏɴ ꜰɪʀsᴛ ʙᴜᴛᴛᴏɴ ᴏʀ ᴀɴʏ ᴘʀᴏʙʟᴇᴍ ɪɴ ʙᴏᴛ ᴛʜᴇɴ ᴄʟɪᴄᴋ ᴏɴ sᴇᴄᴏɴᴅ ʙᴜᴛᴛᴏɴ</b>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("📝 ʀᴇǫᴜᴇsᴛ ʜᴇʀᴇ​ ", url=f"https://telegram.me/AllRequestGroups")]]), disable_web_page_preview=True ) await bot.send_message( chat_id=LOG_CHANNEL, text=f"<b>#𝐌𝐒𝐆\n\nNᴀᴍᴇ : {user}\n\nID : {user_id}\n\nMᴇssᴀɢᴇ : {content}</b>" ) @Client.on_callback_query(filters.regex(r"^next")) async def next_page(bot, query): ident, req, key, offset = query.data.split("_") if int(req) not in [query.from_user.id, 0]:
return await query.answer(script.ALRT_TXT.format(query.from_user.first_name), show_alert=True)
0
2023-11-28 13:36:56+00:00
24k
chenxx89/BFRffusion
models/models.py
[ { "identifier": "timestep_embedding", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):\n \"\"\"\n Create sinusoidal timestep embeddings.\n :param timesteps: a 1-D Tensor of N indices, one per batch element.\n These may be fractional.\n :param dim: the dimension of the output.\n :param max_period: controls the minimum frequency of the embeddings.\n :return: an [N x dim] Tensor of positional embeddings.\n \"\"\"\n if not repeat_only:\n half = dim // 2\n freqs = torch.exp(\n -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half\n ).to(device=timesteps.device)\n args = timesteps[:, None].float() * freqs[None]\n embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)\n if dim % 2:\n embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)\n else:\n embedding = repeat(timesteps, 'b -> b d', d=dim)\n return embedding" }, { "identifier": "UNetModel", "path": "ldm/modules/diffusionmodules/openaimodel.py", "snippet": "class UNetModel(nn.Module):\n \"\"\"\n The full UNet model with attention and timestep embedding.\n :param in_channels: channels in the input Tensor.\n :param model_channels: base channel count for the model.\n :param out_channels: channels in the output Tensor.\n :param num_res_blocks: number of residual blocks per downsample.\n :param attention_resolutions: a collection of downsample rates at which\n attention will take place. May be a set, list, or tuple.\n For example, if this contains 4, then at 4x downsampling, attention\n will be used.\n :param dropout: the dropout probability.\n :param channel_mult: channel multiplier for each level of the UNet.\n :param conv_resample: if True, use learned convolutions for upsampling and\n downsampling.\n :param dims: determines if the signal is 1D, 2D, or 3D.\n :param num_classes: if specified (as an int), then this model will be\n class-conditional with `num_classes` classes.\n :param use_checkpoint: use gradient checkpointing to reduce memory usage.\n :param num_heads: the number of attention heads in each attention layer.\n :param num_heads_channels: if specified, ignore num_heads and instead use\n a fixed channel width per attention head.\n :param num_heads_upsample: works with num_heads to set a different number\n of heads for upsampling. Deprecated.\n :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.\n :param resblock_updown: use residual blocks for up/downsampling.\n :param use_new_attention_order: use a different attention pattern for potentially\n increased efficiency.\n \"\"\"\n\n def __init__(\n self,\n image_size,\n in_channels,\n model_channels,\n out_channels,\n num_res_blocks,\n attention_resolutions,\n dropout=0,\n channel_mult=(1, 2, 4, 8),\n conv_resample=True,\n dims=2,\n num_classes=None,\n use_checkpoint=False,\n use_fp16=False,\n num_heads=-1,\n num_head_channels=-1,\n num_heads_upsample=-1,\n use_scale_shift_norm=False,\n resblock_updown=False,\n use_new_attention_order=False,\n use_spatial_transformer=False, # custom transformer support\n transformer_depth=1, # custom transformer support\n context_dim=None, # custom transformer support\n n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model\n legacy=True,\n disable_self_attentions=None,\n num_attention_blocks=None,\n disable_middle_self_attn=False,\n use_linear_in_transformer=False,\n ):\n super().__init__()\n if use_spatial_transformer:\n assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'\n\n if context_dim is not None:\n assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'\n from omegaconf.listconfig import ListConfig\n if type(context_dim) == ListConfig:\n context_dim = list(context_dim)\n\n if num_heads_upsample == -1:\n num_heads_upsample = num_heads\n\n if num_heads == -1:\n assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'\n\n if num_head_channels == -1:\n assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'\n\n self.image_size = image_size\n self.in_channels = in_channels\n self.model_channels = model_channels\n self.out_channels = out_channels\n if isinstance(num_res_blocks, int):\n self.num_res_blocks = len(channel_mult) * [num_res_blocks]\n else:\n if len(num_res_blocks) != len(channel_mult):\n raise ValueError(\"provide num_res_blocks either as an int (globally constant) or \"\n \"as a list/tuple (per-level) with the same length as channel_mult\")\n self.num_res_blocks = num_res_blocks\n if disable_self_attentions is not None:\n # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not\n assert len(disable_self_attentions) == len(channel_mult)\n if num_attention_blocks is not None:\n assert len(num_attention_blocks) == len(self.num_res_blocks)\n assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))\n print(f\"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. \"\n f\"This option has LESS priority than attention_resolutions {attention_resolutions}, \"\n f\"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, \"\n f\"attention will still not be set.\")\n\n self.attention_resolutions = attention_resolutions\n self.dropout = dropout\n self.channel_mult = channel_mult\n self.conv_resample = conv_resample\n self.num_classes = num_classes\n self.use_checkpoint = use_checkpoint\n self.dtype = th.float16 if use_fp16 else th.float32\n self.num_heads = num_heads\n self.num_head_channels = num_head_channels\n self.num_heads_upsample = num_heads_upsample\n self.predict_codebook_ids = n_embed is not None\n\n time_embed_dim = model_channels * 4\n self.time_embed = nn.Sequential(\n linear(model_channels, time_embed_dim),\n nn.SiLU(),\n linear(time_embed_dim, time_embed_dim),\n )\n\n if self.num_classes is not None:\n if isinstance(self.num_classes, int):\n self.label_emb = nn.Embedding(num_classes, time_embed_dim)\n elif self.num_classes == \"continuous\":\n print(\"setting up linear c_adm embedding layer\")\n self.label_emb = nn.Linear(1, time_embed_dim)\n else:\n raise ValueError()\n\n self.input_blocks = nn.ModuleList(\n [\n TimestepEmbedSequential(\n conv_nd(dims, in_channels, model_channels, 3, padding=1)\n )\n ]\n )\n self._feature_size = model_channels\n input_block_chans = [model_channels]\n ch = model_channels\n ds = 1\n for level, mult in enumerate(channel_mult):\n for nr in range(self.num_res_blocks[level]):\n layers = [\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n out_channels=mult * model_channels,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n )\n ]\n ch = mult * model_channels\n if ds in attention_resolutions:\n if num_head_channels == -1:\n dim_head = ch // num_heads\n else:\n num_heads = ch // num_head_channels\n dim_head = num_head_channels\n if legacy:\n #num_heads = 1\n dim_head = ch // num_heads if use_spatial_transformer else num_head_channels\n if exists(disable_self_attentions):\n disabled_sa = disable_self_attentions[level]\n else:\n disabled_sa = False\n\n if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:\n layers.append(\n AttentionBlock(\n ch,\n use_checkpoint=use_checkpoint,\n num_heads=num_heads,\n num_head_channels=dim_head,\n use_new_attention_order=use_new_attention_order,\n ) if not use_spatial_transformer else SpatialTransformer(\n ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,\n disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,\n use_checkpoint=use_checkpoint\n )\n )\n self.input_blocks.append(TimestepEmbedSequential(*layers))\n self._feature_size += ch\n input_block_chans.append(ch)\n if level != len(channel_mult) - 1:\n out_ch = ch\n self.input_blocks.append(\n TimestepEmbedSequential(\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n out_channels=out_ch,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n down=True,\n )\n if resblock_updown\n else Downsample(\n ch, conv_resample, dims=dims, out_channels=out_ch\n )\n )\n )\n ch = out_ch\n input_block_chans.append(ch)\n ds *= 2\n self._feature_size += ch\n\n if num_head_channels == -1:\n dim_head = ch // num_heads\n else:\n num_heads = ch // num_head_channels\n dim_head = num_head_channels\n if legacy:\n #num_heads = 1\n dim_head = ch // num_heads if use_spatial_transformer else num_head_channels\n self.middle_block = TimestepEmbedSequential(\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n ),\n AttentionBlock(\n ch,\n use_checkpoint=use_checkpoint,\n num_heads=num_heads,\n num_head_channels=dim_head,\n use_new_attention_order=use_new_attention_order,\n ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn\n ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,\n disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,\n use_checkpoint=use_checkpoint\n ),\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n ),\n )\n self._feature_size += ch\n\n self.output_blocks = nn.ModuleList([])\n for level, mult in list(enumerate(channel_mult))[::-1]:\n for i in range(self.num_res_blocks[level] + 1):\n ich = input_block_chans.pop()\n layers = [\n ResBlock(\n ch + ich,\n time_embed_dim,\n dropout,\n out_channels=model_channels * mult,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n )\n ]\n ch = model_channels * mult\n if ds in attention_resolutions:\n if num_head_channels == -1:\n dim_head = ch // num_heads\n else:\n num_heads = ch // num_head_channels\n dim_head = num_head_channels\n if legacy:\n #num_heads = 1\n dim_head = ch // num_heads if use_spatial_transformer else num_head_channels\n if exists(disable_self_attentions):\n disabled_sa = disable_self_attentions[level]\n else:\n disabled_sa = False\n\n if not exists(num_attention_blocks) or i < num_attention_blocks[level]:\n layers.append(\n AttentionBlock(\n ch,\n use_checkpoint=use_checkpoint,\n num_heads=num_heads_upsample,\n num_head_channels=dim_head,\n use_new_attention_order=use_new_attention_order,\n ) if not use_spatial_transformer else SpatialTransformer(\n ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,\n disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,\n use_checkpoint=use_checkpoint\n )\n )\n if level and i == self.num_res_blocks[level]:\n out_ch = ch\n layers.append(\n ResBlock(\n ch,\n time_embed_dim,\n dropout,\n out_channels=out_ch,\n dims=dims,\n use_checkpoint=use_checkpoint,\n use_scale_shift_norm=use_scale_shift_norm,\n up=True,\n )\n if resblock_updown\n else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)\n )\n ds //= 2\n self.output_blocks.append(TimestepEmbedSequential(*layers))\n self._feature_size += ch\n\n self.out = nn.Sequential(\n normalization(ch),\n nn.SiLU(),\n zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),\n )\n if self.predict_codebook_ids:\n self.id_predictor = nn.Sequential(\n normalization(ch),\n conv_nd(dims, model_channels, n_embed, 1),\n #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits\n )\n\n def convert_to_fp16(self):\n \"\"\"\n Convert the torso of the model to float16.\n \"\"\"\n self.input_blocks.apply(convert_module_to_f16)\n self.middle_block.apply(convert_module_to_f16)\n self.output_blocks.apply(convert_module_to_f16)\n\n def convert_to_fp32(self):\n \"\"\"\n Convert the torso of the model to float32.\n \"\"\"\n self.input_blocks.apply(convert_module_to_f32)\n self.middle_block.apply(convert_module_to_f32)\n self.output_blocks.apply(convert_module_to_f32)\n\n def forward(self, x, timesteps=None, context=None, y=None,**kwargs):\n \"\"\"\n Apply the model to an input batch.\n :param x: an [N x C x ...] Tensor of inputs.\n :param timesteps: a 1-D batch of timesteps.\n :param context: conditioning plugged in via crossattn\n :param y: an [N] Tensor of labels, if class-conditional.\n :return: an [N x C x ...] Tensor of outputs.\n \"\"\"\n assert (y is not None) == (\n self.num_classes is not None\n ), \"must specify y if and only if the model is class-conditional\"\n hs = []\n t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)\n emb = self.time_embed(t_emb)\n\n if self.num_classes is not None:\n assert y.shape[0] == x.shape[0]\n emb = emb + self.label_emb(y)\n\n h = x.type(self.dtype)\n for module in self.input_blocks:\n h = module(h, emb, context)\n hs.append(h)\n h = self.middle_block(h, emb, context)\n for module in self.output_blocks:\n h = th.cat([h, hs.pop()], dim=1)\n h = module(h, emb, context)\n h = h.type(x.dtype)\n if self.predict_codebook_ids:\n return self.id_predictor(h)\n else:\n return self.out(h)" }, { "identifier": "LatentDiffusion", "path": "ldm/models/diffusion/ddpm.py", "snippet": "class LatentDiffusion(DDPM):\n \"\"\"main class\"\"\"\n\n def __init__(self,\n first_stage_config,\n cond_stage_config,\n num_timesteps_cond=None,\n cond_stage_key=\"image\",\n cond_stage_trainable=False,\n concat_mode=True,\n cond_stage_forward=None,\n conditioning_key=None,\n scale_factor=1.0,\n scale_by_std=False,\n force_null_conditioning=False,\n *args, **kwargs):\n self.force_null_conditioning = force_null_conditioning\n self.num_timesteps_cond = default(num_timesteps_cond, 1)\n self.scale_by_std = scale_by_std\n assert self.num_timesteps_cond <= kwargs['timesteps']\n # for backwards compatibility after implementation of DiffusionWrapper\n if conditioning_key is None:\n conditioning_key = 'concat' if concat_mode else 'crossattn'\n if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning:\n conditioning_key = None\n ckpt_path = kwargs.pop(\"ckpt_path\", None)\n reset_ema = kwargs.pop(\"reset_ema\", False)\n reset_num_ema_updates = kwargs.pop(\"reset_num_ema_updates\", False)\n ignore_keys = kwargs.pop(\"ignore_keys\", [])\n super().__init__(conditioning_key=conditioning_key, *args, **kwargs)\n self.concat_mode = concat_mode\n self.cond_stage_trainable = cond_stage_trainable\n self.cond_stage_key = cond_stage_key\n try:\n self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1\n except:\n self.num_downs = 0\n if not scale_by_std:\n self.scale_factor = scale_factor\n else:\n self.register_buffer('scale_factor', torch.tensor(scale_factor))\n self.instantiate_first_stage(first_stage_config)\n self.instantiate_cond_stage(cond_stage_config)\n self.cond_stage_forward = cond_stage_forward\n self.clip_denoised = False\n self.bbox_tokenizer = None\n\n self.restarted_from_ckpt = False\n if ckpt_path is not None:\n self.init_from_ckpt(ckpt_path, ignore_keys)\n self.restarted_from_ckpt = True\n if reset_ema:\n assert self.use_ema\n print(\n f\"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.\")\n self.model_ema = LitEma(self.model)\n if reset_num_ema_updates:\n print(\" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ \")\n assert self.use_ema\n self.model_ema.reset_num_updates()\n\n def make_cond_schedule(self, ):\n self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)\n ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()\n self.cond_ids[:self.num_timesteps_cond] = ids\n\n @rank_zero_only\n @torch.no_grad()\n def on_train_batch_start(self, batch, batch_idx, dataloader_idx):\n # only for very first batch\n if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:\n assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'\n # set rescale weight to 1./std of encodings\n print(\"### USING STD-RESCALING ###\")\n x = super().get_input(batch, self.first_stage_key)\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n del self.scale_factor\n self.register_buffer('scale_factor', 1. / z.flatten().std())\n print(f\"setting self.scale_factor to {self.scale_factor}\")\n print(\"### USING STD-RESCALING ###\")\n\n def register_schedule(self,\n given_betas=None, beta_schedule=\"linear\", timesteps=1000,\n linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):\n super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)\n\n self.shorten_cond_schedule = self.num_timesteps_cond > 1\n if self.shorten_cond_schedule:\n self.make_cond_schedule()\n\n def instantiate_first_stage(self, config):\n model = instantiate_from_config(config)\n self.first_stage_model = model.eval()\n self.first_stage_model.train = disabled_train\n for param in self.first_stage_model.parameters():\n param.requires_grad = False\n\n def instantiate_cond_stage(self, config):\n if not self.cond_stage_trainable:\n if config == \"__is_first_stage__\":\n print(\"Using first stage also as cond stage.\")\n self.cond_stage_model = self.first_stage_model\n elif config == \"__is_unconditional__\":\n print(f\"Training {self.__class__.__name__} as an unconditional model.\")\n self.cond_stage_model = None\n # self.be_unconditional = True\n else:\n model = instantiate_from_config(config)\n self.cond_stage_model = model.eval()\n self.cond_stage_model.train = disabled_train\n for param in self.cond_stage_model.parameters():\n param.requires_grad = False\n else:\n assert config != '__is_first_stage__'\n assert config != '__is_unconditional__'\n model = instantiate_from_config(config)\n self.cond_stage_model = model\n\n def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):\n denoise_row = []\n for zd in tqdm(samples, desc=desc):\n denoise_row.append(self.decode_first_stage(zd.to(self.device),\n force_not_quantize=force_no_decoder_quantization))\n n_imgs_per_row = len(denoise_row)\n denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W\n denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')\n denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')\n denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)\n return denoise_grid\n\n def get_first_stage_encoding(self, encoder_posterior):\n if isinstance(encoder_posterior, DiagonalGaussianDistribution):\n z = encoder_posterior.sample()\n elif isinstance(encoder_posterior, torch.Tensor):\n z = encoder_posterior\n else:\n raise NotImplementedError(f\"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented\")\n return self.scale_factor * z\n\n def get_learned_conditioning(self, c):\n if self.cond_stage_forward is None:\n if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):\n c = self.cond_stage_model.encode(c)\n if isinstance(c, DiagonalGaussianDistribution):\n c = c.mode()\n else:\n c = self.cond_stage_model(c)\n else:\n assert hasattr(self.cond_stage_model, self.cond_stage_forward)\n c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)\n return c\n\n def meshgrid(self, h, w):\n y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)\n x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)\n\n arr = torch.cat([y, x], dim=-1)\n return arr\n\n def delta_border(self, h, w):\n \"\"\"\n :param h: height\n :param w: width\n :return: normalized distance to image border,\n wtith min distance = 0 at border and max dist = 0.5 at image center\n \"\"\"\n lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)\n arr = self.meshgrid(h, w) / lower_right_corner\n dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]\n dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]\n edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]\n return edge_dist\n\n def get_weighting(self, h, w, Ly, Lx, device):\n weighting = self.delta_border(h, w)\n weighting = torch.clip(weighting, self.split_input_params[\"clip_min_weight\"],\n self.split_input_params[\"clip_max_weight\"], )\n weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)\n\n if self.split_input_params[\"tie_braker\"]:\n L_weighting = self.delta_border(Ly, Lx)\n L_weighting = torch.clip(L_weighting,\n self.split_input_params[\"clip_min_tie_weight\"],\n self.split_input_params[\"clip_max_tie_weight\"])\n\n L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)\n weighting = weighting * L_weighting\n return weighting\n\n def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code\n \"\"\"\n :param x: img of size (bs, c, h, w)\n :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])\n \"\"\"\n bs, nc, h, w = x.shape\n\n # number of crops in image\n Ly = (h - kernel_size[0]) // stride[0] + 1\n Lx = (w - kernel_size[1]) // stride[1] + 1\n\n if uf == 1 and df == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)\n\n weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))\n\n elif uf > 1 and df == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),\n dilation=1, padding=0,\n stride=(stride[0] * uf, stride[1] * uf))\n fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)\n\n weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))\n\n elif df > 1 and uf == 1:\n fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)\n unfold = torch.nn.Unfold(**fold_params)\n\n fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),\n dilation=1, padding=0,\n stride=(stride[0] // df, stride[1] // df))\n fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)\n\n weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)\n normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap\n weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))\n\n else:\n raise NotImplementedError\n\n return fold, unfold, normalization, weighting\n\n @torch.no_grad()\n def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,\n cond_key=None, return_original_cond=False, bs=None, return_x=False):\n x = super().get_input(batch, k)\n if bs is not None:\n x = x[:bs]\n x = x.to(self.device)\n encoder_posterior = self.encode_first_stage(x)\n z = self.get_first_stage_encoding(encoder_posterior).detach()\n\n if self.model.conditioning_key is not None and not self.force_null_conditioning:\n if cond_key is None:\n cond_key = self.cond_stage_key\n if cond_key != self.first_stage_key:\n if cond_key in ['caption', 'coordinates_bbox', \"txt\"]:\n xc = batch[cond_key]\n elif cond_key in ['class_label', 'cls']:\n xc = batch\n else:\n xc = super().get_input(batch, cond_key).to(self.device)\n else:\n xc = x\n if not self.cond_stage_trainable or force_c_encode:\n if isinstance(xc, dict) or isinstance(xc, list):\n c = self.get_learned_conditioning(xc)\n else:\n c = self.get_learned_conditioning(xc.to(self.device))\n else:\n c = xc\n if bs is not None:\n c = c[:bs]\n\n if self.use_positional_encodings:\n pos_x, pos_y = self.compute_latent_shifts(batch)\n ckey = __conditioning_keys__[self.model.conditioning_key]\n c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}\n\n else:\n c = None\n xc = None\n if self.use_positional_encodings:\n pos_x, pos_y = self.compute_latent_shifts(batch)\n c = {'pos_x': pos_x, 'pos_y': pos_y}\n out = [z, c]\n if return_first_stage_outputs:\n xrec = self.decode_first_stage(z)\n out.extend([x, xrec])\n if return_x:\n out.extend([x])\n if return_original_cond:\n out.append(xc)\n return out\n\n @torch.no_grad()\n def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):\n if predict_cids:\n if z.dim() == 4:\n z = torch.argmax(z.exp(), dim=1).long()\n z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)\n z = rearrange(z, 'b h w c -> b c h w').contiguous()\n\n z = 1. / self.scale_factor * z\n return self.first_stage_model.decode(z)\n\n @torch.no_grad()\n def encode_first_stage(self, x):\n return self.first_stage_model.encode(x)\n\n def shared_step(self, batch, **kwargs):\n x, c = self.get_input(batch, self.first_stage_key)\n loss = self(x, c)\n return loss\n\n def forward(self, x, c, *args, **kwargs):\n t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()\n if self.model.conditioning_key is not None:\n assert c is not None\n # if self.cond_stage_trainable:\n # c = self.get_learned_conditioning(c)\n if self.shorten_cond_schedule: # TODO: drop this option\n tc = self.cond_ids[t].to(self.device)\n c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))\n return self.p_losses(x, c, t, *args, **kwargs)\n\n def apply_model(self, x_noisy, t, cond, return_ids=False):\n if isinstance(cond, dict):\n # hybrid case, cond is expected to be a dict\n pass\n else:\n if not isinstance(cond, list):\n cond = [cond]\n key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'\n cond = {key: cond}\n\n x_recon = self.model(x_noisy, t, **cond)\n\n if isinstance(x_recon, tuple) and not return_ids:\n return x_recon[0]\n else:\n return x_recon\n\n def _predict_eps_from_xstart(self, x_t, t, pred_xstart):\n return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \\\n extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)\n\n def _prior_bpd(self, x_start):\n \"\"\"\n Get the prior KL term for the variational lower-bound, measured in\n bits-per-dim.\n This term can't be optimized, as it only depends on the encoder.\n :param x_start: the [N x C x ...] tensor of inputs.\n :return: a batch of [N] KL values (in bits), one per batch element.\n \"\"\"\n batch_size = x_start.shape[0]\n t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)\n qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)\n kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)\n return mean_flat(kl_prior) / np.log(2.0)\n\n def p_losses(self, x_start, cond, t, noise=None):\n noise = default(noise, lambda: torch.randn_like(x_start))\n x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)\n model_output = self.apply_model(x_noisy, t, cond)\n\n loss_dict = {}\n prefix = 'train' if self.training else 'val'\n\n if self.parameterization == \"x0\":\n target = x_start\n elif self.parameterization == \"eps\":\n target = noise\n elif self.parameterization == \"v\":\n target = self.get_v(x_start, noise, t)\n else:\n raise NotImplementedError()\n\n loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])\n loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})\n\n logvar_t = self.logvar[t].to(self.device)\n loss = loss_simple / torch.exp(logvar_t) + logvar_t\n # loss = loss_simple / torch.exp(self.logvar) + self.logvar\n if self.learn_logvar:\n loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})\n loss_dict.update({'logvar': self.logvar.data.mean()})\n\n loss = self.l_simple_weight * loss.mean()\n\n loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))\n loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()\n loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})\n loss += (self.original_elbo_weight * loss_vlb)\n loss_dict.update({f'{prefix}/loss': loss})\n\n return loss, loss_dict\n\n def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,\n return_x0=False, score_corrector=None, corrector_kwargs=None):\n t_in = t\n model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)\n\n if score_corrector is not None:\n assert self.parameterization == \"eps\"\n model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)\n\n if return_codebook_ids:\n model_out, logits = model_out\n\n if self.parameterization == \"eps\":\n x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)\n elif self.parameterization == \"x0\":\n x_recon = model_out\n else:\n raise NotImplementedError()\n\n if clip_denoised:\n x_recon.clamp_(-1., 1.)\n if quantize_denoised:\n x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)\n model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)\n if return_codebook_ids:\n return model_mean, posterior_variance, posterior_log_variance, logits\n elif return_x0:\n return model_mean, posterior_variance, posterior_log_variance, x_recon\n else:\n return model_mean, posterior_variance, posterior_log_variance\n\n @torch.no_grad()\n def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,\n return_codebook_ids=False, quantize_denoised=False, return_x0=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):\n b, *_, device = *x.shape, x.device\n outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,\n return_codebook_ids=return_codebook_ids,\n quantize_denoised=quantize_denoised,\n return_x0=return_x0,\n score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)\n if return_codebook_ids:\n raise DeprecationWarning(\"Support dropped.\")\n model_mean, _, model_log_variance, logits = outputs\n elif return_x0:\n model_mean, _, model_log_variance, x0 = outputs\n else:\n model_mean, _, model_log_variance = outputs\n\n noise = noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n # no noise when t == 0\n nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))\n\n if return_codebook_ids:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)\n if return_x0:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0\n else:\n return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise\n\n @torch.no_grad()\n def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,\n img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,\n score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,\n log_every_t=None):\n if not log_every_t:\n log_every_t = self.log_every_t\n timesteps = self.num_timesteps\n if batch_size is not None:\n b = batch_size if batch_size is not None else shape[0]\n shape = [batch_size] + list(shape)\n else:\n b = batch_size = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=self.device)\n else:\n img = x_T\n intermediates = []\n if cond is not None:\n if isinstance(cond, dict):\n cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else\n list(map(lambda x: x[:batch_size], cond[key])) for key in cond}\n else:\n cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',\n total=timesteps) if verbose else reversed(\n range(0, timesteps))\n if type(temperature) == float:\n temperature = [temperature] * timesteps\n\n for i in iterator:\n ts = torch.full((b,), i, device=self.device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != 'hybrid'\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img, x0_partial = self.p_sample(img, cond, ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised, return_x0=True,\n temperature=temperature[i], noise_dropout=noise_dropout,\n score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)\n if mask is not None:\n assert x0 is not None\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1. - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(x0_partial)\n if callback: callback(i)\n if img_callback: img_callback(img, i)\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_loop(self, cond, shape, return_intermediates=False,\n x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, start_T=None,\n log_every_t=None):\n\n if not log_every_t:\n log_every_t = self.log_every_t\n device = self.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n intermediates = [img]\n if timesteps is None:\n timesteps = self.num_timesteps\n\n if start_T is not None:\n timesteps = min(timesteps, start_T)\n iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(\n range(0, timesteps))\n\n if mask is not None:\n assert x0 is not None\n assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match\n\n for i in iterator:\n ts = torch.full((b,), i, device=device, dtype=torch.long)\n if self.shorten_cond_schedule:\n assert self.model.conditioning_key != 'hybrid'\n tc = self.cond_ids[ts].to(cond.device)\n cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))\n\n img = self.p_sample(img, cond, ts,\n clip_denoised=self.clip_denoised,\n quantize_denoised=quantize_denoised)\n if mask is not None:\n img_orig = self.q_sample(x0, ts)\n img = img_orig * mask + (1. - mask) * img\n\n if i % log_every_t == 0 or i == timesteps - 1:\n intermediates.append(img)\n if callback: callback(i)\n if img_callback: img_callback(img, i)\n\n if return_intermediates:\n return img, intermediates\n return img\n\n @torch.no_grad()\n def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,\n verbose=True, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, shape=None, **kwargs):\n if shape is None:\n shape = (batch_size, self.channels, self.image_size, self.image_size)\n if cond is not None:\n if isinstance(cond, dict):\n cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else\n list(map(lambda x: x[:batch_size], cond[key])) for key in cond}\n else:\n cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]\n return self.p_sample_loop(cond,\n shape,\n return_intermediates=return_intermediates, x_T=x_T,\n verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,\n mask=mask, x0=x0)\n\n @torch.no_grad()\n def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):\n if ddim:\n ddim_sampler = DDIMSampler(self)\n shape = (self.channels, self.image_size, self.image_size)\n samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,\n shape, cond, verbose=False, **kwargs)\n\n else:\n samples, intermediates = self.sample(cond=cond, batch_size=batch_size,\n return_intermediates=True, **kwargs)\n\n return samples, intermediates\n\n @torch.no_grad()\n def get_unconditional_conditioning(self, batch_size, null_label=None):\n if null_label is not None:\n xc = null_label\n if isinstance(xc, ListConfig):\n xc = list(xc)\n if isinstance(xc, dict) or isinstance(xc, list):\n c = self.get_learned_conditioning(xc)\n else:\n if hasattr(xc, \"to\"):\n xc = xc.to(self.device)\n c = self.get_learned_conditioning(xc)\n else:\n if self.cond_stage_key in [\"class_label\", \"cls\"]:\n xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)\n return self.get_learned_conditioning(xc)\n else:\n raise NotImplementedError(\"todo\")\n if isinstance(c, list): # in case the encoder gives us a list\n for i in range(len(c)):\n c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)\n else:\n c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)\n return c\n\n @torch.no_grad()\n def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,\n quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,\n plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,\n use_ema_scope=True,\n **kwargs):\n ema_scope = self.ema_scope if use_ema_scope else nullcontext\n use_ddim = ddim_steps is not None\n\n log = dict()\n z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,\n return_first_stage_outputs=True,\n force_c_encode=True,\n return_original_cond=True,\n bs=N)\n N = min(x.shape[0], N)\n n_row = min(x.shape[0], n_row)\n log[\"inputs\"] = x\n log[\"reconstruction\"] = xrec\n if self.model.conditioning_key is not None:\n if hasattr(self.cond_stage_model, \"decode\"):\n xc = self.cond_stage_model.decode(c)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in [\"caption\", \"txt\"]:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in ['class_label', \"cls\"]:\n try:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[\"human_label\"], size=x.shape[2] // 25)\n log['conditioning'] = xc\n except KeyError:\n # probably no \"human_label\" in batch\n pass\n elif isimage(xc):\n log[\"conditioning\"] = xc\n if ismap(xc):\n log[\"original_conditioning\"] = self.to_rgb(xc)\n\n if plot_diffusion_rows:\n # get diffusion row\n diffusion_row = list()\n z_start = z[:n_row]\n for t in range(self.num_timesteps):\n if t % self.log_every_t == 0 or t == self.num_timesteps - 1:\n t = repeat(torch.tensor([t]), '1 -> b', b=n_row)\n t = t.to(self.device).long()\n noise = torch.randn_like(z_start)\n z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)\n diffusion_row.append(self.decode_first_stage(z_noisy))\n\n diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W\n diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')\n diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')\n diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])\n log[\"diffusion_row\"] = diffusion_grid\n\n if sample:\n # get denoise row\n with ema_scope(\"Sampling\"):\n samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta)\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)\n x_samples = self.decode_first_stage(samples)\n log[\"samples\"] = x_samples\n if plot_denoise_rows:\n denoise_grid = self._get_denoise_row_from_list(z_denoise_row)\n log[\"denoise_row\"] = denoise_grid\n\n if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(\n self.first_stage_model, IdentityFirstStage):\n # also display when quantizing x0 while sampling\n with ema_scope(\"Plotting Quantized Denoised\"):\n samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta,\n quantize_denoised=True)\n # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,\n # quantize_denoised=True)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_x0_quantized\"] = x_samples\n\n if unconditional_guidance_scale > 1.0:\n uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)\n if self.model.conditioning_key == \"crossattn-adm\":\n uc = {\"c_crossattn\": [uc], \"c_adm\": c[\"c_adm\"]}\n with ema_scope(\"Sampling with classifier-free guidance\"):\n samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,\n ddim_steps=ddim_steps, eta=ddim_eta,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=uc,\n )\n x_samples_cfg = self.decode_first_stage(samples_cfg)\n log[f\"samples_cfg_scale_{unconditional_guidance_scale:.2f}\"] = x_samples_cfg\n\n if inpaint:\n # make a simple center square\n b, h, w = z.shape[0], z.shape[2], z.shape[3]\n mask = torch.ones(N, h, w).to(self.device)\n # zeros will be filled in\n mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.\n mask = mask[:, None, ...]\n with ema_scope(\"Plotting Inpaint\"):\n samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,\n ddim_steps=ddim_steps, x0=z[:N], mask=mask)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_inpainting\"] = x_samples\n log[\"mask\"] = mask\n\n # outpaint\n mask = 1. - mask\n with ema_scope(\"Plotting Outpaint\"):\n samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,\n ddim_steps=ddim_steps, x0=z[:N], mask=mask)\n x_samples = self.decode_first_stage(samples.to(self.device))\n log[\"samples_outpainting\"] = x_samples\n\n if plot_progressive_rows:\n with ema_scope(\"Plotting Progressives\"):\n img, progressives = self.progressive_denoising(c,\n shape=(self.channels, self.image_size, self.image_size),\n batch_size=N)\n prog_row = self._get_denoise_row_from_list(progressives, desc=\"Progressive Generation\")\n log[\"progressive_row\"] = prog_row\n\n if return_keys:\n if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:\n return log\n else:\n return {key: log[key] for key in return_keys}\n return log\n\n def configure_optimizers(self):\n lr = self.learning_rate\n params = list(self.model.parameters())\n if self.cond_stage_trainable:\n print(f\"{self.__class__.__name__}: Also optimizing conditioner params!\")\n params = params + list(self.cond_stage_model.parameters())\n if self.learn_logvar:\n print('Diffusion model optimizing logvar')\n params.append(self.logvar)\n opt = torch.optim.AdamW(params, lr=lr)\n if self.use_scheduler:\n assert 'target' in self.scheduler_config\n scheduler = instantiate_from_config(self.scheduler_config)\n\n print(\"Setting up LambdaLR scheduler...\")\n scheduler = [\n {\n 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),\n 'interval': 'step',\n 'frequency': 1\n }]\n return [opt], scheduler\n return opt\n\n @torch.no_grad()\n def to_rgb(self, x):\n x = x.float()\n if not hasattr(self, \"colorize\"):\n self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)\n x = nn.functional.conv2d(x, weight=self.colorize)\n x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.\n return x" }, { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n draw = ImageDraw.Draw(txt)\n font = ImageFont.truetype('font/DejaVuSans.ttf', size=size)\n nc = int(40 * (wh[0] / 256))\n lines = \"\\n\".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))\n\n try:\n draw.text((0, 0), lines, fill=\"black\", font=font)\n except UnicodeEncodeError:\n print(\"Cant encode string for logging. Skipping.\")\n\n txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0\n txts.append(txt)\n txts = np.stack(txts)\n txts = torch.tensor(txts)\n return txts" }, { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))" }, { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n def __init__(self, model, schedule=\"linear\", **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n dynamic_threshold=None,\n ucg_schedule=None,\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n ctmp = conditioning[list(conditioning.keys())[0]]\n while isinstance(ctmp, list): ctmp = ctmp[0]\n cbs = ctmp.shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n\n elif isinstance(conditioning, list):\n for ctmp in conditioning:\n if ctmp.shape[0] != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n # print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n dynamic_threshold=dynamic_threshold,\n ucg_schedule=ucg_schedule\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,\n ucg_schedule=None):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n # print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n # iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(time_range):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n if ucg_schedule is not None:\n assert len(ucg_schedule) == len(time_range)\n unconditional_guidance_scale = ucg_schedule[i]\n\n outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n dynamic_threshold=dynamic_threshold)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,\n dynamic_threshold=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n model_output = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n if isinstance(c, dict):\n assert isinstance(unconditional_conditioning, dict)\n c_in = dict()\n for k in c:\n if isinstance(c[k], list):\n c_in[k] = [torch.cat([\n unconditional_conditioning[k][i],\n c[k][i]]) for i in range(len(c[k]))]\n else:\n c_in[k] = torch.cat([\n unconditional_conditioning[k],\n c[k]])\n elif isinstance(c, list):\n c_in = list()\n assert isinstance(unconditional_conditioning, list)\n for i in range(len(c)):\n c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))\n else:\n c_in = torch.cat([unconditional_conditioning, c])\n model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)\n\n if self.model.parameterization == \"v\":\n e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)\n else:\n e_t = model_output\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\", 'not implemented'\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n if self.model.parameterization != \"v\":\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n else:\n pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)\n\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n\n if dynamic_threshold is not None:\n raise NotImplementedError()\n\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,\n unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):\n num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]\n\n assert t_enc <= num_reference_steps\n num_steps = t_enc\n\n if use_original_steps:\n alphas_next = self.alphas_cumprod[:num_steps]\n alphas = self.alphas_cumprod_prev[:num_steps]\n else:\n alphas_next = self.ddim_alphas[:num_steps]\n alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])\n\n x_next = x0\n intermediates = []\n inter_steps = []\n for i in tqdm(range(num_steps), desc='Encoding Image'):\n t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)\n if unconditional_guidance_scale == 1.:\n noise_pred = self.model.apply_model(x_next, t, c)\n else:\n assert unconditional_conditioning is not None\n e_t_uncond, noise_pred = torch.chunk(\n self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),\n torch.cat((unconditional_conditioning, c))), 2)\n noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)\n\n xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next\n weighted_noise_pred = alphas_next[i].sqrt() * (\n (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred\n x_next = xt_weighted + weighted_noise_pred\n if return_intermediates and i % (\n num_steps // return_intermediates) == 0 and i < num_steps - 1:\n intermediates.append(x_next)\n inter_steps.append(i)\n elif return_intermediates and i >= num_steps - 2:\n intermediates.append(x_next)\n inter_steps.append(i)\n if callback: callback(i)\n\n out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}\n if return_intermediates:\n out.update({'intermediates': intermediates})\n return x_next, out\n\n @torch.no_grad()\n def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):\n # fast, but does not allow for exact reconstruction\n # t serves as an index to gather the correct alphas\n if use_original_steps:\n sqrt_alphas_cumprod = self.sqrt_alphas_cumprod\n sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod\n else:\n sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)\n sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas\n\n if noise is None:\n noise = torch.randn_like(x0)\n return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +\n extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)\n\n @torch.no_grad()\n def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False, callback=None):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n if callback: callback(i)\n return x_dec" }, { "identifier": "instantiate_from_config", "path": "data/dataset_instantiate.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(config.get(\"params\", dict()))" }, { "identifier": "calculate_psnr_ssim", "path": "metrics/metrics_all.py", "snippet": "def calculate_psnr_ssim(gt_path, restored_path, test_y_channel = False, crop_border = 0, suffix = '', correct_mean_var = False, show_details =False):\n \"\"\"\n Calculate PSNR and SSIM for images.\n gt_path: Path to gt (Ground-Truth)\n restored_path: Path to restored images\n test_y_channel: If True, test Y channel (In MatLab YCbCr format). If False, test RGB channels.\n crop_border: Crop border for each side\n suffix: Suffix for restored images\n \"\"\"\n print(\"Calculate PSNR and SSIM for images\")\n psnr_all = []\n ssim_all = []\n img_list_gt = sorted(list(scandir(gt_path, recursive=True, full_path=True)))\n img_list_restored = sorted(list(scandir(restored_path, recursive=True, full_path=True)))\n\n if test_y_channel:\n print('Testing Y channel.')\n else:\n print('Testing RGB channels.')\n\n for i, img_path in tqdm(enumerate(img_list_gt)):\n basename, ext = osp.splitext(osp.basename(img_path))\n img_gt = cv2.imread(img_path, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255.\n if suffix == '':\n img_path_restored = img_list_restored[i]\n else:\n img_path_restored = osp.join(restored_path, basename + suffix + ext)\n img_restored = cv2.imread(img_path_restored, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255.\n # img_restored = cv2.imread(img_path_restored, cv2.IMREAD_COLOR).astype(np.float32) / 255.\n img_restored\n if correct_mean_var:\n mean_l = []\n std_l = []\n for j in range(3):\n mean_l.append(np.mean(img_gt[:, :, j]))\n std_l.append(np.std(img_gt[:, :, j]))\n for j in range(3):\n # correct twice\n mean = np.mean(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] - mean + mean_l[j]\n std = np.std(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] / std * std_l[j]\n\n mean = np.mean(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] - mean + mean_l[j]\n std = np.std(img_restored[:, :, j])\n img_restored[:, :, j] = img_restored[:, :, j] / std * std_l[j]\n\n if test_y_channel and img_gt.ndim == 3 and img_gt.shape[2] == 3:\n img_gt = bgr2ycbcr(img_gt, y_only=True)\n img_restored = bgr2ycbcr(img_restored, y_only=True)\n\n # calculate PSNR and SSIM\n psnr = calculate_psnr(img_gt * 255, img_restored * 255, crop_border=crop_border, input_order='HWC')\n ssim = calculate_ssim(img_gt * 255, img_restored * 255, crop_border=crop_border, input_order='HWC')\n if show_details:\n print(f'{basename + suffix + ext:25}. \\tPSNR: {psnr:.6f} dB, \\tSSIM: {ssim:.6f}')\n psnr_all.append(psnr)\n ssim_all.append(ssim)\n Average_psnr = sum(psnr_all) / len(psnr_all)\n Average_ssim = sum(ssim_all) / len(ssim_all)\n print(f'PSNR: {Average_psnr:.6f} dB, SSIM: {Average_ssim:.6f}')\n return Average_psnr, Average_ssim" }, { "identifier": "calculate_lpips", "path": "metrics/metrics_all.py", "snippet": "def calculate_lpips(gt_path, restored_path, suffix = '', show_details =False):\n \"\"\"\n Calculate LPIPS for images.\n gt_path: Path to gt (Ground-Truth)\n restored_path: Path to restored images\n suffix: Suffix for restored images\n \"\"\"\n print(\"Calculate LPIPS for images\")\n loss_fn_vgg = lpips.LPIPS(net='vgg').cuda() # RGB, normalized to [-1,1]\n lpips_all = []\n img_list = sorted(glob.glob(osp.join(gt_path, '*')))\n img_list_restored = sorted(list(scandir(restored_path, recursive=True, full_path=True)))\n\n mean = [0.5, 0.5, 0.5]\n std = [0.5, 0.5, 0.5]\n for i, img_path in tqdm(enumerate(img_list)):\n basename, ext = osp.splitext(osp.basename(img_path))\n img_gt = cv2.imread(img_path, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255.\n\n if suffix == '':\n img_path_restored = img_list_restored[i]\n else:\n img_path_restored = osp.join(restored_path, basename + suffix + ext)\n img_restored = cv2.imread(img_path_restored, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255. \n # img_restored = cv2.imread(img_path_restored, cv2.IMREAD_COLOR).astype(np.float32) / 255. \n\n img_gt, img_restored = img2tensor([img_gt, img_restored], bgr2rgb=True, float32=True)\n # norm to [-1, 1]\n normalize(img_gt, mean, std, inplace=True)\n normalize(img_restored, mean, std, inplace=True)\n\n # calculate lpips\n lpips_val = loss_fn_vgg(img_restored.unsqueeze(0).cuda(), img_gt.unsqueeze(0).cuda())\n lpips_val = lpips_val.cpu().item()\n if show_details:\n print(f'{i+1:3d}: {basename:25}. \\tLPIPS: {lpips_val:.6f}.')\n lpips_all.append(lpips_val)\n Average_lpips = sum(lpips_all) / len(lpips_all)\n print(f'LPIPS: {Average_lpips:.6f}')\n return Average_lpips" }, { "identifier": "calculate_NIQE", "path": "metrics/metrics_all.py", "snippet": "def calculate_NIQE(restored_path, crop_border = 0, show_details =False):\n \"\"\"\n Calculate NIQE for images.\n restored_path: Path to restored images\n crop_border: Crop border for each side\n \"\"\"\n print(\"Calculate NIQE for images\")\n niqe_all = []\n img_list = sorted(scandir(restored_path, recursive=True, full_path=True))\n\n for i, img_path in tqdm(enumerate(img_list)):\n basename, _ = os.path.splitext(os.path.basename(img_path))\n img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', category=RuntimeWarning)\n niqe_score = calculate_niqe(img, crop_border, input_order='HWC', convert_to='y')\n if show_details:\n print(f'{i+1:3d}: {basename:25}. \\tNIQE: {niqe_score:.6f}')\n niqe_all.append(niqe_score)\n Average_niqe = sum(niqe_all) / len(niqe_all)\n print(f'NIQE: {Average_niqe:.6f}')\n return Average_niqe " }, { "identifier": "calculate_fid_folder", "path": "metrics/metrics_all.py", "snippet": "def calculate_fid_folder(restored_path):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n fid_stats = ''\n batch_size = 64\n num_sample = 50000\n num_workers = 4\n backend = 'disk'\n\n # inception model\n inception = load_patched_inception_v3(device)\n\n # create dataset\n opt = {}\n opt['name'] = 'SingleImageDataset'\n opt['type'] = 'SingleImageDataset'\n opt['dataroot_lq'] = restored_path\n opt['io_backend'] = dict(type=backend)\n opt['mean'] = [0.5, 0.5, 0.5]\n opt['std'] = [0.5, 0.5, 0.5]\n dataset = build_dataset(opt)\n\n # create dataloader\n data_loader = DataLoader(\n dataset=dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_workers,\n sampler=None,\n drop_last=False)\n num_sample = min(num_sample, len(dataset))\n total_batch = math.ceil(num_sample / batch_size)\n\n def data_generator(data_loader, total_batch):\n for idx, data in enumerate(data_loader):\n if idx >= total_batch:\n break\n else:\n yield data['lq']\n\n features = extract_inception_features(data_generator(data_loader, total_batch), inception, total_batch, device)\n features = features.numpy()\n total_len = features.shape[0]\n features = features[:num_sample]\n print(f'Extracted {total_len} features, use the first {features.shape[0]} features to calculate stats.')\n\n sample_mean = np.mean(features, 0)\n sample_cov = np.cov(features, rowvar=False)\n\n # load the dataset stats\n stats = torch.load(fid_stats)\n real_mean = stats['mean']\n real_cov = stats['cov']\n\n # calculate FID metric\n fid = calculate_fid(sample_mean, sample_cov, real_mean, real_cov)\n print('fid:', fid)\n return fid" } ]
import torch import os import numpy as np import math import shutil import safetensors.torch from ldm.modules.diffusionmodules.util import timestep_embedding from einops import rearrange, repeat from torchvision.utils import make_grid from ldm.modules.diffusionmodules.openaimodel import UNetModel from ldm.models.diffusion.ddpm import LatentDiffusion from ldm.util import log_txt_as_img, instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from data.dataset_instantiate import instantiate_from_config as instantiate_dataset_from_config from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from metrics.metrics_all import calculate_psnr_ssim, calculate_lpips, calculate_NIQE, calculate_fid_folder from torch.utils.data import DataLoader from PIL import Image from torch.optim.lr_scheduler import LambdaLR from omegaconf import OmegaConf
21,337
def get_state_dict(d): return d.get('state_dict', d) def load_state_dict(ckpt_path, location='cpu'): _, extension = os.path.splitext(ckpt_path) if extension.lower() == ".safetensors": state_dict = safetensors.torch.load_file(ckpt_path, device=location) else: state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location))) state_dict = get_state_dict(state_dict) print(f'Loaded state_dict from [{ckpt_path}]') return state_dict def create_model(config_path): config = OmegaConf.load(config_path) model = instantiate_from_config(config.model).cpu() print(f'Loaded model config from [{config_path}]') return model class ControlledUnetModel(UNetModel): def forward(self, x, timesteps=None, context=None, control=None, **kwargs): hs = [] t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) emb = self.time_embed(t_emb) h = x.type(self.dtype) for i, module in enumerate(self.input_blocks): h = module(h, emb, context) if ((i+1)%3 == 0) and control is not None: h = h + control.pop(0) hs.append(h) h = self.middle_block(h, emb, context) if control is not None: h += control.pop(0) for i, module in enumerate(self.output_blocks): if control is None: h = torch.cat([h, hs.pop()], dim=1) else: h = torch.cat([h, hs.pop()], dim=1) h = module(h, emb, context) if ((i+2)%3 == 0) and control is not None: h = h + control.pop(0) h = h.type(x.dtype) return self.out(h) class BFRffusion(LatentDiffusion): def __init__(self, control_stage_config, control_key,sd_locked_steps,CosineAnnealing_steps, *args, **kwargs): super().__init__(*args, **kwargs) self.control_model = instantiate_from_config(control_stage_config) self.control_key = control_key self.sd_locked_steps = sd_locked_steps self.CosineAnnealing_steps = CosineAnnealing_steps self.top5_psnr_dict = {} @torch.no_grad() def get_input(self, batch, k, bs=None, *args, **kwargs): x = batch[self.first_stage_key] # x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) x = self.get_first_stage_encoding(encoder_posterior).detach() c = None control = batch[self.control_key] if bs is not None: control = control[:bs] control = control.to(self.device) # control = einops.rearrange(control, 'b h w c -> b c h w') control = control.to(memory_format=torch.contiguous_format).float() return x, dict(c_crossattn=[c], c_concat=[control]) def apply_model(self, x_noisy, t, cond, *args, **kwargs): assert isinstance(cond, dict) diffusion_model = self.model.diffusion_model cond_txt = self.cond_stage_model(t) # cond_txt = torch.cat(cond['c_crossattn'], 1) if cond['c_concat'] is None: eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None) else: control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt) eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control) return eps @torch.no_grad() def get_unconditional_conditioning(self, N): return self.get_learned_conditioning([""] * N) @torch.no_grad() def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None, use_ema_scope=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, c = self.get_input(batch, self.first_stage_key, bs=N) c_cat = c["c_concat"][0][:N] c = None N = min(z.shape[0], N) n_row = min(z.shape[0], n_row) log["reconstruction"] = self.decode_first_stage(z) log["control"] = c_cat * 2.0 - 1.0
def get_state_dict(d): return d.get('state_dict', d) def load_state_dict(ckpt_path, location='cpu'): _, extension = os.path.splitext(ckpt_path) if extension.lower() == ".safetensors": state_dict = safetensors.torch.load_file(ckpt_path, device=location) else: state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location))) state_dict = get_state_dict(state_dict) print(f'Loaded state_dict from [{ckpt_path}]') return state_dict def create_model(config_path): config = OmegaConf.load(config_path) model = instantiate_from_config(config.model).cpu() print(f'Loaded model config from [{config_path}]') return model class ControlledUnetModel(UNetModel): def forward(self, x, timesteps=None, context=None, control=None, **kwargs): hs = [] t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) emb = self.time_embed(t_emb) h = x.type(self.dtype) for i, module in enumerate(self.input_blocks): h = module(h, emb, context) if ((i+1)%3 == 0) and control is not None: h = h + control.pop(0) hs.append(h) h = self.middle_block(h, emb, context) if control is not None: h += control.pop(0) for i, module in enumerate(self.output_blocks): if control is None: h = torch.cat([h, hs.pop()], dim=1) else: h = torch.cat([h, hs.pop()], dim=1) h = module(h, emb, context) if ((i+2)%3 == 0) and control is not None: h = h + control.pop(0) h = h.type(x.dtype) return self.out(h) class BFRffusion(LatentDiffusion): def __init__(self, control_stage_config, control_key,sd_locked_steps,CosineAnnealing_steps, *args, **kwargs): super().__init__(*args, **kwargs) self.control_model = instantiate_from_config(control_stage_config) self.control_key = control_key self.sd_locked_steps = sd_locked_steps self.CosineAnnealing_steps = CosineAnnealing_steps self.top5_psnr_dict = {} @torch.no_grad() def get_input(self, batch, k, bs=None, *args, **kwargs): x = batch[self.first_stage_key] # x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) x = self.get_first_stage_encoding(encoder_posterior).detach() c = None control = batch[self.control_key] if bs is not None: control = control[:bs] control = control.to(self.device) # control = einops.rearrange(control, 'b h w c -> b c h w') control = control.to(memory_format=torch.contiguous_format).float() return x, dict(c_crossattn=[c], c_concat=[control]) def apply_model(self, x_noisy, t, cond, *args, **kwargs): assert isinstance(cond, dict) diffusion_model = self.model.diffusion_model cond_txt = self.cond_stage_model(t) # cond_txt = torch.cat(cond['c_crossattn'], 1) if cond['c_concat'] is None: eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None) else: control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt) eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control) return eps @torch.no_grad() def get_unconditional_conditioning(self, N): return self.get_learned_conditioning([""] * N) @torch.no_grad() def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None, use_ema_scope=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, c = self.get_input(batch, self.first_stage_key, bs=N) c_cat = c["c_concat"][0][:N] c = None N = min(z.shape[0], N) n_row = min(z.shape[0], n_row) log["reconstruction"] = self.decode_first_stage(z) log["control"] = c_cat * 2.0 - 1.0
log["conditioning"] = log_txt_as_img((512, 512), batch[self.cond_stage_key], size=16)
3
2023-11-30 13:50:58+00:00
24k
IanYeung/MGLD-VSR
scripts/vsr_val_ddpm_text_T_vqganfin_oldcanvas_tile.py
[ { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))" }, { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n def __init__(self, model, schedule=\"linear\", **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,verbose=verbose)\n\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def q_sample(self, x_start, t, noise=None, ddim_num_steps=200):\n self.make_schedule(ddim_num_steps=ddim_num_steps)\n noise = default(noise, lambda: torch.randn_like(x_start))\n return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +\n extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):\n # fast, but does not allow for exact reconstruction\n # t serves as an index to gather the correct alphas\n if use_original_steps:\n sqrt_alphas_cumprod = self.sqrt_alphas_cumprod\n sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod\n else:\n sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)\n sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas\n\n if noise is None:\n noise = torch.randn_like(x0)\n return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +\n extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)\n\n @torch.no_grad()\n def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n return x_dec\n\n\n @torch.no_grad()\n def p_sample_ddim_sr(self, x, c, struct_c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c, struct_c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in, struct_c).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n @torch.no_grad()\n def decode_sr(self, x_latent, cond, struct_cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,\n use_original_steps=False):\n\n timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps\n timesteps = timesteps[:t_start]\n\n time_range = np.flip(timesteps)\n total_steps = timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='Decoding image', total=total_steps)\n x_dec = x_latent\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)\n x_dec, _ = self.p_sample_ddim_sr(x_dec, cond, struct_cond, ts, index=index, use_original_steps=use_original_steps,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n return x_dec\n\n @torch.no_grad()\n def sample_sr(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n struct_cond=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n _, C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling_sr(conditioning, struct_cond, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling_sr(self, cond, struct_cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim_sr(img, cond, struct_cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim_sr(self, x, c, struct_c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c, struct_c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in, struct_c).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n\n @torch.no_grad()\n def sample_sr_t(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n struct_cond=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n _, C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling_sr_t(conditioning, struct_cond, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling_sr_t(self, cond, struct_cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n # timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else sorted(set(space_timesteps(1000, [self.ddim_timesteps.shape[0]])))\n timesteps = np.array(timesteps)\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim_sr_t(img, cond, struct_cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim_sr_t(self, x, c, struct_c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n struct_c_t = self.model.structcond_stage_model(struct_c, t)\n e_t = self.model.apply_model(x, t, c, struct_c_t)\n else:\n assert NotImplementedError\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in, struct_c).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0" }, { "identifier": "PLMSSampler", "path": "ldm/models/diffusion/plms.py", "snippet": "class PLMSSampler(object):\n def __init__(self, model, schedule=\"linear\", **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n if ddim_eta != 0:\n raise ValueError('ddim_eta must be 0 for PLMS')\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n if conditioning is not None:\n if isinstance(conditioning, dict):\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for PLMS sampling is {size}')\n\n samples, intermediates = self.plms_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def plms_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running PLMS Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps)\n old_eps = []\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n old_eps=old_eps, t_next=ts_next)\n img, pred_x0, e_t = outs\n old_eps.append(e_t)\n if len(old_eps) >= 4:\n old_eps.pop(0)\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None):\n b, *_, device = *x.shape, x.device\n\n def get_model_output(x, t):\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n return e_t\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n\n def get_x_prev_and_pred_x0(e_t, index):\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0\n\n e_t = get_model_output(x, t)\n if len(old_eps) == 0:\n # Pseudo Improved Euler (2nd order)\n x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index)\n e_t_next = get_model_output(x_prev, t_next)\n e_t_prime = (e_t + e_t_next) / 2\n elif len(old_eps) == 1:\n # 2nd order Pseudo Linear Multistep (Adams-Bashforth)\n e_t_prime = (3 * e_t - old_eps[-1]) / 2\n elif len(old_eps) == 2:\n # 3nd order Pseudo Linear Multistep (Adams-Bashforth)\n e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12\n elif len(old_eps) >= 3:\n # 4nd order Pseudo Linear Multistep (Adams-Bashforth)\n e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24\n\n x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index)\n\n return x_prev, pred_x0, e_t" }, { "identifier": "resize_flow", "path": "basicsr/archs/arch_util.py", "snippet": "def resize_flow(flow, size_type, sizes, interp_mode='bilinear', align_corners=False):\n \"\"\"Resize a flow according to ratio or shape.\n\n Args:\n flow (Tensor): Precomputed flow. shape [N, 2, H, W].\n size_type (str): 'ratio' or 'shape'.\n sizes (list[int | float]): the ratio for resizing or the final output\n shape.\n 1) The order of ratio should be [ratio_h, ratio_w]. For\n downsampling, the ratio should be smaller than 1.0 (i.e., ratio\n < 1.0). For upsampling, the ratio should be larger than 1.0 (i.e.,\n ratio > 1.0).\n 2) The order of output_size should be [out_h, out_w].\n interp_mode (str): The mode of interpolation for resizing.\n Default: 'bilinear'.\n align_corners (bool): Whether align corners. Default: False.\n\n Returns:\n Tensor: Resized flow.\n \"\"\"\n _, _, flow_h, flow_w = flow.size()\n if size_type == 'ratio':\n output_h, output_w = int(flow_h * sizes[0]), int(flow_w * sizes[1])\n elif size_type == 'shape':\n output_h, output_w = sizes[0], sizes[1]\n else:\n raise ValueError(f'Size type should be ratio or shape, but got type {size_type}.')\n\n input_flow = flow.clone()\n ratio_h = output_h / flow_h\n ratio_w = output_w / flow_w\n input_flow[:, 0, :, :] *= ratio_w\n input_flow[:, 1, :, :] *= ratio_h\n resized_flow = F.interpolate(\n input=input_flow, size=(output_h, output_w), mode=interp_mode, align_corners=align_corners)\n return resized_flow" }, { "identifier": "forward_backward_consistency_check", "path": "scripts/util_flow.py", "snippet": "def forward_backward_consistency_check(fwd_flow,\n bwd_flow,\n alpha=0.01,\n beta=0.5):\n # fwd_flow, bwd_flow: [B, 2, H, W]\n # alpha and beta values are following UnFlow\n # (https://arxiv.org/abs/1711.07837)\n assert fwd_flow.dim() == 4 and bwd_flow.dim() == 4\n assert fwd_flow.size(1) == 2 and bwd_flow.size(1) == 2\n flow_mag = torch.norm(fwd_flow, dim=1) + torch.norm(bwd_flow, dim=1) # [B, H, W]\n\n warped_bwd_flow = flow_warp(bwd_flow, fwd_flow) # [B, 2, H, W]\n warped_fwd_flow = flow_warp(fwd_flow, bwd_flow) # [B, 2, H, W]\n\n diff_fwd = torch.norm(fwd_flow + warped_bwd_flow, dim=1) # [B, H, W]\n diff_bwd = torch.norm(bwd_flow + warped_fwd_flow, dim=1)\n\n threshold = alpha * flow_mag + beta\n\n fwd_occ = (diff_fwd > threshold).float() # [B, H, W]\n bwd_occ = (diff_bwd > threshold).float()\n\n return fwd_occ, bwd_occ" }, { "identifier": "wavelet_reconstruction", "path": "scripts/wavelet_color_fix.py", "snippet": "def wavelet_reconstruction(content_feat:Tensor, style_feat:Tensor):\n \"\"\"\n Apply wavelet decomposition, so that the content will have the same color as the style.\n \"\"\"\n # calculate the wavelet decomposition of the content feature\n content_high_freq, content_low_freq = wavelet_decomposition(content_feat)\n del content_low_freq\n # calculate the wavelet decomposition of the style feature\n style_high_freq, style_low_freq = wavelet_decomposition(style_feat)\n del style_high_freq\n # reconstruct the content feature with the style's high frequency\n return content_high_freq + style_low_freq" }, { "identifier": "adaptive_instance_normalization", "path": "scripts/wavelet_color_fix.py", "snippet": "def adaptive_instance_normalization(content_feat:Tensor, style_feat:Tensor):\n \"\"\"Adaptive instance normalization.\n Adjust the reference features to have the similar color and illuminations\n as those in the degradate features.\n Args:\n content_feat (Tensor): The reference feature.\n style_feat (Tensor): The degradate features.\n \"\"\"\n size = content_feat.size()\n style_mean, style_std = calc_mean_std(style_feat)\n content_mean, content_std = calc_mean_std(content_feat)\n normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand(size)\n return normalized_feat * style_std.expand(size) + style_mean.expand(size)" } ]
import argparse, os, sys, glob import PIL import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import torchvision import time import math import copy import torch.nn.functional as F import cv2 from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange, repeat from torchvision.utils import make_grid from torch import autocast from contextlib import nullcontext from pytorch_lightning import seed_everything from ldm.util import instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from ldm.models.diffusion.plms import PLMSSampler from util_image import ImageSpliterTh from pathlib import Path from basicsr.archs.arch_util import resize_flow from scripts.util_flow import forward_backward_consistency_check from scripts.wavelet_color_fix import wavelet_reconstruction, adaptive_instance_normalization
15,477
upsample_scale = max(512 / size_min, opt.upscale) cur_image = F.interpolate( cur_image, size=(int(cur_image.size(-2) * upsample_scale), int(cur_image.size(-1) * upsample_scale)), mode='bicubic', ) temp_frame_buffer.append(cur_image) if idx % n_frames == n_frames - 1: # [1, c, h, w] -> [b, c, h, w] temp_frame = torch.cat(copy.deepcopy(temp_frame_buffer), dim=0) print('Segment shape: ', temp_frame.shape) init_segment_list.append(temp_frame) temp_frame_buffer.clear() # print(f"Found {len(img_name_list)} inputs.") precision_scope = autocast if opt.precision == "autocast" else nullcontext niqe_list = [] with torch.no_grad(): with precision_scope("cuda"): with model.ema_scope(): tic = time.time() all_samples = list() for n in trange(len(init_segment_list), desc="Sampling"): init_image = init_segment_list[n] im_lq_bs = init_image.clamp(-1.0, 1.0).to(device) print('>>>>>>>>>>>>>>>>>>>>>>>') print('seq: ', seq_item, 'seg: ', n, 'size: ', im_lq_bs.size()) ori_h, ori_w = im_lq_bs.shape[2:] ref_patch=None if not (ori_h % 32 == 0 and ori_w % 32 == 0): flag_pad = True pad_h = ((ori_h // 32) + 1) * 32 - ori_h pad_w = ((ori_w // 32) + 1) * 32 - ori_w im_lq_bs = F.pad(im_lq_bs, pad=(0, pad_w, 0, pad_h), mode='reflect') else: flag_pad = False im_lq_bs_0_1 = torch.clamp((im_lq_bs + 1.0) / 2.0, min=0.0, max=1.0) _, _, im_h, im_w = im_lq_bs_0_1.shape # flow estimation im_lq_bs_0_1 = F.interpolate(im_lq_bs_0_1, size=(im_h//4, im_w//4), mode='bicubic') im_lq_bs_0_1 = rearrange(im_lq_bs_0_1, '(b t) c h w -> b t c h w', t=init_image.size(0)) flows = model.compute_flow(im_lq_bs_0_1) # flows: [flows_bwd(forward_prop), flows_fwd(backward_prop)] flows = [rearrange(flow, 'b t c h w -> (b t) c h w') for flow in flows] flows = [resize_flow(flow, size_type='shape', sizes=(im_h//8, im_w//8)) for flow in flows] flows = [rearrange(flow, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) for flow in flows] # occlusion mask estimation fwd_occ_list, bwd_occ_list = list(), list() for i in range(init_image.size(0)-1): fwd_flow, bwd_flow = flows[1][:, i, :, :, :], flows[0][:, i, :, :, :] fwd_occ, bwd_occ = forward_backward_consistency_check(fwd_flow, bwd_flow, alpha=0.01, beta=0.5) fwd_occ_list.append(fwd_occ.unsqueeze_(1)) bwd_occ_list.append(bwd_occ.unsqueeze_(1)) fwd_occs = torch.stack(fwd_occ_list, dim=1) fwd_occs = rearrange(fwd_occs, 'b t c h w -> (b t) c h w') bwd_occs = torch.stack(bwd_occ_list, dim=1) bwd_occs = rearrange(bwd_occs, 'b t c h w -> (b t) c h w') # masks = [fwd_occ_list, bwd_occ_list] flows = [rearrange(flow, 'b t c h w -> (b t) c h w') for flow in flows] if im_lq_bs.shape[2] > opt.vqgantile_size or im_lq_bs.shape[3] > opt.vqgantile_size: imlq_spliter = ImageSpliterTh(im_lq_bs, opt.vqgantile_size, opt.vqgantile_stride, sf=1) flow_spliter_f = ImageSpliterTh(flows[0], opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) flow_spliter_b = ImageSpliterTh(flows[1], opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) fwd_occ_spliter = ImageSpliterTh(fwd_occs, opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) bwd_occ_spliter = ImageSpliterTh(bwd_occs, opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) for (im_lq_pch, index_infos), (flow_f, _), (flow_b, _), (fwd_occ, _), (bwd_occ, _) \ in zip(imlq_spliter, flow_spliter_f, flow_spliter_b, fwd_occ_spliter, bwd_occ_spliter): seed_everything(opt.seed) init_latent = model.get_first_stage_encoding(model.encode_first_stage(im_lq_pch)) text_init = ['']*opt.n_samples semantic_c = model.cond_stage_model(text_init) noise = torch.randn_like(init_latent) # If you would like to start from the intermediate steps, # you can add noise to LR to the specific steps. t = repeat(torch.tensor([999]), '1 -> b', b=im_lq_bs.size(0)) t = t.to(device).long() x_T = model.q_sample_respace(x_start=init_latent, t=t, sqrt_alphas_cumprod=sqrt_alphas_cumprod, sqrt_one_minus_alphas_cumprod=sqrt_one_minus_alphas_cumprod, noise=noise) # x_T = noise # im_lq_pch_0_1 = torch.clamp((im_lq_pch + 1.0) / 2.0, min=0.0, max=1.0) flow_f = rearrange(flow_f, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) flow_b = rearrange(flow_b, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) fwd_occ = rearrange(fwd_occ, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) bwd_occ = rearrange(bwd_occ, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) flows = (flow_f, flow_b) masks = (fwd_occ, bwd_occ) samples, _ = model.sample_canvas(cond=semantic_c, struct_cond=init_latent, lr_images=None, flows=flows, masks=masks, cond_flow=None, batch_size=im_lq_pch.size(0), timesteps=opt.ddpm_steps, time_replace=opt.ddpm_steps, x_T=x_T, return_intermediates=True, tile_size=64, tile_overlap=opt.tile_overlap, batch_size_sample=opt.n_samples) _, enc_fea_lq = vq_model.encode(im_lq_pch) x_samples = vq_model.decode(samples * 1. / model.scale_factor, enc_fea_lq) # x_samples = model.decode_first_stage(samples) if opt.colorfix_type == 'adain': x_samples = adaptive_instance_normalization(x_samples, im_lq_pch) elif opt.colorfix_type == 'wavelet':
def space_timesteps(num_timesteps, section_counts): """ Create a list of timesteps to use from an original diffusion process, given the number of timesteps we want to take from equally-sized portions of the original process. For example, if there's 300 timesteps and the section counts are [10,15,20] then the first 100 timesteps are strided to be 10 timesteps, the second 100 are strided to be 15 timesteps, and the final 100 are strided to be 20. If the stride is a string starting with "ddim", then the fixed striding from the DDIM paper is used, and only one section is allowed. :param num_timesteps: the number of diffusion steps in the original process to divide up. :param section_counts: either a list of numbers, or a string containing comma-separated numbers, indicating the step count per section. As a special case, use "ddimN" where N is a number of steps to use the striding from the DDIM paper. :return: a set of diffusion steps from the original process to use. """ if isinstance(section_counts, str): if section_counts.startswith("ddim"): desired_count = int(section_counts[len("ddim"):]) for i in range(1, num_timesteps): if len(range(0, num_timesteps, i)) == desired_count: return set(range(0, num_timesteps, i)) raise ValueError( f"cannot create exactly {num_timesteps} steps with an integer stride" ) section_counts = [int(x) for x in section_counts.split(",")] #[250,] size_per = num_timesteps // len(section_counts) extra = num_timesteps % len(section_counts) start_idx = 0 all_steps = [] for i, section_count in enumerate(section_counts): size = size_per + (1 if i < extra else 0) if size < section_count: raise ValueError( f"cannot divide section of {size} steps into {section_count}" ) if section_count <= 1: frac_stride = 1 else: frac_stride = (size - 1) / (section_count - 1) cur_idx = 0.0 taken_steps = [] for _ in range(section_count): taken_steps.append(start_idx + round(cur_idx)) cur_idx += frac_stride all_steps += taken_steps start_idx += size return set(all_steps) def chunk(it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) def load_model_from_config(config, ckpt, verbose=False): print(f"Loading model from {ckpt}") pl_sd = torch.load(ckpt, map_location="cpu") if "global_step" in pl_sd: print(f"Global Step: {pl_sd['global_step']}") sd = pl_sd["state_dict"] model = instantiate_from_config(config.model) m, u = model.load_state_dict(sd, strict=False) if len(m) > 0 and verbose: print("missing keys:") print(m) if len(u) > 0 and verbose: print("unexpected keys:") print(u) model.cuda() model.eval() return model def load_img(path): image = Image.open(path).convert("RGB") w, h = image.size print(f"loaded input image of size ({w}, {h}) from {path}") w, h = map(lambda x: x - x % 8, (w, h)) # resize to integer multiple of 32 image = image.resize((w, h), resample=PIL.Image.LANCZOS) image = np.array(image).astype(np.float32) / 255.0 image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image) return 2.*image - 1. def read_image(im_path): im = np.array(Image.open(im_path).convert("RGB")) im = im.astype(np.float32) / 255.0 im = im[None].transpose(0, 3, 1, 2) im = (torch.from_numpy(im) - 0.5) / 0.5 return im def main(): parser = argparse.ArgumentParser() parser.add_argument( "--seqs-path", type=str, nargs="?", help="path to the input image", default="inputs/user_upload" ) # parser.add_argument( # "--init-img", # type=str, # nargs="?", # help="path to the input image", # default="inputs/user_upload" # ) parser.add_argument( "--outdir", type=str, nargs="?", help="dir to write results to", default="outputs/user_upload" ) parser.add_argument( "--device", type=str, help="device", default="cuda" ) parser.add_argument( "--ddpm_steps", type=int, default=1000, help="number of ddpm sampling steps", ) parser.add_argument( "--n_iter", type=int, default=1, help="sample this often", ) parser.add_argument( "--C", type=int, default=4, help="latent channels", ) parser.add_argument( "--f", type=int, default=8, help="downsampling factor, most often 8 or 16", ) parser.add_argument( "--n_frames", type=int, default=5, help="number of frames to perform inference", ) parser.add_argument( "--n_samples", type=int, default=1, help="how many samples to produce for each given prompt. A.k.a batch size", ) parser.add_argument( "--config", type=str, default="configs/stable-diffusion/v1-inference.yaml", help="path to config which constructs model", ) parser.add_argument( "--ckpt", type=str, default="checkpoints/stablevsr_025.ckpt", help="path to checkpoint of model", ) parser.add_argument( "--vqgan_ckpt", type=str, default="checkpoints/vqgan_cfw_00011.ckpt", help="path to checkpoint of VQGAN model", ) parser.add_argument( "--seed", type=int, default=42, help="the seed (for reproducible sampling)", ) parser.add_argument( "--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast" ) parser.add_argument( "--select_idx", type=int, default=0, help="selected sequence index", ) parser.add_argument( "--n_gpus", type=int, default=1, help="number of gpu for testing", ) parser.add_argument( "--dec_w", type=float, default=0.5, help="weight for combining VQGAN and Diffusion", ) parser.add_argument( "--tile_overlap", type=int, default=32, help="tile overlap size (in latent)", ) parser.add_argument( "--upscale", type=float, default=4.0, help="upsample scale", ) parser.add_argument( "--colorfix_type", type=str, default="nofix", help="Color fix type to adjust the color of HR result according to LR input: adain (used in paper); wavelet; nofix", ) parser.add_argument( "--vqgantile_stride", type=int, default=750, help="the stride for tile operation before VQGAN decoder (in pixel)", ) parser.add_argument( "--vqgantile_size", type=int, default=960, help="the size for tile operation before VQGAN decoder (in pixel)", ) opt = parser.parse_args() seed_everything(opt.seed) print('>>>>>>>>>>color correction>>>>>>>>>>>') if opt.colorfix_type == 'adain': print('Use adain color correction') elif opt.colorfix_type == 'wavelet': print('Use wavelet color correction') else: print('No color correction') print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>') # Testing select_idx = opt.select_idx num_gpu_test = opt.n_gpus # Model config = OmegaConf.load(f"{opt.config}") model = load_model_from_config(config, f"{opt.ckpt}") device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") model = model.to(device) model.configs = config vqgan_config = OmegaConf.load("configs/video_autoencoder/video_autoencoder_kl_64x64x4_resi.yaml") vq_model = load_model_from_config(vqgan_config, opt.vqgan_ckpt) vq_model = vq_model.to(device) vq_model.decoder.fusion_w = opt.dec_w model.register_schedule(given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=0.00085, linear_end=0.0120, cosine_s=8e-3) model.num_timesteps = 1000 sqrt_alphas_cumprod = copy.deepcopy(model.sqrt_alphas_cumprod) sqrt_one_minus_alphas_cumprod = copy.deepcopy(model.sqrt_one_minus_alphas_cumprod) use_timesteps = set(space_timesteps(1000, [opt.ddpm_steps])) last_alpha_cumprod = 1.0 new_betas = [] timestep_map = [] for i, alpha_cumprod in enumerate(model.alphas_cumprod): if i in use_timesteps: new_betas.append(1 - alpha_cumprod / last_alpha_cumprod) last_alpha_cumprod = alpha_cumprod timestep_map.append(i) new_betas = [beta.data.cpu().numpy() for beta in new_betas] model.register_schedule(given_betas=np.array(new_betas), timesteps=len(new_betas)) model.num_timesteps = 1000 model.ori_timesteps = list(use_timesteps) model.ori_timesteps.sort() model = model.to(device) model.cond_stage_model.device = device # Data n_frames = opt.n_frames batch_size = opt.n_samples seq_name_list = sorted(os.listdir(opt.seqs_path)) for seq_idx, seq_item in enumerate(seq_name_list): if seq_idx % num_gpu_test != select_idx: continue seq_path = os.path.join(opt.seqs_path, seq_item) temp_frame_buffer = [] init_segment_list = [] img_name_list = sorted(os.listdir(seq_path)) # naive way to handle the boundary problem while len(img_name_list) % n_frames != 0: img_name_list.append(img_name_list[-1]) for idx, item in enumerate(img_name_list): # img_name = item.split('/')[-1] cur_image = read_image(os.path.join(seq_path, item)) size_min = min(cur_image.size(-1), cur_image.size(-2)) upsample_scale = max(512 / size_min, opt.upscale) cur_image = F.interpolate( cur_image, size=(int(cur_image.size(-2) * upsample_scale), int(cur_image.size(-1) * upsample_scale)), mode='bicubic', ) temp_frame_buffer.append(cur_image) if idx % n_frames == n_frames - 1: # [1, c, h, w] -> [b, c, h, w] temp_frame = torch.cat(copy.deepcopy(temp_frame_buffer), dim=0) print('Segment shape: ', temp_frame.shape) init_segment_list.append(temp_frame) temp_frame_buffer.clear() # print(f"Found {len(img_name_list)} inputs.") precision_scope = autocast if opt.precision == "autocast" else nullcontext niqe_list = [] with torch.no_grad(): with precision_scope("cuda"): with model.ema_scope(): tic = time.time() all_samples = list() for n in trange(len(init_segment_list), desc="Sampling"): init_image = init_segment_list[n] im_lq_bs = init_image.clamp(-1.0, 1.0).to(device) print('>>>>>>>>>>>>>>>>>>>>>>>') print('seq: ', seq_item, 'seg: ', n, 'size: ', im_lq_bs.size()) ori_h, ori_w = im_lq_bs.shape[2:] ref_patch=None if not (ori_h % 32 == 0 and ori_w % 32 == 0): flag_pad = True pad_h = ((ori_h // 32) + 1) * 32 - ori_h pad_w = ((ori_w // 32) + 1) * 32 - ori_w im_lq_bs = F.pad(im_lq_bs, pad=(0, pad_w, 0, pad_h), mode='reflect') else: flag_pad = False im_lq_bs_0_1 = torch.clamp((im_lq_bs + 1.0) / 2.0, min=0.0, max=1.0) _, _, im_h, im_w = im_lq_bs_0_1.shape # flow estimation im_lq_bs_0_1 = F.interpolate(im_lq_bs_0_1, size=(im_h//4, im_w//4), mode='bicubic') im_lq_bs_0_1 = rearrange(im_lq_bs_0_1, '(b t) c h w -> b t c h w', t=init_image.size(0)) flows = model.compute_flow(im_lq_bs_0_1) # flows: [flows_bwd(forward_prop), flows_fwd(backward_prop)] flows = [rearrange(flow, 'b t c h w -> (b t) c h w') for flow in flows] flows = [resize_flow(flow, size_type='shape', sizes=(im_h//8, im_w//8)) for flow in flows] flows = [rearrange(flow, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) for flow in flows] # occlusion mask estimation fwd_occ_list, bwd_occ_list = list(), list() for i in range(init_image.size(0)-1): fwd_flow, bwd_flow = flows[1][:, i, :, :, :], flows[0][:, i, :, :, :] fwd_occ, bwd_occ = forward_backward_consistency_check(fwd_flow, bwd_flow, alpha=0.01, beta=0.5) fwd_occ_list.append(fwd_occ.unsqueeze_(1)) bwd_occ_list.append(bwd_occ.unsqueeze_(1)) fwd_occs = torch.stack(fwd_occ_list, dim=1) fwd_occs = rearrange(fwd_occs, 'b t c h w -> (b t) c h w') bwd_occs = torch.stack(bwd_occ_list, dim=1) bwd_occs = rearrange(bwd_occs, 'b t c h w -> (b t) c h w') # masks = [fwd_occ_list, bwd_occ_list] flows = [rearrange(flow, 'b t c h w -> (b t) c h w') for flow in flows] if im_lq_bs.shape[2] > opt.vqgantile_size or im_lq_bs.shape[3] > opt.vqgantile_size: imlq_spliter = ImageSpliterTh(im_lq_bs, opt.vqgantile_size, opt.vqgantile_stride, sf=1) flow_spliter_f = ImageSpliterTh(flows[0], opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) flow_spliter_b = ImageSpliterTh(flows[1], opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) fwd_occ_spliter = ImageSpliterTh(fwd_occs, opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) bwd_occ_spliter = ImageSpliterTh(bwd_occs, opt.vqgantile_size // 8, opt.vqgantile_stride // 8, sf=1) for (im_lq_pch, index_infos), (flow_f, _), (flow_b, _), (fwd_occ, _), (bwd_occ, _) \ in zip(imlq_spliter, flow_spliter_f, flow_spliter_b, fwd_occ_spliter, bwd_occ_spliter): seed_everything(opt.seed) init_latent = model.get_first_stage_encoding(model.encode_first_stage(im_lq_pch)) text_init = ['']*opt.n_samples semantic_c = model.cond_stage_model(text_init) noise = torch.randn_like(init_latent) # If you would like to start from the intermediate steps, # you can add noise to LR to the specific steps. t = repeat(torch.tensor([999]), '1 -> b', b=im_lq_bs.size(0)) t = t.to(device).long() x_T = model.q_sample_respace(x_start=init_latent, t=t, sqrt_alphas_cumprod=sqrt_alphas_cumprod, sqrt_one_minus_alphas_cumprod=sqrt_one_minus_alphas_cumprod, noise=noise) # x_T = noise # im_lq_pch_0_1 = torch.clamp((im_lq_pch + 1.0) / 2.0, min=0.0, max=1.0) flow_f = rearrange(flow_f, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) flow_b = rearrange(flow_b, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) fwd_occ = rearrange(fwd_occ, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) bwd_occ = rearrange(bwd_occ, '(b t) c h w -> b t c h w', t=init_image.size(0)-1) flows = (flow_f, flow_b) masks = (fwd_occ, bwd_occ) samples, _ = model.sample_canvas(cond=semantic_c, struct_cond=init_latent, lr_images=None, flows=flows, masks=masks, cond_flow=None, batch_size=im_lq_pch.size(0), timesteps=opt.ddpm_steps, time_replace=opt.ddpm_steps, x_T=x_T, return_intermediates=True, tile_size=64, tile_overlap=opt.tile_overlap, batch_size_sample=opt.n_samples) _, enc_fea_lq = vq_model.encode(im_lq_pch) x_samples = vq_model.decode(samples * 1. / model.scale_factor, enc_fea_lq) # x_samples = model.decode_first_stage(samples) if opt.colorfix_type == 'adain': x_samples = adaptive_instance_normalization(x_samples, im_lq_pch) elif opt.colorfix_type == 'wavelet':
x_samples = wavelet_reconstruction(x_samples, im_lq_pch)
5
2023-11-30 01:50:29+00:00
24k
Czm369/MixPL
mmdet/configs/rtmdet/rtmdet_tiny_8xb32_300e_coco.py
[ { "identifier": "PackDetInputs", "path": "mmdet/datasets/transforms/formatting.py", "snippet": "class PackDetInputs(BaseTransform):\n \"\"\"Pack the inputs data for the detection / semantic segmentation /\n panoptic segmentation.\n\n The ``img_meta`` item is always populated. The contents of the\n ``img_meta`` dictionary depends on ``meta_keys``. By default this includes:\n\n - ``img_id``: id of the image\n\n - ``img_path``: path to the image file\n\n - ``ori_shape``: original shape of the image as a tuple (h, w)\n\n - ``img_shape``: shape of the image input to the network as a tuple \\\n (h, w). Note that images may be zero padded on the \\\n bottom/right if the batch tensor is larger than this shape.\n\n - ``scale_factor``: a float indicating the preprocessing scale\n\n - ``flip``: a boolean indicating if image flip transform was used\n\n - ``flip_direction``: the flipping direction\n\n Args:\n meta_keys (Sequence[str], optional): Meta keys to be converted to\n ``mmcv.DataContainer`` and collected in ``data[img_metas]``.\n Default: ``('img_id', 'img_path', 'ori_shape', 'img_shape',\n 'scale_factor', 'flip', 'flip_direction')``\n \"\"\"\n mapping_table = {\n 'gt_bboxes': 'bboxes',\n 'gt_bboxes_labels': 'labels',\n 'gt_masks': 'masks'\n }\n\n def __init__(self,\n meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n 'scale_factor', 'flip', 'flip_direction')):\n self.meta_keys = meta_keys\n\n def transform(self, results: dict) -> dict:\n \"\"\"Method to pack the input data.\n\n Args:\n results (dict): Result dict from the data pipeline.\n\n Returns:\n dict:\n\n - 'inputs' (obj:`torch.Tensor`): The forward data of models.\n - 'data_sample' (obj:`DetDataSample`): The annotation info of the\n sample.\n \"\"\"\n packed_results = dict()\n if 'img' in results:\n img = results['img']\n if len(img.shape) < 3:\n img = np.expand_dims(img, -1)\n # To improve the computational speed by by 3-5 times, apply:\n # If image is not contiguous, use\n # `numpy.transpose()` followed by `numpy.ascontiguousarray()`\n # If image is already contiguous, use\n # `torch.permute()` followed by `torch.contiguous()`\n # Refer to https://github.com/open-mmlab/mmdetection/pull/9533\n # for more details\n if not img.flags.c_contiguous:\n img = np.ascontiguousarray(img.transpose(2, 0, 1))\n img = to_tensor(img)\n else:\n img = to_tensor(img).permute(2, 0, 1).contiguous()\n\n packed_results['inputs'] = img\n\n if 'gt_ignore_flags' in results:\n valid_idx = np.where(results['gt_ignore_flags'] == 0)[0]\n ignore_idx = np.where(results['gt_ignore_flags'] == 1)[0]\n\n data_sample = DetDataSample()\n instance_data = InstanceData()\n ignore_instance_data = InstanceData()\n\n for key in self.mapping_table.keys():\n if key not in results:\n continue\n if key == 'gt_masks' or isinstance(results[key], BaseBoxes):\n if 'gt_ignore_flags' in results:\n instance_data[\n self.mapping_table[key]] = results[key][valid_idx]\n ignore_instance_data[\n self.mapping_table[key]] = results[key][ignore_idx]\n else:\n instance_data[self.mapping_table[key]] = results[key]\n else:\n if 'gt_ignore_flags' in results:\n instance_data[self.mapping_table[key]] = to_tensor(\n results[key][valid_idx])\n ignore_instance_data[self.mapping_table[key]] = to_tensor(\n results[key][ignore_idx])\n else:\n instance_data[self.mapping_table[key]] = to_tensor(\n results[key])\n data_sample.gt_instances = instance_data\n data_sample.ignored_instances = ignore_instance_data\n\n if 'proposals' in results:\n proposals = InstanceData(\n bboxes=to_tensor(results['proposals']),\n scores=to_tensor(results['proposals_scores']))\n data_sample.proposals = proposals\n\n if 'gt_seg_map' in results:\n gt_sem_seg_data = dict(\n sem_seg=to_tensor(results['gt_seg_map'][None, ...].copy()))\n gt_sem_seg_data = PixelData(**gt_sem_seg_data)\n if 'ignore_index' in results:\n metainfo = dict(ignore_index=results['ignore_index'])\n gt_sem_seg_data.set_metainfo(metainfo)\n data_sample.gt_sem_seg = gt_sem_seg_data\n\n img_meta = {}\n for key in self.meta_keys:\n if key in results:\n img_meta[key] = results[key]\n data_sample.set_metainfo(img_meta)\n packed_results['data_samples'] = data_sample\n\n return packed_results\n\n def __repr__(self) -> str:\n repr_str = self.__class__.__name__\n repr_str += f'(meta_keys={self.meta_keys})'\n return repr_str" }, { "identifier": "LoadAnnotations", "path": "mmdet/datasets/transforms/loading.py", "snippet": "class LoadAnnotations(MMCV_LoadAnnotations):\n \"\"\"Load and process the ``instances`` and ``seg_map`` annotation provided\n by dataset.\n\n The annotation format is as the following:\n\n .. code-block:: python\n\n {\n 'instances':\n [\n {\n # List of 4 numbers representing the bounding box of the\n # instance, in (x1, y1, x2, y2) order.\n 'bbox': [x1, y1, x2, y2],\n\n # Label of image classification.\n 'bbox_label': 1,\n\n # Used in instance/panoptic segmentation. The segmentation mask\n # of the instance or the information of segments.\n # 1. If list[list[float]], it represents a list of polygons,\n # one for each connected component of the object. Each\n # list[float] is one simple polygon in the format of\n # [x1, y1, ..., xn, yn] (n >= 3). The Xs and Ys are absolute\n # coordinates in unit of pixels.\n # 2. If dict, it represents the per-pixel segmentation mask in\n # COCO's compressed RLE format. The dict should have keys\n # “size” and “counts”. Can be loaded by pycocotools\n 'mask': list[list[float]] or dict,\n\n }\n ]\n # Filename of semantic or panoptic segmentation ground truth file.\n 'seg_map_path': 'a/b/c'\n }\n\n After this module, the annotation has been changed to the format below:\n\n .. code-block:: python\n\n {\n # In (x1, y1, x2, y2) order, float type. N is the number of bboxes\n # in an image\n 'gt_bboxes': BaseBoxes(N, 4)\n # In int type.\n 'gt_bboxes_labels': np.ndarray(N, )\n # In built-in class\n 'gt_masks': PolygonMasks (H, W) or BitmapMasks (H, W)\n # In uint8 type.\n 'gt_seg_map': np.ndarray (H, W)\n # in (x, y, v) order, float type.\n }\n\n Required Keys:\n\n - height\n - width\n - instances\n\n - bbox (optional)\n - bbox_label\n - mask (optional)\n - ignore_flag\n\n - seg_map_path (optional)\n\n Added Keys:\n\n - gt_bboxes (BaseBoxes[torch.float32])\n - gt_bboxes_labels (np.int64)\n - gt_masks (BitmapMasks | PolygonMasks)\n - gt_seg_map (np.uint8)\n - gt_ignore_flags (bool)\n\n Args:\n with_bbox (bool): Whether to parse and load the bbox annotation.\n Defaults to True.\n with_label (bool): Whether to parse and load the label annotation.\n Defaults to True.\n with_mask (bool): Whether to parse and load the mask annotation.\n Default: False.\n with_seg (bool): Whether to parse and load the semantic segmentation\n annotation. Defaults to False.\n poly2mask (bool): Whether to convert mask to bitmap. Default: True.\n box_type (str): The box type used to wrap the bboxes. If ``box_type``\n is None, gt_bboxes will keep being np.ndarray. Defaults to 'hbox'.\n reduce_zero_label (bool): Whether reduce all label value\n by 1. Usually used for datasets where 0 is background label.\n Defaults to False.\n ignore_index (int): The label index to be ignored.\n Valid only if reduce_zero_label is true. Defaults is 255.\n imdecode_backend (str): The image decoding backend type. The backend\n argument for :func:``mmcv.imfrombytes``.\n See :fun:``mmcv.imfrombytes`` for details.\n Defaults to 'cv2'.\n backend_args (dict, optional): Arguments to instantiate the\n corresponding backend. Defaults to None.\n \"\"\"\n\n def __init__(\n self,\n with_mask: bool = False,\n poly2mask: bool = True,\n box_type: str = 'hbox',\n # use for semseg\n reduce_zero_label: bool = False,\n ignore_index: int = 255,\n **kwargs) -> None:\n super(LoadAnnotations, self).__init__(**kwargs)\n self.with_mask = with_mask\n self.poly2mask = poly2mask\n self.box_type = box_type\n self.reduce_zero_label = reduce_zero_label\n self.ignore_index = ignore_index\n\n def _load_bboxes(self, results: dict) -> None:\n \"\"\"Private function to load bounding box annotations.\n\n Args:\n results (dict): Result dict from :obj:``mmengine.BaseDataset``.\n Returns:\n dict: The dict contains loaded bounding box annotations.\n \"\"\"\n gt_bboxes = []\n gt_ignore_flags = []\n for instance in results.get('instances', []):\n gt_bboxes.append(instance['bbox'])\n gt_ignore_flags.append(instance['ignore_flag'])\n if self.box_type is None:\n results['gt_bboxes'] = np.array(\n gt_bboxes, dtype=np.float32).reshape((-1, 4))\n else:\n _, box_type_cls = get_box_type(self.box_type)\n results['gt_bboxes'] = box_type_cls(gt_bboxes, dtype=torch.float32)\n results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool)\n\n def _load_labels(self, results: dict) -> None:\n \"\"\"Private function to load label annotations.\n\n Args:\n results (dict): Result dict from :obj:``mmengine.BaseDataset``.\n\n Returns:\n dict: The dict contains loaded label annotations.\n \"\"\"\n gt_bboxes_labels = []\n for instance in results.get('instances', []):\n gt_bboxes_labels.append(instance['bbox_label'])\n # TODO: Inconsistent with mmcv, consider how to deal with it later.\n results['gt_bboxes_labels'] = np.array(\n gt_bboxes_labels, dtype=np.int64)\n\n def _poly2mask(self, mask_ann: Union[list, dict], img_h: int,\n img_w: int) -> np.ndarray:\n \"\"\"Private function to convert masks represented with polygon to\n bitmaps.\n\n Args:\n mask_ann (list | dict): Polygon mask annotation input.\n img_h (int): The height of output mask.\n img_w (int): The width of output mask.\n\n Returns:\n np.ndarray: The decode bitmap mask of shape (img_h, img_w).\n \"\"\"\n\n if isinstance(mask_ann, list):\n # polygon -- a single object might consist of multiple parts\n # we merge all parts into one mask rle code\n rles = maskUtils.frPyObjects(mask_ann, img_h, img_w)\n rle = maskUtils.merge(rles)\n elif isinstance(mask_ann['counts'], list):\n # uncompressed RLE\n rle = maskUtils.frPyObjects(mask_ann, img_h, img_w)\n else:\n # rle\n rle = mask_ann\n mask = maskUtils.decode(rle)\n return mask\n\n def _process_masks(self, results: dict) -> list:\n \"\"\"Process gt_masks and filter invalid polygons.\n\n Args:\n results (dict): Result dict from :obj:``mmengine.BaseDataset``.\n\n Returns:\n list: Processed gt_masks.\n \"\"\"\n gt_masks = []\n gt_ignore_flags = []\n for instance in results.get('instances', []):\n gt_mask = instance['mask']\n # If the annotation of segmentation mask is invalid,\n # ignore the whole instance.\n if isinstance(gt_mask, list):\n gt_mask = [\n np.array(polygon) for polygon in gt_mask\n if len(polygon) % 2 == 0 and len(polygon) >= 6\n ]\n if len(gt_mask) == 0:\n # ignore this instance and set gt_mask to a fake mask\n instance['ignore_flag'] = 1\n gt_mask = [np.zeros(6)]\n elif not self.poly2mask:\n # `PolygonMasks` requires a ploygon of format List[np.array],\n # other formats are invalid.\n instance['ignore_flag'] = 1\n gt_mask = [np.zeros(6)]\n elif isinstance(gt_mask, dict) and \\\n not (gt_mask.get('counts') is not None and\n gt_mask.get('size') is not None and\n isinstance(gt_mask['counts'], (list, str))):\n # if gt_mask is a dict, it should include `counts` and `size`,\n # so that `BitmapMasks` can uncompressed RLE\n instance['ignore_flag'] = 1\n gt_mask = [np.zeros(6)]\n gt_masks.append(gt_mask)\n # re-process gt_ignore_flags\n gt_ignore_flags.append(instance['ignore_flag'])\n results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool)\n return gt_masks\n\n def _load_masks(self, results: dict) -> None:\n \"\"\"Private function to load mask annotations.\n\n Args:\n results (dict): Result dict from :obj:``mmengine.BaseDataset``.\n \"\"\"\n h, w = results['ori_shape']\n gt_masks = self._process_masks(results)\n if self.poly2mask:\n gt_masks = BitmapMasks(\n [self._poly2mask(mask, h, w) for mask in gt_masks], h, w)\n else:\n # fake polygon masks will be ignored in `PackDetInputs`\n gt_masks = PolygonMasks([mask for mask in gt_masks], h, w)\n results['gt_masks'] = gt_masks\n\n def _load_seg_map(self, results: dict) -> None:\n \"\"\"Private function to load semantic segmentation annotations.\n\n Args:\n results (dict): Result dict from :obj:``mmcv.BaseDataset``.\n\n Returns:\n dict: The dict contains loaded semantic segmentation annotations.\n \"\"\"\n if results.get('seg_map_path', None) is None:\n return\n\n img_bytes = get(\n results['seg_map_path'], backend_args=self.backend_args)\n gt_semantic_seg = mmcv.imfrombytes(\n img_bytes, flag='unchanged',\n backend=self.imdecode_backend).squeeze()\n\n if self.reduce_zero_label:\n # avoid using underflow conversion\n gt_semantic_seg[gt_semantic_seg == 0] = self.ignore_index\n gt_semantic_seg = gt_semantic_seg - 1\n gt_semantic_seg[gt_semantic_seg == self.ignore_index -\n 1] = self.ignore_index\n\n # modify if custom classes\n if results.get('label_map', None) is not None:\n # Add deep copy to solve bug of repeatedly\n # replace `gt_semantic_seg`, which is reported in\n # https://github.com/open-mmlab/mmsegmentation/pull/1445/\n gt_semantic_seg_copy = gt_semantic_seg.copy()\n for old_id, new_id in results['label_map'].items():\n gt_semantic_seg[gt_semantic_seg_copy == old_id] = new_id\n results['gt_seg_map'] = gt_semantic_seg\n results['ignore_index'] = self.ignore_index\n\n def transform(self, results: dict) -> dict:\n \"\"\"Function to load multiple types annotations.\n\n Args:\n results (dict): Result dict from :obj:``mmengine.BaseDataset``.\n\n Returns:\n dict: The dict contains loaded bounding box, label and\n semantic segmentation.\n \"\"\"\n\n if self.with_bbox:\n self._load_bboxes(results)\n if self.with_label:\n self._load_labels(results)\n if self.with_mask:\n self._load_masks(results)\n if self.with_seg:\n self._load_seg_map(results)\n return results\n\n def __repr__(self) -> str:\n repr_str = self.__class__.__name__\n repr_str += f'(with_bbox={self.with_bbox}, '\n repr_str += f'with_label={self.with_label}, '\n repr_str += f'with_mask={self.with_mask}, '\n repr_str += f'with_seg={self.with_seg}, '\n repr_str += f'poly2mask={self.poly2mask}, '\n repr_str += f\"imdecode_backend='{self.imdecode_backend}', \"\n repr_str += f'backend_args={self.backend_args})'\n return repr_str" }, { "identifier": "CachedMixUp", "path": "mmdet/datasets/transforms/transforms.py", "snippet": "class CachedMixUp(BaseTransform):\n \"\"\"Cached mixup data augmentation.\n\n .. code:: text\n\n mixup transform\n +------------------------------+\n | mixup image | |\n | +--------|--------+ |\n | | | | |\n |---------------+ | |\n | | | |\n | | image | |\n | | | |\n | | | |\n | |-----------------+ |\n | pad |\n +------------------------------+\n\n The cached mixup transform steps are as follows:\n\n 1. Append the results from the last transform into the cache.\n 2. Another random image is picked from the cache and embedded in\n the top left patch(after padding and resizing)\n 3. The target of mixup transform is the weighted average of mixup\n image and origin image.\n\n Required Keys:\n\n - img\n - gt_bboxes (np.float32) (optional)\n - gt_bboxes_labels (np.int64) (optional)\n - gt_ignore_flags (bool) (optional)\n - mix_results (List[dict])\n\n\n Modified Keys:\n\n - img\n - img_shape\n - gt_bboxes (optional)\n - gt_bboxes_labels (optional)\n - gt_ignore_flags (optional)\n\n\n Args:\n img_scale (Sequence[int]): Image output size after mixup pipeline.\n The shape order should be (width, height). Defaults to (640, 640).\n ratio_range (Sequence[float]): Scale ratio of mixup image.\n Defaults to (0.5, 1.5).\n flip_ratio (float): Horizontal flip ratio of mixup image.\n Defaults to 0.5.\n pad_val (int): Pad value. Defaults to 114.\n max_iters (int): The maximum number of iterations. If the number of\n iterations is greater than `max_iters`, but gt_bbox is still\n empty, then the iteration is terminated. Defaults to 15.\n bbox_clip_border (bool, optional): Whether to clip the objects outside\n the border of the image. In some dataset like MOT17, the gt bboxes\n are allowed to cross the border of images. Therefore, we don't\n need to clip the gt bboxes in these cases. Defaults to True.\n max_cached_images (int): The maximum length of the cache. The larger\n the cache, the stronger the randomness of this transform. As a\n rule of thumb, providing 10 caches for each image suffices for\n randomness. Defaults to 20.\n random_pop (bool): Whether to randomly pop a result from the cache\n when the cache is full. If set to False, use FIFO popping method.\n Defaults to True.\n prob (float): Probability of applying this transformation.\n Defaults to 1.0.\n \"\"\"\n\n def __init__(self,\n img_scale: Tuple[int, int] = (640, 640),\n ratio_range: Tuple[float, float] = (0.5, 1.5),\n flip_ratio: float = 0.5,\n pad_val: float = 114.0,\n max_iters: int = 15,\n bbox_clip_border: bool = True,\n max_cached_images: int = 20,\n random_pop: bool = True,\n prob: float = 1.0) -> None:\n assert isinstance(img_scale, tuple)\n assert max_cached_images >= 2, 'The length of cache must >= 2, ' \\\n f'but got {max_cached_images}.'\n assert 0 <= prob <= 1.0, 'The probability should be in range [0,1]. ' \\\n f'got {prob}.'\n self.dynamic_scale = img_scale\n self.ratio_range = ratio_range\n self.flip_ratio = flip_ratio\n self.pad_val = pad_val\n self.max_iters = max_iters\n self.bbox_clip_border = bbox_clip_border\n self.results_cache = []\n\n self.max_cached_images = max_cached_images\n self.random_pop = random_pop\n self.prob = prob\n\n @cache_randomness\n def get_indexes(self, cache: list) -> int:\n \"\"\"Call function to collect indexes.\n\n Args:\n cache (list): The result cache.\n\n Returns:\n int: index.\n \"\"\"\n\n for i in range(self.max_iters):\n index = random.randint(0, len(cache) - 1)\n gt_bboxes_i = cache[index]['gt_bboxes']\n if len(gt_bboxes_i) != 0:\n break\n return index\n\n @autocast_box_type()\n def transform(self, results: dict) -> dict:\n \"\"\"MixUp transform function.\n\n Args:\n results (dict): Result dict.\n\n Returns:\n dict: Updated result dict.\n \"\"\"\n # cache and pop images\n self.results_cache.append(copy.deepcopy(results))\n if len(self.results_cache) > self.max_cached_images:\n if self.random_pop:\n index = random.randint(0, len(self.results_cache) - 1)\n else:\n index = 0\n self.results_cache.pop(index)\n\n if len(self.results_cache) <= 1:\n return results\n\n if random.uniform(0, 1) > self.prob:\n return results\n\n index = self.get_indexes(self.results_cache)\n retrieve_results = copy.deepcopy(self.results_cache[index])\n\n # TODO: refactor mixup to reuse these code.\n if retrieve_results['gt_bboxes'].shape[0] == 0:\n # empty bbox\n return results\n\n retrieve_img = retrieve_results['img']\n with_mask = True if 'gt_masks' in results else False\n\n jit_factor = random.uniform(*self.ratio_range)\n is_flip = random.uniform(0, 1) > self.flip_ratio\n\n if len(retrieve_img.shape) == 3:\n out_img = np.ones(\n (self.dynamic_scale[1], self.dynamic_scale[0], 3),\n dtype=retrieve_img.dtype) * self.pad_val\n else:\n out_img = np.ones(\n self.dynamic_scale[::-1],\n dtype=retrieve_img.dtype) * self.pad_val\n\n # 1. keep_ratio resize\n scale_ratio = min(self.dynamic_scale[1] / retrieve_img.shape[0],\n self.dynamic_scale[0] / retrieve_img.shape[1])\n retrieve_img = mmcv.imresize(\n retrieve_img, (int(retrieve_img.shape[1] * scale_ratio),\n int(retrieve_img.shape[0] * scale_ratio)))\n\n # 2. paste\n out_img[:retrieve_img.shape[0], :retrieve_img.shape[1]] = retrieve_img\n\n # 3. scale jit\n scale_ratio *= jit_factor\n out_img = mmcv.imresize(out_img, (int(out_img.shape[1] * jit_factor),\n int(out_img.shape[0] * jit_factor)))\n\n # 4. flip\n if is_flip:\n out_img = out_img[:, ::-1, :]\n\n # 5. random crop\n ori_img = results['img']\n origin_h, origin_w = out_img.shape[:2]\n target_h, target_w = ori_img.shape[:2]\n padded_img = np.ones((max(origin_h, target_h), max(\n origin_w, target_w), 3)) * self.pad_val\n padded_img = padded_img.astype(np.uint8)\n padded_img[:origin_h, :origin_w] = out_img\n\n x_offset, y_offset = 0, 0\n if padded_img.shape[0] > target_h:\n y_offset = random.randint(0, padded_img.shape[0] - target_h)\n if padded_img.shape[1] > target_w:\n x_offset = random.randint(0, padded_img.shape[1] - target_w)\n padded_cropped_img = padded_img[y_offset:y_offset + target_h,\n x_offset:x_offset + target_w]\n\n # 6. adjust bbox\n retrieve_gt_bboxes = retrieve_results['gt_bboxes']\n retrieve_gt_bboxes.rescale_([scale_ratio, scale_ratio])\n if with_mask:\n retrieve_gt_masks = retrieve_results['gt_masks'].rescale(\n scale_ratio)\n\n if self.bbox_clip_border:\n retrieve_gt_bboxes.clip_([origin_h, origin_w])\n\n if is_flip:\n retrieve_gt_bboxes.flip_([origin_h, origin_w],\n direction='horizontal')\n if with_mask:\n retrieve_gt_masks = retrieve_gt_masks.flip()\n\n # 7. filter\n cp_retrieve_gt_bboxes = retrieve_gt_bboxes.clone()\n cp_retrieve_gt_bboxes.translate_([-x_offset, -y_offset])\n if with_mask:\n retrieve_gt_masks = retrieve_gt_masks.translate(\n out_shape=(target_h, target_w),\n offset=-x_offset,\n direction='horizontal')\n retrieve_gt_masks = retrieve_gt_masks.translate(\n out_shape=(target_h, target_w),\n offset=-y_offset,\n direction='vertical')\n\n if self.bbox_clip_border:\n cp_retrieve_gt_bboxes.clip_([target_h, target_w])\n\n # 8. mix up\n ori_img = ori_img.astype(np.float32)\n mixup_img = 0.5 * ori_img + 0.5 * padded_cropped_img.astype(np.float32)\n\n retrieve_gt_bboxes_labels = retrieve_results['gt_bboxes_labels']\n retrieve_gt_ignore_flags = retrieve_results['gt_ignore_flags']\n\n mixup_gt_bboxes = cp_retrieve_gt_bboxes.cat(\n (results['gt_bboxes'], cp_retrieve_gt_bboxes), dim=0)\n mixup_gt_bboxes_labels = np.concatenate(\n (results['gt_bboxes_labels'], retrieve_gt_bboxes_labels), axis=0)\n mixup_gt_ignore_flags = np.concatenate(\n (results['gt_ignore_flags'], retrieve_gt_ignore_flags), axis=0)\n if with_mask:\n mixup_gt_masks = retrieve_gt_masks.cat(\n [results['gt_masks'], retrieve_gt_masks])\n\n # remove outside bbox\n inside_inds = mixup_gt_bboxes.is_inside([target_h, target_w]).numpy()\n mixup_gt_bboxes = mixup_gt_bboxes[inside_inds]\n mixup_gt_bboxes_labels = mixup_gt_bboxes_labels[inside_inds]\n mixup_gt_ignore_flags = mixup_gt_ignore_flags[inside_inds]\n if with_mask:\n mixup_gt_masks = mixup_gt_masks[inside_inds]\n\n results['img'] = mixup_img.astype(np.uint8)\n results['img_shape'] = mixup_img.shape[:2]\n results['gt_bboxes'] = mixup_gt_bboxes\n results['gt_bboxes_labels'] = mixup_gt_bboxes_labels\n results['gt_ignore_flags'] = mixup_gt_ignore_flags\n if with_mask:\n results['gt_masks'] = mixup_gt_masks\n return results\n\n def __repr__(self):\n repr_str = self.__class__.__name__\n repr_str += f'(dynamic_scale={self.dynamic_scale}, '\n repr_str += f'ratio_range={self.ratio_range}, '\n repr_str += f'flip_ratio={self.flip_ratio}, '\n repr_str += f'pad_val={self.pad_val}, '\n repr_str += f'max_iters={self.max_iters}, '\n repr_str += f'bbox_clip_border={self.bbox_clip_border}, '\n repr_str += f'max_cached_images={self.max_cached_images}, '\n repr_str += f'random_pop={self.random_pop}, '\n repr_str += f'prob={self.prob})'\n return repr_str" }, { "identifier": "CachedMosaic", "path": "mmdet/datasets/transforms/transforms.py", "snippet": "class CachedMosaic(Mosaic):\n \"\"\"Cached mosaic augmentation.\n\n Cached mosaic transform will random select images from the cache\n and combine them into one output image.\n\n .. code:: text\n\n mosaic transform\n center_x\n +------------------------------+\n | pad | pad |\n | +-----------+ |\n | | | |\n | | image1 |--------+ |\n | | | | |\n | | | image2 | |\n center_y |----+-------------+-----------|\n | | cropped | |\n |pad | image3 | image4 |\n | | | |\n +----|-------------+-----------+\n | |\n +-------------+\n\n The cached mosaic transform steps are as follows:\n\n 1. Append the results from the last transform into the cache.\n 2. Choose the mosaic center as the intersections of 4 images\n 3. Get the left top image according to the index, and randomly\n sample another 3 images from the result cache.\n 4. Sub image will be cropped if image is larger than mosaic patch\n\n Required Keys:\n\n - img\n - gt_bboxes (np.float32) (optional)\n - gt_bboxes_labels (np.int64) (optional)\n - gt_ignore_flags (bool) (optional)\n\n Modified Keys:\n\n - img\n - img_shape\n - gt_bboxes (optional)\n - gt_bboxes_labels (optional)\n - gt_ignore_flags (optional)\n\n Args:\n img_scale (Sequence[int]): Image size before mosaic pipeline of single\n image. The shape order should be (width, height).\n Defaults to (640, 640).\n center_ratio_range (Sequence[float]): Center ratio range of mosaic\n output. Defaults to (0.5, 1.5).\n bbox_clip_border (bool, optional): Whether to clip the objects outside\n the border of the image. In some dataset like MOT17, the gt bboxes\n are allowed to cross the border of images. Therefore, we don't\n need to clip the gt bboxes in these cases. Defaults to True.\n pad_val (int): Pad value. Defaults to 114.\n prob (float): Probability of applying this transformation.\n Defaults to 1.0.\n max_cached_images (int): The maximum length of the cache. The larger\n the cache, the stronger the randomness of this transform. As a\n rule of thumb, providing 10 caches for each image suffices for\n randomness. Defaults to 40.\n random_pop (bool): Whether to randomly pop a result from the cache\n when the cache is full. If set to False, use FIFO popping method.\n Defaults to True.\n \"\"\"\n\n def __init__(self,\n *args,\n max_cached_images: int = 40,\n random_pop: bool = True,\n **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self.results_cache = []\n self.random_pop = random_pop\n assert max_cached_images >= 4, 'The length of cache must >= 4, ' \\\n f'but got {max_cached_images}.'\n self.max_cached_images = max_cached_images\n\n @cache_randomness\n def get_indexes(self, cache: list) -> list:\n \"\"\"Call function to collect indexes.\n\n Args:\n cache (list): The results cache.\n\n Returns:\n list: indexes.\n \"\"\"\n\n indexes = [random.randint(0, len(cache) - 1) for _ in range(3)]\n return indexes\n\n @autocast_box_type()\n def transform(self, results: dict) -> dict:\n \"\"\"Mosaic transform function.\n\n Args:\n results (dict): Result dict.\n\n Returns:\n dict: Updated result dict.\n \"\"\"\n # cache and pop images\n self.results_cache.append(copy.deepcopy(results))\n if len(self.results_cache) > self.max_cached_images:\n if self.random_pop:\n index = random.randint(0, len(self.results_cache) - 1)\n else:\n index = 0\n self.results_cache.pop(index)\n\n if len(self.results_cache) <= 4:\n return results\n\n if random.uniform(0, 1) > self.prob:\n return results\n indices = self.get_indexes(self.results_cache)\n mix_results = [copy.deepcopy(self.results_cache[i]) for i in indices]\n\n # TODO: refactor mosaic to reuse these code.\n mosaic_bboxes = []\n mosaic_bboxes_labels = []\n mosaic_ignore_flags = []\n mosaic_masks = []\n with_mask = True if 'gt_masks' in results else False\n\n if len(results['img'].shape) == 3:\n mosaic_img = np.full(\n (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2), 3),\n self.pad_val,\n dtype=results['img'].dtype)\n else:\n mosaic_img = np.full(\n (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2)),\n self.pad_val,\n dtype=results['img'].dtype)\n\n # mosaic center x, y\n center_x = int(\n random.uniform(*self.center_ratio_range) * self.img_scale[0])\n center_y = int(\n random.uniform(*self.center_ratio_range) * self.img_scale[1])\n center_position = (center_x, center_y)\n\n loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right')\n for i, loc in enumerate(loc_strs):\n if loc == 'top_left':\n results_patch = copy.deepcopy(results)\n else:\n results_patch = copy.deepcopy(mix_results[i - 1])\n\n img_i = results_patch['img']\n h_i, w_i = img_i.shape[:2]\n # keep_ratio resize\n scale_ratio_i = min(self.img_scale[1] / h_i,\n self.img_scale[0] / w_i)\n img_i = mmcv.imresize(\n img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i)))\n\n # compute the combine parameters\n paste_coord, crop_coord = self._mosaic_combine(\n loc, center_position, img_i.shape[:2][::-1])\n x1_p, y1_p, x2_p, y2_p = paste_coord\n x1_c, y1_c, x2_c, y2_c = crop_coord\n\n # crop and paste image\n mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c]\n\n # adjust coordinate\n gt_bboxes_i = results_patch['gt_bboxes']\n gt_bboxes_labels_i = results_patch['gt_bboxes_labels']\n gt_ignore_flags_i = results_patch['gt_ignore_flags']\n\n padw = x1_p - x1_c\n padh = y1_p - y1_c\n gt_bboxes_i.rescale_([scale_ratio_i, scale_ratio_i])\n gt_bboxes_i.translate_([padw, padh])\n mosaic_bboxes.append(gt_bboxes_i)\n mosaic_bboxes_labels.append(gt_bboxes_labels_i)\n mosaic_ignore_flags.append(gt_ignore_flags_i)\n if with_mask and results_patch.get('gt_masks', None) is not None:\n gt_masks_i = results_patch['gt_masks']\n gt_masks_i = gt_masks_i.rescale(float(scale_ratio_i))\n gt_masks_i = gt_masks_i.translate(\n out_shape=(int(self.img_scale[0] * 2),\n int(self.img_scale[1] * 2)),\n offset=padw,\n direction='horizontal')\n gt_masks_i = gt_masks_i.translate(\n out_shape=(int(self.img_scale[0] * 2),\n int(self.img_scale[1] * 2)),\n offset=padh,\n direction='vertical')\n mosaic_masks.append(gt_masks_i)\n\n mosaic_bboxes = mosaic_bboxes[0].cat(mosaic_bboxes, 0)\n mosaic_bboxes_labels = np.concatenate(mosaic_bboxes_labels, 0)\n mosaic_ignore_flags = np.concatenate(mosaic_ignore_flags, 0)\n\n if self.bbox_clip_border:\n mosaic_bboxes.clip_([2 * self.img_scale[1], 2 * self.img_scale[0]])\n # remove outside bboxes\n inside_inds = mosaic_bboxes.is_inside(\n [2 * self.img_scale[1], 2 * self.img_scale[0]]).numpy()\n mosaic_bboxes = mosaic_bboxes[inside_inds]\n mosaic_bboxes_labels = mosaic_bboxes_labels[inside_inds]\n mosaic_ignore_flags = mosaic_ignore_flags[inside_inds]\n\n results['img'] = mosaic_img\n results['img_shape'] = mosaic_img.shape[:2]\n results['gt_bboxes'] = mosaic_bboxes\n results['gt_bboxes_labels'] = mosaic_bboxes_labels\n results['gt_ignore_flags'] = mosaic_ignore_flags\n\n if with_mask:\n mosaic_masks = mosaic_masks[0].cat(mosaic_masks)\n results['gt_masks'] = mosaic_masks[inside_inds]\n return results\n\n def __repr__(self):\n repr_str = self.__class__.__name__\n repr_str += f'(img_scale={self.img_scale}, '\n repr_str += f'center_ratio_range={self.center_ratio_range}, '\n repr_str += f'pad_val={self.pad_val}, '\n repr_str += f'prob={self.prob}, '\n repr_str += f'max_cached_images={self.max_cached_images}, '\n repr_str += f'random_pop={self.random_pop})'\n return repr_str" }, { "identifier": "Pad", "path": "mmdet/datasets/transforms/transforms.py", "snippet": "class Pad(MMCV_Pad):\n \"\"\"Pad the image & segmentation map.\n\n There are three padding modes: (1) pad to a fixed size and (2) pad to the\n minimum size that is divisible by some number. and (3)pad to square. Also,\n pad to square and pad to the minimum size can be used as the same time.\n\n Required Keys:\n\n - img\n - gt_bboxes (BaseBoxes[torch.float32]) (optional)\n - gt_masks (BitmapMasks | PolygonMasks) (optional)\n - gt_seg_map (np.uint8) (optional)\n\n Modified Keys:\n\n - img\n - img_shape\n - gt_masks\n - gt_seg_map\n\n Added Keys:\n\n - pad_shape\n - pad_fixed_size\n - pad_size_divisor\n\n Args:\n size (tuple, optional): Fixed padding size.\n Expected padding shape (width, height). Defaults to None.\n size_divisor (int, optional): The divisor of padded size. Defaults to\n None.\n pad_to_square (bool): Whether to pad the image into a square.\n Currently only used for YOLOX. Defaults to False.\n pad_val (Number | dict[str, Number], optional) - Padding value for if\n the pad_mode is \"constant\". If it is a single number, the value\n to pad the image is the number and to pad the semantic\n segmentation map is 255. If it is a dict, it should have the\n following keys:\n\n - img: The value to pad the image.\n - seg: The value to pad the semantic segmentation map.\n Defaults to dict(img=0, seg=255).\n padding_mode (str): Type of padding. Should be: constant, edge,\n reflect or symmetric. Defaults to 'constant'.\n\n - constant: pads with a constant value, this value is specified\n with pad_val.\n - edge: pads with the last value at the edge of the image.\n - reflect: pads with reflection of image without repeating the last\n value on the edge. For example, padding [1, 2, 3, 4] with 2\n elements on both sides in reflect mode will result in\n [3, 2, 1, 2, 3, 4, 3, 2].\n - symmetric: pads with reflection of image repeating the last value\n on the edge. For example, padding [1, 2, 3, 4] with 2 elements on\n both sides in symmetric mode will result in\n [2, 1, 1, 2, 3, 4, 4, 3]\n \"\"\"\n\n def _pad_masks(self, results: dict) -> None:\n \"\"\"Pad masks according to ``results['pad_shape']``.\"\"\"\n if results.get('gt_masks', None) is not None:\n pad_val = self.pad_val.get('masks', 0)\n pad_shape = results['pad_shape'][:2]\n results['gt_masks'] = results['gt_masks'].pad(\n pad_shape, pad_val=pad_val)\n\n def transform(self, results: dict) -> dict:\n \"\"\"Call function to pad images, masks, semantic segmentation maps.\n\n Args:\n results (dict): Result dict from loading pipeline.\n\n Returns:\n dict: Updated result dict.\n \"\"\"\n self._pad_img(results)\n self._pad_seg(results)\n self._pad_masks(results)\n return results" }, { "identifier": "RandomCrop", "path": "mmdet/datasets/transforms/transforms.py", "snippet": "class RandomCrop(BaseTransform):\n \"\"\"Random crop the image & bboxes & masks.\n\n The absolute ``crop_size`` is sampled based on ``crop_type`` and\n ``image_size``, then the cropped results are generated.\n\n Required Keys:\n\n - img\n - gt_bboxes (BaseBoxes[torch.float32]) (optional)\n - gt_bboxes_labels (np.int64) (optional)\n - gt_masks (BitmapMasks | PolygonMasks) (optional)\n - gt_ignore_flags (bool) (optional)\n - gt_seg_map (np.uint8) (optional)\n\n Modified Keys:\n\n - img\n - img_shape\n - gt_bboxes (optional)\n - gt_bboxes_labels (optional)\n - gt_masks (optional)\n - gt_ignore_flags (optional)\n - gt_seg_map (optional)\n - gt_instances_ids (options, only used in MOT/VIS)\n\n Added Keys:\n\n - homography_matrix\n\n Args:\n crop_size (tuple): The relative ratio or absolute pixels of\n (width, height).\n crop_type (str, optional): One of \"relative_range\", \"relative\",\n \"absolute\", \"absolute_range\". \"relative\" randomly crops\n (h * crop_size[0], w * crop_size[1]) part from an input of size\n (h, w). \"relative_range\" uniformly samples relative crop size from\n range [crop_size[0], 1] and [crop_size[1], 1] for height and width\n respectively. \"absolute\" crops from an input with absolute size\n (crop_size[0], crop_size[1]). \"absolute_range\" uniformly samples\n crop_h in range [crop_size[0], min(h, crop_size[1])] and crop_w\n in range [crop_size[0], min(w, crop_size[1])].\n Defaults to \"absolute\".\n allow_negative_crop (bool, optional): Whether to allow a crop that does\n not contain any bbox area. Defaults to False.\n recompute_bbox (bool, optional): Whether to re-compute the boxes based\n on cropped instance masks. Defaults to False.\n bbox_clip_border (bool, optional): Whether clip the objects outside\n the border of the image. Defaults to True.\n\n Note:\n - If the image is smaller than the absolute crop size, return the\n original image.\n - The keys for bboxes, labels and masks must be aligned. That is,\n ``gt_bboxes`` corresponds to ``gt_labels`` and ``gt_masks``, and\n ``gt_bboxes_ignore`` corresponds to ``gt_labels_ignore`` and\n ``gt_masks_ignore``.\n - If the crop does not contain any gt-bbox region and\n ``allow_negative_crop`` is set to False, skip this image.\n \"\"\"\n\n def __init__(self,\n crop_size: tuple,\n crop_type: str = 'absolute',\n allow_negative_crop: bool = False,\n recompute_bbox: bool = False,\n bbox_clip_border: bool = True) -> None:\n if crop_type not in [\n 'relative_range', 'relative', 'absolute', 'absolute_range'\n ]:\n raise ValueError(f'Invalid crop_type {crop_type}.')\n if crop_type in ['absolute', 'absolute_range']:\n assert crop_size[0] > 0 and crop_size[1] > 0\n assert isinstance(crop_size[0], int) and isinstance(\n crop_size[1], int)\n if crop_type == 'absolute_range':\n assert crop_size[0] <= crop_size[1]\n else:\n assert 0 < crop_size[0] <= 1 and 0 < crop_size[1] <= 1\n self.crop_size = crop_size\n self.crop_type = crop_type\n self.allow_negative_crop = allow_negative_crop\n self.bbox_clip_border = bbox_clip_border\n self.recompute_bbox = recompute_bbox\n\n def _crop_data(self, results: dict, crop_size: Tuple[int, int],\n allow_negative_crop: bool) -> Union[dict, None]:\n \"\"\"Function to randomly crop images, bounding boxes, masks, semantic\n segmentation maps.\n\n Args:\n results (dict): Result dict from loading pipeline.\n crop_size (Tuple[int, int]): Expected absolute size after\n cropping, (h, w).\n allow_negative_crop (bool): Whether to allow a crop that does not\n contain any bbox area.\n\n Returns:\n results (Union[dict, None]): Randomly cropped results, 'img_shape'\n key in result dict is updated according to crop size. None will\n be returned when there is no valid bbox after cropping.\n \"\"\"\n assert crop_size[0] > 0 and crop_size[1] > 0\n img = results['img']\n margin_h = max(img.shape[0] - crop_size[0], 0)\n margin_w = max(img.shape[1] - crop_size[1], 0)\n offset_h, offset_w = self._rand_offset((margin_h, margin_w))\n crop_y1, crop_y2 = offset_h, offset_h + crop_size[0]\n crop_x1, crop_x2 = offset_w, offset_w + crop_size[1]\n\n # Record the homography matrix for the RandomCrop\n homography_matrix = np.array(\n [[1, 0, -offset_w], [0, 1, -offset_h], [0, 0, 1]],\n dtype=np.float32)\n if results.get('homography_matrix', None) is None:\n results['homography_matrix'] = homography_matrix\n else:\n results['homography_matrix'] = homography_matrix @ results[\n 'homography_matrix']\n\n # crop the image\n img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]\n img_shape = img.shape\n results['img'] = img\n results['img_shape'] = img_shape[:2]\n\n # crop bboxes accordingly and clip to the image boundary\n if results.get('gt_bboxes', None) is not None:\n bboxes = results['gt_bboxes']\n bboxes.translate_([-offset_w, -offset_h])\n if self.bbox_clip_border:\n bboxes.clip_(img_shape[:2])\n valid_inds = bboxes.is_inside(img_shape[:2]).numpy()\n # If the crop does not contain any gt-bbox area and\n # allow_negative_crop is False, skip this image.\n if (not valid_inds.any() and not allow_negative_crop):\n return None\n\n results['gt_bboxes'] = bboxes[valid_inds]\n\n if results.get('gt_ignore_flags', None) is not None:\n results['gt_ignore_flags'] = \\\n results['gt_ignore_flags'][valid_inds]\n\n if results.get('gt_bboxes_labels', None) is not None:\n results['gt_bboxes_labels'] = \\\n results['gt_bboxes_labels'][valid_inds]\n\n if results.get('gt_masks', None) is not None:\n results['gt_masks'] = results['gt_masks'][\n valid_inds.nonzero()[0]].crop(\n np.asarray([crop_x1, crop_y1, crop_x2, crop_y2]))\n if self.recompute_bbox:\n results['gt_bboxes'] = results['gt_masks'].get_bboxes(\n type(results['gt_bboxes']))\n\n # We should remove the instance ids corresponding to invalid boxes.\n if results.get('gt_instances_ids', None) is not None:\n results['gt_instances_ids'] = \\\n results['gt_instances_ids'][valid_inds]\n\n # crop semantic seg\n if results.get('gt_seg_map', None) is not None:\n results['gt_seg_map'] = results['gt_seg_map'][crop_y1:crop_y2,\n crop_x1:crop_x2]\n\n return results\n\n @cache_randomness\n def _rand_offset(self, margin: Tuple[int, int]) -> Tuple[int, int]:\n \"\"\"Randomly generate crop offset.\n\n Args:\n margin (Tuple[int, int]): The upper bound for the offset generated\n randomly.\n\n Returns:\n Tuple[int, int]: The random offset for the crop.\n \"\"\"\n margin_h, margin_w = margin\n offset_h = np.random.randint(0, margin_h + 1)\n offset_w = np.random.randint(0, margin_w + 1)\n\n return offset_h, offset_w\n\n @cache_randomness\n def _get_crop_size(self, image_size: Tuple[int, int]) -> Tuple[int, int]:\n \"\"\"Randomly generates the absolute crop size based on `crop_type` and\n `image_size`.\n\n Args:\n image_size (Tuple[int, int]): (h, w).\n\n Returns:\n crop_size (Tuple[int, int]): (crop_h, crop_w) in absolute pixels.\n \"\"\"\n h, w = image_size\n if self.crop_type == 'absolute':\n return min(self.crop_size[1], h), min(self.crop_size[0], w)\n elif self.crop_type == 'absolute_range':\n crop_h = np.random.randint(\n min(h, self.crop_size[0]),\n min(h, self.crop_size[1]) + 1)\n crop_w = np.random.randint(\n min(w, self.crop_size[0]),\n min(w, self.crop_size[1]) + 1)\n return crop_h, crop_w\n elif self.crop_type == 'relative':\n crop_w, crop_h = self.crop_size\n return int(h * crop_h + 0.5), int(w * crop_w + 0.5)\n else:\n # 'relative_range'\n crop_size = np.asarray(self.crop_size, dtype=np.float32)\n crop_h, crop_w = crop_size + np.random.rand(2) * (1 - crop_size)\n return int(h * crop_h + 0.5), int(w * crop_w + 0.5)\n\n @autocast_box_type()\n def transform(self, results: dict) -> Union[dict, None]:\n \"\"\"Transform function to randomly crop images, bounding boxes, masks,\n semantic segmentation maps.\n\n Args:\n results (dict): Result dict from loading pipeline.\n\n Returns:\n results (Union[dict, None]): Randomly cropped results, 'img_shape'\n key in result dict is updated according to crop size. None will\n be returned when there is no valid bbox after cropping.\n \"\"\"\n image_size = results['img'].shape[:2]\n crop_size = self._get_crop_size(image_size)\n results = self._crop_data(results, crop_size, self.allow_negative_crop)\n return results\n\n def __repr__(self) -> str:\n repr_str = self.__class__.__name__\n repr_str += f'(crop_size={self.crop_size}, '\n repr_str += f'crop_type={self.crop_type}, '\n repr_str += f'allow_negative_crop={self.allow_negative_crop}, '\n repr_str += f'recompute_bbox={self.recompute_bbox}, '\n repr_str += f'bbox_clip_border={self.bbox_clip_border})'\n return repr_str" }, { "identifier": "RandomFlip", "path": "mmdet/datasets/transforms/transforms.py", "snippet": "class RandomFlip(MMCV_RandomFlip):\n \"\"\"Flip the image & bbox & mask & segmentation map. Added or Updated keys:\n flip, flip_direction, img, gt_bboxes, and gt_seg_map. There are 3 flip\n modes:\n\n - ``prob`` is float, ``direction`` is string: the image will be\n ``direction``ly flipped with probability of ``prob`` .\n E.g., ``prob=0.5``, ``direction='horizontal'``,\n then image will be horizontally flipped with probability of 0.5.\n - ``prob`` is float, ``direction`` is list of string: the image will\n be ``direction[i]``ly flipped with probability of\n ``prob/len(direction)``.\n E.g., ``prob=0.5``, ``direction=['horizontal', 'vertical']``,\n then image will be horizontally flipped with probability of 0.25,\n vertically with probability of 0.25.\n - ``prob`` is list of float, ``direction`` is list of string:\n given ``len(prob) == len(direction)``, the image will\n be ``direction[i]``ly flipped with probability of ``prob[i]``.\n E.g., ``prob=[0.3, 0.5]``, ``direction=['horizontal',\n 'vertical']``, then image will be horizontally flipped with\n probability of 0.3, vertically with probability of 0.5.\n\n\n Required Keys:\n\n - img\n - gt_bboxes (BaseBoxes[torch.float32]) (optional)\n - gt_masks (BitmapMasks | PolygonMasks) (optional)\n - gt_seg_map (np.uint8) (optional)\n\n Modified Keys:\n\n - img\n - gt_bboxes\n - gt_masks\n - gt_seg_map\n\n Added Keys:\n\n - flip\n - flip_direction\n - homography_matrix\n\n\n Args:\n prob (float | list[float], optional): The flipping probability.\n Defaults to None.\n direction(str | list[str]): The flipping direction. Options\n If input is a list, the length must equal ``prob``. Each\n element in ``prob`` indicates the flip probability of\n corresponding direction. Defaults to 'horizontal'.\n \"\"\"\n\n def _record_homography_matrix(self, results: dict) -> None:\n \"\"\"Record the homography matrix for the RandomFlip.\"\"\"\n cur_dir = results['flip_direction']\n h, w = results['img'].shape[:2]\n\n if cur_dir == 'horizontal':\n homography_matrix = np.array([[-1, 0, w], [0, 1, 0], [0, 0, 1]],\n dtype=np.float32)\n elif cur_dir == 'vertical':\n homography_matrix = np.array([[1, 0, 0], [0, -1, h], [0, 0, 1]],\n dtype=np.float32)\n elif cur_dir == 'diagonal':\n homography_matrix = np.array([[-1, 0, w], [0, -1, h], [0, 0, 1]],\n dtype=np.float32)\n else:\n homography_matrix = np.eye(3, dtype=np.float32)\n\n if results.get('homography_matrix', None) is None:\n results['homography_matrix'] = homography_matrix\n else:\n results['homography_matrix'] = homography_matrix @ results[\n 'homography_matrix']\n\n @autocast_box_type()\n def _flip(self, results: dict) -> None:\n \"\"\"Flip images, bounding boxes, and semantic segmentation map.\"\"\"\n # flip image\n results['img'] = mmcv.imflip(\n results['img'], direction=results['flip_direction'])\n\n img_shape = results['img'].shape[:2]\n\n # flip bboxes\n if results.get('gt_bboxes', None) is not None:\n results['gt_bboxes'].flip_(img_shape, results['flip_direction'])\n\n # flip masks\n if results.get('gt_masks', None) is not None:\n results['gt_masks'] = results['gt_masks'].flip(\n results['flip_direction'])\n\n # flip segs\n if results.get('gt_seg_map', None) is not None:\n results['gt_seg_map'] = mmcv.imflip(\n results['gt_seg_map'], direction=results['flip_direction'])\n\n # record homography matrix for flip\n self._record_homography_matrix(results)" }, { "identifier": "Resize", "path": "mmdet/datasets/transforms/transforms.py", "snippet": "class Resize(MMCV_Resize):\n \"\"\"Resize images & bbox & seg.\n\n This transform resizes the input image according to ``scale`` or\n ``scale_factor``. Bboxes, masks, and seg map are then resized\n with the same scale factor.\n if ``scale`` and ``scale_factor`` are both set, it will use ``scale`` to\n resize.\n\n Required Keys:\n\n - img\n - gt_bboxes (BaseBoxes[torch.float32]) (optional)\n - gt_masks (BitmapMasks | PolygonMasks) (optional)\n - gt_seg_map (np.uint8) (optional)\n\n Modified Keys:\n\n - img\n - img_shape\n - gt_bboxes\n - gt_masks\n - gt_seg_map\n\n\n Added Keys:\n\n - scale\n - scale_factor\n - keep_ratio\n - homography_matrix\n\n Args:\n scale (int or tuple): Images scales for resizing. Defaults to None\n scale_factor (float or tuple[float]): Scale factors for resizing.\n Defaults to None.\n keep_ratio (bool): Whether to keep the aspect ratio when resizing the\n image. Defaults to False.\n clip_object_border (bool): Whether to clip the objects\n outside the border of the image. In some dataset like MOT17, the gt\n bboxes are allowed to cross the border of images. Therefore, we\n don't need to clip the gt bboxes in these cases. Defaults to True.\n backend (str): Image resize backend, choices are 'cv2' and 'pillow'.\n These two backends generates slightly different results. Defaults\n to 'cv2'.\n interpolation (str): Interpolation method, accepted values are\n \"nearest\", \"bilinear\", \"bicubic\", \"area\", \"lanczos\" for 'cv2'\n backend, \"nearest\", \"bilinear\" for 'pillow' backend. Defaults\n to 'bilinear'.\n \"\"\"\n\n def _resize_masks(self, results: dict) -> None:\n \"\"\"Resize masks with ``results['scale']``\"\"\"\n if results.get('gt_masks', None) is not None:\n if self.keep_ratio:\n results['gt_masks'] = results['gt_masks'].rescale(\n results['scale'])\n else:\n results['gt_masks'] = results['gt_masks'].resize(\n results['img_shape'])\n\n def _resize_bboxes(self, results: dict) -> None:\n \"\"\"Resize bounding boxes with ``results['scale_factor']``.\"\"\"\n if results.get('gt_bboxes', None) is not None:\n results['gt_bboxes'].rescale_(results['scale_factor'])\n if self.clip_object_border:\n results['gt_bboxes'].clip_(results['img_shape'])\n\n def _record_homography_matrix(self, results: dict) -> None:\n \"\"\"Record the homography matrix for the Resize.\"\"\"\n w_scale, h_scale = results['scale_factor']\n homography_matrix = np.array(\n [[w_scale, 0, 0], [0, h_scale, 0], [0, 0, 1]], dtype=np.float32)\n if results.get('homography_matrix', None) is None:\n results['homography_matrix'] = homography_matrix\n else:\n results['homography_matrix'] = homography_matrix @ results[\n 'homography_matrix']\n\n @autocast_box_type()\n def transform(self, results: dict) -> dict:\n \"\"\"Transform function to resize images, bounding boxes and semantic\n segmentation map.\n\n Args:\n results (dict): Result dict from loading pipeline.\n Returns:\n dict: Resized results, 'img', 'gt_bboxes', 'gt_seg_map',\n 'scale', 'scale_factor', 'height', 'width', and 'keep_ratio' keys\n are updated in result dict.\n \"\"\"\n if self.scale:\n results['scale'] = self.scale\n else:\n img_shape = results['img'].shape[:2]\n results['scale'] = _scale_size(img_shape[::-1], self.scale_factor)\n self._resize_img(results)\n self._resize_bboxes(results)\n self._resize_masks(results)\n self._resize_seg(results)\n self._record_homography_matrix(results)\n return results\n\n def __repr__(self) -> str:\n repr_str = self.__class__.__name__\n repr_str += f'(scale={self.scale}, '\n repr_str += f'scale_factor={self.scale_factor}, '\n repr_str += f'keep_ratio={self.keep_ratio}, '\n repr_str += f'clip_object_border={self.clip_object_border}), '\n repr_str += f'backend={self.backend}), '\n repr_str += f'interpolation={self.interpolation})'\n return repr_str" }, { "identifier": "YOLOXHSVRandomAug", "path": "mmdet/datasets/transforms/transforms.py", "snippet": "class YOLOXHSVRandomAug(BaseTransform):\n \"\"\"Apply HSV augmentation to image sequentially. It is referenced from\n https://github.com/Megvii-\n BaseDetection/YOLOX/blob/main/yolox/data/data_augment.py#L21.\n\n Required Keys:\n\n - img\n\n Modified Keys:\n\n - img\n\n Args:\n hue_delta (int): delta of hue. Defaults to 5.\n saturation_delta (int): delta of saturation. Defaults to 30.\n value_delta (int): delat of value. Defaults to 30.\n \"\"\"\n\n def __init__(self,\n hue_delta: int = 5,\n saturation_delta: int = 30,\n value_delta: int = 30) -> None:\n self.hue_delta = hue_delta\n self.saturation_delta = saturation_delta\n self.value_delta = value_delta\n\n @cache_randomness\n def _get_hsv_gains(self):\n hsv_gains = np.random.uniform(-1, 1, 3) * [\n self.hue_delta, self.saturation_delta, self.value_delta\n ]\n # random selection of h, s, v\n hsv_gains *= np.random.randint(0, 2, 3)\n # prevent overflow\n hsv_gains = hsv_gains.astype(np.int16)\n return hsv_gains\n\n def transform(self, results: dict) -> dict:\n img = results['img']\n hsv_gains = self._get_hsv_gains()\n img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype(np.int16)\n\n img_hsv[..., 0] = (img_hsv[..., 0] + hsv_gains[0]) % 180\n img_hsv[..., 1] = np.clip(img_hsv[..., 1] + hsv_gains[1], 0, 255)\n img_hsv[..., 2] = np.clip(img_hsv[..., 2] + hsv_gains[2], 0, 255)\n cv2.cvtColor(img_hsv.astype(img.dtype), cv2.COLOR_HSV2BGR, dst=img)\n\n results['img'] = img\n return results\n\n def __repr__(self):\n repr_str = self.__class__.__name__\n repr_str += f'(hue_delta={self.hue_delta}, '\n repr_str += f'saturation_delta={self.saturation_delta}, '\n repr_str += f'value_delta={self.value_delta})'\n return repr_str" } ]
from mmengine.config import read_base from .rtmdet_s_8xb32_300e_coco import * from mmcv.transforms.loading import LoadImageFromFile from mmcv.transforms.processing import RandomResize from mmdet.datasets.transforms.formatting import PackDetInputs from mmdet.datasets.transforms.loading import LoadAnnotations from mmdet.datasets.transforms.transforms import (CachedMixUp, CachedMosaic, Pad, RandomCrop, RandomFlip, Resize, YOLOXHSVRandomAug)
16,450
# Copyright (c) OpenMMLab. All rights reserved. # Please refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#a-pure-python-style-configuration-file-beta for more details. # noqa # mmcv >= 2.0.1 # mmengine >= 0.8.0 with read_base(): checkpoint = 'https://download.openmmlab.com/mmdetection/v3.0/rtmdet/cspnext_rsb_pretrain/cspnext-tiny_imagenet_600e.pth' # noqa model.update( dict( backbone=dict( deepen_factor=0.167, widen_factor=0.375, init_cfg=dict( type='Pretrained', prefix='backbone.', checkpoint=checkpoint)), neck=dict( in_channels=[96, 192, 384], out_channels=96, num_csp_blocks=1), bbox_head=dict(in_channels=96, feat_channels=96, exp_on_reg=False))) train_pipeline = [ dict(type=LoadImageFromFile, backend_args=backend_args), dict(type=LoadAnnotations, with_bbox=True), dict( type=CachedMosaic, img_scale=(640, 640), pad_val=114.0, max_cached_images=20, random_pop=False), dict( type=RandomResize, scale=(1280, 1280), ratio_range=(0.5, 2.0), resize_type=Resize, keep_ratio=True), dict(type=RandomCrop, crop_size=(640, 640)), dict(type=YOLOXHSVRandomAug),
# Copyright (c) OpenMMLab. All rights reserved. # Please refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#a-pure-python-style-configuration-file-beta for more details. # noqa # mmcv >= 2.0.1 # mmengine >= 0.8.0 with read_base(): checkpoint = 'https://download.openmmlab.com/mmdetection/v3.0/rtmdet/cspnext_rsb_pretrain/cspnext-tiny_imagenet_600e.pth' # noqa model.update( dict( backbone=dict( deepen_factor=0.167, widen_factor=0.375, init_cfg=dict( type='Pretrained', prefix='backbone.', checkpoint=checkpoint)), neck=dict( in_channels=[96, 192, 384], out_channels=96, num_csp_blocks=1), bbox_head=dict(in_channels=96, feat_channels=96, exp_on_reg=False))) train_pipeline = [ dict(type=LoadImageFromFile, backend_args=backend_args), dict(type=LoadAnnotations, with_bbox=True), dict( type=CachedMosaic, img_scale=(640, 640), pad_val=114.0, max_cached_images=20, random_pop=False), dict( type=RandomResize, scale=(1280, 1280), ratio_range=(0.5, 2.0), resize_type=Resize, keep_ratio=True), dict(type=RandomCrop, crop_size=(640, 640)), dict(type=YOLOXHSVRandomAug),
dict(type=RandomFlip, prob=0.5),
6
2023-11-30 08:58:00+00:00
24k
SEU-ProactiveSecurity-Group/MalPurifier
examples/amd_kde_test.py
[ { "identifier": "Dataset", "path": "core/defense/dataset.py", "snippet": "class Dataset(torch.utils.data.Dataset):\n def __init__(self, seed=0, device='cuda', feature_ext_args=None):\n \"\"\"\n 为机器学习模型学习构建数据集。\n \n :param seed: 随机种子\n :param device: 设备类型,'cuda' 或 'cpu'\n :param feature_ext_args: 提取特征的参数\n \"\"\"\n \n # 设置随机种子,并确保随机性在不同库之间是一致的\n self.seed = seed\n random.seed(self.seed)\n np.random.seed(self.seed)\n torch.manual_seed(self.seed)\n \n # 设置PyTorch的默认数据类型为float32\n torch.set_default_dtype(torch.float32)\n \n # 初始化简化类的临时数据存储\n self.temp_data = utils.SimplifyClass(Manager())\n \n # 设定使用的设备\n self.device = device\n\n # 根据提供的参数初始化特征提取器\n self.feature_ext_args = feature_ext_args\n if feature_ext_args is None:\n self.feature_extractor = Apk2features(config.get('metadata', 'naive_data_pool'),\n config.get('dataset', 'intermediate'))\n else:\n assert isinstance(feature_ext_args, dict)\n self.feature_extractor = Apk2features(config.get('metadata', 'naive_data_pool'),\n config.get('dataset', 'intermediate'),\n **feature_ext_args)\n\n # 分割数据集为训练、验证和测试集\n data_saving_path = os.path.join(config.get('dataset', 'intermediate'), 'dataset.idx')\n \n # 检查是否已保存了分割数据,且不需要更新\n if os.path.exists(data_saving_path) and (not self.feature_extractor.update):\n (self.train_dataset, self.validation_dataset, self.test_dataset) = utils.read_pickle(data_saving_path)\n\n # # 计算良性和恶意apk的数量\n # benign_train = np.sum(self.train_dataset[1] == 0)\n # malicious_train = np.sum(self.train_dataset[1] == 1)\n\n # benign_val = np.sum(self.validation_dataset[1] == 0)\n # malicious_val = np.sum(self.validation_dataset[1] == 1)\n\n # benign_test = np.sum(self.test_dataset[1] == 0)\n # malicious_test = np.sum(self.test_dataset[1] == 1)\n\n # # 打印数据量\n # total_data = len(self.train_dataset[0]) + len(self.validation_dataset[0]) + len(self.test_dataset[0])\n # print(f\"总数据量: {total_data}\")\n # print(f\"训练数据量: {len(self.train_dataset[0])} (良性: {benign_train}, 恶意: {malicious_train})\")\n # print(f\"验证数据量: {len(self.validation_dataset[0])} (良性: {benign_val}, 恶意: {malicious_val})\")\n # print(f\"测试数据量: {len(self.test_dataset[0])} (良性: {benign_test}, 恶意: {malicious_test})\")\n\n # 更新数据路径\n def path_tran(data_paths):\n return np.array(\n [os.path.join(config.get('metadata', 'naive_data_pool'),\n os.path.splitext(os.path.basename(name))[0] + self.feature_extractor.file_ext) for \n name in data_paths])\n\n self.train_dataset = (path_tran(self.train_dataset[0]), self.train_dataset[1])\n self.validation_dataset = (path_tran(self.validation_dataset[0]), self.validation_dataset[1])\n self.test_dataset = (path_tran(self.test_dataset[0]), self.test_dataset[1])\n else:\n # 预处理恶意软件和良性软件的APK文件,并获取其特征路径\n mal_feature_paths = self.apk_preprocess(config.get('dataset', 'malware_dir'))\n ben_feature_paths = self.apk_preprocess(config.get('dataset', 'benware_dir'))\n feature_paths = mal_feature_paths + ben_feature_paths\n \n # 根据恶意软件和良性软件的数量生成标签\n gt_labels = np.zeros((len(mal_feature_paths) + len(ben_feature_paths)), dtype=np.int32)\n gt_labels[:len(mal_feature_paths)] = 1\n \n # 根据特征路径和标签分割数据\n self.train_dataset, self.validation_dataset, self.test_dataset = self.data_split(feature_paths, gt_labels)\n \n # 保存分割后的数据\n utils.dump_pickle((self.train_dataset, self.validation_dataset, self.test_dataset), data_saving_path)\n\n # 获取特征词汇表和大小\n self.vocab, _1, _2 = self.feature_extractor.get_vocab(*self.train_dataset)\n self.vocab_size = len(self.vocab)\n \n # 获取非API的数量\n self.non_api_size = self.feature_extractor.get_non_api_size(self.vocab)\n \n # 获取类别数量\n self.n_classes = np.unique(self.train_dataset[1]).size\n\n\n def data_split(self, feature_paths, labels):\n \"\"\"\n 将数据分为训练、验证和测试集。\n\n :param feature_paths: 特征文件的路径列表。\n :param labels: 对应的标签列表。\n :return: (训练数据, 训练标签), (验证数据, 验证标签), (测试数据, 测试标签)\n \"\"\"\n \n # 确保特征文件路径数量与标签数量相同\n assert len(feature_paths) == len(labels)\n \n # 初始化训练、验证和测试集的文件名列表为None\n train_dn, validation_dn, test_dn = None, None, None\n \n # 定义数据集切分文件的路径\n data_split_path = os.path.join(config.get('dataset', 'dataset_dir'), 'tr_te_va_split.name')\n \n # 检查数据切分文件是否存在\n if os.path.exists(data_split_path):\n train_dn, val_dn, test_dn = utils.read_pickle(data_split_path)\n\n # 如果任何文件名列表为空\n if (train_dn is None) or (validation_dn is None) or (test_dn is None):\n # 从特征文件路径中提取文件名\n data_names = [os.path.splitext(os.path.basename(path))[0] for path in feature_paths]\n \n # 分割数据为训练和测试集,20%为测试集\n train_dn, test_dn = train_test_split(data_names, test_size=0.2, random_state=self.seed, shuffle=True)\n \n # 从训练集中进一步分割出验证集,25%为验证集\n train_dn, validation_dn = train_test_split(train_dn, test_size=0.25, random_state=self.seed, shuffle=True)\n \n # 将切分结果保存为pickle文件\n utils.dump_pickle((train_dn, validation_dn, test_dn), path=data_split_path)\n\n # 根据提供的文件名列表查询路径\n def query_path(_data_names):\n return np.array(\n [path for path in feature_paths if os.path.splitext(os.path.basename(path))[0] in _data_names])\n\n # 根据提供的文件名列表查询对应的指示器(布尔列表)\n def query_indicator(_data_names):\n return [True if os.path.splitext(os.path.basename(path))[0] in _data_names else False for path in\n feature_paths]\n\n # 查询训练、验证和测试数据的路径\n train_data = query_path(train_dn)\n val_data = query_path(validation_dn)\n test_data = query_path(test_dn)\n \n # 为确保数据与标签一致,随机打乱训练数据和标签\n random.seed(self.seed)\n random.shuffle(train_data)\n train_y = labels[query_indicator(train_dn)]\n random.seed(self.seed)\n random.shuffle(train_y)\n \n # 查询训练、验证和测试数据的标签\n val_y = labels[query_indicator(validation_dn)]\n test_y = labels[query_indicator(test_dn)]\n \n # 返回切分的数据和标签\n return (train_data, train_y), (val_data, val_y), (test_data, test_y)\n\n\n def apk_preprocess(self, apk_paths, labels=None, update_feature_extraction=False):\n \"\"\"\n APK 文件的预处理。\n \n :param apk_paths: APK文件路径列表。\n :param labels: APK文件对应的标签列表,可以为None。\n :param update_feature_extraction: 是否更新特征提取器的状态。\n :return: 处理后的特征路径,和可选的标签。\n \"\"\"\n \n # 保存特征提取器的当前更新状态\n old_status = self.feature_extractor.update\n \n # 将特征提取器的更新状态设置为提供的参数值\n self.feature_extractor.update = update_feature_extraction\n \n # 如果没有提供标签\n if labels is None:\n # 使用特征提取器从apk_paths中提取特征\n feature_paths = self.feature_extractor.feature_extraction(apk_paths)\n \n # 恢复特征提取器的原始状态\n self.feature_extractor.update = old_status\n \n # 返回特征路径\n return feature_paths\n else:\n # 确保apk文件的数量与标签的数量相匹配\n assert len(apk_paths) == len(labels), \\\n '不匹配的数据形状 {} vs. {}'.format(len(apk_paths), len(labels))\n \n # 使用特征提取器从apk_paths中提取特征\n feature_paths = self.feature_extractor.feature_extraction(apk_paths)\n \n labels_ = []\n for i, feature_path in enumerate(feature_paths):\n # 获取不带扩展名的文件名\n fname = os.path.splitext(os.path.basename(feature_path))[0]\n \n # 确保当前文件名在对应的apk路径中\n if fname in apk_paths[i]:\n # 添加对应的标签到labels_列表中\n labels_.append(labels[i])\n \n # 恢复特征提取器的原始状态\n self.feature_extractor.update = old_status\n \n # 返回特征路径和对应的标签\n return feature_paths, np.array(labels_)\n\n\n def feature_preprocess(self, feature_paths):\n raise NotImplementedError\n # self.feature_extractor.update_cg(feature_paths)\n\n\n def feature_api_rpst_sum(self, api_feat_representation_list):\n \"\"\"\n 对API表示进行求和\n :param api_feat_representation_list: 一个稀疏矩阵列表\n \"\"\"\n \n # 确保输入是一个列表\n assert isinstance(api_feat_representation_list, list), \"期望输入是一个列表。\"\n \n # 如果列表不为空\n if len(api_feat_representation_list) > 0:\n # 确保列表中的第一个元素是 csr_matrix 类型的稀疏矩阵\n assert isinstance(api_feat_representation_list[0], csr_matrix)\n else:\n # 如果列表为空,则返回一个全为0的矩阵\n return np.zeros(shape=(self.vocab_size - self.non_api_size, self.vocab_size - self.non_api_size),\n dtype=np.float)\n \n # 将第一个稀疏矩阵转为密集型矩阵,并转换为浮点类型\n adj_array = np.asarray(api_feat_representation_list[0].todense()).astype(np.float32)\n \n # 遍历列表中的其余稀疏矩阵\n for sparse_mat in api_feat_representation_list[1:]:\n # 将稀疏矩阵转为密集型矩阵,转换为浮点类型,并与之前的结果进行相加\n adj_array += np.asarray(sparse_mat.todense()).astype(np.float32)\n \n # 将最终结果中的所有值限制在[0,1]之间\n return np.clip(adj_array, a_min=0, a_max=1)\n\n\n def get_numerical_input(self, feature_path, label):\n \"\"\"\n loading features for given a feature path\n # results:\n # --->> mapping feature path to numerical representations\n # --->> features: 1d array, and a list of sparse matrices\n # --->> label: scalar\n \"\"\"\n feature_vector, label = self.feature_extractor.feature2ipt(feature_path, label,\n self.vocab,\n None)\n return feature_vector, label\n\n\n def get_input_producer(self, feature_paths, y, batch_size, name='train', use_cache=False):\n \"\"\"\n 获取输入生产器,返回一个 DataLoader 对象。\n \n :param feature_paths: 特征路径列表。\n :param y: 标签。\n :param batch_size: 每个批次的数据数量。\n :param name: 使用场景名称,默认为'train'。\n :param use_cache: 是否使用缓存,默认为False。\n :return: 返回一个 DataLoader 对象。\n \"\"\"\n \n # 定义 DataLoader 的参数\n params = {\n 'batch_size': batch_size,\n 'num_workers': self.feature_ext_args['proc_number'],\n 'shuffle': False\n }\n \n # 如果是训练过程,则使用用户设定的缓存值;否则,不使用缓存\n use_cache = use_cache if name == 'train' else False\n \n # 创建 DataLoader,它会使用自定义的 DatasetTorch 数据集对象\n # worker_init_fn 参数用于为每个工作线程设定一个随机种子,确保数据的打乱是随机的\n return torch.utils.data.DataLoader(\n DatasetTorch(feature_paths, y, self, name=name, use_cache=use_cache),\n worker_init_fn=lambda x: np.random.seed(torch.randint(0, 2**31, [1,])[0] + x),\n **params\n )\n\n\n def clear_up(self):\n self.temp_data.reset()\n\n @staticmethod\n def get_modification(adv_x, x, idx, sp=True):\n # 确认adv_x和x是numpy.ndarray类型或torch.Tensor类型的实例\n assert isinstance(adv_x, (np.ndarray, torch.Tensor))\n assert isinstance(x, (np.ndarray, torch.Tensor))\n \n # 计算对抗样本和原始样本之间的差异\n x_mod = adv_x - x\n \n # 根据索引idx选择对应的元素\n if isinstance(x_mod, np.ndarray):\n x_mod = np.array([x_mod[i, idx[i]] for i in range(x.shape[0])])\n else:\n x_mod = torch.stack([x_mod[i, idx[i]] for i in range(x.shape[0])])\n \n # 判断是否需要转为稀疏表示\n if sp:\n # 如果x_mod是torch.Tensor,那么将其转换为稀疏表示并移到cpu上\n # 如果x_mod是numpy.ndarray,那么先将其转换为torch.Tensor,然后转换为稀疏表示并移到cpu上\n if isinstance(x_mod, torch.Tensor):\n return x_mod.to_sparse().cpu().unbind(dim=0)\n else:\n return torch.tensor(x_mod, dtype=torch.int).to_sparse().cpu().unbind(dim=0)\n else:\n # 如果不需要转为稀疏表示,那么直接将其移到cpu上或者分割为numpy数组\n if isinstance(x_mod, torch.Tensor):\n return x_mod.cpu().unbind(dim=0)\n else:\n return np.split(x_mod, x_mod.shape[0], axis=0)\n\n\n @staticmethod\n def modification_integ(x_mod_integrated, x_mod):\n # 确认x_mod_integrated和x_mod是列表类型的实例\n assert isinstance(x_mod_integrated, list) and isinstance(x_mod, list)\n \n # 如果x_mod_integrated为空列表,则返回x_mod\n if len(x_mod_integrated) == 0:\n return x_mod\n \n # 确认x_mod_integrated和x_mod的长度相同\n assert len(x_mod_integrated) == len(x_mod)\n \n # 遍历x_mod和x_mod_integrated中的每个元素\n for i in range(len(x_mod)):\n # 确认当前x_mod中的元素不在GPU上,\n # 因为在GPU上的Tensor进行list相加操作的时候是列表拼接,而在CPU上则是张量之间的加法\n assert not x_mod[i].is_cuda\n \n # 更新x_mod_integrated中的元素\n x_mod_integrated[i] += x_mod[i]\n \n # 返回更新后的x_mod_integrated\n return x_mod_integrated" }, { "identifier": "MalwareDetectionDNN", "path": "core/defense/md_dnn.py", "snippet": "class MalwareDetectionDNN(nn.Module):\n def __init__(self, input_size, n_classes, device='cpu', name='DNN', **kwargs):\n \"\"\"\n 初始化恶意软件检测器\n\n 参数:\n ----------\n @param input_size: 整数,输入向量的维度数量。\n @param n_classes: 整数,表示分类的数量,例如二分类问题中n=2。\n @param device: 字符串,可以是'cpu'或'cuda',表示模型应该在CPU还是GPU上运行。\n @param name: 字符串,用于命名模型。\n \"\"\"\n super(MalwareDetectionDNN, self).__init__() # 调用父类初始化\n self.input_size = input_size # 定义输入尺寸\n self.n_classes = n_classes # 定义分类数量\n self.device = device # 定义运行设备\n self.name = name # 定义模型名称\n\n self.parse_args(**kwargs) # 解析额外参数\n\n self.dense_layers = [] # 初始化一个空的密集层列表\n \n # 检查是否至少有一个隐藏层\n if len(self.dense_hidden_units) >= 1:\n # 添加第一个密集层\n self.dense_layers.append(nn.Linear(self.input_size, self.dense_hidden_units[0]))\n else:\n # 如果没有隐藏层,抛出异常\n raise ValueError(\"Expect at least one hidden layer.\")\n\n # 为每一对连续的隐藏单元添加一个密集层\n for i in range(len(self.dense_hidden_units[0:-1])):\n self.dense_layers.append(nn.Linear(self.dense_hidden_units[i], \n self.dense_hidden_units[i + 1]))\n \n # 添加最后一个连接到输出层的密集层\n self.dense_layers.append(nn.Linear(self.dense_hidden_units[-1], self.n_classes))\n \n # 将密集层添加到模型中以进行跟踪\n for idx_i, dense_layer in enumerate(self.dense_layers):\n self.add_module('nn_model_layer_{}'.format(idx_i), dense_layer)\n\n # 根据参数选择使用SELU或ReLU激活函数\n if self.smooth:\n self.activation_func = F.selu # 使用SELU激活函数\n else:\n self.activation_func = F.relu # 使用ReLU激活函数\n\n # 定义模型的保存路径\n self.model_save_path = path.join(config.get('experiments', 'md_dnn') + '_' + self.name,\n 'model.pth')\n \n # 日志中打印模型的结构信息\n logger.info('========================================dnn model architecture===============================')\n logger.info(self)\n logger.info('===============================================end==========================================')\n\n\n def parse_args(self,\n dense_hidden_units=None,\n dropout=0.6,\n alpha_=0.2,\n smooth=False,\n **kwargs\n ):\n \"\"\"\n 解析并设置网络的超参数。\n\n 参数:\n ----------\n dense_hidden_units : list, 可选\n 网络中每个隐藏层的单元数。如果没有指定,则默认为两个隐藏层,每层200个单元。\n dropout : float, 可选\n dropout正则化的比率,默认为0.6。\n alpha_ : float, 可选\n 某些激活函数的参数,默认为0.2。\n smooth : bool, 可选\n 是否使用平滑的激活函数,默认为False。\n **kwargs : dict\n 其他超参数。\n \"\"\"\n\n # 如果用户没有指定隐藏层,使用默认的配置\n if dense_hidden_units is None:\n self.dense_hidden_units = [200, 200]\n # 如果用户指定了一个列表,使用它\n elif isinstance(dense_hidden_units, list):\n self.dense_hidden_units = dense_hidden_units\n # 否则抛出一个异常\n else:\n raise TypeError(\"Expect a list of hidden units.\")\n\n # 设置dropout, alpha和smooth参数\n self.dropout = dropout\n self.alpha_ = alpha_\n self.smooth = smooth\n\n # 从kwargs中获取并设置proc_number\n self.proc_number = kwargs.get('proc_number', None) # 如果不存在,则返回None\n\n # 如果还有其他参数,记录警告,因为这些参数可能是未知的\n if len(kwargs) > 0:\n logger.warning(\"Unknown hyper-parameters {}\".format(str(kwargs)))\n\n\n def forward(self, x):\n \"\"\"\n 使输入数据 x 通过神经网络\n \n 参数\n ----------\n @param x: 2D张量,特征表示\n \"\"\"\n # 遍历神经网络的每一层,除了最后一层\n for dense_layer in self.dense_layers[:-1]:\n x = self.activation_func(dense_layer(x)) # 使用激活函数处理每一层的输出\n\n # 对处理过的数据进行 dropout 操作,用于防止过拟合\n latent_representation = F.dropout(x, self.dropout, training=self.training)\n \n # 用最后一层进行处理,得到logits(未归一化的预测或分类得分)\n logits = self.dense_layers[-1](latent_representation)\n return logits\n\n def inference(self, test_data_producer):\n \"\"\"\n 进行模型推理,获得预测的置信度和真实标签\n \n 参数\n ----------\n @param test_data_producer: 数据生产者或数据加载器,用于产生测试数据\n \n 返回值\n ----------\n 返回预测的置信度和真实标签\n \"\"\"\n confidences = [] # 存储每批数据的预测置信度\n gt_labels = [] # 存储每批数据的真实标签\n self.eval() # 设置模型为评估模式\n\n # 使用torch.no_grad()来告诉PyTorch不要在推理过程中计算梯度\n with torch.no_grad():\n # 遍历每一批测试数据\n for x, y in test_data_producer:\n # 将数据转移到指定的设备(CPU或GPU)并调整数据类型\n x, y = utils.to_device(x.double(), y.long(), self.device)\n # 得到每一批数据的logits\n logits = self.forward(x)\n # 使用softmax函数得到每一批数据的置信度,并将其添加到confidences列表中\n confidences.append(F.softmax(logits, dim=-1))\n # 将每一批数据的真实标签添加到gt_labels列表中\n gt_labels.append(y)\n\n # 将所有批次的置信度垂直堆叠成一个张量\n confidences = torch.vstack(confidences)\n # 将所有批次的真实标签连接成一个张量\n gt_labels = torch.cat(gt_labels, dim=0)\n \n return confidences, gt_labels\n\n def inference_dae(self, test_data_producer):\n \"\"\"\n 进行模型推理,获得预测的置信度和真实标签\n \n 参数\n ----------\n @param test_data_producer: 数据生产者或数据加载器,用于产生测试数据\n \n 返回值\n ----------\n 返回预测的置信度和真实标签\n \"\"\"\n confidences = [] # 存储每批数据的预测置信度\n gt_labels = [] # 存储每批数据的真实标签\n self.eval() # 设置模型为评估模式\n\n # 使用torch.no_grad()来告诉PyTorch不要在推理过程中计算梯度\n with torch.no_grad():\n # 遍历每一批测试数据\n for x, y in test_data_producer:\n # 将数据转移到指定的设备(CPU或GPU)并调整数据类型\n x, y = utils.to_device(x.double(), y.long(), self.device)\n # 得到每一批数据的logits\n logits = self.forward(x)\n # 使用softmax函数得到每一批数据的置信度,并将其添加到confidences列表中\n confidences.append(F.softmax(logits, dim=-1))\n # 将每一批数据的真实标签添加到gt_labels列表中\n gt_labels.append(y)\n \n return confidences, gt_labels\n\n\n def get_important_attributes(self, test_data_producer, target_label=1):\n \"\"\"\n 使用集成梯度(Integrated Gradients)方法获取重要的属性/特征\n\n 参数\n ----------\n @param test_data_producer: 数据生产者或数据加载器,用于产生测试数据\n @param target_label: 目标标签,默认为1\n \n 返回值\n ----------\n 返回重要的属性/特征\n \"\"\"\n attributions = [] # 存储属性或特征的重要性得分\n gt_labels = [] # 存储真实标签\n\n # 定义一个使用集成梯度方法的包装器\n def _ig_wrapper(_x):\n logits = self.forward(_x)\n return F.softmax(logits, dim=-1)\n\n # 初始化集成梯度对象\n ig = IntegratedGradients(_ig_wrapper)\n\n # 遍历测试数据集\n for i, (x, y) in enumerate(test_data_producer):\n # 将数据和标签转移到指定的设备上\n x, y = utils.to_device(x.double(), y.long(), self.device)\n # 使x能够计算梯度\n x.requires_grad = True\n # 定义基线,用于集成梯度的计算\n baseline = torch.zeros_like(x, dtype=torch.double, device=self.device)\n # 计算属性的重要性\n attribution_bs = ig.attribute(x,\n baselines=baseline,\n target=target_label)\n # 将所有批次的属性垂直堆叠\n attribution = torch.hstack(attribution_bs)\n # 保存得到的属性重要性得分和真实标签\n attributions.append(attribution.clone().detach().cpu().numpy())\n gt_labels.append(y.clone().detach().cpu().numpy())\n # 将真实标签保存为.npy文件\n np.save('./labels', np.concatenate(gt_labels))\n \n return np.vstack(attributions)\n\n\n def inference_batch_wise(self, x):\n \"\"\"\n 仅支持恶意软件样本的批量推理\n \n 参数\n ----------\n @param x: 输入数据的张量\n \n 返回值\n ----------\n 返回推理的置信度和标签\n \"\"\"\n # 确保输入是一个张量\n assert isinstance(x, torch.Tensor)\n \n # 获得模型的输出\n logit = self.forward(x)\n \n # 返回每个样本的置信度和一个与logit形状相同的全1数组(表示恶意软件样本)\n return torch.softmax(logit, dim=-1).detach().cpu().numpy(), np.ones((logit.size()[0],))\n\n\n def predict(self, test_data_producer, indicator_masking=True):\n \"\"\"\n 预测标签并进行评估\n\n 参数\n --------\n @param test_data_producer: torch.DataLoader, 用于生成测试数据的数据加载器\n \"\"\"\n # 进行评估\n confidence, y_true = self.inference(test_data_producer)\n y_pred = confidence.argmax(1).cpu().numpy() # 预测标签\n y_true = y_true.cpu().numpy() # 真实标签\n \n # print(\"y_true.shape:\", y_true.shape)\n # print(\"y_pred.shape:\", y_pred.shape)\n \n # 使用sklearn的评估指标进行评估\n from sklearn.metrics import f1_score, accuracy_score, confusion_matrix, balanced_accuracy_score\n accuracy = accuracy_score(y_true, y_pred)\n b_accuracy = balanced_accuracy_score(y_true, y_pred)\n \n MSG = \"The accuracy on the test dataset is {:.5f}%\"\n logger.info(MSG.format(accuracy * 100))\n \n MSG = \"The balanced accuracy on the test dataset is {:.5f}%\"\n logger.info(MSG.format(b_accuracy * 100))\n\n # 检查数据中是否存在缺失的类别\n if np.any([np.all(y_true == i) for i in range(self.n_classes)]):\n logger.warning(\"class absent.\")\n return\n\n # 计算混淆矩阵\n tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n fpr = fp / float(tn + fp) # 计算假阳性率\n fnr = fn / float(tp + fn) # 计算假阴性率\n f1 = f1_score(y_true, y_pred, average='binary') # 计算F1分数\n\n print(\"Other evaluation metrics we may need:\")\n MSG = \"False Negative Rate (FNR) is {:.5f}%、False Positive Rate (FPR) is {:.5f}%, F1 score is {:.5f}%\"\n logger.info(MSG.format(fnr * 100, fpr * 100, f1 * 100))\n\n\n def customize_loss(self, logits, gt_labels, representation=None, mini_batch_idx=None):\n \"\"\"\n 自定义损失函数\n\n 参数\n --------\n @param logits: Tensor, 模型的输出\n @param gt_labels: Tensor, 真实的标签\n @param representation: Tensor, 可选参数,表示特征表示\n @param mini_batch_idx: Int, 可选参数,表示小批次的索引\n \n 返回值\n --------\n 返回交叉熵损失\n \"\"\"\n return F.cross_entropy(logits, gt_labels)\n\n\n def fit(self, train_data_producer, validation_data_producer, epochs=100, lr=0.005, weight_decay=0., weight_sampling=0.5, verbose=True):\n \"\"\"\n 训练恶意软件检测器,根据验证集上的交叉熵损失选择最佳模型。\n\n 参数\n ----------\n @param train_data_producer: 对象, 用于生成一批训练数据的迭代器\n @param validation_data_producer: 对象, 用于生成验证数据的迭代器\n @param epochs: 整数, 训练的周期数\n @param lr: 浮点数, Adam优化器的学习率\n @param weight_decay: 浮点数, 惩罚因子\n @param verbose: 布尔值, 是否显示详细的日志\n \"\"\"\n # 初始化优化器\n optimizer = optim.Adam(self.parameters(), lr=lr, weight_decay=weight_decay)\n best_avg_acc = 0. # 记录验证集上的最佳准确率\n best_epoch = 0 # 记录最佳准确率对应的周期\n total_time = 0. # 总的训练时间\n\n # 获取训练数据批次的数量\n nbatches = len(train_data_producer)\n \n # 进行指定次数的训练周期\n for i in range(epochs):\n # 设置模型为训练模式\n self.train()\n # 初始化列表用于保存每批数据的损失值和准确率\n losses, accuracies = [], []\n\n # 对每个训练数据批次进行遍历\n for idx_batch, (x_train, y_train) in enumerate(train_data_producer):\n # 将数据转移到指定的计算设备(例如GPU或CPU)\n x_train, y_train = utils.to_device(x_train.double(), y_train.long(), self.device)\n\n # 记录开始训练的时间\n start_time = time.time()\n\n # 清空之前累积的梯度\n optimizer.zero_grad() \n \n # 对输入数据进行前向传播\n logits = self.forward(x_train) \n \n # 根据模型的输出和真实标签计算损失\n loss_train = self.customize_loss(logits, y_train) \n\n # 对损失进行反向传播\n loss_train.backward()\n \n # 使用优化器更新模型参数\n optimizer.step()\n\n # 计算训练这批数据所花费的总时间\n total_time += time.time() - start_time\n \n # 计算这批数据上的准确率\n acc_train = (logits.argmax(1) == y_train).sum().item() / x_train.size()[0]\n \n # 将时间转换为分钟和秒\n mins, secs = int(total_time / 60), int(total_time % 60)\n \n # 将这批数据的损失和准确率加入到列表中\n losses.append(loss_train.item())\n accuracies.append(acc_train)\n\n # 如果开启了详细输出模式,显示当前训练进度和这批数据上的损失和准确率\n if verbose:\n logger.info(f'小批次: {i * nbatches + idx_batch + 1}/{epochs * nbatches} | 训练时间为 {mins:.0f} 分钟, {secs} 秒。')\n logger.info(f'训练损失(小批次级别): {losses[-1]:.4f} | 训练精度: {acc_train * 100:.2f}')\n\n\n self.eval() # 将模型设置为评估模式\n avg_acc_val = []\n\n with torch.no_grad(): # 确保在评估模式下不进行梯度的计算\n for x_val, y_val in validation_data_producer:\n # 将数据移动到指定设备(例如GPU或CPU)上,并确保数据的类型为双精度浮点数和长整型\n x_val, y_val = utils.to_device(x_val.double(), y_val.long(), self.device)\n \n # 使用模型进行前向传播,得到输出结果\n logits = self.forward(x_val)\n \n # 计算验证数据上的准确率\n acc_val = (logits.argmax(1) == y_val).sum().item() / x_val.size()[0]\n \n # 保存每一批验证数据的准确率\n avg_acc_val.append(acc_val)\n \n # 计算所有验证数据的平均准确率\n avg_acc_val = np.mean(avg_acc_val)\n\n # 如果当前周期的验证精度超过之前的最佳验证精度\n if avg_acc_val >= best_avg_acc:\n # 更新最佳验证精度\n best_avg_acc = avg_acc_val\n best_epoch = i\n \n # 检查模型保存路径是否存在,如果不存在,则创建\n if not path.exists(self.model_save_path):\n utils.mkdir(path.dirname(self.model_save_path))\n \n # 保存当前的模型参数\n torch.save(self.state_dict(), self.model_save_path)\n \n # 如果开启了详细输出模式,显示模型保存路径\n if verbose:\n print(f'模型保存在路径: {self.model_save_path}')\n\n # 如果开启了详细输出模式,显示训练损失、训练精度、验证精度和最佳验证精度\n if verbose:\n logger.info(f'训练损失(周期级别): {np.mean(losses):.4f} | 训练精度: {np.mean(accuracies) * 100:.2f}')\n logger.info(f'验证精度: {avg_acc_val * 100:.2f} | 最佳验证精度: {best_avg_acc * 100:.2f} 在第 {best_epoch} 个周期')\n\n def load(self):\n \"\"\"\n 从磁盘加载模型参数\n \"\"\"\n self.load_state_dict(torch.load(self.model_save_path))" }, { "identifier": "KernelDensityEstimation", "path": "core/defense/amd_kde.py", "snippet": "class KernelDensityEstimation(DetectorTemplate):\n \"\"\"\n 核密度估计在倒数第二层\n\n 参数\n -------------\n @param model, torch.nn.Module, 一个模型对象实例\n @param bandwidth, float, 高斯密度函数的方差\n @param n_classes, 整数, 类别数量\n @param ratio, float [0,1], 计算阈值的比例\n \"\"\"\n\n def __init__(self, model, n_centers=1000, bandwidth=20., n_classes=2, ratio=0.9):\n super(KernelDensityEstimation, self).__init__() # 调用父类的初始化函数\n assert isinstance(model, torch.nn.Module) # 确保提供的模型是torch.nn.Module类型\n \n self.model = model # 设置模型\n self.device = model.device # 设定设备\n self.n_centers = n_centers # 设置中心点数量\n self.bandwidth = bandwidth # 设置带宽\n self.n_classes = n_classes # 设置类别数量\n self.ratio = ratio # 设置比例\n self.gaussian_means = None # 初始化高斯均值为None\n\n # 初始化tau为一个不需要梯度的参数,大小为[n_classes,]\n self.tau = nn.Parameter(torch.zeros([self.n_classes, ], device=self.device), requires_grad=False)\n self.name = self.model.name # 设置名称为模型的名称\n self.model.load() # 加载模型\n \n # 设置模型保存路径\n self.model_save_path = path.join(config.get('experiments', 'amd_kde').rstrip('/') + '_' + self.name, 'model.pth')\n self.model.model_save_path = self.model_save_path\n\n\n def forward(self, x):\n # 对于模型中的密集层除了最后一个,都进行前向传播,并使用激活函数\n for dense_layer in self.model.dense_layers[:-1]:\n x = self.model.activation_func(dense_layer(x))\n \n # 获取最后一层的输出\n logits = self.model.dense_layers[-1](x) \n \n # print(\"logits.shape:\", logits.shape)\n \n if len(logits.shape) == 1:\n x_prob = self.forward_g(x, logits.argmax().detach()) # 适用于形状为[2]的logits\n else:\n x_prob = self.forward_g(x, logits.argmax(1).detach()) # 适用于形状为[10, 2]的logits\n \n return logits, x_prob\n\n\n def forward_f(self, x):\n # 对于模型中的密集层除了最后一个,都进行前向传播,并使用激活函数\n for dense_layer in self.model.dense_layers[:-1]:\n x = self.model.activation_func(dense_layer(x))\n logits = self.model.dense_layers[-1](x) # 获取最后一层的输出\n return logits, x\n\n\n # 这里,我们计算了每个样本和gaussian_means(高斯均值)之间的距离,\n # 然后使用核密度估计计算其概率。最后,我们返回与预测标签对应的密度值的负数。\n def forward_g(self, x_hidden, y_pred):\n \"\"\"\n 根据核密度估计对隐藏层表示计算其概率。\n\n 参数\n -----------\n @param x_hidden, torch.tensor, 节点的隐藏表示\n @param y_pred, torch.tensor, 预测结果\n \"\"\"\n \n # print(\"x_hidden shape:\", x_hidden.shape)\n # print(\"size = x_hidden.size()\", x_hidden.size())\n\n # 如果x_hidden只有一个维度, 我们增加一个新的维度来符合后面的操作\n if len(x_hidden.shape) == 1:\n x_hidden = x_hidden.unsqueeze(0)\n\n size = x_hidden.size()[0] # 获取x_hidden的第一维度大小,这应该是批次大小\n\n # 计算每个样本与高斯均值之间的距离,并平方\n dist = [torch.sum(torch.square(means.unsqueeze(dim=0) - x_hidden.unsqueeze(dim=1)), dim=-1) for means in\n self.gaussian_means]\n\n # 对计算得到的距离进行核密度估计\n kd = torch.stack([torch.mean(torch.exp(-d / self.bandwidth ** 2), dim=-1) for d in dist], dim=1)\n\n # 返回与预测标签对应的密度的负值\n return -1 * kd[torch.arange(size), y_pred]\n\n\n\n def get_threshold(self, validation_data_producer, ratio=None):\n \"\"\"\n 获取核密度估计的阈值\n :@param validation_data_producer: 对象,用于生成验证数据集的迭代器\n :@param ratio: 阈值计算所使用的比例\n \"\"\"\n\n # 如果提供了比例参数,则使用提供的值,否则使用类初始化时设定的比例值\n ratio = ratio if ratio is not None else self.ratio\n assert 0 <= ratio <= 1 # 确保比例在0到1之间\n\n self.eval() # 将模型设置为评估模式(不使用dropout等)\n probabilities = [] # 用于存储概率的列表\n gt_labels = [] # 用于存储真实标签的列表\n\n # 确保不计算梯度(提高计算效率,减少内存使用)\n with torch.no_grad():\n for x_val, y_val in validation_data_producer:\n # 将数据转为tensor,并移至指定设备(例如GPU)\n x_val, y_val = utils.to_tensor(x_val.double(), y_val.long(), self.device)\n logits, x_prob = self.forward(x_val) # 使用模型进行前向传播\n probabilities.append(x_prob) # 将概率值添加到列表中\n gt_labels.append(y_val) # 将真实标签添加到列表中\n\n # 将所有概率和标签的列表连接成一个大的tensor\n prob = torch.cat(probabilities, dim=0)\n gt_labels = torch.cat(gt_labels)\n\n # 对于每个类别,找出该类别下的密度值,并根据比例找出对应的阈值\n for i in range(self.n_classes):\n prob_x_y = prob[gt_labels == i]\n s, _ = torch.sort(prob_x_y) # 对密度值进行排序\n self.tau[i] = s[int((s.shape[0] - 1) * ratio)] # 根据比例选择阈值,并存入tau中\n\n\n def predict(self, test_data_producer, indicator_masking=True):\n \"\"\"\n 对测试数据进行预测并评估结果。\n :@param test_data_producer: 对象,用于生成测试数据的迭代器\n :@param indicator_masking: 布尔值,决定是否使用指示器进行筛选\n \"\"\"\n\n # 在测试数据上进行推理,并获取中心预测、概率值和真实标签\n y_cent, x_prob, y_true = self.inference(test_data_producer)\n \n # 获取最大概率的类别作为预测标签\n y_pred = y_cent.argmax(1).cpu().numpy()\n y_true = y_true.cpu().numpy()\n \n # 使用指示器进行筛选\n indicator_flag = self.indicator(x_prob, y_pred).cpu().numpy()\n if indicator_masking:\n # 如果开启指示器筛选,则只保留\"确定\"的样本\n flag_of_retaining = indicator_flag\n y_pred = y_pred[flag_of_retaining]\n y_true = y_true[flag_of_retaining]\n else:\n # 否则,将\"不确定\"的样本预测为类别1\n y_pred[~indicator_flag] = 1.\n\n logger.info('The indicator is turning on...')\n \n # 从sklearn库中导入多个评估指标\n from sklearn.metrics import f1_score, accuracy_score, confusion_matrix, balanced_accuracy_score\n \n # 计算准确率和平衡准确率\n accuracy = accuracy_score(y_true, y_pred)\n b_accuracy = balanced_accuracy_score(y_true, y_pred)\n logger.info(\"The accuracy on the test dataset is {:.5f}%\".format(accuracy * 100))\n logger.info(\"The balanced accuracy on the test dataset is {:.5f}%\".format(b_accuracy * 100))\n\n # 检查是否有缺失的类别\n if np.any([np.all(y_true == i) for i in range(self.n_classes)]):\n logger.warning(\"class absent.\")\n return\n\n # 计算混淆矩阵,并从中获取真正例、假正例、真负例和假负例的数量\n tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n fpr = fp / float(tn + fp) # 假正例率\n fnr = fn / float(tp + fn) # 假负例率\n f1 = f1_score(y_true, y_pred, average='binary') # F1分数\n\n print(\"Other evaluation metrics we may need:\")\n logger.info(\"False Negative Rate (FNR) is {:.5f}%, False Positive Rate (FPR) is {:.5f}%, F1 score is {:.5f}%\"\n .format(fnr * 100, fpr * 100, f1 * 100))\n\n\n def eval(self):\n self.model.eval()\n\n def inference(self, test_data_producer):\n \"\"\"\n 对给定的测试数据进行推理,获取类别中心、概率值和真实标签。\n :@param test_data_producer: 对象,用于生成测试数据的迭代器\n :return: 类别中心、概率值和真实标签\n \"\"\"\n\n y_cent, x_prob = [], [] # 用于存储类别中心和概率值的列表\n gt_labels = [] # 用于存储真实标签的列表\n \n # 将模型设置为评估模式,确保在推理时不进行权重更新或其他训练特定的操作\n self.eval()\n \n # 不进行梯度计算\n with torch.no_grad():\n for x, y in test_data_producer:\n # 转换数据类型并将其移动到正确的设备(例如,GPU)\n x, y = utils.to_tensor(x.double(), y.long(), self.device)\n \n # 使用模型进行前向传播\n logits_f, logits_g = self.forward(x)\n \n # 将结果添加到列表中\n y_cent.append(F.softmax(logits_f, dim=-1)) # 使用softmax函数计算类别中心\n x_prob.append(logits_g) # 将概率值添加到列表\n gt_labels.append(y) # 添加真实标签\n\n # 将列表内容连接成张量\n gt_labels = torch.cat(gt_labels, dim=0)\n y_cent = torch.cat(y_cent, dim=0)\n x_prob = torch.cat(x_prob, dim=0)\n \n return y_cent, x_prob, gt_labels\n\n def inference_batch_wise(self, x):\n \"\"\"\n 批量推理函数。对给定的输入张量进行推理,并返回softmax后的输出和概率值。\n :@param x: torch.Tensor,输入数据张量\n :return: softmax后的输出和概率值\n \"\"\"\n\n # 确保输入是一个torch张量\n assert isinstance(x, torch.Tensor)\n\n # 使用模型进行前向传播\n logits, x_prob = self.forward(x)\n \n # 返回softmax处理后的输出和概率值\n return torch.softmax(logits, dim=-1).detach().cpu().numpy(), x_prob.detach().cpu().numpy()\n\n\n def get_tau_sample_wise(self, y_pred=None):\n return self.tau[y_pred]\n\n def indicator(self, x_prob, y_pred=None):\n \"\"\"\n 指示器函数,根据概率值x_prob和预测标签y_pred,判断概率值是否小于等于给定样本的tau值。\n :@param x_prob: 概率值,可以是numpy数组或torch张量。\n :@param y_pred: 预测标签,应为非空。\n :return: 布尔数组或张量,表示x_prob中的每个值是否小于等于相应的tau值。\n \"\"\"\n \n # 确保提供了预测标签\n assert y_pred is not None\n \n # 如果x_prob是numpy数组\n if isinstance(x_prob, np.ndarray):\n # 转换x_prob为torch张量\n x_prob = torch.tensor(x_prob, device=self.device)\n # 检查x_prob中的每个值是否小于等于对应的tau值,并将结果返回为numpy数组\n return (x_prob <= self.get_tau_sample_wise(y_pred)).cpu().numpy()\n \n # 如果x_prob是torch张量\n elif isinstance(x_prob, torch.Tensor):\n # 检查x_prob中的每个值是否小于等于对应的tau值,并返回结果张量\n return x_prob <= self.get_tau_sample_wise(y_pred)\n \n else:\n # 如果x_prob既不是numpy数组也不是torch张量,则抛出类型错误\n raise TypeError(\"Tensor or numpy.ndarray are expected.\")\n\n # fit函数首先使用训练数据集生成器处理输入数据\n # 收集隐藏层的输出并为每个类别计算高斯均值。\n # 然后,它使用验证数据集生成器来计算和设置核密度估计的阈值,并将训练好的模型保存到磁盘。\n def fit(self, train_dataset_producer, val_dataset_producer):\n \"\"\"\n 根据给定的训练数据集训练并设置模型,同时为核密度估计确定阈值。\n \n :@param train_dataset_producer: 训练数据集的生成器。\n :@param val_dataset_producer: 验证数据集的生成器。\n \"\"\"\n\n # 用于存储隐藏层的输出和真实标签的列表\n X_hidden, gt_labels = [], []\n \n # 设置模型为评估模式\n self.eval()\n\n # 确保不进行梯度计算\n with torch.no_grad():\n # 对于train_dataset_producer中的每一批数据\n for x, y in train_dataset_producer:\n # 将输入数据和标签转换为torch张量,并将其移动到模型所在的设备上\n x, y = utils.to_tensor(x.double(), y.long(), self.device)\n\n # 使用模型的forward_f函数处理输入数据,并获取输出结果\n logits, x_hidden = self.forward_f(x)\n\n # 将隐藏层的输出和真实标签添加到对应的列表中\n X_hidden.append(x_hidden)\n gt_labels.append(y)\n\n # 检查每个类别的样本数量,确保每个类别都有足够的样本进行后续的处理\n _, count = torch.unique(torch.cat(gt_labels), return_counts=True)\n if torch.min(count) >= self.n_centers:\n break\n\n # 将收集的隐藏层输出和真实标签列表转换为torch张量\n X_hidden = torch.vstack(X_hidden)\n gt_labels = torch.cat(gt_labels)\n\n # 为每个类别计算高斯均值,并存储到self.gaussian_means中\n self.gaussian_means = [X_hidden[gt_labels == i][:self.n_centers] for i in range(self.n_classes)]\n\n # 使用验证数据集来计算和设置核密度估计的阈值\n self.get_threshold(val_dataset_producer)\n\n # 如果模型保存路径不存在,则创建相应的目录\n if not path.exists(self.model_save_path):\n utils.mkdir(path.dirname(self.model_save_path))\n \n # 将模型保存到磁盘\n self.save_to_disk()\n\n\n def load(self):\n \"\"\"\n 从磁盘加载保存的模型参数和其他重要数据。\n \"\"\"\n ckpt = torch.load(self.model_save_path) # 从给定的保存路径加载模型检查点\n self.gaussian_means = ckpt['gaussian_means'] # 从检查点中加载高斯均值\n self.tau = ckpt['tau'] # 从检查点中加载阈值\n self.model.load_state_dict(ckpt['base_model']) # 从检查点中加载基模型的参数\n\n def save_to_disk(self):\n \"\"\"\n 将模型参数和其他重要数据保存到磁盘。\n \"\"\"\n torch.save({\n 'gaussian_means': self.gaussian_means, # 保存高斯均值\n 'tau': self.tau, # 保存阈值\n 'base_model': self.model.state_dict() # 保存基模型的参数\n },\n self.model_save_path # 指定保存路径\n )" }, { "identifier": "save_args", "path": "tools/utils.py", "snippet": "def save_args(fout, args):\n if isinstance(args, str):\n dump_txt(args, fout, mode='w')\n elif isinstance(args, dict):\n args_str = build_kwargs(args.keys(), args)\n dump_txt(args_str, fout, mode='w')\n else:\n raise TypeError(\"Expected str or dict.\")" }, { "identifier": "dump_pickle", "path": "tools/utils.py", "snippet": "def dump_pickle(data, path, use_gzip=False):\n print(\"tr_te_va_split path:\", path)\n if not os.path.exists(os.path.dirname(path)):\n mkdir(os.path.dirname(path))\n if not use_gzip:\n with open(path, 'wb') as wr:\n pkl.dump(data, wr)\n else:\n with gzip.open(path, 'wb') as wr:\n pkl.dump(data, wr)\n return True" }, { "identifier": "config", "path": "config.py", "snippet": "def parser_config():" }, { "identifier": "utils", "path": "tools/utils.py", "snippet": "ENC_KEY = 'cab228a122d3486bac7fab148e8b5aba'\n MSG = \"No such directory or file {} exists!\".format(sample_dir)\n MSG = \"A directory or a list of paths are allowed!\"\ndef pool_initializer():\ndef retrive_files_set(base_dir, dir_ext, file_ext):\n def get_file_name(root_dir, file_ext):\ndef check_dir(sample_dir):\ndef dump_joblib(data, path):\ndef read_joblib(path):\ndef load_json(json_path):\ndef dump_json(obj_dict, file_path):\ndef dump_pickle(data, path, use_gzip=False):\ndef read_pickle(path, use_gzip=False):\ndef dump_pickle_frd_space(data, path):\ndef read_pickle_frd_space(path):\ndef dump_list_of_lists(data, path):\ndef read_list_of_lists(path):\ndef mkdir(target):\ndef read_txt(path, mode='r'):\ndef dump_txt(data_str, path, mode='w'):\ndef read_file_by_fileinput(file_path, inplace=True):\n def __init__(self, manager, use_cache=True):\n def is_cached(self, key):\n def reset(self):\n def get(self, key):\n def cache(self, key, img, lbl):\ndef build_kwargs(keys, arg_dict):\ndef inverse_kwargs(vars):\ndef save_args(fout, args):\ndef load_args(fout):\ndef get_group_args(args, args_parser, title):\ndef tensor_coo_sp_to_ivs(sparse_tensor):\ndef ivs_to_tensor_coo_sp(ivs, device='cpu'):\ndef sp_to_symmetric_sp(sparse_mx):\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\ndef to_tensor(feature_x=None, labels=None, device='cpu'):\n def _to_torch_tensor(mat):\ndef to_device(feature_x=None, labels=None, device='cpu'):\ndef psn(x_tensor, prob, lower_value=0., upper_value=1.):\n def __init__(self):\n def __call__(self, module):\ndef round_x(x, alpha=0.5):\ndef get_x0(x, rounding_threshold=0.5, is_sample=False):\ndef or_tensors(x_1, x_2):\ndef xor_tensors(x_1, x_2):\ndef get_mal_data(x_batch, y_batch):\ndef get_mal_ben_data(x_batch, y_batch):\ndef java_class_name2smali_name(cls):\ndef remove_duplicate(components):\ndef crypt_identifier(idf, seed=2345):\n def md5_transform():\ndef random_string(code):\n def sha1_transform():\ndef string_on_code(code):\n def md5_transform():\ndef random_name(seed=2345, code='abc'):\ndef apply_encryption(base_string):\ndef get_sha256(file_path):\nclass SimplifyClass:\nclass NonnegWeightConstraint(object):" } ]
import os.path as path import argparse from core.defense import Dataset from core.defense import MalwareDetectionDNN, KernelDensityEstimation from tools.utils import save_args, dump_pickle from config import config from tools import utils
15,744
from __future__ import absolute_import from __future__ import division from __future__ import print_function # 初始化一个 ArgumentParser 对象,用于解析命令行参数。描述为“核密度估计的参数” kde_argparse = argparse.ArgumentParser(description='arguments for kernel density estimation') # 添加一个命令行参数 --n_centers,类型为整数, 默认值为500,描述为“分布的数量” kde_argparse.add_argument('--n_centers', type=int, default=500, help='number of distributions') # 添加一个命令行参数 --bandwidth,类型为浮点数, 默认值为20.,描述为“高斯核的方差” kde_argparse.add_argument('--bandwidth', type=float, default=20., help='variance of Gaussian kernel') # 添加一个命令行参数 --ratio,类型为浮点数, 默认值为0.95,描述为“保留的验证示例的百分比” kde_argparse.add_argument('--ratio', type=float, default=0.9, help='the percentage of reminded validation examples') # 添加一个命令行参数 --cache,它是一个标志, 默认值为False,描述为“是否使用缓存数据” kde_argparse.add_argument('--cache', action='store_true', default=False, help='use cache data or not.') # 添加一个命令行参数 --mode,类型为字符串, 默认值为'train',可选值为 ['train', 'test'],描述为“学习模型或测试模型” kde_argparse.add_argument('--mode', type=str, default='train', choices=['train', 'test'], required=False, help='learn a model or test it.') # 添加一个命令行参数 --model_name,类型为字符串, 默认值为'xxxxxxxx-xxxxxx',描述为“模型的时间戳” kde_argparse.add_argument('--model_name', type=str, default='xxxxxxxx-xxxxxx', help='model timestamp.') def _main(): # 解析命令行参数 args = kde_argparse.parse_args() # 根据模型名称和配置文件确定保存的目录 save_dir = config.get('experiments', 'md_dnn') + '_' + args.model_name # 从保存目录中读取模型超参数 hp_params = utils.read_pickle(path.join(save_dir, 'hparam.pkl')) # 根据超参数中的proc_number加载数据集 dataset = Dataset(feature_ext_args={'proc_number': hp_params['proc_number']}) # 获取训练数据集的输入生成器 train_dataset_producer = dataset.get_input_producer(*dataset.train_dataset, batch_size=hp_params['batch_size'], name='train', use_cache=args.cache) # 获取验证数据集的输入生成器 val_dataset_producer = dataset.get_input_producer(*dataset.validation_dataset, batch_size=hp_params['batch_size'], name='val') # 获取测试数据集的输入生成器 test_dataset_producer = dataset.get_input_producer(*dataset.test_dataset, batch_size=hp_params['batch_size'], name='test') # 确保数据集只有两个类别(可能是恶意软件和非恶意软件) assert dataset.n_classes == 2 # 根据超参数决定使用CPU还是CUDA dv = 'cuda' if hp_params['cuda'] else 'cpu' # 初始化恶意软件检测的深度神经网络模型
from __future__ import absolute_import from __future__ import division from __future__ import print_function # 初始化一个 ArgumentParser 对象,用于解析命令行参数。描述为“核密度估计的参数” kde_argparse = argparse.ArgumentParser(description='arguments for kernel density estimation') # 添加一个命令行参数 --n_centers,类型为整数, 默认值为500,描述为“分布的数量” kde_argparse.add_argument('--n_centers', type=int, default=500, help='number of distributions') # 添加一个命令行参数 --bandwidth,类型为浮点数, 默认值为20.,描述为“高斯核的方差” kde_argparse.add_argument('--bandwidth', type=float, default=20., help='variance of Gaussian kernel') # 添加一个命令行参数 --ratio,类型为浮点数, 默认值为0.95,描述为“保留的验证示例的百分比” kde_argparse.add_argument('--ratio', type=float, default=0.9, help='the percentage of reminded validation examples') # 添加一个命令行参数 --cache,它是一个标志, 默认值为False,描述为“是否使用缓存数据” kde_argparse.add_argument('--cache', action='store_true', default=False, help='use cache data or not.') # 添加一个命令行参数 --mode,类型为字符串, 默认值为'train',可选值为 ['train', 'test'],描述为“学习模型或测试模型” kde_argparse.add_argument('--mode', type=str, default='train', choices=['train', 'test'], required=False, help='learn a model or test it.') # 添加一个命令行参数 --model_name,类型为字符串, 默认值为'xxxxxxxx-xxxxxx',描述为“模型的时间戳” kde_argparse.add_argument('--model_name', type=str, default='xxxxxxxx-xxxxxx', help='model timestamp.') def _main(): # 解析命令行参数 args = kde_argparse.parse_args() # 根据模型名称和配置文件确定保存的目录 save_dir = config.get('experiments', 'md_dnn') + '_' + args.model_name # 从保存目录中读取模型超参数 hp_params = utils.read_pickle(path.join(save_dir, 'hparam.pkl')) # 根据超参数中的proc_number加载数据集 dataset = Dataset(feature_ext_args={'proc_number': hp_params['proc_number']}) # 获取训练数据集的输入生成器 train_dataset_producer = dataset.get_input_producer(*dataset.train_dataset, batch_size=hp_params['batch_size'], name='train', use_cache=args.cache) # 获取验证数据集的输入生成器 val_dataset_producer = dataset.get_input_producer(*dataset.validation_dataset, batch_size=hp_params['batch_size'], name='val') # 获取测试数据集的输入生成器 test_dataset_producer = dataset.get_input_producer(*dataset.test_dataset, batch_size=hp_params['batch_size'], name='test') # 确保数据集只有两个类别(可能是恶意软件和非恶意软件) assert dataset.n_classes == 2 # 根据超参数决定使用CPU还是CUDA dv = 'cuda' if hp_params['cuda'] else 'cpu' # 初始化恶意软件检测的深度神经网络模型
model = MalwareDetectionDNN(dataset.vocab_size,
1
2023-11-27 02:00:23+00:00
24k
Matrixeigs/UncertaintyManagementInteroperablePowerTransportationSystems
TestCaseDistributionSystems/uc_mmgs_tess_stochastic.py
[ { "identifier": "case33", "path": "TestCaseDistributionSystems/test_cases/case33.py", "snippet": "def case33():\n \"\"\"Power flow data for 33 bus, 6 generator case.\n Please see L{caseformat} for details on the case file format.\n\n Based on data from ...\n\n Alsac, O. & Stott, B., I{\"Optimal Load Flow with Steady State Security\"},\n IEEE Transactions on Power Apparatus and Systems, Vol. PAS 93, No. 3,\n 1974, pp. 745-751.\n\n ... with branch parameters rounded to nearest 0.01, shunt values divided\n by 100 and shunt on bus 10 moved to bus 5, load at bus 5 zeroed out.\n Generator locations, costs and limits and bus areas were taken from ...\n\n Ferrero, R.W., Shahidehpour, S.M., Ramesh, V.C., I{\"Transaction analysis\n in deregulated power systems using game theory\"}, IEEE Transactions on\n Power Systems, Vol. 12, No. 3, Aug 1997, pp. 1340-1347.\n\n Generator Q limits were derived from Alsac & Stott, using their Pmax\n capacities. V limits and line |S| limits taken from Alsac & Stott.\n\n @return: Power flow data for 30 bus, 6 generator case.\n @see: U{http://www.pserc.cornell.edu/matpower/}\n \"\"\"\n ppc = {\"version\": '2'}\n\n ##----- Power Flow Data -----##\n ## system MVA base\n ppc[\"baseMVA\"] = 100.0\n\n ## bus data\n # bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin\n ppc[\"bus\"] = array([\n [1, 3, 0, 0, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [2, 1, 0.1, 0.06, 0, 0, 1, 1, 0, 12.66, 1, 1.1, 0.95],\n [3, 1, 0.09, 0.04, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [4, 1, 0.12, 0.08, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [5, 1, 0.06, 0.03, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [6, 1, 0.06, 0.02, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [7, 1, 0.2, 0.1, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [8, 1, 0.2, 0.1, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [9, 1, 0.06, 0.02, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [10, 1, 0.06, 0.02, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [11, 1, 0.045, 0.03, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [12, 1, 0.06, 0.035, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [13, 1, 0.06, 0.035, 0, 0, 2, 1, 0, 12.66, 1, 1.1, 0.95],\n [14, 1, 0.12, 0.08, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [15, 1, 0.06, 0.01, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [16, 1, 0.06, 0.02, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [17, 1, 0.06, 0.02, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [18, 1, 0.09, 0.04, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [19, 1, 0.09, 0.04, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [20, 1, 0.09, 0.04, 0, 0, 2, 1, 0, 12.66, 1, 1.05, 0.95],\n [21, 1, 0.09, 0.04, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [22, 2, 0.09, 0.04, 0, 0, 3, 1, 0, 12.66, 1, 1.1, 0.95],\n [23, 2, 0.09, 0.05, 0, 0, 2, 1, 0, 12.66, 1, 1.1, 0.95],\n [24, 1, 0.42, 0.20, 0, 0.04, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [25, 1, 0.42, 0.2, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [26, 1, 0.06, 0.025, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [27, 1, 0.06, 0.025, 0, 0, 3, 1, 0, 12.66, 1, 1.1, 0.95],\n [28, 1, 0.06, 0.02, 0, 0, 1, 1, 0, 12.66, 1, 1.05, 0.95],\n [29, 1, 0.12, 0.07, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [30, 1, 0.2, 0.6, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [31, 1, 0.15, 0.07, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [32, 1, 0.21, 0.1, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n [33, 1, 0.06, 0.04, 0, 0, 3, 1, 0, 12.66, 1, 1.05, 0.95],\n ])\n\n ## generator data\n # bus, Pg, Qg, Qmax, Qmin, Vg, mBase, status, Pmax, Pmin, Pc1, Pc2,\n # Qc1min, Qc1max, Qc2min, Qc2max, ramp_agc, ramp_10, ramp_30, ramp_q, apf, start-up time, shut-down time and initial condition!\n ppc[\"gen\"] = array([\n [1, 23.54, 0, 150, -20, 1, 100, 1, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 1],\n ])\n\n ## branch data\n # fbus, tbus, r, x, b, rateA, rateB, rateC, ratio, angle, status, angmin, angmax\n ppc[\"branch\"] = array([\n [1, 2, 0.057525912, 0.029324489, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [2, 3, 0.307595167, 0.15666764, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [3, 4, 0.228356656, 0.116299674, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [4, 5, 0.237777928, 0.121103899, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [5, 6, 0.510994811, 0.441115179, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [6, 7, 0.116798814, 0.386084969, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [7, 8, 0.44386045, 0.146684835, 0, 90, 90, 90, 0, 0, 1, -360, 360],\n [8, 9, 0.642643047, 0.461704714, 0, 70, 70, 70, 0, 0, 1, -360, 360],\n [9, 10, 0.651378001, 0.461704714, 0, 130, 130, 130, 0, 0, 1, -360, 360],\n [10, 11, 0.122663712, 0.040555144, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [11, 12, 0.233597628, 0.077241951, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [12, 13, 0.915922324, 0.720633708, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [13, 14, 0.337917936, 0.444796338, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [14, 15, 0.368739846, 0.328184702, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [15, 16, 0.465635443, 0.340039282, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [16, 17, 0.804239697, 1.073775422, 0, 65, 65, 65, 0, 0, 1, -360, 360],\n [17, 18, 0.456713311, 0.358133116, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [2, 19, 0.102323747, 0.097644308, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [19, 20, 0.938508419, 0.845668336, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [20, 21, 0.255497406, 0.298485858, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [21, 22, 0.442300637, 0.584805173, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [3, 23, 0.28151509, 0.192356167, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [23, 24, 0.560284909, 0.442425422, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [24, 25, 0.559037059, 0.43743402, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [6, 26, 0.126656834, 0.064513875, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [26, 27, 0.177319567, 0.090281989, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [27, 28, 0.660736881, 0.582559042, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [28, 29, 0.501760717, 0.437122057, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [29, 30, 0.316642084, 0.161284687, 0, 32, 32, 32, 0, 0, 1, -360, 360],\n [30, 31, 0.607952801, 0.600840053, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [31, 32, 0.193728802, 0.225798562, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [32, 33, 0.212758523, 0.330805188, 0, 16, 16, 16, 0, 0, 1, -360, 360],\n [7, 20, 1.2479, 1.2479, 0, 16, 16, 16, 0, 0, 0, -360, 360],\n [8, 14, 1.2479, 1.2479, 0, 16, 16, 16, 0, 0, 0, -360, 360],\n [11, 21, 1.2479, 1.2479, 0, 16, 16, 16, 0, 0, 0, -360, 360],\n [17, 32, 0.3120, 0.3120, 0, 65, 65, 65, 0, 0, 0, -360, 360],\n [24, 28, 0.3120, 0.3120, 0, 16, 16, 16, 0, 0, 0, -360, 360]\n ])\n\n ##----- OPF Data -----##\n ## area data\n # area refbus\n ppc[\"areas\"] = array([\n [1, 8],\n [2, 23],\n [3, 26],\n ])\n\n ## generator cost data\n # 1 startup shutdown n x1 y1 ... xn yn\n # 2 startup shutdown n c(n-1) ... c0\n ppc[\"gencost\"] = array([\n [0, 0, 0, 3, 0.0, 20, 0]\n ])\n\n return ppc" }, { "identifier": "micro_grid", "path": "TestCasesMicrogrids/test_cases/cases_unit_commitment.py", "snippet": "AC_PD = array([323.0284, 308.2374, 318.1886, 307.9809, 331.2170, 368.6539, 702.0040, 577.7045, 1180.4547, 1227.6240,\n 1282.9344, 1311.9738, 1268.9502, 1321.7436, 1323.9218, 1327.1464, 1386.9117, 1321.6387, 1132.0476,\n 1109.2701, 882.5698, 832.4520, 349.3568, 299.9920])\nDC_PD = array([287.7698, 287.7698, 287.7698, 287.7698, 299.9920, 349.3582, 774.4047, 664.0625, 1132.6996, 1107.7366,\n 1069.6837, 1068.9819, 1027.3295, 1096.3820, 1109.4778, 1110.7039, 1160.1270, 1078.7839, 852.2514,\n 791.5814, 575.4085, 551.1441, 349.3568, 299.992])\nDG = {\"PMIN\": 0,\n \"PMAX\": 5,\n \"QMIN\": -5,\n \"QMAX\": 5,\n \"COST_A\": 0.01,\n \"COST_B\": 0.5}\nUG = {\"PMIN\": -5,\n \"PMAX\": 5,\n \"QMIN\": -5,\n \"QMAX\": 5,\n \"COST\": Price_UG, } # The cost should be a profile\nESS = {\"PDC_MAX\": 5,\n \"PCH_MAX\": 5,\n \"EFF_DC\": 0.95,\n \"EFF_CH\": 0.95,\n \"E0\": 10,\n \"EMIN\": 5,\n \"EMAX\": 20, }\nBIC = {\"PMAX\": 5,\n \"QMAX\": 5,\n \"SMAX\": 5,\n \"EFF_AC2DC\": 0.9,\n \"EFF_DC2AC\": 0.9, }\nMG = {\"PMAX\": 5,\n \"PMIN\": -5,\n \"QMAX\": 5,\n \"QMIN\": -5\n }\nPD = {\"AC\": AC_PD / max(AC_PD),\n \"AC_MAX\": 5,\n \"DC\": DC_PD / max(DC_PD),\n \"DC_MAX\": 5}\nQD = {\"AC\": AC_PD / max(AC_PD),\n \"AC_MAX\": 5, }\nPV = {\"PMAX\": 0,\n \"COST\": 0}" }, { "identifier": "PBIC_AC2DC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PBIC_AC2DC = 4" }, { "identifier": "PG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PG = 0" }, { "identifier": "PESS_DC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PESS_DC = 8" }, { "identifier": "PBIC_DC2AC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PBIC_DC2AC = 5" }, { "identifier": "PUG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PUG = 2" }, { "identifier": "PESS_CH", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PESS_CH = 7" }, { "identifier": "PMESS", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "PMESS = 10 # Reactive power unit commitment of" }, { "identifier": "EESS", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "EESS = 9" }, { "identifier": "NX_MG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "NX_MG = 11" }, { "identifier": "QBIC", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "QBIC = 6" }, { "identifier": "QUG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "QUG = 3" }, { "identifier": "QG", "path": "TestCaseDistributionSystems/data_format/idx_MG.py", "snippet": "QG = 1" }, { "identifier": "DataBaseManagement", "path": "TestCaseDistributionSystems/database_management.py", "snippet": "class DataBaseManagement():\n\n def __init__(self, host=\"localhost\", user=\"root\", password=\"Ntu@1003\", db=\"mess\"):\n \"\"\"\n Initialized the database connection string\n :param host: host ip\n :param user: user name\n :param password: password\n :param db: database name\n :return\n \"\"\"\n self.db = pymysql.connect(host=host, user=user, password=password, db=db)\n\n def create_table(self, table_name, nl=32, nb=33, ng=6, nmg=3, nmes=3):\n \"\"\"\n Creat table name\n :param table_name:\n :param nb:\n :param nb:\n :param ng:\n :return: no return value\n \"\"\"\n cursor = self.db.cursor()\n sql = \"DROP TABLE IF EXISTS \"\n cursor.execute(sql + table_name)\n if table_name == \"distribution_networks\":\n sql_start = \"\"\"CREATE TABLE distribution_networks (\"\"\"\n sql = 'SCENARIO INT,\\n TIME INT NOT NULL,\\n '\n for i in range(nl):\n sql += \"PIJ{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(nl):\n sql += \"QIJ{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(nl):\n sql += \"IIJ{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(nb):\n sql += \"V{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(ng):\n sql += \"PG{0} DECIMAL(8,6),\\n \".format(i)\n for i in range(ng - 1):\n sql += \"QG{0} DECIMAL(8,6),\\n \".format(i)\n sql += \"QG{0} DECIMAL(8,6)\\n \".format(ng - 1)\n sql_end = \"\"\")\"\"\"\n elif table_name == \"micro_grids\":\n sql_start = \"\"\"CREATE TABLE micro_grids (\"\"\"\n sql = 'SCENARIO INT,\\n MG INT,\\n TIME INT,\\n '\n sql += 'PG DECIMAL(7,4),\\n QG DECIMAL(7,4),\\n PUG DECIMAL(7,4),\\n QUG DECIMAL(7,4),\\n '\n sql += 'PBIC_AC2DC DECIMAL(7,4),\\n PBIC_DC2AC DECIMAL(7,4),\\n QBIC DECIMAL(7,4),\\n PESS_CH DECIMAL(7,4),\\n '\n sql += 'PESS_DC DECIMAL(7,4),\\n EESS DECIMAL(7,4),\\n PMESS DECIMAL(7,4)'\n sql_end = \"\"\")\"\"\"\n elif table_name == \"mobile_energy_storage_systems\":\n sql_start = \"\"\"CREATE TABLE mobile_energy_storage_systems (\"\"\"\n sql = 'SCENARIO INT,\\n MESS INT,\\n TIME INT,\\n'\n for i in range(nmg):\n sql += \"PDC_MG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"PCH_MG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"EESS DECIMAL(7,4)\\n \"\n sql_end = \"\"\")\"\"\"\n elif table_name == \"first_stage_solutions\": # First-stage solution table\n sql_start = \"\"\"CREATE TABLE first_stage_solutions (\"\"\"\n sql = 'TIME INT,\\n'\n for i in range(ng):\n sql += \"PG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"RG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg - 1):\n sql += \"PG_MG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"RG_MG{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"IESS{0} INT,\\n \".format(i)\n sql += \"PESS_DC{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"PESS_CH{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"RESS{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"ESS{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"PG_MG{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"RG_MG{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"IESS{0} INT,\\n \".format(nmg - 1)\n sql += \"PESS_DC{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"PESS_CH{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"RESS{0} DECIMAL(7,4),\\n \".format(nmg - 1)\n sql += \"ESS{0} DECIMAL(7,4)\\n \".format(nmg - 1)\n sql_end = \"\"\")\"\"\"\n elif table_name == \"fisrt_stage_mess\": # First-stage solution table\n sql_start = \"\"\"CREATE TABLE fisrt_stage_mess (\"\"\"\n sql = 'MESS INT,\\n TIME INT,\\n'\n for i in range(nmg):\n sql += \"IDC_MG{0} INT,\\n \".format(i)\n for i in range(nmg):\n sql += \"PDC_MG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"PCH_MG{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"RMESS{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"MESS_F_STOP INT,\\n \"\n sql += \"MESS_T_STOP INT\\n \"\n sql_end = \"\"\")\"\"\"\n else:\n sql_start = \"\"\"CREATE TABLE scenarios (\"\"\"\n sql = 'SCENARIO INT,\\n WEIGHT DECIMAL(7,4),\\n TIME INT,\\n'\n for i in range(nb):\n sql += \"PD{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg):\n sql += \"PD_AC{0} DECIMAL(7,4),\\n \".format(i)\n for i in range(nmg - 1):\n sql += \"PD_DC{0} DECIMAL(7,4),\\n \".format(i)\n sql += \"PD_DC{0} DECIMAL(7,4)\\n\".format(nmg - 1)\n sql_end = \"\"\")\"\"\"\n\n cursor.execute(sql_start + sql + sql_end)\n cursor.close()\n\n def insert_data_ds(self, table_name, nl=32, nb=33, ng=6, scenario=0, time=0, pij=0, qij=0, lij=0, vi=0, pg=0, qg=0):\n \"\"\"\n Insert data into table_name\n :param table_name:\n :param nl:\n :param nb:\n :param ng:\n :param pij:\n :param qij:\n :param lij:\n :param vi:\n :param pg:\n :param qg:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,TIME,\"\n value = \"{0},{1},\".format(scenario, time)\n for i in range(nl):\n sql += \"PIJ{0},\".format(i)\n value += \"{0},\".format(pij[i])\n for i in range(nl):\n sql += \"QIJ{0},\".format(i)\n value += \"{0},\".format(qij[i])\n for i in range(nl):\n sql += \"IIJ{0},\".format(i)\n value += \"{0},\".format(lij[i])\n for i in range(nb):\n sql += \"V{0},\".format(i)\n value += \"{0},\".format(vi[i])\n for i in range(ng):\n sql += \"PG{0},\".format(i)\n value += \"{0},\".format(pg[i])\n for i in range(ng - 1):\n sql += \"QG{0},\".format(i)\n value += \"{0},\".format(qg[i])\n sql += \"QG{0}\".format(ng - 1)\n value += \"{0}\".format(qg[ng - 1])\n\n sql += \") VALUES (\" + value + \")\"\n\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_mg(self, table_name, scenario=0, time=0, mg=0, pg=0, qg=0, pug=0, qug=0, pbic_ac2dc=0, pbic_dc2ac=0,\n qbic=0, pess_ch=0, pess_dc=0, eess=0, pmess=0):\n \"\"\"\n insert microgrid data\n :param table_name:\n :param scenario:\n :param time:\n :param mg:\n :param pg:\n :param qg:\n :param pug:\n :param qug:\n :param pbic_ac2dc:\n :param pbic_dc2ac:\n :param qbic:\n :param pess_ch:\n :param pess_dc:\n :param eess:\n :param pmess:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,MG,TIME,\"\n value = \"{0},{1},{2},\".format(scenario, mg, time)\n sql += \"PG,QG,PUG,QUG,PBIC_AC2DC,PBIC_DC2AC,QBIC,PESS_CH,PESS_DC,EESS,PMESS\"\n value += \"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}\".format(pg, qg, pug, qug, pbic_ac2dc, pbic_dc2ac, qbic,\n pess_ch, pess_dc, eess, pmess)\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_first_stage_mess(self, table_name, time=0, mess=0, imess=[0, 0, 0], pmess_ch=[0, 0, 0],\n pmess_dc=[0, 0, 0], rmess=[0, 0, 0], mess_f_stop=0, mess_t_stop=0, nmg=3):\n \"\"\"\n insert mobile energy storage systems data in the first-stage\n :param table_name:\n :param scenario:\n :param time:\n :param mess:\n :param pess_ch:\n :param pess_dc:\n :param eess:\n :param nmg:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"MESS,TIME,\"\n value = \"{0},{1},\".format(mess, time)\n for i in range(nmg):\n sql += \"IDC_MG{0},\".format(i)\n value += \"{0},\".format(imess[i])\n for i in range(nmg):\n sql += \"PDC_MG{0},\".format(i)\n value += \"{0},\".format(pmess_dc[i])\n for i in range(nmg):\n sql += \"PCH_MG{0},\".format(i)\n value += \"{0},\".format(pmess_ch[i])\n for i in range(nmg):\n sql += \"RMESS{0},\".format(i)\n value += \"{0},\".format(rmess[i])\n sql += \"MESS_F_STOP,MESS_T_STOP\"\n value += \"{0},{1}\".format(mess_f_stop, mess_t_stop)\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_mess(self, table_name, scenario=0, time=0, mess=0, pmess_ch=[0, 0, 0], pmess_dc=[0, 0, 0],\n emess=0, nmg=3):\n \"\"\"\n insert mobile energy storage systems data\n :param table_name:\n :param scenario:\n :param time:\n :param mess:\n :param pess_ch:\n :param pess_dc:\n :param eess:\n :param nmg:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,MESS,TIME,\"\n value = \"{0},{1},{2},\".format(scenario, mess, time)\n for i in range(nmg):\n sql += \"PDC_MG{0},\".format(i)\n value += \"{0},\".format(pmess_dc[i])\n for i in range(nmg):\n sql += \"PCH_MG{0},\".format(i)\n value += \"{0},\".format(pmess_ch[i])\n sql += \"EESS\"\n value += \"{0}\".format(emess)\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_first_stage(self, table_name, time=0, ng=2, nmg=2, pg=[0, 0], rg=[0, 0], pg_mg=[0, 0],\n rg_mg=[0, 0], iess=[0, 0], pess_dc=[0, 0], pess_ch=[0, 0], ress=[0, 0], ess=[0, 0]):\n \"\"\"\n insert scenario data\n :param table_name:\n :param scenario:\n :param weight:\n :param time:\n :param nb:\n :param nmg:\n :param pd:\n :param pd_ac:\n :param pd_dc:\n :return:\n \"\"\"\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"TIME,\"\n value = \"{0},\".format(time)\n for i in range(ng):\n sql += \"PG{0},\".format(i)\n sql += \"RG{0},\".format(i)\n value += \"{0},\".format(pg[i])\n value += \"{0},\".format(rg[i])\n if nmg > 1:\n for i in range(nmg - 1):\n sql += \"PG_MG{0},\".format(i)\n sql += \"RG_MG{0},\".format(i)\n sql += \"IESS{0},\".format(i)\n sql += \"PESS_DC{0},\".format(i)\n sql += \"PESS_CH{0},\".format(i)\n sql += \"RESS{0},\".format(i)\n sql += \"ESS{0},\".format(i)\n value += \"{0},\".format(pg_mg[i])\n value += \"{0},\".format(rg_mg[i])\n value += \"{0},\".format(iess[i])\n value += \"{0},\".format(pess_dc[i])\n value += \"{0},\".format(pess_ch[i])\n value += \"{0},\".format(ress[i])\n value += \"{0},\".format(ess[i])\n sql += \"PG_MG{0},\".format(nmg - 1)\n sql += \"RG_MG{0},\".format(nmg - 1)\n sql += \"IESS{0},\".format(nmg - 1)\n sql += \"PESS_DC{0},\".format(nmg - 1)\n sql += \"PESS_CH{0},\".format(nmg - 1)\n sql += \"RESS{0},\".format(nmg - 1)\n sql += \"ESS{0}\".format(nmg - 1)\n value += \"{0},\".format(pg_mg[nmg - 1])\n value += \"{0},\".format(rg_mg[nmg - 1])\n value += \"{0},\".format(iess[nmg - 1])\n value += \"{0},\".format(pess_dc[nmg - 1])\n value += \"{0},\".format(pess_ch[nmg - 1])\n value += \"{0},\".format(ress[nmg - 1])\n value += \"{0}\".format(ess[nmg - 1])\n else:\n sql += \"PG_MG{0},\".format(nmg - 1)\n sql += \"RG_MG{0},\".format(nmg - 1)\n sql += \"IESS{0},\".format(nmg - 1)\n sql += \"PESS_DC{0},\".format(nmg - 1)\n sql += \"PESS_CH{0},\".format(nmg - 1)\n sql += \"RESS{0},\".format(nmg - 1)\n sql += \"ESS{0}\".format(nmg - 1)\n value += \"{0},\".format(pg_mg)\n value += \"{0},\".format(rg_mg)\n value += \"{0},\".format(iess)\n value += \"{0},\".format(pess_dc)\n value += \"{0},\".format(pess_ch)\n value += \"{0},\".format(ress)\n value += \"{0}\".format(ess)\n\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def insert_data_scenario(self, table_name, scenario=0, weight=0, time=0, nb=1, nmg=2, pd=[0, 0], pd_ac=[0, 0],\n pd_dc=[0, 0]):\n cursor = self.db.cursor()\n sql_start = \"INSERT INTO \" + table_name + \" (\"\n sql = \"SCENARIO,WEIGHT,TIME,\"\n value = \"{0},{1},{2},\".format(scenario, weight, time)\n for i in range(nb):\n sql += \"PD{0},\".format(i)\n value += \"{0},\".format(pd[i])\n for i in range(nmg):\n sql += \"PD_AC{0},\".format(i)\n value += \"{0},\".format(pd_ac[i])\n for i in range(nmg - 1):\n sql += \"PD_DC{0},\".format(i)\n value += \"{0},\".format(pd_dc[i])\n if nmg > 1:\n sql += \"PD_DC{0}\".format(nmg - 1)\n value += \"{0}\".format(pd_dc[nmg - 1])\n\n sql += \") VALUES (\" + value + \")\"\n cursor.execute(sql_start + sql)\n self.db.commit()\n cursor.close()\n\n def inquery_data_scenario(self, table_name, scenario=0, time=0):\n cursor = self.db.cursor()\n # sql = \"SELECT * FROM \" + table_name + \" ;\"\n sql = \"SELECT * FROM \" + table_name + \" WHERE SCENARIO={0} AND TIME={1};\".format(scenario, time)\n cursor.execute(sql)\n data = cursor.fetchall()\n n_data = len(data[0])\n\n temp = []\n for i in range(n_data): temp.append(float(data[0][i]))\n\n cursor.close()\n return temp" }, { "identifier": "ScenarioReduction", "path": "StochasticOptimization/scenario_reduction.py", "snippet": "class ScenarioReduction():\n def __init__(self):\n self.name = \"Scenario reduction\"\n\n def run(self, scenario, weight, n_reduced, power):\n \"\"\"\n\n :param scenario: A fan scenario tree, when more stage are considered, some merge operation can be implemented\n :param weight: Weight of each scenario\n :param n_reduced: Number of scenarios needs to be reduced\n :param power: The power in the distance calculation\n :return:\n \"\"\"\n n_scenario = scenario.shape[0] # number of original scenarios\n c = zeros((n_scenario, n_scenario))\n # Calculate the c matrix\n for i in range(n_scenario):\n for j in range(n_scenario):\n c[i, j] = linalg.norm((scenario[i, :] - scenario[j, :]), 2)\n c[i, j] = max([1, linalg.norm(scenario[i, :], power - 1), linalg.norm(scenario[j, :], power - 1)]) * \\\n c[i, j]\n\n J = arange(n_scenario) # The original index range\n J_reduced = array([])\n # Implement the iteration\n for n in range(n_reduced): # find the minimal distance\n print(\"The reduction is in process {0}\".format(n))\n c_n = inf * ones(n_scenario)\n c_n[J] = 0\n for u in J:\n # Delete the i-th distance\n J_temp = delete(J, where(J == u))\n for k in J_temp:\n c_k_j = delete(c[int(k)], J_temp)\n c_n[int(u)] += weight[int(k)] * min(c_k_j)\n u_i = argmin(c_n)\n J_reduced = append(J_reduced, u_i)\n J = delete(J, where(J == u_i))\n # Optimal redistribution\n p_s = weight.copy()\n p_s[J_reduced.astype(int)] = 0\n\n for i in J_reduced:\n c_temp = c[int(i), :]\n c_temp[J_reduced.astype(int)] = inf\n index = argmin(c_temp)\n p_s[index] += weight[int(i)]\n\n scenario_reduced = scenario[J.astype(int), :]\n weight_reduced = p_s[J.astype(int)]\n\n return scenario_reduced, weight_reduced" } ]
from TestCaseDistributionSystems.test_cases import case33 from TestCasesMicrogrids.test_cases.cases_unit_commitment import micro_grid from TestCasesTransportationSystems.test_cases import case3, TIME, LOCATION from numpy import zeros, shape, ones, diag, concatenate, eye from scipy.sparse import csr_matrix as sparse from scipy.sparse import hstack, vstack, lil_matrix from numpy import flatnonzero as find from numpy import array, tile, arange, random from pypower.idx_brch import F_BUS, T_BUS, BR_R, BR_X, RATE_A from pypower.idx_bus import PD, VMAX, VMIN, QD from pypower.idx_gen import GEN_BUS, PMAX, PMIN, QMAX, QMIN from pypower.ext2int import ext2int from Solvers.mixed_integer_quadratic_constrained_cplex import mixed_integer_quadratic_constrained_programming as miqcp from Solvers.mixed_integer_solvers_cplex import mixed_integer_linear_programming as milp from copy import deepcopy from TestCaseDistributionSystems.data_format.idx_MG import PBIC_AC2DC, PG, PESS_DC, PBIC_DC2AC, PUG, PESS_CH, \ PMESS, EESS, NX_MG, QBIC, QUG, QG from TestCaseDistributionSystems.database_management import DataBaseManagement from StochasticOptimization.scenario_reduction import ScenarioReduction
15,499
if t == 0: beq[t] = mess["E0"] else: Aeq[t, n_stops * 2 + t - 1] = -1 c = concatenate((ones(n_stops * 2) * mess["COST_OP"], zeros(T))) # sol = milp(c, Aeq=Aeq, beq=beq, A=None, b=None, xmin=lx, xmax=ux) model_tess = {"c": c, "q": zeros(nv), "lb": lb, "ub": ub, "vtypes": vtypes, "A": None, "b": None, "Aeq": Aeq, "beq": beq, "NX": nv, } return model_tess def scenario_generation_reduction(self, micro_grids, profile, pns, update=1, ns=2, ns_reduced=2, std=0.03, interval=0.05): """ Scenario generation function for the second-stage scheduling Stochastic variables include 1) loads in distribution networks, active loads for 2) AC bus and 3)DC bus. The assumption is that, the 1) loads in distribution networks follow normal distribution nb*T 2) loads for AC bus and DC bus follow uniform distribution nmg*T*4 3) update is the parameters to control the :return: """ T = self.T nmg = self.nmg nb = self.nb db_management = DataBaseManagement(host="localhost", user="root", password="Ntu@1003", db="mess") if update > 0: # 1) scenario generation bus_load = zeros((ns, nb * T)) mg_load = zeros((ns, nmg * T * 2)) weight = ones(ns) / ns for i in range(ns): for t in range(T): for j in range(nb): bus_load[i, t * nb + j] = pns["bus"][j, PD] * (1 + random.normal(0, std)) * profile[t] for j in range(nmg): mg_load[i, t * nmg + j] = micro_grids[j]["PD"]["AC"][t] * \ (1 + random.uniform(-interval, interval)) mg_load[i, nmg * T + t * nmg + j] = micro_grids[j]["PD"]["DC"][t] * \ (1 + random.uniform(-interval, interval)) # 2) scenario reduction scenario_reduction = ScenarioReduction() (scenario_reduced, weight_reduced) = \ scenario_reduction.run(scenario=concatenate([bus_load, mg_load], axis=1), weight=weight, n_reduced=ns_reduced, power=2) # 3) Store the data into database db_management.create_table("scenarios", nb=nb, nmg=nmg) for i in range(ns - ns_reduced): for t in range(T): db_management.insert_data_scenario("scenarios", scenario=i, weight=weight_reduced[i], time=t, nb=nb, pd=scenario_reduced[i, t * nb:(t + 1) * nb].tolist(), nmg=nmg, pd_ac=scenario_reduced[i, nb * T + t * nmg: nb * T + (t + 1) * nmg].tolist(), pd_dc=scenario_reduced[i, nb * T + nmg * T + t * nmg: nb * T + nmg * T + ( t + 1) * nmg].tolist()) else: # 4) if not updated, inquery the database scenario_reduced = zeros((ns - ns_reduced, nb * T + nmg * T * 2)) weight_reduced = zeros(ns - ns_reduced) for i in range(ns - ns_reduced): for t in range(T): data = db_management.inquery_data_scenario(table_name="scenarios", scenario=i, time=t) weight_reduced[i] = data[1] scenario_reduced[i, nb * t:nb * (t + 1)] = array(data[3:nb + 3]) scenario_reduced[i, nb * T + nmg * t:nb * T + nmg * (t + 1)] = array(data[nb + 3:nb + 3 + nmg]) scenario_reduced[i, nb * T + nmg * T + nmg * t:nb * T + nmg * T + nmg * (t + 1)] = \ array(data[nb + 3:nb + 3 + nmg]) # assert sum(weight_reduced) == 1, "The weight factor is not right!" # 4) return value ds_load_profile = scenario_reduced[:, 0:nb * T] mgs_load_profile = scenario_reduced[:, nb * T:] # profile_second_stage = zeros((ns, T)) microgrids_second_stage = [0] * (ns - ns_reduced) # for i in range(ns): # for j in range(T): # profile_second_stage[i, j] = profile[j] * (1 + 0.5 * random.random()) # for i in range(ns - ns_reduced): microgrids_second_stage[i] = deepcopy(micro_grids) for j in range(nmg): for t in range(T): microgrids_second_stage[i][j]["PD"]["AC"][t] = mgs_load_profile[i, t * nmg + j] microgrids_second_stage[i][j]["QD"]["AC"][t] = mgs_load_profile[i, t * nmg + j] * 0.2 microgrids_second_stage[i][j]["PD"]["DC"][t] = mgs_load_profile[i, T * nmg + t * nmg + j] return ds_load_profile, microgrids_second_stage, weight_reduced if __name__ == "__main__": # Distribution network information mpc = case33.case33() # Default test case load_profile = array( [0.17, 0.41, 0.63, 0.86, 0.94, 1.00, 0.95, 0.81, 0.59, 0.35, 0.14, 0.17, 0.41, 0.63, 0.86, 0.94, 1.00, 0.95, 0.81, 0.59, 0.35, 0.14, 0.17, 0.41]) * 2 # Microgrid information Profile = array([ [0.64, 0.63, 0.65, 0.64, 0.66, 0.69, 0.75, 0.91, 0.95, 0.97, 1.00, 0.97, 0.97, 0.95, 0.98, 0.99, 0.95, 0.95, 0.94, 0.95, 0.97, 0.93, 0.85, 0.69], [0.78, 0.75, 0.74, 0.74, 0.75, 0.81, 0.91, 0.98, 0.99, 0.99, 1.00, 0.99, 0.99, 0.99, 0.98, 0.97, 0.96, 0.95, 0.95, 0.95, 0.96, 0.95, 0.88, 0.82], [0.57, 0.55, 0.55, 0.56, 0.62, 0.70, 0.78, 0.83, 0.84, 0.89, 0.87, 0.82, 0.80, 0.80, 0.84, 0.89, 0.94, 0.98, 1.00, 0.97, 0.87, 0.79, 0.72, 0.62] ]) # Add start-up, shut-down status, initial status, start-up/shut cost of DGs # The DGs within the DS are optimized!
""" Stochastic optimal power flow with multiple microgrids and mobile energy storage systems @author: Zhao Tianyang @e-mail: [email protected] @date: 10 Jan 2019 Major updates: 1) Update code style using PEP 8 -- Style Guide for Python Code 2) Store data in database 3) Scenario generation and reduction 4) Automatic results analysis Nomenclature: nV: number of variables mg: microgrid ds: distribution systems me: mobile energy storage systems ch: charging dc: discharging ele: electricity tra: traffic i,j,k: index t: time index T: time periods tns:traffic networks pns:power networks """ class StochasticDynamicOptimalPowerFlowTess(): def __init__(self): self.name = "Stochastic optimal power flow with tess" def main(self, power_networks, micro_grids, profile, mess, traffic_networks, ns=100): """ Main entrance for network reconfiguration problems :param case: electric network information :param profile: load profile within the distribution networks :param micrgrids: dictionary for microgrids :param tess: dictionary for tess :return: network reconfiguration, distribution network status, and microgrid status """ T = len(profile) # Time spans self.T = T nmg = len(micro_grids) # Number of microgrids self.nmg = nmg nmes = len(mess) # Number of mobile energy storage systems self.nmes = nmes nb_tra = traffic_networks["bus"].shape[0] # Number of buses in the transportation networks self.nb_tra = nb_tra assert nb_tra == nmg, "The microgrids within the transportation networks are not synchronized!" # 1) Formulate the first stage optimization problem model_first_stage = self.first_stage_problem_formualtion(pns=power_networks, mgs=micro_grids, mess=mess, tns=traffic_networks) # (sol_first_stage, obj, success) = milp(model_first_stage["c"], Aeq=model_first_stage["Aeq"], # beq=model_first_stage["beq"], # A=model_first_stage["A"], b=model_first_stage["b"], # vtypes=model_first_stage["vtypes"], # xmax=model_first_stage["ub"], xmin=model_first_stage["lb"]) # sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 2) Formulate the second stage optimization problem # Formulate the second stage scenarios (ds_second_stage, mgs_second_stage, weight) = self.scenario_generation_reduction(profile=profile, micro_grids=micro_grids, ns=ns, pns=power_networks, ns_reduced=round(0.98 * ns)) ns -= round(0.98 * ns) model_second_stage = {} for i in range(ns): model_second_stage[i] = self.second_stage_problem_formualtion(pns=power_networks, mgs=mgs_second_stage[i], mess=mess, tns=traffic_networks, profile=ds_second_stage[i, :], index=i, weight=weight[i]) # 3) Merge the first-stage problem and second stage problem lb = model_first_stage["lb"] ub = model_first_stage["ub"] vtypes = model_first_stage["vtypes"] c = model_first_stage["c"] Qc = dict() if model_first_stage["Aeq"] is not None: neq = model_first_stage["Aeq"].shape[0] else: neq = 0 if model_first_stage["A"] is not None: nineq = model_first_stage["A"].shape[0] else: nineq = 0 nv_first_stage = self.nv_first_stage nv_second_stage = self.nv_second_stage q = zeros(nv_first_stage) nv_index = zeros(ns + 1).astype(int) neq_index = zeros(ns + 1).astype(int) nineq_index = zeros(ns + 1).astype(int) neq_index[0] = neq nineq_index[0] = nineq nv_index[0] = nv_first_stage beq = model_first_stage["beq"] for i in range(ns): if model_second_stage[i]["Aeq"] is not None: neq_index[i + 1] = neq_index[i] + model_second_stage[i]["Aeq"].shape[0] else: neq_index[i + 1] = neq_index[i] if model_second_stage[i]["Ts"] is not None: nineq_index[i + 1] = nineq_index[i] + model_second_stage[i]["Ts"].shape[0] else: nineq_index[i + 1] = nineq_index[i] nv_index[i + 1] = nv_index[i] + nv_second_stage c = concatenate([c, model_second_stage[i]["c"]]) q = concatenate([q, model_second_stage[i]["q"]]) lb = concatenate([lb, model_second_stage[i]["lb"]]) ub = concatenate([ub, model_second_stage[i]["ub"]]) vtypes += model_second_stage[i]["vtypes"] beq = concatenate([beq, model_second_stage[i]["beq"]]) Aeq_full = lil_matrix((neq_index[-1], nv_index[-1])) Aeq_full[0:neq_index[0], 0:nv_index[0]] = model_first_stage["Aeq"] rc = zeros(0) for i in range(ns): Aeq_full[neq_index[i]:neq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Aeq"] Qc.update(model_second_stage[i]["Qc"]) rc = concatenate([rc, model_second_stage[i]["rc"]]) A_full = lil_matrix((nineq_index[-1], nv_index[-1])) b = model_first_stage["b"] A_full[0:int(nineq_index[0]), 0:int(nv_index[0])] = model_first_stage["A"] for i in range(ns): A_full[nineq_index[i]:nineq_index[i + 1], 0:nv_index[0]] = model_second_stage[i]["Ts"] A_full[nineq_index[i]:nineq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Ws"] b = concatenate([b, model_second_stage[i]["hs"]]) # 3) Obtain the results for first-stage and second stage optimization problems # 3.1) Obtain the integrated solution (sol, obj, success) = miqcp(c, q, Aeq=Aeq_full, beq=beq, A=A_full, b=b, Qc=Qc, rc=rc, xmin=lb, xmax=ub, vtypes=vtypes) # 3.2) decouple the solution into multiple subsystems sol_first_stage = sol[0:nv_second_stage] sol_second_stage = {} for i in range(ns): sol_second_stage[i] = sol[int(nv_index[i]):int(nv_index[i + 1])] # 4) Verify the first-stage and second stage optization problem # 4.1) First-stage solution sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 4.2) Second-stage solution sol_second_stage_checked = {} db_management = DataBaseManagement() db_management.create_table(table_name="distribution_networks", nl=self.nl, nb=self.nb, ng=self.ng) db_management.create_table(table_name="micro_grids", nmg=self.nmg) db_management.create_table(table_name="mobile_energy_storage_systems", nmg=self.nmg) db_management.create_table(table_name="first_stage_solutions", nmg=self.nmg, ng=self.ng, nmes=self.nmes) db_management.create_table(table_name="fisrt_stage_mess", nmg=self.nmg) for t in range(T): db_management.insert_data_first_stage(table_name="first_stage_solutions", time=t, ng=self.ng, nmg=self.nmg, pg=sol_first_stage["pg"][:, t].tolist(), rg=sol_first_stage["rg"][:, t].tolist(), pg_mg=sol_first_stage["pg_mg"][:, t].tolist(), rg_mg=sol_first_stage["rg_mg"][:, t].tolist(), pess_ch=sol_first_stage["pess_ch"][:, t].tolist(), pess_dc=sol_first_stage["pess_dc"][:, t].tolist(), ress=sol_first_stage["ress"][:, t].tolist(), ess=sol_first_stage["eess"][:, t].tolist(), iess=sol_first_stage["iess"][:, t].tolist()) for i in range(nmes): for t in range(T): db_management.insert_data_first_stage_mess(table_name="fisrt_stage_mess", nmg=self.nmg, time=t, mess=i, imess=sol_first_stage["MESS"][i]["idc"][:, t].tolist(), rmess=sol_first_stage["MESS"][i]["rmess"][:, t].tolist(), pmess_ch= sol_first_stage["MESS"][i]["pmess_ch"][:, t].tolist(), pmess_dc= sol_first_stage["MESS"][i]["pmess_dc"][:, t].tolist(), mess_f_stop=sol_first_stage["MESS"][i]["VRP"][t + 1][0], mess_t_stop=sol_first_stage["MESS"][i]["VRP"][t + 1][1]) for i in range(ns): sol_second_stage_checked[i] = self.second_stage_solution_validation(sol_second_stage[i]) for i in range(ns): for t in range(T): db_management.insert_data_ds(table_name="distribution_networks", nl=self.nl, nb=self.nb, ng=self.ng, scenario=i, time=t, pij=sol_second_stage_checked[i]["DS"]["pij"][:, t].tolist(), qij=sol_second_stage_checked[i]["DS"]["qij"][:, t].tolist(), lij=sol_second_stage_checked[i]["DS"]["lij"][:, t].tolist(), vi=sol_second_stage_checked[i]["DS"]["vi"][:, t].tolist(), pg=sol_second_stage_checked[i]["DS"]["pg"][:, t].tolist(), qg=sol_second_stage_checked[i]["DS"]["qg"][:, t].tolist(), ) for i in range(ns): for j in range(nmg): for t in range(T): db_management.insert_data_mg(table_name="micro_grids", scenario=i, time=t, mg=j, pg=sol_second_stage_checked[i]["MG"]["pg"][j, t], qg=sol_second_stage_checked[i]["MG"]["qg"][j, t], pug=sol_second_stage_checked[i]["MG"]["pug"][j, t], qug=sol_second_stage_checked[i]["MG"]["qug"][j, t], pbic_ac2dc=sol_second_stage_checked[i]["MG"]["pbic_ac2dc"][j, t], pbic_dc2ac=sol_second_stage_checked[i]["MG"]["pbic_dc2ac"][j, t], qbic=sol_second_stage_checked[i]["MG"]["qbic"][j, t], pess_ch=sol_second_stage_checked[i]["MG"]["pess_ch"][j, t], pess_dc=sol_second_stage_checked[i]["MG"]["pess_dc"][j, t], eess=sol_second_stage_checked[i]["MG"]["eess"][j, t], pmess=sol_second_stage_checked[i]["MG"]["pmess"][j, t]) for i in range(ns): for j in range(nmes): for t in range(T): db_management.insert_data_mess(table_name="mobile_energy_storage_systems", scenario=i, time=t, mess=j, nmg=self.nmg, pmess_dc= sol_second_stage_checked[i]["MESS"][j]["pmess_dc"][:, t].tolist(), pmess_ch= sol_second_stage_checked[i]["MESS"][j]["pmess_ch"][:, t].tolist(), emess=sol_second_stage_checked[i]["MESS"][j]["emess"][0, t]) # 4.3) Cross validation of the first-stage and second-stage decision variables tess_check = {} for i in range(ns): tess_temp = {} for j in range(nmes): tess_temp[j] = sol_second_stage_checked[i]["MESS"][j]["pmess_dc"] - \ sol_second_stage_checked[i]["MESS"][j]["pmess_ch"] - \ sol_first_stage["MESS"][j]["pmess_dc"] + \ sol_first_stage["MESS"][j]["pmess_ch"] - \ sol_first_stage["MESS"][j]["rmess"] tess_temp[j + nmes] = sol_second_stage_checked[i]["MESS"][j]["pmess_ch"] - \ sol_second_stage_checked[i]["MESS"][j]["pmess_dc"] - \ sol_first_stage["MESS"][j]["pmess_ch"] + \ sol_first_stage["MESS"][j]["pmess_dc"] - \ sol_first_stage["MESS"][j]["rmess"] tess_check[i] = tess_temp # return sol_distribution_network, sol_microgrids, sol_tess return sol_first_stage, sol_second_stage_checked def first_stage_problem_formualtion(self, pns, mgs, mess, tns): """ Problem formulation for the first stage optimization, Decision variables include, DGs within power networks, DGs within MGs, EESs within MGs and TESSs :param power_networks: Parameters for the power networks :param micro_grids: Parameters for the microgrids :param tess: Parameters for the mobile energy storage systems :param traffic_networks: Parameters for the transportation networks :return: Formulated first-stage problem """ T = self.T # Time slots nmg = self.nmg # Number of mgs nmes = self.nmes # Number of tess mpc = ext2int(pns) baseMVA, bus, gen, branch, gencost = mpc["baseMVA"], mpc["bus"], mpc["gen"], mpc["branch"], mpc["gencost"] ng = shape(mpc['gen'])[0] ## number of dispatchable injections nb = shape(mpc["bus"])[0] self.nb = nb self.ng = ng # Obtain the initial status, start-up and shut down of generators Ig0 = gen[:, -1].astype(int) MIN_DOWN = gen[:, -2].astype(int) MIN_UP = gen[:, -3].astype(int) alpha_l = zeros(ng) beta_l = zeros(ng) Ig_l = zeros(ng) pg_l = zeros(ng) # Boundary for DGs within distribution networks rg_l = zeros(ng) alpha_u = ones(ng) beta_u = ones(ng) Ig_u = ones(ng) pg_u = gen[:, PMAX] / baseMVA rg_u = gen[:, PMAX] / baseMVA c_alpha = gencost[:, 0] c_beta = gencost[:, 1] c_ig = gencost[:, 6] cg = gencost[:, 5] * baseMVA cr = zeros(ng) pg_mg_l = zeros(nmg) # Boundary for DGs within MGs rg_mg_l = zeros(nmg) pg_mg_u = zeros(nmg) rg_mg_u = zeros(nmg) cg_mg = zeros(nmg) cr_mg = zeros(nmg) for i in range(nmg): pg_mg_l[i] = mgs[i]["DG"]["PMIN"] pg_mg_u[i] = mgs[i]["DG"]["PMAX"] rg_mg_u[i] = mgs[i]["DG"]["PMAX"] cg_mg[i] = mgs[i]["DG"]["COST_B"] pes_ch_l = zeros(nmg) # Lower boundary for ESSs within MGs pes_dc_l = zeros(nmg) ees_l = zeros(nmg) res_l = zeros(nmg) ies_l = zeros(nmg) pes_ch_u = zeros(nmg) # Upper boundary for ESSs within MGs pes_dc_u = zeros(nmg) ees_u = zeros(nmg) res_u = zeros(nmg) ies_u = ones(nmg) ces_ch = zeros(nmg) # Cost boundary for ESSs within MGs ces_dc = zeros(nmg) ces_r = zeros(nmg) ces = zeros(nmg) ces_i = zeros(nmg) for i in range(nmg): pes_ch_u[i] = mgs[i]["ESS"]["PCH_MAX"] pes_dc_u[i] = mgs[i]["ESS"]["PDC_MAX"] + mgs[i]["ESS"]["PCH_MAX"] res_u[i] = mgs[i]["ESS"]["PCH_MAX"] ees_l[i] = mgs[i]["ESS"]["EMIN"] ees_u[i] = mgs[i]["ESS"]["EMAX"] _nv_first_stage = ng * 5 + nmg * 2 + nmg * 5 nv_first_stage = _nv_first_stage * T # Formulate the boundaries lb = concatenate( [tile(concatenate( [alpha_l, beta_l, Ig_l, pg_l, rg_l, pg_mg_l, rg_mg_l, pes_ch_l, pes_dc_l, res_l, ees_l, ies_l]), T)]) ub = concatenate( [tile(concatenate( [alpha_u, beta_u, Ig_u, pg_u, rg_u, pg_mg_u, rg_mg_u, pes_ch_u, pes_dc_u, res_u, ees_u, ies_u]), T)]) # Objective value c = concatenate( [tile(concatenate([c_alpha, c_beta, c_ig, cg, cr, cg_mg, cr_mg, ces_ch, ces_dc, ces, ces_r, ces_i]), T)]) # Variable types vtypes = (["b"] * ng * 3 + ["c"] * (ng * 2 + nmg * 2 + nmg * 4) + ["b"] * nmg) * T ## Constraint sets # 1) Pg+Rg<=PguIg A = lil_matrix((ng * T, nv_first_stage)) b = zeros(ng * T) for t in range(T): for j in range(ng): A[t * ng + j, t * _nv_first_stage + ng * 3 + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * 4 + j] = 1 A[t * ng + j, t * _nv_first_stage + ng * 2 + j] = -pg_u[j] # 2) Pg-Rg>=IgPgl A_temp = lil_matrix((ng * T, nv_first_stage)) b_temp = zeros(ng * T) for t in range(T): for j in range(ng): A_temp[t * ng + j, t * _nv_first_stage + ng * 3 + j] = -1 A_temp[t * ng + j, t * _nv_first_stage + ng * 4 + j] = 1 A_temp[t * ng + j, t * _nv_first_stage + j] = pg_l[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 3) Start-up and shut-down constraints of DGs UP_LIMIT = zeros(ng).astype(int) DOWN_LIMIT = zeros(ng).astype(int) for i in range(ng): UP_LIMIT[i] = T - MIN_UP[i] DOWN_LIMIT[i] = T - MIN_DOWN[i] # 3.1) Up limit A_temp = lil_matrix((sum(UP_LIMIT), nv_first_stage)) b_temp = zeros(sum(UP_LIMIT)) for i in range(ng): for t in range(MIN_UP[i], T): for k in range(t - MIN_UP[i], t): A_temp[sum(UP_LIMIT[0:i]) + t - MIN_UP[i], k * _nv_first_stage + i] = 1 A_temp[sum(UP_LIMIT[0:i]) + t - MIN_UP[i], t * _nv_first_stage + ng * 2 + i] = -1 A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # # 3.2) Down limit A_temp = lil_matrix((sum(DOWN_LIMIT), nv_first_stage)) b_temp = ones(sum(DOWN_LIMIT)) for i in range(ng): for t in range(MIN_DOWN[i], T): for k in range(t - MIN_DOWN[i], t): A_temp[sum(DOWN_LIMIT[0:i]) + t - MIN_DOWN[i], k * _nv_first_stage + ng + i] = 1 A_temp[sum(DOWN_LIMIT[0:i]) + t - MIN_DOWN[i], t * _nv_first_stage + ng * 2 + i] = 1 A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 4) Status transformation of each unit Aeq = lil_matrix((T * ng, nv_first_stage)) beq = zeros(T * ng) for i in range(ng): for t in range(T): Aeq[i * T + t, t * _nv_first_stage + i] = 1 Aeq[i * T + t, t * _nv_first_stage + ng + i] = -1 Aeq[i * T + t, t * _nv_first_stage + ng * 2 + i] = -1 if t != 0: Aeq[i * T + t, (t - 1) * _nv_first_stage + ng * 2 + i] = 1 else: beq[i * T + t] = -Ig0[i] # 3) Pg_mg+Rg_mg<=Pg_mg_u A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg + j] = 1 b_temp[t * nmg + j] = pg_mg_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 4) Pg_mg-Rg_mg<=Pg_mg_l A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + j] = -1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg + j] = 1 b_temp[t * nmg + j] = pg_mg_l[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 5) Pess_dc-Pess_ch+Ress<=Pess_dc_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + j] = -1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 2 + j] = 1 b_temp[t * nmg + j] = pes_dc_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 6) Pess_ch-Pess_dc+Ress<=Pess_ch_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, ng * 5 + nmg * 2 + t] = 1 A_temp[t * nmg + j, ng * 5 + nmg * 2 + nmg + t] = -1 A_temp[t * nmg + j, ng * 5 + nmg * 2 + nmg * 2 + t] = 1 b_temp[t * nmg + j] = pes_ch_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 7) Energy storage balance equation Aeq_temp = lil_matrix((T * nmg, nv_first_stage)) beq_temp = zeros(T * nmg) for t in range(T): for j in range(nmg): Aeq_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 3 + j] = 1 Aeq_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + j] = -mgs[j]["ESS"]["EFF_CH"] Aeq_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg + j] = 1 / mgs[j]["ESS"]["EFF_DC"] if t == 0: beq_temp[i * nmg + j] = mgs[j]["ESS"]["E0"] else: Aeq_temp[i * nmg + j, (i - 1) * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 3 + j] = -1 Aeq = vstack([Aeq, Aeq_temp]) beq = concatenate([beq, beq_temp]) # 8) Pess_ch<=I*Pess_ch_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 4 + j] = -pes_ch_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 9) Pess_dc<=(1-I)*Pess_dc_max A_temp = lil_matrix((nmg * T, nv_first_stage)) b_temp = zeros(nmg * T) for t in range(T): for j in range(nmg): A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg + j] = 1 A_temp[t * nmg + j, t * _nv_first_stage + ng * 5 + nmg * 2 + nmg * 4 + j] = pes_dc_u[j] b_temp[t * nmg + j] = pes_dc_u[j] A = vstack([A, A_temp]) b = concatenate([b, b_temp]) # 2) Transportation energy storage systems problem model_mess = {} for i in range(nmes): model_mess[i] = self.problem_formulation_tess(mess=mess[i], tns=tns) # 3) Merge the DGs, ESSs and TESSs neq = Aeq.shape[0] nineq = A.shape[0] nV_index = zeros(nmes + 1).astype(int) neq_index = zeros(nmes + 1).astype(int) nineq_index = zeros(nmes + 1).astype(int) nV_index[0] = nv_first_stage neq_index[0] = neq nineq_index[0] = nineq for i in range(nmes): nV_index[i + 1] = nV_index[i] + len(model_mess[i]["c"]) neq_index[i + 1] = neq_index[i] + model_mess[i]["Aeq"].shape[0] nineq_index[i + 1] = nineq_index[i] + model_mess[i]["A"].shape[0] neq += model_mess[i]["Aeq"].shape[0] nineq += model_mess[i]["A"].shape[0] # Merge the objective function, boundaries, types and rhs c = concatenate([c, model_mess[i]["c"]]) lb = concatenate([lb, model_mess[i]["lb"]]) ub = concatenate([ub, model_mess[i]["ub"]]) vtypes += model_mess[i]["vtypes"] beq = concatenate([beq, model_mess[i]["beq"]]) b = concatenate([b, model_mess[i]["b"]]) A_full = lil_matrix((nineq_index[-1], nV_index[-1])) Aeq_full = lil_matrix((neq_index[-1], nV_index[-1])) if Aeq is not None: Aeq_full[0:int(neq_index[0]), 0:int(nV_index[0])] = Aeq if A is not None: A_full[0:int(nineq_index[0]), 0:int(nV_index[0])] = A for i in range(nmes): Aeq_full[neq_index[i]:neq_index[i + 1], nV_index[i]:nV_index[i + 1]] = model_mess[i]["Aeq"] A_full[nineq_index[i]:nineq_index[i + 1], nV_index[i]:nV_index[i + 1]] = model_mess[i]["A"] self.nv_first_stage = nV_index[-1] # The number of first stage decision variables self._nv_first_stage = _nv_first_stage model_first_stage = {"c": c, "lb": lb, "ub": ub, "vtypes": vtypes, "A": A_full, "b": b, "Aeq": Aeq_full, "beq": beq, } return model_first_stage def first_stage_solution_validation(self, sol): """ Validation of the first-stage solution :param sol: The first stage solution :return: the first stage solution """ T = self.T ng = self.ng nmg = self.nmg nmes = self.nmes # Set-points of DGs within DSs, MGs and ESSs _nv_first_stage = self._nv_first_stage alpha = zeros((ng, T)) beta = zeros((ng, T)) Ig = zeros((ng, T)) Pg = zeros((ng, T)) Rg = zeros((ng, T)) Pg_mg = zeros((nmg, T)) Rg_mg = zeros((nmg, T)) Pess_dc = zeros((nmg, T)) Pess_ch = zeros((nmg, T)) Ress = zeros((nmg, T)) Eess = zeros((nmg, T)) Iess = zeros((nmg, T)) for i in range(T): alpha[:, i] = sol[_nv_first_stage * i:_nv_first_stage * i + ng] beta[:, i] = sol[_nv_first_stage * i + ng:_nv_first_stage * i + ng * 2] Ig[:, i] = sol[_nv_first_stage * i + ng * 2:_nv_first_stage * i + ng * 3] Pg[:, i] = sol[_nv_first_stage * i + ng * 3:_nv_first_stage * i + ng * 4] Rg[:, i] = sol[_nv_first_stage * i + ng * 4:_nv_first_stage * i + ng * 5] Pg_mg[:, i] = sol[_nv_first_stage * i + ng * 5:_nv_first_stage * i + ng * 5 + nmg] Rg_mg[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg:_nv_first_stage * i + ng * 5 + nmg * 2] Pess_ch[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 2:_nv_first_stage * i + ng * 5 + nmg * 3] Pess_dc[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 3:_nv_first_stage * i + ng * 5 + nmg * 4] Ress[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 4:_nv_first_stage * i + ng * 5 + nmg * 5] Eess[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 5:_nv_first_stage * i + ng * 5 + nmg * 6] Iess[:, i] = sol[_nv_first_stage * i + ng * 5 + nmg * 6:_nv_first_stage * i + ng * 5 + nmg * 7] # Set-points and scheduling of mobile energy storage systems nv_tra = self.nv_tra nl_traffic = self.nl_tra n_stops = self.n_stops nb_tra_ele = self.nb_tra_ele sol_ev = {} for i in range(nmes): ev_temp = {} ev_temp["VRP"] = [] for t in range(nl_traffic): if sol[_nv_first_stage * T + nv_tra * i + t] > 0: # obtain the solution for vrp if self.connection_matrix[t, TIME] > 0: for j in range(int(self.connection_matrix[t, TIME])): ev_temp["VRP"].append(((self.connection_matrix[t, F_BUS] - 1) % nmg, (self.connection_matrix[t, T_BUS] - 1) % nmg)) else: ev_temp["VRP"].append(((self.connection_matrix[t, F_BUS] - 1) % nmg, (self.connection_matrix[t, T_BUS] - 1) % nmg)) ev_temp["idc"] = zeros((nb_tra_ele, T)) ev_temp["pmess_dc"] = zeros((nb_tra_ele, T)) ev_temp["pmess_ch"] = zeros((nb_tra_ele, T)) ev_temp["rmess"] = zeros((nb_tra_ele, T)) for t in range(T): for k in range(nb_tra_ele): ev_temp["idc"][k, t] = sol[_nv_first_stage * T + nv_tra * i + nl_traffic + nb_tra_ele * t + k] ev_temp["pmess_dc"][k, t] = \ sol[_nv_first_stage * T + nv_tra * i + nl_traffic + n_stops + nb_tra_ele * t + k] ev_temp["pmess_ch"][k, t] = \ sol[_nv_first_stage * T + nv_tra * i + nl_traffic + n_stops * 2 + nb_tra_ele * t + k] ev_temp["rmess"][k, t] = \ sol[_nv_first_stage * T + nv_tra * i + nl_traffic + n_stops * 3 + nb_tra_ele * t + k] sol_ev[i] = ev_temp sol_first_stage = {"alpha": alpha, "beta": beta, "ig": Ig, "rg": Rg, "pg": Pg, "pg_mg": Pg_mg, "rg_mg": Rg_mg, "pess_ch": Pess_ch, "pess_dc": Pess_dc, "ress": Ress, "eess": Eess, "iess": Iess, "MESS": sol_ev, } return sol_first_stage def second_stage_problem_formualtion(self, pns, mgs, mess, tns, profile, index=0, weight=1): """ Second-stage problem formulation, the decision variables includes DGs within power networks, DGs within MGs, EESs within MGs and TESSs and other systems' information :param power_networks: :param micro_grids: :param tess: :param traffic_networks: :return: The second stage problems as list, including coupling constraints, and other constraint set """ # I) Formulate the problem for distribution systems operator T = self.T mpc = ext2int(pns) baseMVA, bus, gen, branch, gencost = mpc["baseMVA"], mpc["bus"], mpc["gen"], mpc["branch"], mpc["gencost"] nb = shape(mpc['bus'])[0] ## number of buses nl = shape(mpc['branch'])[0] ## number of branches ng = shape(mpc['gen'])[0] ## number of dispatchable injections nmg = self.nmg nmes = self.nmes self.nl = nl self.nb = nb self.ng = ng m = zeros(nmg) ## list of integration index pmg_l = zeros(nmg) ## list of lower boundary pmg_u = zeros(nmg) ## list of upper boundary qmg_l = zeros(nmg) ## list of lower boundary qmg_u = zeros(nmg) ## list of upper boundary for i in range(nmg): m[i] = mgs[i]["BUS"] pmg_l[i] = mgs[i]["UG"]["PMIN"] / 1000 / baseMVA pmg_u[i] = mgs[i]["UG"]["PMAX"] / 1000 / baseMVA qmg_l[i] = mgs[i]["UG"]["QMIN"] / 1000 / baseMVA qmg_u[i] = mgs[i]["UG"]["QMAX"] / 1000 / baseMVA f = branch[:, F_BUS] ## list of "from" buses t = branch[:, T_BUS] ## list of "to" buses i = range(nl) ## double set of row indices self.f = f ## record from bus for each branch # Connection matrix Cf = sparse((ones(nl), (i, f)), (nl, nb)) Ct = sparse((ones(nl), (i, t)), (nl, nb)) Cg = sparse((ones(ng), (gen[:, GEN_BUS], range(ng))), (nb, ng)) Cmg = sparse((ones(nmg), (m, range(nmg))), (nb, nmg)) Branch_R = branch[:, BR_R] Branch_X = branch[:, BR_X] Cf = Cf.T Ct = Ct.T # Obtain the boundary information slmax = branch[:, RATE_A] / baseMVA pij_l = -slmax qij_l = -slmax lij_l = zeros(nl) vm_l = bus[:, VMIN] ** 2 pg_l = gen[:, PMIN] / baseMVA qg_l = gen[:, QMIN] / baseMVA pij_u = slmax qij_u = slmax lij_u = slmax vm_u = bus[:, VMAX] ** 2 pg_u = 2 * gen[:, PMAX] / baseMVA qg_u = 2 * gen[:, QMAX] / baseMVA _nv_second_stage = int(3 * nl + nb + 2 * ng + 2 * nmg) self._nv_second_stage = _nv_second_stage # Number of decision variable within each time slot lb = concatenate([tile(concatenate([pij_l, qij_l, lij_l, vm_l, pg_l, qg_l, pmg_l, qmg_l]), T)]) ub = concatenate([tile(concatenate([pij_u, qij_u, lij_u, vm_u, pg_u, qg_u, pmg_u, qmg_u]), T)]) vtypes = ["c"] * _nv_second_stage * T nv_ds = _nv_second_stage * T # Number of total decision variables # Add system level constraints # 1) Active power balance Aeq_p = lil_matrix((nb * T, nv_ds)) beq_p = zeros(nb * T) for i in range(T): Aeq_p[i * nb:(i + 1) * nb, i * _nv_second_stage: (i + 1) * _nv_second_stage] = \ hstack([Ct - Cf, zeros((nb, nl)), -diag(Ct * Branch_R) * Ct, zeros((nb, nb)), Cg, zeros((nb, ng)), -Cmg, zeros((nb, nmg))]) beq_p[i * nb:(i + 1) * nb] = profile[i * nb:(i + 1) * nb] / baseMVA # 2) Reactive power balance Aeq_q = lil_matrix((nb * T, nv_ds)) beq_q = zeros(nb * T) for i in range(T): Aeq_q[i * nb:(i + 1) * nb, i * _nv_second_stage: (i + 1) * _nv_second_stage] = \ hstack([zeros((nb, nl)), Ct - Cf, -diag(Ct * Branch_X) * Ct, zeros((nb, nb)), zeros((nb, ng)), Cg, zeros((nb, nmg)), -Cmg]) for j in range(nb): if bus[j, PD] > 0: beq_q[i * nb:(i + 1) * nb] = profile[i * nb + j] / bus[j, PD] * bus[j, QD] / baseMVA # 3) KVL equation Aeq_kvl = lil_matrix((nl * T, nv_ds)) beq_kvl = zeros(nl * T) for i in range(T): Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage: i * _nv_second_stage + nl] = -2 * diag(Branch_R) Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage + nl: i * _nv_second_stage + 2 * nl] = -2 * diag(Branch_X) Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage + 2 * nl: i * _nv_second_stage + 3 * nl] = diag( Branch_R ** 2) + diag(Branch_X ** 2) Aeq_kvl[i * nl:(i + 1) * nl, i * _nv_second_stage + 3 * nl:i * _nv_second_stage + 3 * nl + nb] = ( Cf.T - Ct.T).toarray() Aeq = vstack([Aeq_p, Aeq_q, Aeq_kvl]) beq = concatenate([beq_p, beq_q, beq_kvl]) c = zeros(nv_ds) q = zeros(nv_ds) c0 = 0 for t in range(T): for i in range(ng): c[t * _nv_second_stage + i + 3 * nl + nb] = gencost[i, 5] * baseMVA q[t * _nv_second_stage + i + 3 * nl + nb] = gencost[i, 4] * baseMVA * baseMVA c0 += gencost[i, 6] # Coupling constraints between the distribution systems and micro_grids Ax2y = lil_matrix((2 * nmg * T, nv_ds)) # connection matrix with the microgrids for i in range(T): for j in range(nmg): # Active power Ax2y[i * nmg + j, i * _nv_second_stage + 3 * nl + nb + 2 * ng + j] = 1000 * baseMVA # Reactive power Ax2y[nmg * T + i * nmg + j, i * _nv_second_stage + 3 * nl + nb + 2 * ng + nmg + j] = 1000 * baseMVA # II) Formulate the problem for microgrids model_microgrids = {} for i in range(nmg): model_microgrids[i] = self.problem_formulation_microgrid(mg=mgs[i], mess=mess) # II.A) Combine the distribution system operation problem and microgrid systems if Aeq is not None: neq_ds = Aeq.shape[0] else: neq_ds = 0 nVariables = int(nv_ds) neq = int(neq_ds) nv_index = zeros(nmg + 1).astype(int) neq_index = zeros(nmg + 1).astype(int) nv_index[0] = nv_ds neq_index[0] = int(neq_ds) for i in range(nmg): nv_index[i + 1] = nv_index[i] + len(model_microgrids[i]["c"]) neq_index[i + 1] = neq_index[i] + model_microgrids[i]["Aeq"].shape[0] nVariables += len(model_microgrids[i]["c"]) neq += int(model_microgrids[i]["Aeq"].shape[0]) Aeq_full = lil_matrix((int(neq_index[-1]), int(nv_index[-1]))) Aeq_full[0:neq_ds, 0:nv_ds] = Aeq for i in range(nmg): lb = concatenate([lb, model_microgrids[i]["lb"]]) ub = concatenate([ub, model_microgrids[i]["ub"]]) c = concatenate([c, model_microgrids[i]["c"]]) q = concatenate([q, model_microgrids[i]["q"]]) vtypes += model_microgrids[i]["vtypes"] beq = concatenate([beq, model_microgrids[i]["beq"]]) Aeq_full[neq_index[i]:neq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_microgrids[i]["Aeq"] # Add coupling constraints, between the microgrids and distribution networks Ay2x = lil_matrix((2 * nmg * T, nv_index[-1] - nv_index[0])) for i in range(T): for j in range(nmg): Ay2x[i * nmg + j, int(nv_index[j] - nv_index[0]) + i * NX_MG + PUG] = -1 Ay2x[nmg * T + i * nmg + j, int(nv_index[j] - nv_index[0]) + i * NX_MG + QUG] = -1 Aeq_temp = hstack([Ax2y, Ay2x]) beq_temp = zeros(2 * nmg * T) Aeq_full = vstack([Aeq_full, Aeq_temp]) beq = concatenate([beq, beq_temp]) # III) Formulate the optimization problem for tess in the second stage optimization model_tess = {} for i in range(nmes): model_tess[i] = self.problem_formulation_tess_second_stage(mess=mess[i]) # III.1) Merge the models of mirogrids and distribution # Formulate the index nv_index_ev = zeros(1 + nmes).astype(int) neq_index_temp = zeros(1 + nmes).astype(int) nv_index_ev[0] = int(Aeq_full.shape[1]) neq_index_temp[0] = int(Aeq_full.shape[0]) for i in range(nmes): nv_index_ev[i + 1] = nv_index_ev[i] + len(model_tess[i]["c"]) neq_index_temp[i + 1] = neq_index_temp[i] + model_tess[i]["Aeq"].shape[0] Aeq = lil_matrix((int(neq_index_temp[-1]), int(nv_index_ev[-1]))) Aeq[0:int(neq_index_temp[0]), 0:int(nv_index_ev[0])] = Aeq_full for i in range(nmes): lb = concatenate([lb, model_tess[i]["lb"]]) ub = concatenate([ub, model_tess[i]["ub"]]) c = concatenate([c, model_tess[i]["c"]]) q = concatenate([q, model_tess[i]["q"]]) vtypes += model_tess[i]["vtypes"] beq = concatenate([beq, model_tess[i]["beq"]]) Aeq[neq_index_temp[i]:neq_index_temp[i + 1], nv_index_ev[i]:nv_index_ev[i + 1]] = model_tess[i]["Aeq"] # III.2) Coupling constraints between the microgrids and mobile energy storage systems # Additional equal constraints, nmg*T Aeq_temp = lil_matrix((nmg * T, nv_index_ev[-1])) beq_temp = zeros(nmg * T) for i in range(nmg): for t in range(T): Aeq_temp[i * T + t, nv_index[i] + t * NX_MG + PMESS] = 1 # TESSs injections to the MGs for j in range(nmes): Aeq_temp[i * T + t, nv_index_ev[j] + t * self.nb_tra_ele + i] = -1 # Discharging Aeq_temp[i * T + t, nv_index_ev[j] + self.nb_tra_ele * T + t * self.nb_tra_ele + i] = 1 # Sort by order Aeq = vstack([Aeq, Aeq_temp]) beq = concatenate((beq, beq_temp)) nv_second_stage = nv_index_ev[-1] nv_first_stage = self.nv_first_stage self.nv_second_stage = nv_second_stage Qc = dict() # 4) Pij**2+Qij**2<=Vi*Iij for t in range(T): for i in range(nl): Qc[(T * nl + T * nmg) * index + t * nl + i] = [ [int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + 2 * nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + f[i] + 3 * nl)], [int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + f[i] + 3 * nl), int(nv_first_stage + index * nv_second_stage + t * _nv_second_stage + i + 2 * nl)], [1, 1, -1 / 2, -1 / 2]] Rc = zeros(nl * T) # 5) (Pbic_ac2dc+Pbic_dc2ac)**2+Qbic**2<=Sbic**2 Rc_temp = zeros(nmg * T) for i in range(nmg): for t in range(T): Qc[(T * nl + T * nmg) * index + T * nl + T * i + t] = [ [int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + QBIC)], [int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_DC2AC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + PBIC_AC2DC), int(nv_first_stage + index * nv_second_stage + nv_ds + NX_MG * T * i + NX_MG * t + QBIC)], [1, 1, 1, 1, 1]] Rc_temp[i * T + t] = mgs[i]["BIC"]["SMAX"] ** 2 Rc = concatenate([Rc, Rc_temp]) ## IV. Coupling constraints between the first stage and second stage decision variables # pg, pg_mg, pess_mg, pess_tess # Ts*x+Ws*ys<=hs ## IV) Formulate the coupling constraints between the first-stage and second-stage problems # 1) -Pg -Rg + pg <= 0 _nv_first_stage = self._nv_first_stage Ts = lil_matrix((ng * T, nv_first_stage)) Ws = lil_matrix((ng * T, nv_second_stage)) hs = zeros(ng * T) for i in range(T): for j in range(ng): Ts[i * ng + j, i * _nv_first_stage + ng * 3 + j] = -1 Ts[i * ng + j, i * _nv_first_stage + ng * 4 + j] = -1 Ws[i * ng + j, i * _nv_second_stage + 3 * nl + nb + j] = 1 # 2) Pg-Rg - pg <= 0 Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 3 + j] = 1 Ts_temp[i * ng + j, i * _nv_first_stage + ng * 4 + j] = -1 Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + j] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 3) Qg <= IgQg_max Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 2 + j] = -qg_u[j] Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + ng + j] = 1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 4) Qg >= IgQg_min Ts_temp = lil_matrix((ng * T, nv_first_stage)) Ws_temp = lil_matrix((ng * T, nv_second_stage)) hs_temp = zeros(ng * T) for i in range(T): for j in range(ng): Ts_temp[i * ng + j, i * _nv_first_stage + ng * 2 + j] = qg_l[j] Ws_temp[i * ng + j, i * _nv_second_stage + 3 * nl + nb + ng + j] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 3) -Pg_mg - Rg_mg + pg_mg <= 0 Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + j] = -1 Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg + j] = -1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PG] = 1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 4) Pg_mg - Rg_mg - pg_mg <= 0 Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + j] = 1 Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg + j] = -1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PG] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 5) pess_dc - pess_ch <= Pess_dc - Pess_ch + Ress Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 2 + j] = 1 # Charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 3 + j] = -1 # Dis-charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 4 + j] = -1 # Reserve Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PESS_CH] = -1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PESS_DC] = 1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 6) pess_ch - pess_dc <= Pess_ch - Pess_dc + Ress Ts_temp = lil_matrix((nmg * T, nv_first_stage)) Ws_temp = lil_matrix((nmg * T, nv_second_stage)) hs_temp = zeros(nmg * T) for i in range(T): for j in range(nmg): Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 2 + j] = -1 # Charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 3 + j] = 1 # Dis-charging Ts_temp[i * nmg + j, i * _nv_first_stage + ng * 5 + nmg * 4 + j] = -1 # Reserve Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PESS_CH] = 1 Ws_temp[i * nmg + j, nv_index[j] + i * NX_MG + PESS_DC] = -1 Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 7) ptss_ch - ptss_dc <= Ptss_ch - Ptss_dc + Rtss nv_tra = self.nv_tra nl_tra = self.nl_tra Ts_temp = lil_matrix((nmg * T * nmes, nv_first_stage)) Ws_temp = lil_matrix((nmg * T * nmes, nv_second_stage)) hs_temp = zeros(nmg * T * nmes) for i in range(nmes): Ts_temp[i * nmg * T:(i + 1) * nmg * T, _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T:_nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 2] = eye( nmg * T) Ts_temp[i * nmg * T:(i + 1) * nmg * T, _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 2: _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 3] = -eye(nmg * T) Ts_temp[i * nmg * T:(i + 1) * nmg * T, _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 3: _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 4] = -eye(nmg * T) Ws_temp[i * nmg * T:(i + 1) * nmg * T, nv_index_ev[i] + nmg * T * 0:nv_index_ev[i] + nmg * T * 1] = \ -eye(nmg * T) Ws_temp[i * nmg * T:(i + 1) * nmg * T, nv_index_ev[i] + nmg * T * 1:nv_index_ev[i] + nmg * T * 2] = \ eye(nmg * T) Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # 8) ptss_dc - ptss_ch <= Ptss_dc - Ptss_ch + Rtss Ts_temp = lil_matrix((nmg * T * nmes, nv_first_stage)) Ws_temp = lil_matrix((nmg * T * nmes, nv_second_stage)) hs_temp = zeros(nmg * T * nmes) for i in range(nmes): Ts_temp[i * nmg * T:(i + 1) * nmg * T, _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T: _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 2] = \ -eye(nmg * T) Ts_temp[i * nmg * T:(i + 1) * nmg * T, _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 2: _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 3] = \ eye(nmg * T) Ts_temp[i * nmg * T:(i + 1) * nmg * T, _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 3: _nv_first_stage * T + nv_tra * i + nl_tra + nmg * T * 4] = \ -eye(nmg * T) Ws_temp[i * nmg * T:(i + 1) * nmg * T, int(nv_index_ev[i]) + nmg * T * 0: int(nv_index_ev[i]) + nmg * T * 1] = eye(nmg * T) Ws_temp[i * nmg * T:(i + 1) * nmg * T, int(nv_index_ev[i]) + nmg * T * 1: int(nv_index_ev[i]) + nmg * T * 2] = -eye(nmg * T) Ts = vstack((Ts, Ts_temp)) Ws = vstack((Ws, Ws_temp)) hs = concatenate((hs, hs_temp)) # sol = miqcp(c, q, Aeq=Aeq, beq=beq, A=None, b=None, Qc=Qc, xmin=lx, xmax=ux) model_second_stage = {"c": c * weight, "q": q * weight, "lb": lb, "ub": ub, "vtypes": vtypes, "A": None, "b": None, "Aeq": Aeq, "beq": beq, "Qc": Qc, "rc": Rc, "c0": c0, "Ts": Ts, "Ws": Ws, "hs": hs} return model_second_stage def second_stage_solution_validation(self, sol): """ :param sol: The second stage solution under specific scenario :return: for each value """ T = self.T nb = self.nb ng = self.ng nl = self.nl nmg = self.nmg nmes = self.nmes f = self.f # Solutions for distribution networks ds_sol = {} _nv_second_stage = self._nv_second_stage ds_sol["pij"] = zeros((nl, T)) ds_sol["qij"] = zeros((nl, T)) ds_sol["lij"] = zeros((nl, T)) ds_sol["vi"] = zeros((nb, T)) ds_sol["pg"] = zeros((ng, T)) ds_sol["qg"] = zeros((ng, T)) ds_sol["pmg"] = zeros((nmg, T)) ds_sol["qmg"] = zeros((nmg, T)) ds_sol["gap"] = zeros((nl, T)) for i in range(T): ds_sol["pij"][:, i] = sol[_nv_second_stage * i:_nv_second_stage * i + nl] ds_sol["qij"][:, i] = sol[_nv_second_stage * i + nl:_nv_second_stage * i + nl * 2] ds_sol["lij"][:, i] = sol[_nv_second_stage * i + nl * 2:_nv_second_stage * i + nl * 3] ds_sol["vi"][:, i] = sol[_nv_second_stage * i + nl * 3:_nv_second_stage * i + nl * 3 + nb] ds_sol["pg"][:, i] = sol[_nv_second_stage * i + nl * 3 + nb:_nv_second_stage * i + nl * 3 + nb + ng] ds_sol["qg"][:, i] = sol[_nv_second_stage * i + nl * 3 + nb + ng: _nv_second_stage * i + nl * 3 + nb + ng * 2] ds_sol["pmg"][:, i] = sol[_nv_second_stage * i + nl * 3 + nb + ng * 2: _nv_second_stage * i + nl * 3 + nb + ng * 2 + nmg] ds_sol["qmg"][:, i] = sol[_nv_second_stage * i + nl * 3 + nb + ng * 2 + nmg: _nv_second_stage * i + nl * 3 + nb + ng * 2 + nmg * 2] for j in range(nl): ds_sol["gap"][j, i] = ds_sol["pij"][j, i] ** 2 + ds_sol["qij"][j, i] ** 2 - \ ds_sol["lij"][j, i] * ds_sol["vi"][int(f[j]), i] # Solutions for the microgrids mg_sol = {} mg_sol["pg"] = zeros((nmg, T)) mg_sol["qg"] = zeros((nmg, T)) mg_sol["pug"] = zeros((nmg, T)) mg_sol["qug"] = zeros((nmg, T)) mg_sol["pbic_ac2dc"] = zeros((nmg, T)) mg_sol["pbic_dc2ac"] = zeros((nmg, T)) mg_sol["qbic"] = zeros((nmg, T)) mg_sol["pess_ch"] = zeros((nmg, T)) mg_sol["pess_dc"] = zeros((nmg, T)) mg_sol["eess"] = zeros((nmg, T)) mg_sol["pmess"] = zeros((nmg, T)) for i in range(nmg): for t in range(T): mg_sol["pg"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + PG] mg_sol["qg"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + QG] mg_sol["pug"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + PUG] mg_sol["qug"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + QUG] mg_sol["pbic_ac2dc"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + PBIC_AC2DC] mg_sol["pbic_dc2ac"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + PBIC_DC2AC] mg_sol["qbic"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + QBIC] mg_sol["pess_ch"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + PESS_CH] mg_sol["pess_dc"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + PESS_DC] mg_sol["eess"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + EESS] mg_sol["pmess"][i, t] = sol[_nv_second_stage * T + NX_MG * T * i + NX_MG * t + PMESS] mg_sol["gap"] = mg_sol["pbic_ac2dc"].__mul__(mg_sol["pbic_dc2ac"]) # Solutions for the mess n_stops = self.n_stops mess_sol = {} for i in range(nmes): mess_temp = {} mess_temp["pmess_dc"] = zeros((nmg, T)) mess_temp["pmess_ch"] = zeros((nmg, T)) mess_temp["emess"] = zeros((1, T)) for t in range(T): mess_temp["pmess_dc"][:, t] = \ sol[_nv_second_stage * T + NX_MG * T * nmg + (2 * n_stops + T) * i + nmg * t: _nv_second_stage * T + NX_MG * T * nmg + (2 * n_stops + T) * i + nmg * (t + 1)] mess_temp["pmess_ch"][:, t] = \ sol[_nv_second_stage * T + NX_MG * T * nmg + (2 * n_stops + T) * i + n_stops + nmg * t: _nv_second_stage * T + NX_MG * T * nmg + (2 * n_stops + T) * i + n_stops + nmg * (t + 1)] mess_temp["emess"][:, t] = \ sol[_nv_second_stage * T + NX_MG * T * nmg + (2 * n_stops + T) * i + n_stops * 2 + t] mess_sol[i] = mess_temp second_stage_solution = {} second_stage_solution["DS"] = ds_sol second_stage_solution["MG"] = mg_sol second_stage_solution["MESS"] = mess_sol return second_stage_solution def problem_formulation_microgrid(self, mg, mess): """ Unit commitment problem formulation of single micro_grid :param micro_grid: :return: """ try: T = self.T except: T = 24 nmes = self.nmes pmess_l = 0 pmess_u = 0 for i in range(nmes): pmess_l -= mess[i]["PCMAX"] pmess_u += mess[i]["PDMAX"] ## 1) boundary information and objective function nv = NX_MG * T lb = zeros(nv) ub = zeros(nv) c = zeros(nv) q = zeros(nv) vtypes = ["c"] * nv for t in range(T): ## 1.1) lower boundary lb[t * NX_MG + PG] = 0 lb[t * NX_MG + QG] = mg["DG"]["QMIN"] lb[t * NX_MG + PUG] = 0 lb[t * NX_MG + QUG] = mg["UG"]["QMIN"] lb[t * NX_MG + PBIC_DC2AC] = 0 lb[t * NX_MG + PBIC_AC2DC] = 0 lb[t * NX_MG + QBIC] = -mg["BIC"]["SMAX"] lb[t * NX_MG + PESS_CH] = 0 lb[t * NX_MG + PESS_DC] = 0 lb[t * NX_MG + EESS] = mg["ESS"]["EMIN"] lb[t * NX_MG + PMESS] = pmess_l ## 1.2) upper boundary ub[t * NX_MG + PG] = mg["DG"]["PMAX"] ub[t * NX_MG + QG] = mg["DG"]["QMAX"] ub[t * NX_MG + PUG] = mg["UG"]["PMAX"] ub[t * NX_MG + QUG] = mg["UG"]["QMAX"] ub[t * NX_MG + PBIC_DC2AC] = mg["BIC"]["PMAX"] ub[t * NX_MG + PBIC_AC2DC] = mg["BIC"]["PMAX"] ub[t * NX_MG + QBIC] = mg["BIC"]["SMAX"] ub[t * NX_MG + PESS_CH] = mg["ESS"]["PCH_MAX"] ub[t * NX_MG + PESS_DC] = mg["ESS"]["PDC_MAX"] ub[t * NX_MG + EESS] = mg["ESS"]["EMAX"] ub[t * NX_MG + PMESS] = pmess_u ## 1.3) Objective functions c[t * NX_MG + PG] = mg["DG"]["COST_A"] c[t * NX_MG + PESS_CH] = mg["ESS"]["COST_OP"] c[t * NX_MG + PESS_DC] = mg["ESS"]["COST_OP"] # c[t * NX_MG + PBIC_AC2DC] = mg["ESS"]["COST_OP"] # c[t * NX_MG + PBIC_DC2AC] = mg["ESS"]["COST_OP"] # c[t * NX_MG + PUG] = mg["DG"]["COST_A"] # c[t * NX_MG + PMESS] = 0.001 ## 1.4) Upper and lower boundary information if t == T - 1: lb[t * NX_MG + EESS] = mg["ESS"]["E0"] ub[t * NX_MG + EESS] = mg["ESS"]["E0"] # 2) Formulate the equal constraints # 2.1) Power balance equation # a) AC bus equation Aeq = lil_matrix((T, nv)) beq = zeros(T) for t in range(T): Aeq[t, t * NX_MG + PG] = 1 Aeq[t, t * NX_MG + PUG] = 1 Aeq[t, t * NX_MG + PBIC_AC2DC] = -1 Aeq[t, t * NX_MG + PBIC_DC2AC] = mg["BIC"]["EFF_DC2AC"] beq[t] = mg["PD"]["AC"][t] # b) DC bus equation Aeq_temp = lil_matrix((T, nv)) beq_temp = zeros(T) for t in range(T): Aeq_temp[t, t * NX_MG + PBIC_AC2DC] = mg["BIC"]["EFF_AC2DC"] Aeq_temp[t, t * NX_MG + PBIC_DC2AC] = -1 Aeq_temp[t, t * NX_MG + PESS_CH] = -1 Aeq_temp[t, t * NX_MG + PESS_DC] = 1 Aeq_temp[t, t * NX_MG + PMESS] = 1 # The power injection from mobile energy storage systems beq_temp[t] = mg["PD"]["DC"][t] Aeq = vstack([Aeq, Aeq_temp]) beq = concatenate([beq, beq_temp]) # c) AC reactive power balance equation Aeq_temp = lil_matrix((T, nv)) beq_temp = zeros(T) for t in range(T): Aeq_temp[t, t * NX_MG + QUG] = 1 Aeq_temp[t, t * NX_MG + QBIC] = 1 Aeq_temp[t, t * NX_MG + QG] = 1 beq_temp[t] = mg["QD"]["AC"][t] Aeq = vstack([Aeq, Aeq_temp]) beq = concatenate([beq, beq_temp]) # 2.2) Energy storage balance equation Aeq_temp = lil_matrix((T, nv)) beq_temp = zeros(T) for t in range(T): Aeq_temp[t, t * NX_MG + EESS] = 1 Aeq_temp[t, t * NX_MG + PESS_CH] = -mg["ESS"]["EFF_CH"] Aeq_temp[t, t * NX_MG + PESS_DC] = 1 / mg["ESS"]["EFF_DC"] if t == 0: beq_temp[t] = mg["ESS"]["E0"] else: Aeq_temp[t, (t - 1) * NX_MG + EESS] = -1 Aeq = vstack([Aeq, Aeq_temp]) beq = concatenate([beq, beq_temp]) # 3) Formualte inequality constraints # There is no inequality constraint. # sol = milp(c, Aeq=Aeq, beq=beq, A=None, b=None, xmin=lb, xmax=ub) model_micro_grid = {"c": c, "q": q, "lb": lb, "ub": ub, "vtypes": vtypes, "A": None, "b": None, "Aeq": Aeq, "beq": beq } return model_micro_grid def problem_formulation_tess(self, mess, tns): """ Problem formulation for transportation energy storage scheduling, including vehicle routine problem and etc. :param tess: specific tess information :param traffic_network: transportation network information :return: """ nb_tra = self.nb_tra T = self.T nb = self.nb nl_tra = tns["branch"].shape[0] # Formulate the connection matrix between the transportation networks and power networks connection_matrix = zeros(((2 * nl_tra + nb_tra) * T, 4)) weight = zeros((2 * nl_tra + nb_tra) * T) for i in range(T): for j in range(nl_tra): # Add from matrix connection_matrix[i * (2 * nl_tra + nb_tra) + j, F_BUS] = tns["branch"][j, F_BUS] + i * nb_tra connection_matrix[i * (2 * nl_tra + nb_tra) + j, T_BUS] = tns["branch"][j, T_BUS] + \ tns["branch"][j, TIME] * nb_tra + i * nb_tra weight[i * (2 * nl_tra + nb_tra) + j] = 1 connection_matrix[i * (2 * nl_tra + nb_tra) + j, TIME] = tns["branch"][j, TIME] for j in range(nl_tra): # Add to matrix connection_matrix[i * (2 * nl_tra + nb_tra) + j + nl_tra, F_BUS] = tns["branch"][j, T_BUS] + i * nb_tra connection_matrix[i * (2 * nl_tra + nb_tra) + j + nl_tra, T_BUS] = tns["branch"][j, F_BUS] + \ tns["branch"][j, TIME] * nb_tra + \ i * nb_tra weight[i * (2 * nl_tra + nb_tra) + j + nl_tra] = 1 connection_matrix[i * (2 * nl_tra + nb_tra) + j + nl_tra, TIME] = tns["branch"][j, TIME] for j in range(nb_tra): connection_matrix[i * (2 * nl_tra + nb_tra) + 2 * nl_tra + j, F_BUS] = j + i * nb_tra connection_matrix[i * (2 * nl_tra + nb_tra) + 2 * nl_tra + j, T_BUS] = j + (i + 1) * nb_tra if tns["bus"][j, LOCATION] >= 0: connection_matrix[i * (2 * nl_tra + nb_tra) + 2 * nl_tra + j, 3] = tns["bus"][j, LOCATION] + i * nb # Delete the out of range lines index = find(connection_matrix[:, T_BUS] < T * nb_tra) connection_matrix = connection_matrix[index, :] weight = weight[index] # add two virtual nodes to represent the initial and end status of vehicles # special attention should be paid here, as the original index has been modified! connection_matrix[:, F_BUS] += 1 connection_matrix[:, T_BUS] += 1 # From matrix temp = zeros((nb_tra, 4)) weight_temp = zeros(nb_tra) for i in range(nb_tra): temp[i, 1] = i + 1 connection_matrix = concatenate([temp, connection_matrix]) weight = concatenate([weight_temp, weight]) # To matrix for i in range(nb_tra): temp = zeros((1, 4)) temp[0, 0] = nb_tra * (T - 1) + i + 1 temp[0, 1] = nb_tra * T + 1 if tns["bus"][i, LOCATION] >= 0: temp[0, 3] = tns["bus"][i, LOCATION] + (T - 1) * nb connection_matrix = concatenate([connection_matrix, temp]) weight_temp = zeros(1) weight = concatenate([weight, weight_temp]) # Status transition matrix nl_tra = connection_matrix.shape[0] # 0 represents that, the bus is not within the power networks nb_tra_ele = sum((tns["bus"][:, 2]) >= 0) status_matrix = zeros((T, nl_tra)) for i in range(T): for j in range(nl_tra): if connection_matrix[j, F_BUS] >= i * nb_tra + 1 and connection_matrix[j, F_BUS] < (i + 1) * nb_tra + 1: status_matrix[i, j] = 1 if connection_matrix[j, F_BUS] <= i * nb_tra + 1 and connection_matrix[j, T_BUS] > (i + 1) * nb_tra + 1: status_matrix[i, j] = 1 # Update connection matrix connection_matrix_f = zeros((T * nb_tra + 2, nl_tra)) connection_matrix_t = zeros((T * nb_tra + 2, nl_tra)) for i in range(T * nb_tra + 2): connection_matrix_f[i, find(connection_matrix[:, F_BUS] == i)] = 1 connection_matrix_t[i, find(connection_matrix[:, T_BUS] == i)] = 1 n_stops = find(connection_matrix[:, 3]).__len__() assert n_stops == nb_tra_ele * T, "The number of bus stop is not right!" nv_tra = nl_tra + 4 * n_stops # Status transition, discharging status, charging rate, discharging rate, spinning reserve lx = zeros(nv_tra) ux = ones(nv_tra) self.nv_tra = nv_tra self.nl_tra = nl_tra self.n_stops = n_stops self.nb_tra_ele = nb_tra_ele self.connection_matrix = connection_matrix ux[nl_tra + 0 * n_stops:nl_tra + 1 * n_stops] = 1 ux[nl_tra + 1 * n_stops:nl_tra + 2 * n_stops] = mess["PDMAX"] ux[nl_tra + 2 * n_stops:nl_tra + 3 * n_stops] = mess["PCMAX"] ux[nl_tra + 3 * n_stops:nl_tra + 4 * n_stops] = mess["PCMAX"] + mess["PDMAX"] # The initial location and stop location lx[find(connection_matrix[:, F_BUS] == 0)] = mess["initial"] ux[find(connection_matrix[:, F_BUS] == 0)] = mess["initial"] lx[find(connection_matrix[:, T_BUS] == T * nb_tra + 1)] = mess["end"] ux[find(connection_matrix[:, T_BUS] == T * nb_tra + 1)] = mess["end"] vtypes = ["b"] * nl_tra + ["b"] * n_stops + ["c"] * 3 * n_stops Aeq = connection_matrix_f - connection_matrix_t beq = zeros(T * nb_tra + 2) beq[0] = 1 beq[-1] = -1 # statue constraints Aeq_temp = status_matrix beq_temp = ones(T) Aeq = concatenate([Aeq, Aeq_temp]) beq = concatenate([beq, beq_temp]) neq_traffic = Aeq.shape[0] # Fulfill the missing zeros Aeq = concatenate([Aeq, zeros((neq_traffic, 4 * n_stops))], axis=1) ## Inequality constraints index_stops = find(connection_matrix[:, 3]) index_operation = arange(n_stops) power_limit = sparse((ones(n_stops), (index_operation, index_stops)), (n_stops, nl_tra)) # This mapping matrix plays an important role in the connection between the power network and traffic network ## 1) Stopping status A = zeros((3 * n_stops, nv_tra)) # Charging, discharging status, RBS # Discharging A[0:n_stops, 0: nl_tra] = -power_limit.toarray() * mess["PDMAX"] A[0:n_stops, nl_tra + n_stops: nl_tra + 2 * n_stops] = eye(n_stops) # Charging A[n_stops:n_stops * 2, 0: nl_tra] = -power_limit.toarray() * mess["PCMAX"] A[n_stops:n_stops * 2, nl_tra + 2 * n_stops:nl_tra + 3 * n_stops] = eye(n_stops) # spinning reserve A[n_stops * 2: n_stops * 3, 0: nl_tra] = -power_limit.toarray() * (mess["PCMAX"] + mess["PDMAX"]) A[n_stops * 2:n_stops * 3, nl_tra + 3 * n_stops:nl_tra + 4 * n_stops] = eye(n_stops) b = zeros(3 * n_stops) ## 2) Operating status Arange = zeros((2 * n_stops, nv_tra)) brange = zeros(2 * n_stops) # 1) Pdc<(1-Ic)*Pdc_max Arange[0: n_stops, nl_tra:nl_tra + n_stops] = eye(n_stops) * mess["PDMAX"] Arange[0: n_stops, nl_tra + n_stops: nl_tra + n_stops * 2] = eye(n_stops) brange[0: n_stops] = ones(n_stops) * mess["PDMAX"] # 2) Pc<Ic*Pch_max Arange[n_stops:n_stops * 2, nl_tra: nl_tra + n_stops] = -eye(n_stops) * mess["PCMAX"] Arange[n_stops:n_stops * 2, nl_tra + n_stops * 2: nl_tra + n_stops * 3] = eye(n_stops) A = concatenate([A, Arange]) b = concatenate([b, brange]) ## 2) Power limitation Areserve = zeros((2 * n_stops, nv_tra)) breserve = zeros(2 * n_stops) # 1) Pdc-Pc+Rbs<=Pdc_max Areserve[0: n_stops, nl_tra + n_stops: nl_tra + n_stops * 2] = eye(n_stops) Areserve[0: n_stops, nl_tra + n_stops * 2:nl_tra + n_stops * 3] = -eye(n_stops) Areserve[0: n_stops, nl_tra + n_stops * 3:nl_tra + n_stops * 4] = eye(n_stops) breserve[0: n_stops] = ones(n_stops) * mess["PDMAX"] # 2) Pc-Pdc+Rbs<=Pc_max Areserve[n_stops:n_stops * 2, nl_tra + n_stops: nl_tra + n_stops * 2] = - eye(n_stops) Areserve[n_stops:n_stops * 2, nl_tra + n_stops * 2:nl_tra + n_stops * 3] = eye(n_stops) Areserve[n_stops:n_stops * 2, nl_tra + n_stops * 3:nl_tra + n_stops * 4] = eye(n_stops) breserve[n_stops:n_stops * 2] = ones(n_stops) * mess["PCMAX"] A = concatenate([A, Areserve]) b = concatenate([b, breserve]) # Add constraints on the energy status Aenergy = zeros((2 * T, nv_tra)) benergy = zeros(2 * T) for j in range(T): # minimal energy Aenergy[j, nl_tra + n_stops:nl_tra + n_stops + (j + 1) * nb_tra_ele] = 1 / mess["EFF_DC"] Aenergy[j, nl_tra + 2 * n_stops:nl_tra + 2 * n_stops + (j + 1) * nb_tra_ele] = -mess["EFF_CH"] # Aenergy[j, NX_status + 3 * n_stops + (j + 1) * nb_traffic_electric - 1] = 0.5 if j != (T - 1): benergy[j] = mess["E0"] - mess["EMIN"] else: benergy[j] = 0 # maximal energy Aenergy[T + j, nl_tra + n_stops: nl_tra + n_stops + (j + 1) * nb_tra_ele] = -1 / mess["EFF_DC"] Aenergy[T + j, nl_tra + 2 * n_stops:nl_tra + 2 * n_stops + (j + 1) * nb_tra_ele] = mess["EFF_CH"] if j != (T - 1): benergy[T + j] = mess["EMAX"] - mess["E0"] else: benergy[T + j] = 0 A = concatenate([A, Aenergy]) b = concatenate([b, benergy]) c = concatenate([connection_matrix[:, TIME], zeros(n_stops * 4)]) # sol = milp(zeros(NX_traffic), q=zeros(NX_traffic), Aeq=Aeq, beq=beq, A=A, b=b, xmin=lx, xmax=ux) model_tess = {"c": c, "q": zeros(nv_tra), "lb": lx, "ub": ux, "vtypes": vtypes, "A": A, "b": b, "Aeq": Aeq, "beq": beq, "NV": nv_tra, } return model_tess def problem_formulation_tess_second_stage(self, mess): """ Problem formulation for transportation energy storage scheduling, including vehicle routine problem and etc. :param tess: specific tess information :param traffic_network: transportation network information :return: """ T = self.T n_stops = self.n_stops # Number of stops in nb_tra_ele = self.nb_tra_ele nv = 2 * n_stops + T # Status transition, charging status, charging rate, discharging rate, spinning reserve lb = zeros(nv) ub = zeros(nv) lb[n_stops * 2:nv] = mess["EMIN"] ub[n_stops * 0:n_stops * 1] = mess["PDMAX"] ub[n_stops * 1:n_stops * 2] = mess["PCMAX"] ub[n_stops * 2:nv] = mess["EMAX"] lb[-1] = mess["E0"] # energy storage systems end status ub[-1] = mess["E0"] # energy storage systems end status vtypes = ["c"] * nv # The energy status dynamics Aeq = zeros((T, nv)) beq = zeros(T) for t in range(T): Aeq[t, n_stops * 2 + t] = 1 Aeq[t, n_stops + nb_tra_ele * t:n_stops + nb_tra_ele * (t + 1)] = -mess["EFF_CH"] Aeq[t, nb_tra_ele * t:nb_tra_ele * (t + 1)] = 1 / mess["EFF_DC"] if t == 0: beq[t] = mess["E0"] else: Aeq[t, n_stops * 2 + t - 1] = -1 c = concatenate((ones(n_stops * 2) * mess["COST_OP"], zeros(T))) # sol = milp(c, Aeq=Aeq, beq=beq, A=None, b=None, xmin=lx, xmax=ux) model_tess = {"c": c, "q": zeros(nv), "lb": lb, "ub": ub, "vtypes": vtypes, "A": None, "b": None, "Aeq": Aeq, "beq": beq, "NX": nv, } return model_tess def scenario_generation_reduction(self, micro_grids, profile, pns, update=1, ns=2, ns_reduced=2, std=0.03, interval=0.05): """ Scenario generation function for the second-stage scheduling Stochastic variables include 1) loads in distribution networks, active loads for 2) AC bus and 3)DC bus. The assumption is that, the 1) loads in distribution networks follow normal distribution nb*T 2) loads for AC bus and DC bus follow uniform distribution nmg*T*4 3) update is the parameters to control the :return: """ T = self.T nmg = self.nmg nb = self.nb db_management = DataBaseManagement(host="localhost", user="root", password="Ntu@1003", db="mess") if update > 0: # 1) scenario generation bus_load = zeros((ns, nb * T)) mg_load = zeros((ns, nmg * T * 2)) weight = ones(ns) / ns for i in range(ns): for t in range(T): for j in range(nb): bus_load[i, t * nb + j] = pns["bus"][j, PD] * (1 + random.normal(0, std)) * profile[t] for j in range(nmg): mg_load[i, t * nmg + j] = micro_grids[j]["PD"]["AC"][t] * \ (1 + random.uniform(-interval, interval)) mg_load[i, nmg * T + t * nmg + j] = micro_grids[j]["PD"]["DC"][t] * \ (1 + random.uniform(-interval, interval)) # 2) scenario reduction scenario_reduction = ScenarioReduction() (scenario_reduced, weight_reduced) = \ scenario_reduction.run(scenario=concatenate([bus_load, mg_load], axis=1), weight=weight, n_reduced=ns_reduced, power=2) # 3) Store the data into database db_management.create_table("scenarios", nb=nb, nmg=nmg) for i in range(ns - ns_reduced): for t in range(T): db_management.insert_data_scenario("scenarios", scenario=i, weight=weight_reduced[i], time=t, nb=nb, pd=scenario_reduced[i, t * nb:(t + 1) * nb].tolist(), nmg=nmg, pd_ac=scenario_reduced[i, nb * T + t * nmg: nb * T + (t + 1) * nmg].tolist(), pd_dc=scenario_reduced[i, nb * T + nmg * T + t * nmg: nb * T + nmg * T + ( t + 1) * nmg].tolist()) else: # 4) if not updated, inquery the database scenario_reduced = zeros((ns - ns_reduced, nb * T + nmg * T * 2)) weight_reduced = zeros(ns - ns_reduced) for i in range(ns - ns_reduced): for t in range(T): data = db_management.inquery_data_scenario(table_name="scenarios", scenario=i, time=t) weight_reduced[i] = data[1] scenario_reduced[i, nb * t:nb * (t + 1)] = array(data[3:nb + 3]) scenario_reduced[i, nb * T + nmg * t:nb * T + nmg * (t + 1)] = array(data[nb + 3:nb + 3 + nmg]) scenario_reduced[i, nb * T + nmg * T + nmg * t:nb * T + nmg * T + nmg * (t + 1)] = \ array(data[nb + 3:nb + 3 + nmg]) # assert sum(weight_reduced) == 1, "The weight factor is not right!" # 4) return value ds_load_profile = scenario_reduced[:, 0:nb * T] mgs_load_profile = scenario_reduced[:, nb * T:] # profile_second_stage = zeros((ns, T)) microgrids_second_stage = [0] * (ns - ns_reduced) # for i in range(ns): # for j in range(T): # profile_second_stage[i, j] = profile[j] * (1 + 0.5 * random.random()) # for i in range(ns - ns_reduced): microgrids_second_stage[i] = deepcopy(micro_grids) for j in range(nmg): for t in range(T): microgrids_second_stage[i][j]["PD"]["AC"][t] = mgs_load_profile[i, t * nmg + j] microgrids_second_stage[i][j]["QD"]["AC"][t] = mgs_load_profile[i, t * nmg + j] * 0.2 microgrids_second_stage[i][j]["PD"]["DC"][t] = mgs_load_profile[i, T * nmg + t * nmg + j] return ds_load_profile, microgrids_second_stage, weight_reduced if __name__ == "__main__": # Distribution network information mpc = case33.case33() # Default test case load_profile = array( [0.17, 0.41, 0.63, 0.86, 0.94, 1.00, 0.95, 0.81, 0.59, 0.35, 0.14, 0.17, 0.41, 0.63, 0.86, 0.94, 1.00, 0.95, 0.81, 0.59, 0.35, 0.14, 0.17, 0.41]) * 2 # Microgrid information Profile = array([ [0.64, 0.63, 0.65, 0.64, 0.66, 0.69, 0.75, 0.91, 0.95, 0.97, 1.00, 0.97, 0.97, 0.95, 0.98, 0.99, 0.95, 0.95, 0.94, 0.95, 0.97, 0.93, 0.85, 0.69], [0.78, 0.75, 0.74, 0.74, 0.75, 0.81, 0.91, 0.98, 0.99, 0.99, 1.00, 0.99, 0.99, 0.99, 0.98, 0.97, 0.96, 0.95, 0.95, 0.95, 0.96, 0.95, 0.88, 0.82], [0.57, 0.55, 0.55, 0.56, 0.62, 0.70, 0.78, 0.83, 0.84, 0.89, 0.87, 0.82, 0.80, 0.80, 0.84, 0.89, 0.94, 0.98, 1.00, 0.97, 0.87, 0.79, 0.72, 0.62] ]) # Add start-up, shut-down status, initial status, start-up/shut cost of DGs # The DGs within the DS are optimized!
micro_grid_1 = deepcopy(micro_grid)
1
2023-11-27 15:57:53+00:00
24k
girgle/DouZero_For_New_HLDDZ
GOOD.py
[ { "identifier": "GameHelper", "path": "GameHelper.py", "snippet": "class GameHelper:\n def __init__(self):\n self.ScreenZoomRate = None\n self.counter = QTime()\n self.Pics = {}\n self.PicsCV = {}\n st = time.time()\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n self.Interrupt = False\n self.RealRate = (1440, 810)\n self.GetZoomRate()\n for file in os.listdir(\"./pics\"):\n info = file.split(\".\")\n if info[1] == \"png\":\n tmpImage = Image.open(\"./pics/\" + file)\n imgCv = cv2.imread(\"./pics/\" + file)\n self.Pics.update({info[0]: tmpImage})\n self.PicsCV.update({info[0]: imgCv})\n\n def sleep(self, ms):\n self.counter.restart()\n while self.counter.elapsed() < ms:\n QtWidgets.QApplication.processEvents(QEventLoop.AllEvents, 50)\n\n def Screenshot(self, region=None): # -> (im, (left, top))\n try_count = 3\n success = False\n while try_count > 0 and not success:\n try:\n try_count -= 1\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n hwnd = self.Handle\n left, top, right, bot = win32gui.GetWindowRect(hwnd)\n width = right - left\n height = bot - top\n self.RealRate = (width, height)\n width = int(width)\n height = int(height)\n hwndDC = win32gui.GetWindowDC(hwnd)\n mfcDC = win32ui.CreateDCFromHandle(hwndDC)\n saveDC = mfcDC.CreateCompatibleDC()\n saveBitMap = win32ui.CreateBitmap()\n saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)\n saveDC.SelectObject(saveBitMap)\n result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 3)\n bmpinfo = saveBitMap.GetInfo()\n bmpstr = saveBitMap.GetBitmapBits(True)\n im = Image.frombuffer(\n \"RGB\",\n (bmpinfo['bmWidth'], bmpinfo['bmHeight']),\n bmpstr, 'raw', 'BGRX', 0, 1)\n win32gui.DeleteObject(saveBitMap.GetHandle())\n saveDC.DeleteDC()\n mfcDC.DeleteDC()\n win32gui.ReleaseDC(hwnd, hwndDC)\n im = im.resize((1440, 810))\n if region is not None:\n im = im.crop((region[0], region[1], region[0] + region[2], region[1] + region[3]))\n if result:\n success = True\n return im, (left, top)\n except Exception as e:\n print(\"截图时出现错误:\", repr(e))\n self.sleep(200)\n return None, (0, 0)\n\n def GetZoomRate(self):\n self.ScreenZoomRate = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100\n\n def LocateOnScreen(self, templateName, region, confidence=0.8, img=None):\n if img is not None:\n image = img\n else:\n image, _ = self.Screenshot()\n imgcv = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)\n return LocateOnImage(imgcv, self.PicsCV[templateName], region=region, confidence=confidence)\n\n def ClickOnImage(self, templateName, region=None, confidence=0.8, img=None):\n if img is not None:\n image = img\n else:\n image, _ = self.Screenshot()\n imgcv = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)\n result = LocateOnImage(imgcv, self.PicsCV[templateName], region=region, confidence=confidence)\n\n if result is not None:\n self.LeftClick(result)\n print(result)\n\n def LeftClick(self, pos):\n x, y = pos\n x = (x / 1440) * self.RealRate[0]\n y = (y / 810) * self.RealRate[1]\n x = int(x)\n y = int(y)\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n left, top, _, _ = win32gui.GetWindowRect(self.Handle)\n x, y = int(left + x), int(top + y)\n\n pyautogui.mouseDown(x, y, button='left')\n time.sleep(0.1)\n pyautogui.mouseUp(x, y, button='left')\n time.sleep(0.1)\n pyautogui.moveTo(int(left + 1000), int(top + 550))\n\n '''win32gui.SetActiveWindow(self.Handle)\n lParam = win32api.MAKELONG(x, y)\n\n win32gui.PostMessage(self.Handle, WM_ACTIVATE, WA_ACTIVE, lParam)\n win32gui.PostMessage(self.Handle, WM_ACTIVATE, WA_ACTIVE, lParam)\n win32gui.PostMessage(self.Handle, WM_MOUSEMOVE, MK_LBUTTON, lParam)\n win32gui.PostMessage(self.Handle, WM_LBUTTONDOWN, MK_LBUTTON, lParam)\n win32gui.PostMessage(self.Handle, WM_LBUTTONUP, MK_LBUTTON, lParam)'''\n\n def LeftClick2(self, pos):\n x, y = pos\n x = (x / 1440) * self.RealRate[0]\n y = (y / 810) * self.RealRate[1]\n x = int(x)\n y = int(y)\n self.Handle = win32gui.FindWindow(\"UnityWndClass\", None)\n left, top, _, _ = win32gui.GetWindowRect(self.Handle)\n x, y = int(left + x), int(top + y)\n\n pyautogui.mouseDown(x, y, button='left')\n time.sleep(0.1)\n pyautogui.mouseUp(x, y, button='left')" }, { "identifier": "get_move_type", "path": "douzero/env/move_detector.py", "snippet": "def get_move_type(move):\n move_size = len(move)\n move_dict = collections.Counter(move)\n\n if move_size == 0:\n return {'type': TYPE_0_PASS}\n\n if move_size == 1:\n return {'type': TYPE_1_SINGLE, 'rank': move[0]}\n\n if move_size == 2:\n if move[0] == move[1]:\n return {'type': TYPE_2_PAIR, 'rank': move[0]}\n elif move == [20, 30]: # Kings\n return {'type': TYPE_5_KING_BOMB}\n else:\n return {'type': TYPE_15_WRONG}\n\n if move_size == 3:\n if len(move_dict) == 1:\n return {'type': TYPE_3_TRIPLE, 'rank': move[0]}\n else:\n return {'type': TYPE_15_WRONG}\n\n if move_size == 4:\n if len(move_dict) == 1:\n return {'type': TYPE_4_BOMB, 'rank': move[0]}\n elif len(move_dict) == 2:\n if move[0] == move[1] == move[2] or move[1] == move[2] == move[3]:\n return {'type': TYPE_6_3_1, 'rank': move[1]}\n else:\n return {'type': TYPE_15_WRONG}\n else:\n return {'type': TYPE_15_WRONG}\n\n if is_continuous_seq(move):\n return {'type': TYPE_8_SERIAL_SINGLE, 'rank': move[0], 'len': len(move)}\n\n if move_size == 5:\n if len(move_dict) == 2:\n return {'type': TYPE_7_3_2, 'rank': move[2]}\n else:\n return {'type': TYPE_15_WRONG}\n\n count_dict = collections.defaultdict(int)\n for c, n in move_dict.items():\n count_dict[n] += 1\n\n if move_size == 6:\n if (len(move_dict) == 2 or len(move_dict) == 3) and count_dict.get(4) == 1 and \\\n (count_dict.get(2) == 1 or count_dict.get(1) == 2):\n return {'type': TYPE_13_4_2, 'rank': move[2]}\n\n if move_size == 8 and (((len(move_dict) == 3 or len(move_dict) == 2) and\n (count_dict.get(4) == 1 and count_dict.get(2) == 2)) or count_dict.get(4) == 2):\n return {'type': TYPE_14_4_22, 'rank': max([c for c, n in move_dict.items() if n == 4])}\n\n mdkeys = sorted(move_dict.keys())\n if len(move_dict) == count_dict.get(2) and is_continuous_seq(mdkeys):\n return {'type': TYPE_9_SERIAL_PAIR, 'rank': mdkeys[0], 'len': len(mdkeys)}\n\n if len(move_dict) == count_dict.get(3) and is_continuous_seq(mdkeys):\n return {'type': TYPE_10_SERIAL_TRIPLE, 'rank': mdkeys[0], 'len': len(mdkeys)}\n\n # Check Type 11 (serial 3+1) and Type 12 (serial 3+2)\n if count_dict.get(3, 0) >= MIN_TRIPLES:\n serial_3 = list()\n single = list()\n pair = list()\n\n for k, v in move_dict.items():\n if v == 3:\n serial_3.append(k)\n elif v == 1:\n single.append(k)\n elif v == 2:\n pair.append(k)\n else: # no other possibilities\n return {'type': TYPE_15_WRONG}\n\n serial_3.sort()\n if is_continuous_seq(serial_3):\n if len(serial_3) == len(single)+len(pair)*2:\n return {'type': TYPE_11_SERIAL_3_1, 'rank': serial_3[0], 'len': len(serial_3)}\n if len(serial_3) == len(pair) and len(move_dict) == len(serial_3) * 2:\n return {'type': TYPE_12_SERIAL_3_2, 'rank': serial_3[0], 'len': len(serial_3)}\n\n if len(serial_3) == 4:\n if is_continuous_seq(serial_3[1:]):\n return {'type': TYPE_11_SERIAL_3_1, 'rank': serial_3[1], 'len': len(serial_3) - 1}\n if is_continuous_seq(serial_3[:-1]):\n return {'type': TYPE_11_SERIAL_3_1, 'rank': serial_3[0], 'len': len(serial_3) - 1}\n\n return {'type': TYPE_15_WRONG}" }, { "identifier": "Ui_Form", "path": "MainWindow.py", "snippet": "class Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(677, 450)\n font = QtGui.QFont()\n font.setFamily(\"Arial\")\n font.setPointSize(9)\n font.setBold(True)\n font.setItalic(False)\n font.setWeight(75)\n Form.setFont(font)\n Form.setWindowOpacity(0.8)\n self.WinRate = QtWidgets.QLabel(Form)\n self.WinRate.setGeometry(QtCore.QRect(320, 120, 121, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.WinRate.setFont(font)\n self.WinRate.setAlignment(QtCore.Qt.AlignCenter)\n self.WinRate.setObjectName(\"WinRate\")\n self.UserHandCards = QtWidgets.QLabel(Form)\n self.UserHandCards.setGeometry(QtCore.QRect(30, 330, 351, 31))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.UserHandCards.setFont(font)\n self.UserHandCards.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.UserHandCards.setObjectName(\"UserHandCards\")\n self.ThreeLandlordCards = QtWidgets.QLabel(Form)\n self.ThreeLandlordCards.setGeometry(QtCore.QRect(30, 120, 121, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.ThreeLandlordCards.setFont(font)\n self.ThreeLandlordCards.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.ThreeLandlordCards.setObjectName(\"ThreeLandlordCards\")\n self.BidWinrate = QtWidgets.QLabel(Form)\n self.BidWinrate.setGeometry(QtCore.QRect(30, 220, 161, 31))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.BidWinrate.setFont(font)\n self.BidWinrate.setObjectName(\"BidWinrate\")\n self.PreWinrate = QtWidgets.QLabel(Form)\n self.PreWinrate.setGeometry(QtCore.QRect(30, 280, 161, 31))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.PreWinrate.setFont(font)\n self.PreWinrate.setObjectName(\"PreWinrate\")\n self.label = QtWidgets.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(490, 320, 101, 41))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.label.setFont(font)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(\"label\")\n self.LPlayedCard = QtWidgets.QLabel(Form)\n self.LPlayedCard.setGeometry(QtCore.QRect(170, 120, 102, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.LPlayedCard.setFont(font)\n self.LPlayedCard.setAlignment(QtCore.Qt.AlignCenter)\n self.LPlayedCard.setObjectName(\"LPlayedCard\")\n self.splitter_2 = QtWidgets.QSplitter(Form)\n self.splitter_2.setGeometry(QtCore.QRect(20, 380, 621, 41))\n self.splitter_2.setOrientation(QtCore.Qt.Horizontal)\n self.splitter_2.setObjectName(\"splitter_2\")\n self.SingleButton = QtWidgets.QPushButton(self.splitter_2)\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.SingleButton.setFont(font)\n self.SingleButton.setObjectName(\"SingleButton\")\n self.LoopButton = QtWidgets.QPushButton(self.splitter_2)\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.LoopButton.setFont(font)\n self.LoopButton.setObjectName(\"LoopButton\")\n self.StopButton = QtWidgets.QPushButton(self.splitter_2)\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.StopButton.setFont(font)\n self.StopButton.setObjectName(\"StopButton\")\n self.tableWidget = QtWidgets.QTableWidget(Form)\n self.tableWidget.setGeometry(QtCore.QRect(20, 10, 611, 75))\n self.tableWidget.setMaximumSize(QtCore.QSize(16777215, 75))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(12)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.tableWidget.setFont(font)\n self.tableWidget.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.tableWidget.setStyleSheet(\"QTableWidget{\\n\"\n\"color:#DCDCDC;\\n\"\n\"background:#444444;\\n\"\n\"border:1px solid #242424;\\n\"\n\"alternate-background-color:#525252;\\n\"\n\"gridline-color:#242424;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QTableWidget::item:selected{\\n\"\n\"color:#DCDCDC;\\n\"\n\"background:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #484848,stop:1 #383838);\\n\"\n\"}\\n\"\n\" \\n\"\n\"QTableWidget::item:hover{\\n\"\n\"background:#5B5B5B;\\n\"\n\"}\\n\"\n\"QHeaderView::section{\\n\"\n\"text-align:center;\\n\"\n\"background:#5E5E5E;\\n\"\n\"padding:3px;\\n\"\n\"margin:0px;\\n\"\n\"color:#DCDCDC;\\n\"\n\"border:1px solid #242424;\\n\"\n\"border-left-width:0;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QScrollBar:vertical{\\n\"\n\"background:#484848;\\n\"\n\"padding:0px;\\n\"\n\"border-radius:6px;\\n\"\n\"max-width:12px;\\n\"\n\"}\\n\"\n\" \\n\"\n\" \\n\"\n\"QScrollBar::handle:vertical{\\n\"\n\"background:#CCCCCC;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QScrollBar::handle:hover:vertical,QScrollBar::handle:pressed:vertical{\\n\"\n\"background:#A7A7A7;\\n\"\n\"}\\n\"\n\"QScrollBar::sub-page:vertical{\\n\"\n\"background:444444;\\n\"\n\"}\\n\"\n\" \\n\"\n\" \\n\"\n\"QScrollBar::add-page:vertical{\\n\"\n\"background:5B5B5B;\\n\"\n\"}\\n\"\n\" \\n\"\n\"QScrollBar::add-line:vertical{\\n\"\n\"background:none;\\n\"\n\"}\\n\"\n\"QScrollBar::sub-line:vertical{\\n\"\n\"background:none;\\n\"\n\"}\")\n self.tableWidget.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.tableWidget.setMidLineWidth(-1)\n self.tableWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.tableWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.tableWidget.setAutoScroll(False)\n self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)\n self.tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)\n self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)\n self.tableWidget.setTextElideMode(QtCore.Qt.ElideNone)\n self.tableWidget.setObjectName(\"tableWidget\")\n self.tableWidget.setColumnCount(15)\n self.tableWidget.setRowCount(1)\n item = QtWidgets.QTableWidgetItem()\n self.tableWidget.setVerticalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(0, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(1, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(2, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(3, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(4, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(5, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(6, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(7, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(8, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(9, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(10, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(11, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(12, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(13, item)\n item = QtWidgets.QTableWidgetItem()\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n self.tableWidget.setHorizontalHeaderItem(14, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 0, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 1, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 2, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 3, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 4, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 5, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 6, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 7, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 8, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 9, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 10, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 11, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 12, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 13, item)\n item = QtWidgets.QTableWidgetItem()\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n self.tableWidget.setItem(0, 14, item)\n self.tableWidget.horizontalHeader().setVisible(True)\n self.tableWidget.horizontalHeader().setCascadingSectionResizes(True)\n self.tableWidget.horizontalHeader().setDefaultSectionSize(41)\n self.tableWidget.horizontalHeader().setStretchLastSection(True)\n self.tableWidget.verticalHeader().setVisible(False)\n self.tableWidget.verticalHeader().setCascadingSectionResizes(False)\n self.tableWidget.verticalHeader().setDefaultSectionSize(40)\n self.tableWidget.verticalHeader().setHighlightSections(True)\n self.tableWidget.verticalHeader().setMinimumSectionSize(40)\n self.tableWidget.verticalHeader().setSortIndicatorShown(False)\n self.RPlayedCard = QtWidgets.QLabel(Form)\n self.RPlayedCard.setGeometry(QtCore.QRect(490, 120, 102, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.RPlayedCard.setFont(font)\n self.RPlayedCard.setAlignment(QtCore.Qt.AlignCenter)\n self.RPlayedCard.setObjectName(\"RPlayedCard\")\n self.PredictedCard = QtWidgets.QLabel(Form)\n self.PredictedCard.setGeometry(QtCore.QRect(320, 190, 121, 51))\n font = QtGui.QFont()\n font.setFamily(\"微软雅黑\")\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.PredictedCard.setFont(font)\n self.PredictedCard.setStyleSheet(\"\")\n self.PredictedCard.setFrameShape(QtWidgets.QFrame.Panel)\n self.PredictedCard.setLineWidth(1)\n self.PredictedCard.setAlignment(QtCore.Qt.AlignCenter)\n self.PredictedCard.setObjectName(\"PredictedCard\")\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n _translate = QtCore.QCoreApplication.translate\n Form.setWindowTitle(_translate(\"Form\", \"Hi\"))\n self.WinRate.setText(_translate(\"Form\", \"评分\"))\n self.UserHandCards.setText(_translate(\"Form\", \"手牌\"))\n self.ThreeLandlordCards.setText(_translate(\"Form\", \"地主牌\"))\n self.BidWinrate.setText(_translate(\"Form\", \"叫牌胜率:\"))\n self.PreWinrate.setText(_translate(\"Form\", \"局前胜率:\"))\n self.label.setText(_translate(\"Form\", \"游戏状态\"))\n self.LPlayedCard.setText(_translate(\"Form\", \"上家出牌区域\"))\n self.SingleButton.setText(_translate(\"Form\", \"单局\"))\n self.LoopButton.setText(_translate(\"Form\", \" 连续\"))\n self.StopButton.setText(_translate(\"Form\", \"停止\"))\n item = self.tableWidget.horizontalHeaderItem(0)\n item.setText(_translate(\"Form\", \"大\"))\n item = self.tableWidget.horizontalHeaderItem(1)\n item.setText(_translate(\"Form\", \"小\"))\n item = self.tableWidget.horizontalHeaderItem(2)\n item.setText(_translate(\"Form\", \"2\"))\n item = self.tableWidget.horizontalHeaderItem(3)\n item.setText(_translate(\"Form\", \"A\"))\n item = self.tableWidget.horizontalHeaderItem(4)\n item.setText(_translate(\"Form\", \"K\"))\n item = self.tableWidget.horizontalHeaderItem(5)\n item.setText(_translate(\"Form\", \"Q\"))\n item = self.tableWidget.horizontalHeaderItem(6)\n item.setText(_translate(\"Form\", \"J\"))\n item = self.tableWidget.horizontalHeaderItem(7)\n item.setText(_translate(\"Form\", \"10\"))\n item = self.tableWidget.horizontalHeaderItem(8)\n item.setText(_translate(\"Form\", \"9\"))\n item = self.tableWidget.horizontalHeaderItem(9)\n item.setText(_translate(\"Form\", \"8\"))\n item = self.tableWidget.horizontalHeaderItem(10)\n item.setText(_translate(\"Form\", \"7\"))\n item = self.tableWidget.horizontalHeaderItem(11)\n item.setText(_translate(\"Form\", \"6\"))\n item = self.tableWidget.horizontalHeaderItem(12)\n item.setText(_translate(\"Form\", \"5\"))\n item = self.tableWidget.horizontalHeaderItem(13)\n item.setText(_translate(\"Form\", \"4\"))\n item = self.tableWidget.horizontalHeaderItem(14)\n item.setText(_translate(\"Form\", \"3\"))\n __sortingEnabled = self.tableWidget.isSortingEnabled()\n self.tableWidget.setSortingEnabled(False)\n item = self.tableWidget.item(0, 0)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 1)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 2)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 3)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 4)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 5)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 6)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 7)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 8)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 9)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 10)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 11)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 12)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 13)\n item.setText(_translate(\"Form\", \"0\"))\n item = self.tableWidget.item(0, 14)\n item.setText(_translate(\"Form\", \"0\"))\n self.tableWidget.setSortingEnabled(__sortingEnabled)\n self.RPlayedCard.setText(_translate(\"Form\", \"下家出牌区域\"))\n self.PredictedCard.setText(_translate(\"Form\", \"AI出牌区域\"))" }, { "identifier": "GameEnv", "path": "douzero/env/game.py", "snippet": "class GameEnv(object):\n\n def __init__(self, players):\n\n self.card_play_action_seq = []\n\n self.three_landlord_cards = None\n self.game_over = False\n\n self.acting_player_position = None\n self.player_utility_dict = None\n\n self.players = players\n\n self.last_move_dict = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.played_cards = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.last_move = []\n self.last_two_moves = []\n\n self.num_wins = {'landlord': 0,\n 'farmer': 0}\n\n self.num_scores = {'landlord': 0,\n 'farmer': 0}\n\n self.info_sets = {'landlord': InfoSet('landlord'),\n 'landlord_up': InfoSet('landlord_up'),\n 'landlord_down': InfoSet('landlord_down')}\n\n self.bomb_num = 0\n self.last_pid = 'landlord'\n\n self.bid_info = [[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]]\n self.bid_count = 0\n self.multiply_count = {'landlord': 1,\n 'landlord_up': 1,\n 'landlord_down': 1}\n self.step_count = 0\n\n\n def card_play_init(self, card_play_data):\n self.info_sets['landlord'].player_hand_cards = \\\n card_play_data['landlord']\n self.info_sets['landlord_up'].player_hand_cards = \\\n card_play_data['landlord_up']\n self.info_sets['landlord_down'].player_hand_cards = \\\n card_play_data['landlord_down']\n self.three_landlord_cards = card_play_data['three_landlord_cards']\n self.get_acting_player_position()\n self.game_infoset = self.get_infoset()\n\n\n def game_done(self):\n if len(self.info_sets['landlord'].player_hand_cards) == 0 or \\\n len(self.info_sets['landlord_up'].player_hand_cards) == 0 or \\\n len(self.info_sets['landlord_down'].player_hand_cards) == 0:\n # if one of the three players discards his hand,\n # then game is over.\n self.compute_player_utility()\n self.update_num_wins_scores()\n\n self.game_over = True\n\n def compute_player_utility(self):\n\n if len(self.info_sets['landlord'].player_hand_cards) == 0:\n self.player_utility_dict = {'landlord': 2,\n 'farmer': -1}\n else:\n self.player_utility_dict = {'landlord': -2,\n 'farmer': 1}\n\n def update_num_wins_scores(self):\n for pos, utility in self.player_utility_dict.items():\n base_score = 2 if pos == 'landlord' else 1\n if utility > 0:\n self.num_wins[pos] += 1\n self.winner = pos\n self.num_scores[pos] += base_score * (2 ** self.bomb_num)\n else:\n self.num_scores[pos] -= base_score * (2 ** self.bomb_num)\n\n def get_winner(self):\n return self.winner\n\n def get_bomb_num(self):\n return self.bomb_num\n\n def step(self, position, action=[]):\n win_rate = 0\n if self.acting_player_position == position:\n action, actions_confidence = self.players[1].act(self.game_infoset)\n # 计算胜率\n win_rate = actions_confidence\n # win_rate = max(actions_confidence, -1)\n # win_rate = min(win_rate, 1)\n # win_rate = str(round(float((win_rate + 1) / 2), 4))\n\n if len(action) > 0:\n self.last_pid = self.acting_player_position\n\n if action in bombs:\n self.bomb_num += 1\n\n self.last_move_dict[\n self.acting_player_position] = action.copy()\n\n self.card_play_action_seq.append((position, action))\n self.update_acting_player_hand_cards(action)\n\n self.played_cards[self.acting_player_position] += action\n\n if self.acting_player_position == 'landlord' and \\\n len(action) > 0 and \\\n len(self.three_landlord_cards) > 0:\n for card in action:\n if len(self.three_landlord_cards) > 0:\n if card in self.three_landlord_cards:\n self.three_landlord_cards.remove(card)\n else:\n break\n self.game_done()\n if not self.game_over:\n self.get_acting_player_position()\n self.game_infoset = self.get_infoset()\n # 返回动作和胜率,只有玩家角色会接受返回值\n action_message = {\"action\": str(''.join([EnvCard2RealCard[c] for c in action])),\n \"win_rate\": str(round(float(win_rate), 4))}\n return action_message\n\n def get_last_move(self):\n last_move = []\n if len(self.card_play_action_seq) != 0:\n if len(self.card_play_action_seq[-1][1]) == 0:\n last_move = self.card_play_action_seq[-2][1]\n else:\n last_move = self.card_play_action_seq[-1][1]\n\n return last_move\n\n def get_last_two_moves(self):\n last_two_moves = [[], []]\n for card in self.card_play_action_seq[-2:]:\n last_two_moves.insert(0, card[1])\n last_two_moves = last_two_moves[:2]\n return last_two_moves\n\n def get_acting_player_position(self):\n if self.acting_player_position is None:\n self.acting_player_position = 'landlord'\n\n else:\n if self.acting_player_position == 'landlord':\n self.acting_player_position = 'landlord_down'\n\n elif self.acting_player_position == 'landlord_down':\n self.acting_player_position = 'landlord_up'\n\n else:\n self.acting_player_position = 'landlord'\n\n return self.acting_player_position\n\n def update_acting_player_hand_cards(self, action):\n if action != []:\n # 更新玩家手牌,删除对应的牌\n if self.acting_player_position == self.players[0]:\n for card in action:\n self.info_sets[self.acting_player_position].player_hand_cards.remove(card)\n # 更新另外两个玩家手牌,删除相同数量的牌\n else:\n del self.info_sets[self.acting_player_position].player_hand_cards[0:len(action)]\n self.info_sets[self.acting_player_position].player_hand_cards.sort()\n\n def get_legal_card_play_actions(self):\n mg = MovesGener(\n self.info_sets[self.acting_player_position].player_hand_cards)\n\n action_sequence = self.card_play_action_seq\n\n rival_move = []\n if len(action_sequence) != 0:\n if len(action_sequence[-1][1]) == 0:\n rival_move = action_sequence[-2][1]\n else:\n rival_move = action_sequence[-1][1]\n\n rival_type = md.get_move_type(rival_move)\n rival_move_type = rival_type['type']\n rival_move_len = rival_type.get('len', 1)\n moves = list()\n\n if rival_move_type == md.TYPE_0_PASS:\n moves = mg.gen_moves()\n\n elif rival_move_type == md.TYPE_1_SINGLE:\n all_moves = mg.gen_type_1_single()\n moves = ms.filter_type_1_single(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_2_PAIR:\n all_moves = mg.gen_type_2_pair()\n moves = ms.filter_type_2_pair(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_3_TRIPLE:\n all_moves = mg.gen_type_3_triple()\n moves = ms.filter_type_3_triple(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_4_BOMB:\n all_moves = mg.gen_type_4_bomb() + mg.gen_type_5_king_bomb()\n moves = ms.filter_type_4_bomb(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_5_KING_BOMB:\n moves = []\n\n elif rival_move_type == md.TYPE_6_3_1:\n all_moves = mg.gen_type_6_3_1()\n moves = ms.filter_type_6_3_1(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_7_3_2:\n all_moves = mg.gen_type_7_3_2()\n moves = ms.filter_type_7_3_2(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_8_SERIAL_SINGLE:\n all_moves = mg.gen_type_8_serial_single(repeat_num=rival_move_len)\n moves = ms.filter_type_8_serial_single(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_9_SERIAL_PAIR:\n all_moves = mg.gen_type_9_serial_pair(repeat_num=rival_move_len)\n moves = ms.filter_type_9_serial_pair(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_10_SERIAL_TRIPLE:\n all_moves = mg.gen_type_10_serial_triple(repeat_num=rival_move_len)\n moves = ms.filter_type_10_serial_triple(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_11_SERIAL_3_1:\n all_moves = mg.gen_type_11_serial_3_1(repeat_num=rival_move_len)\n moves = ms.filter_type_11_serial_3_1(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_12_SERIAL_3_2:\n all_moves = mg.gen_type_12_serial_3_2(repeat_num=rival_move_len)\n moves = ms.filter_type_12_serial_3_2(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_13_4_2:\n all_moves = mg.gen_type_13_4_2()\n moves = ms.filter_type_13_4_2(all_moves, rival_move)\n\n elif rival_move_type == md.TYPE_14_4_22:\n all_moves = mg.gen_type_14_4_22()\n moves = ms.filter_type_14_4_22(all_moves, rival_move)\n\n if rival_move_type not in [md.TYPE_0_PASS,\n md.TYPE_4_BOMB, md.TYPE_5_KING_BOMB]:\n moves = moves + mg.gen_type_4_bomb() + mg.gen_type_5_king_bomb()\n\n if len(rival_move) != 0: # rival_move is not 'pass'\n moves = moves + [[]]\n\n for m in moves:\n m.sort()\n\n return moves\n\n def reset(self):\n self.card_play_action_seq = []\n\n self.three_landlord_cards = None\n self.game_over = False\n\n self.acting_player_position = None\n self.player_utility_dict = None\n\n self.last_move_dict = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.played_cards = {'landlord': [],\n 'landlord_up': [],\n 'landlord_down': []}\n\n self.last_move = []\n self.last_two_moves = []\n\n self.info_sets = {'landlord': InfoSet('landlord'),\n 'landlord_up': InfoSet('landlord_up'),\n 'landlord_down': InfoSet('landlord_down')}\n\n self.bomb_num = 0\n self.last_pid = 'landlord'\n self.bid_info = [[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]]\n self.bid_count = 0\n self.multiply_count = {'landlord': 0,\n 'landlord_up': 0,\n 'landlord_down': 0}\n self.step_count = 0\n\n def get_infoset(self):\n self.info_sets[\n self.acting_player_position].last_pid = self.last_pid\n\n self.info_sets[\n self.acting_player_position].legal_actions = \\\n self.get_legal_card_play_actions()\n\n self.info_sets[\n self.acting_player_position].bomb_num = self.bomb_num\n\n self.info_sets[\n self.acting_player_position].last_move = self.get_last_move()\n\n self.info_sets[\n self.acting_player_position].last_two_moves = self.get_last_two_moves()\n\n self.info_sets[\n self.acting_player_position].last_move_dict = self.last_move_dict\n\n self.info_sets[self.acting_player_position].num_cards_left_dict = \\\n {pos: len(self.info_sets[pos].player_hand_cards)\n for pos in ['landlord', 'landlord_up', 'landlord_down']}\n\n self.info_sets[self.acting_player_position].other_hand_cards = []\n\n '''\n 调整计算其他人手牌的方法,整副牌减去玩家手牌与出过的牌\n for pos in ['landlord', 'landlord_up', 'landlord_down']:\n if pos != self.acting_player_position:\n self.info_sets[\n self.acting_player_position].other_hand_cards += \\\n self.info_sets[pos].player_hand_cards\n '''\n # 把出过的牌中三个子列表合成一个列表\n played_cards_tmp = []\n for i in list(self.played_cards.values()):\n played_cards_tmp.extend(i)\n # 出过的牌和玩家手上的牌\n played_and_hand_cards = played_cards_tmp + self.info_sets[self.acting_player_position].player_hand_cards\n # 整副牌减去出过的牌和玩家手上的牌,就是其他人的手牌\n for i in set(AllEnvCard):\n self.info_sets[\n self.acting_player_position].other_hand_cards.extend([i] * (AllEnvCard.count(i) - played_and_hand_cards.count(i)))\n\n self.info_sets[self.acting_player_position].played_cards = \\\n self.played_cards\n self.info_sets[self.acting_player_position].three_landlord_cards = \\\n self.three_landlord_cards\n self.info_sets[self.acting_player_position].card_play_action_seq = \\\n self.card_play_action_seq\n\n self.info_sets[\n self.acting_player_position].all_handcards = \\\n {pos: self.info_sets[pos].player_hand_cards\n for pos in ['landlord', 'landlord_up', 'landlord_down']}\n\n # Custom bid info\n self.info_sets[self.acting_player_position].bid_info = bid_infos[self.acting_player_position]\n\n return deepcopy(self.info_sets[self.acting_player_position])" }, { "identifier": "DeepAgent", "path": "douzero/evaluation/deep_agent.py", "snippet": "class DeepAgent:\n\n def __init__(self, position, model_path):\n self.model_type = \"old\"\n if \"general\" in model_path:\n self.model_type = \"general\"\n elif \"resnet\" in model_path:\n self.model_type = \"resnet\"\n self.model = _load_model(position, model_path, self.model_type)\n\n def act(self, infoset):\n obs = get_obs(infoset, model_type=self.model_type)\n z_batch = torch.from_numpy(obs['z_batch']).float()\n x_batch = torch.from_numpy(obs['x_batch']).float()\n if torch.cuda.is_available():\n z_batch, x_batch = z_batch.cuda(), x_batch.cuda()\n y_pred = self.model.forward(z_batch, x_batch, return_value=True)['values']\n y_pred = y_pred.detach().cpu().numpy()\n\n best_action_index = np.argmax(y_pred, axis=0)[0]\n best_action = infoset.legal_actions[best_action_index]\n best_action_confidence = y_pred[best_action_index]\n return best_action, best_action_confidence" } ]
import GameHelper as gh import os import sys import time import threading import pyautogui import win32gui import multiprocessing as mp import DetermineColor as DC import cv2 import numpy as np import traceback import BidModel import LandlordModel import FarmerModel from GameHelper import GameHelper from PIL import Image from skimage.metrics import structural_similarity as ssim from collections import defaultdict from douzero.env.move_detector import get_move_type from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtWidgets import QTableWidgetItem, QInputDialog, QMessageBox from PyQt5.QtGui import QPixmap, QIcon from PyQt5.QtCore import QTime, QEventLoop, Qt from MainWindow import Ui_Form from douzero.env.game import GameEnv from douzero.evaluation.deep_agent import DeepAgent
15,212
except AttributeError as e: traceback.print_exc() def init_display(self): self.WinRate.setText("评分") self.label.setText("游戏状态") self.label.setStyleSheet('background-color: rgba(255, 0, 0, 0);') self.UserHandCards.setText("手牌") # self.LBrowser.clear() # self.RBrowser.clear() self.LPlayedCard.setText("上家出牌区域") self.RPlayedCard.setText("下家出牌区域") self.PredictedCard.setText("AI出牌区域") self.ThreeLandlordCards.setText("地主牌") self.recorder2zero() for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') def init_cards(self): self.RunGame = True GameHelper.Interrupt = False self.user_hand_cards_real = "" self.user_hand_cards_env = [] # 其他玩家出牌 self.other_played_cards_real = "" self.other_played_cards_env = [] # 其他玩家手牌(整副牌减去玩家手牌,后续再减掉历史出牌) self.other_hand_cards = [] # 三张底牌 self.three_landlord_cards_real = "" self.three_landlord_cards_env = [] # 玩家角色代码:0-地主上家, 1-地主, 2-地主下家 self.user_position_code = None self.user_position = "" # 开局时三个玩家的手牌 self.card_play_data_list = {} # 识别玩家手牌 self.user_hand_cards_real = self.find_my_cards() while len(self.user_hand_cards_real) != 17 and len(self.user_hand_cards_real) != 20: self.detect_start_btn() if not self.RunGame: break self.sleep(200) self.user_hand_cards_real = self.find_my_cards() self.user_hand_cards_env = [RealCard2EnvCard[c] for c in list(self.user_hand_cards_real)] # 识别三张底牌 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] while len(self.three_landlord_cards_env) != 3: self.detect_start_btn() if not self.RunGame: break if len(self.three_landlord_cards_env) > 3: self.ThreeLandlordCardsConfidence += 0.05 elif len(self.three_landlord_cards_env) < 3: self.ThreeLandlordCardsConfidence -= 0.05 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] # 识别玩家的角色 self.sleep(500) self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) while self.user_position_code is None: self.detect_start_btn() if not self.RunGame: break self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) print("正在出牌人的代码: ", self.user_position_code) if self.user_position_code is None: items = ("地主上家", "地主", "地主下家") item, okPressed = QInputDialog.getItem(self, "选择角色", "未识别到地主,请手动选择角色:", items, 0, False) if okPressed and item: self.user_position_code = items.index(item) else: return self.user_position = ['landlord_up', 'landlord', 'landlord_down'][self.user_position_code] print("我现在在地主的方向:", self.user_position) for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') self.Players[self.user_position_code].setStyleSheet('background-color: rgba(0, 255, 0, 0.5);') # 整副牌减去玩家手上的牌,就是其他人的手牌,再分配给另外两个角色(如何分配对AI判断没有影响) for i in set(AllEnvCard): self.other_hand_cards.extend([i] * (AllEnvCard.count(i) - self.user_hand_cards_env.count(i))) self.other_hands_cards_str = str(''.join([EnvCard2RealCard[c] for c in self.other_hand_cards]))[::-1] self.cards_recorder(self.other_hands_cards_str) self.card_play_data_list.update({ 'three_landlord_cards': self.three_landlord_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 0) % 3]: self.user_hand_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 1) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 != 1 else self.other_hand_cards[17:], ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 2) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 == 1 else self.other_hand_cards[17:] }) print("开始对局") print("手牌:", self.user_hand_cards_real) print("地主牌:", self.three_landlord_cards_real) # 生成手牌结束,校验手牌数量 if len(self.card_play_data_list["three_landlord_cards"]) != 3: QMessageBox.critical(self, "底牌识别出错", "底牌必须是3张!", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return if len(self.card_play_data_list["landlord_up"]) != 17 or \ len(self.card_play_data_list["landlord_down"]) != 17 or \ len(self.card_play_data_list["landlord"]) != 20: QMessageBox.critical(self, "手牌识别出错", "初始手牌数目有误", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return # 出牌顺序:0-玩家出牌, 1-玩家下家出牌, 2-玩家上家出牌 self.play_order = 0 if self.user_position == "landlord" else 1 if self.user_position == "landlord_up" else 2 # 创建一个代表玩家的AI ai_players = [0, 0] ai_players[0] = self.user_position
# -*- coding: utf-8 -*- # Created by: Raf # Modify by: Vincentzyx EnvCard2RealCard = {3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'T', 11: 'J', 12: 'Q', 13: 'K', 14: 'A', 17: '2', 20: 'X', 30: 'D'} RealCard2EnvCard = {'3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, '2': 17, 'X': 20, 'D': 30} AllEnvCard = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30] AllCards = ['D', 'X', '2', 'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3'] helper = GameHelper() class MyPyQT_Form(QtWidgets.QWidget, Ui_Form): def __init__(self): super(MyPyQT_Form, self).__init__() self.other_hands_cards_str = None self.stop_sign = None self.loop_sign = None self.env = None self.three_landlord_cards_env = None self.three_landlord_cards_real = None self.user_hand_cards_env = None self.user_hand_cards_real = None self.play_order = None self.card_play_data_list = None self.other_hand_cards = None self.other_played_cards_env = None self.other_played_cards_real = None self.user_position = None self.user_position_code = None self.setupUi(self) self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | # 使能最小化按钮 QtCore.Qt.WindowStaysOnTopHint | # 窗体总在最前端 QtCore.Qt.WindowCloseButtonHint) self.setWindowIcon(QIcon(':/pics/favicon.ico')) self.setWindowTitle("DouZero欢乐斗地主v2.0") self.setFixedSize(self.width(), self.height()) # 固定窗体大小 self.move(50, 50) # self.setWindowIcon(QIcon('pics/favicon.ico')) window_pale = QtGui.QPalette() # window_pale.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap("pics/bg.png"))) self.setPalette(window_pale) self.SingleButton.clicked.connect(self.game_single) self.LoopButton.clicked.connect(self.game_loop) self.StopButton.clicked.connect(self.stop) # self.Players = [self.RPlayer, self.Player, self.LPlayer] self.Players = [self.RPlayedCard, self.PredictedCard, self.LPlayedCard] self.counter = QTime() # 参数 self.MyConfidence = 0.8 # 我的牌的置信度 self.OtherConfidence = 0.8 # 别人的牌的置信度 self.WhiteConfidence = 0.85 # 检测白块的置信度 self.LandlordFlagConfidence = 0.8 # 检测地主标志的置信度 self.ThreeLandlordCardsConfidence = 0.8 # 检测地主底牌的置信度 self.PassConfidence = 0.7 self.PassConfidence = 0.8 self.WaitTime = 1 # 等待状态稳定延时 self.MyFilter = 40 # 我的牌检测结果过滤参数 self.OtherFilter = 25 # 别人的牌检测结果过滤参数 self.SleepTime = 0.1 # 循环中睡眠时间 self.RunGame = False self.AutoPlay = False self.BidThreshold1 = 65 # 叫地主阈值 self.BidThreshold2 = 72 # 抢地主阈值 self.JiabeiThreshold = ( (85, 72), # 叫地主 超级加倍 加倍 阈值 (85, 75) # 叫地主 超级加倍 加倍 阈值 (在地主是抢来的情况下) ) self.MingpaiThreshold = 92 # 坐标 self.MyHandCardsPos = (180, 560, 1050, 90) # 我的截图区域 self.LPlayedCardsPos = (320, 280, 500, 120) # 左边出牌截图区域 self.RPlayedCardsPos = (600, 280, 500, 120) # 右边出牌截图区域 self.LandlordCardsPos = (600, 33, 220, 103) # 地主底牌截图区域 self.LPassPos = (360, 360, 120, 80) # 左边不出截图区域 self.RPassPos = (940, 360, 120, 80) # 右边不出截图区域 self.PassBtnPos = (200, 450, 1000, 120) # 要不起截图区域 self.GeneralBtnPos = (200, 450, 1000, 120) # 叫地主、抢地主、加倍按钮截图区域 self.LandlordFlagPos = [(1247, 245, 48, 52), (12, 661, 51, 53), (123, 243, 52, 54)] # 地主标志截图区域(右-我-左) self.card_play_model_path_dict = { 'landlord': "baselines/resnet/resnet_landlord.ckpt", 'landlord_up': "baselines/resnet/resnet_landlord_up.ckpt", 'landlord_down': "baselines/resnet/resnet_landlord_down.ckpt" } def game_single(self): self.loop_sign = 0 self.stop_sign = 0 self.detect_start_btn() self.before_start() self.init_cards() def game_loop(self): self.loop_sign = 1 self.stop_sign = 0 while True: if self.stop_sign == 1: break self.detect_start_btn() self.before_start() self.init_cards() self.sleep(5000) def stop(self): self.stop_sign = 1 print("按下停止键") try: self.RunGame = False self.loop_sign = 0 self.env.game_over = True self.env.reset() self.init_display() self.PreWinrate.setText("局前胜率: ") self.BidWinrate.setText("叫牌胜率: ") except AttributeError as e: traceback.print_exc() def init_display(self): self.WinRate.setText("评分") self.label.setText("游戏状态") self.label.setStyleSheet('background-color: rgba(255, 0, 0, 0);') self.UserHandCards.setText("手牌") # self.LBrowser.clear() # self.RBrowser.clear() self.LPlayedCard.setText("上家出牌区域") self.RPlayedCard.setText("下家出牌区域") self.PredictedCard.setText("AI出牌区域") self.ThreeLandlordCards.setText("地主牌") self.recorder2zero() for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') def init_cards(self): self.RunGame = True GameHelper.Interrupt = False self.user_hand_cards_real = "" self.user_hand_cards_env = [] # 其他玩家出牌 self.other_played_cards_real = "" self.other_played_cards_env = [] # 其他玩家手牌(整副牌减去玩家手牌,后续再减掉历史出牌) self.other_hand_cards = [] # 三张底牌 self.three_landlord_cards_real = "" self.three_landlord_cards_env = [] # 玩家角色代码:0-地主上家, 1-地主, 2-地主下家 self.user_position_code = None self.user_position = "" # 开局时三个玩家的手牌 self.card_play_data_list = {} # 识别玩家手牌 self.user_hand_cards_real = self.find_my_cards() while len(self.user_hand_cards_real) != 17 and len(self.user_hand_cards_real) != 20: self.detect_start_btn() if not self.RunGame: break self.sleep(200) self.user_hand_cards_real = self.find_my_cards() self.user_hand_cards_env = [RealCard2EnvCard[c] for c in list(self.user_hand_cards_real)] # 识别三张底牌 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] while len(self.three_landlord_cards_env) != 3: self.detect_start_btn() if not self.RunGame: break if len(self.three_landlord_cards_env) > 3: self.ThreeLandlordCardsConfidence += 0.05 elif len(self.three_landlord_cards_env) < 3: self.ThreeLandlordCardsConfidence -= 0.05 self.three_landlord_cards_real = self.find_landlord_cards() self.ThreeLandlordCards.setText("底牌:" + self.three_landlord_cards_real) self.three_landlord_cards_env = [RealCard2EnvCard[c] for c in list(self.three_landlord_cards_real)] # 识别玩家的角色 self.sleep(500) self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) while self.user_position_code is None: self.detect_start_btn() if not self.RunGame: break self.user_position_code = self.find_landlord(self.LandlordFlagPos) self.sleep(200) print("正在出牌人的代码: ", self.user_position_code) if self.user_position_code is None: items = ("地主上家", "地主", "地主下家") item, okPressed = QInputDialog.getItem(self, "选择角色", "未识别到地主,请手动选择角色:", items, 0, False) if okPressed and item: self.user_position_code = items.index(item) else: return self.user_position = ['landlord_up', 'landlord', 'landlord_down'][self.user_position_code] print("我现在在地主的方向:", self.user_position) for player in self.Players: player.setStyleSheet('background-color: rgba(0, 255, 0, 0);') self.Players[self.user_position_code].setStyleSheet('background-color: rgba(0, 255, 0, 0.5);') # 整副牌减去玩家手上的牌,就是其他人的手牌,再分配给另外两个角色(如何分配对AI判断没有影响) for i in set(AllEnvCard): self.other_hand_cards.extend([i] * (AllEnvCard.count(i) - self.user_hand_cards_env.count(i))) self.other_hands_cards_str = str(''.join([EnvCard2RealCard[c] for c in self.other_hand_cards]))[::-1] self.cards_recorder(self.other_hands_cards_str) self.card_play_data_list.update({ 'three_landlord_cards': self.three_landlord_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 0) % 3]: self.user_hand_cards_env, ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 1) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 != 1 else self.other_hand_cards[17:], ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 2) % 3]: self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 == 1 else self.other_hand_cards[17:] }) print("开始对局") print("手牌:", self.user_hand_cards_real) print("地主牌:", self.three_landlord_cards_real) # 生成手牌结束,校验手牌数量 if len(self.card_play_data_list["three_landlord_cards"]) != 3: QMessageBox.critical(self, "底牌识别出错", "底牌必须是3张!", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return if len(self.card_play_data_list["landlord_up"]) != 17 or \ len(self.card_play_data_list["landlord_down"]) != 17 or \ len(self.card_play_data_list["landlord"]) != 20: QMessageBox.critical(self, "手牌识别出错", "初始手牌数目有误", QMessageBox.Yes, QMessageBox.Yes) self.init_display() return # 出牌顺序:0-玩家出牌, 1-玩家下家出牌, 2-玩家上家出牌 self.play_order = 0 if self.user_position == "landlord" else 1 if self.user_position == "landlord_up" else 2 # 创建一个代表玩家的AI ai_players = [0, 0] ai_players[0] = self.user_position
ai_players[1] = DeepAgent(self.user_position, self.card_play_model_path_dict[self.user_position])
4
2023-12-01 04:04:30+00:00
24k
super1207/satoricq
satori.py
[ { "identifier": "AdapterKook", "path": "kook_adapter.py", "snippet": "class AdapterKook:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._access_token = config[\"access_token\"]\n self._http_url = \"https://www.kookapp.cn/api/v3\"\n self._is_stop = False\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n self._sn = 0\n self._self_id = None\n\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n \n\n async def _ws_recv(self,websocket):\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n return reply\n except asyncio.TimeoutError:\n return None\n\n async def _ws_connect(self):\n self._login_status = SatoriLogin.LoginStatus.CONNECT\n ws_url = (await self._api_call(\"/gateway/index?compress=0\"))[\"url\"]\n async with connect(ws_url) as websocket:\n tm = time.time()\n while not self._is_stop:\n reply = await self._ws_recv(websocket)\n if not reply:\n now_time = time.time()\n if now_time - tm > 30:\n tm = now_time\n await websocket.send(json.dumps({\"s\": 2,\"sn\": self._sn}))\n continue\n js = json.loads(reply)\n s = js[\"s\"]\n if s == 5:raise Exception(\"recv reset ws\")\n elif s == 3:pass # heartbeat\n elif s == 1:\n self._login_status = SatoriLogin.LoginStatus.ONLINE\n print(\"kook:ws连接成功\")\n elif s == 0:\n self._sn = js[\"sn\"]\n asyncio.create_task(self._event_deal(js[\"d\"]))\n\n async def _ws_server(self) -> None:\n while not self._is_stop:\n try:\n await self._ws_connect()\n except:\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n print(traceback.format_exc())\n await asyncio.sleep(3)\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n\n async def init_after(self) -> None:\n '''适配器创建之后会调用一次,应该在这里进行ws连接等操作,如果不需要,可以不写'''\n asyncio.create_task(self._ws_server())\n\n def _kook_msg_to_satori(self,msg_type:int,message:str)->str:\n ret = \"\"\n if msg_type == 2: #图片\n ret += \"<img src={}/>\".format(json.dumps(message))\n else:\n def kook_msg_f(msg):\n ret = \"\"\n is_f = False\n for ch in msg:\n if is_f:\n is_f = False\n ret += ch\n elif ch == \"\\\\\":\n is_f = True\n else:\n ret += ch\n return ret\n \n index = 0\n msg_list = message.split(\"(met)\")\n for it in msg_list:\n if index % 2 == 0:\n ret += satori_to_plain(kook_msg_f(it))\n else:\n if it == \"all\":\n ret += \"<at type=\\\"all\\\"/>\"\n else:\n ret += \"<at id=\\\"{}\\\"/>\".format(it)\n index += 1\n return ret\n\n\n async def _deal_group_message_event(self,data,user_id:str):\n group_id = data[\"target_id\"]\n kook_msg = data[\"content\"]\n extra = data[\"extra\"]\n author = extra[\"author\"]\n msg_type = data[\"type\"]\n\n if msg_type == 10:#卡牌\n return\n satori_msg = self._kook_msg_to_satori(msg_type,kook_msg)\n\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=data[\"msg_timestamp\"],\n platform=\"kook\",\n channel=SatoriChannel(\n id=\"GROUP_\"+group_id,\n type=SatoriChannel.ChannelType.TEXT,\n name=extra[\"channel_name\"]\n ),\n message=SatoriMessage(\n id=data[\"msg_id\"],\n content=satori_msg,\n created_at=data[\"msg_timestamp\"]\n ),\n user=SatoriUser(\n id=author[\"id\"],\n name=author[\"username\"],\n avatar=author[\"avatar\"],\n is_bot=author[\"bot\"]\n ),\n member=SatoriGuildMember(\n nick=author[\"nickname\"],\n avatar=author[\"avatar\"]\n ),\n guild=SatoriGuild(\n id=extra[\"guild_id\"]\n ),\n role=SatoriGuildRole(\n id=json.dumps(sorted(author[\"roles\"]))\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _deal_private_message_event(self,data,user_id:str):\n\n kook_msg = data[\"content\"]\n extra = data[\"extra\"]\n author = extra[\"author\"]\n msg_type = data[\"type\"]\n\n if msg_type == 10:#卡牌\n return\n satori_msg = self._kook_msg_to_satori(msg_type,kook_msg)\n\n satori_evt = SatoriPrivateMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=data[\"msg_timestamp\"],\n channel=SatoriChannel(\n id=user_id,\n type=SatoriChannel.ChannelType.TEXT,\n name=author[\"username\"]\n ),\n message=SatoriMessage(\n id=data[\"msg_id\"],\n content=satori_msg,\n created_at=data[\"msg_timestamp\"]\n ),\n user=SatoriUser(\n id=user_id,\n name=author[\"username\"],\n avatar=author[\"avatar\"],\n is_bot=author[\"bot\"]\n ),\n platform=\"kook\"\n ).to_dict()\n self._id += 1\n self._queue.put_nowait(satori_evt)\n\n async def _deal_group_increase_event(self,data):\n extra = data[\"extra\"]\n satori_evt = {\n \"id\":self._id,\n \"type\":\"guild-member-added\",\n \"platform\":\"kook\",\n \"self_id\":self._self_id,\n \"timestamp\":data[\"msg_timestamp\"],\n \"guild\":SatoriGuild(id=data[\"target_id\"]).to_dict(),\n \"member\":SatoriGuildMember(joined_at=extra[\"body\"][\"joined_at\"]).to_dict(),\n \"user\":SatoriUser(id=extra[\"body\"][\"user_id\"]).to_dict()\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n\n\n\n async def _deal_group_evt(self,data):\n user_id:str = data[\"author_id\"]\n if user_id == \"1\": # system message\n tp = data[\"type\"]\n if tp != 255:\n return\n sub_type = data[\"extra\"][\"type\"]\n if sub_type == \"joined_guild\":\n await self._deal_group_increase_event(data)\n else:\n if self._self_id:\n if user_id != self._self_id:\n await self._deal_group_message_event(data,user_id)\n\n\n async def _deal_person_evt(self,data):\n user_id:str = data[\"author_id\"]\n if user_id != 1: # 不是系统消息\n if self._self_id:\n if user_id != self._self_id:\n await self._deal_private_message_event(data,user_id)\n\n\n async def _event_deal(self,data:dict):\n try:\n tp = data[\"channel_type\"]\n if tp == \"GROUP\":\n await self._deal_group_evt(data)\n else:\n await self._deal_person_evt(data)\n except:\n print(traceback.format_exc())\n \n async def _api_call(self,path,data = None) -> dict:\n url:str = self._http_url + path\n headers = {\"Authorization\":\"Bot {}\".format(self._access_token)}\n if data == None:\n async with httpx.AsyncClient() as client:\n return (await client.get(url,headers=headers)).json()[\"data\"]\n else:\n async with httpx.AsyncClient() as client:\n return (await client.post(url,headers=headers,data=data)).json()[\"data\"]\n\n def _make_kook_text(self,text):\n ret = \"\"\n for ch in text:\n if ch in [\"\\\\\",\"*\",\"~\",\"[\",\"(\",\")\",\"]\",\"-\",\">\",\"`\"]:\n ret += \"\\\\\"\n ret += ch\n return ret\n \n async def _satori_to_kook(self,satori_obj) -> [dict]:\n to_send_data = []\n last_type = 1\n for node in satori_obj:\n if isinstance(node,str):\n text = self._make_kook_text(node)\n if last_type == 1 and len(to_send_data) != 0:\n l = len(to_send_data)\n to_send_data[l - 1][\"content\"] += text\n else:\n to_send_data.append({\n \"type\":1,\n \"content\":text\n })\n last_type = 1\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n text = \"(met)all(met)\"\n elif id != None:\n text = \"(met){}(met)\".format(self._make_kook_text(id))\n if last_type == 1 and len(to_send_data) != 0:\n l = len(to_send_data)\n to_send_data[l - 1][\"content\"] += text\n else:\n to_send_data.append({\n \"type\":1,\n \"content\":text\n })\n last_type = 1\n elif node[\"type\"] == \"img\":\n img_url:str = node[\"attrs\"][\"src\"]\n kook_img_url = \"\"\n if img_url.startswith(\"https://img.kookapp.cn\"):\n kook_img_url = img_url\n else:\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_content = base64.b64decode(img_url[base64_start + 7:])\n else:\n async with httpx.AsyncClient() as client:\n img_content = (await client.get(img_url)).content\n files = {\n 'file':('test',img_content)\n }\n headers = {\"Authorization\":\"Bot {}\".format(self._access_token)}\n async with httpx.AsyncClient() as client:\n ret = (await client.post(self._http_url + \"/asset/create\",files=files,headers=headers)).json()\n kook_img_url = ret[\"data\"][\"url\"]\n to_send_data.append({\n \"type\":2,\n \"content\":kook_img_url\n })\n last_type = 2\n return to_send_data\n \n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n satori_obj = parse_satori_html(content)\n to_sends = await self._satori_to_kook(satori_obj)\n if channel_id.startswith(\"GROUP_\"):\n channel_id = int(channel_id[6:])\n to_ret = []\n for it in to_sends:\n ret = await self._api_call(\"/message/create\",{\"content\":it[\"content\"],\"type\":it[\"type\"],\"target_id\":channel_id})\n to_ret.append(SatoriMessage(id=ret[\"msg_id\"],content=\"\").to_dict())\n return to_ret\n else:\n to_ret = []\n for it in to_sends:\n ret = await self._api_call(\"/direct-message/create\",{\"content\":it[\"content\"],\"type\":it[\"type\"],\"target_id\":channel_id})\n to_ret.append(SatoriMessage(id=ret[\"msg_id\"],content=\"\").to_dict())\n return to_ret\n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n obret = (await self._api_call(\"/user/me\"))\n satori_ret = SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=obret[\"id\"],\n name=obret[\"username\"],\n avatar=get_json_or(obret,\"avatar\",None),\n is_bot=True\n ),\n self_id=obret[\"id\"],\n platform=\"kook\"\n ).to_dict()\n self._self_id = obret[\"id\"]\n if platform == None and self_id == None:\n return [satori_ret]\n else:\n return satori_ret\n \n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n url = \"/user/view?user_id={}&guild_id={}\".format(user_id,guild_id)\n obret = (await self._api_call(url))\n satori_ret = SatoriGuildMember(\n user=SatoriUser(\n id=obret[\"id\"],\n name=get_json_or(obret,\"username\",None),\n avatar=get_json_or(obret,\"avatar\",None),\n is_bot=get_json_or(obret,\"bot\",None)\n ),\n nick=get_json_or(obret,\"nickname\",None),\n avatar=get_json_or(obret,\"avatar\",None),\n joined_at=get_json_or(obret,\"join_time\",None)\n ).to_dict()\n return satori_ret\n \n async def get_user(self,platform:Optional[str],self_id:Optional[str],user_id:str) -> [dict]:\n '''获取用户信息'''\n url = \"/user/view?user_id={}\".format(user_id)\n obret = (await self._api_call(url))\n satori_ret = SatoriUser(\n id=obret[\"id\"],\n name=obret[\"username\"],\n avatar=obret[\"avatar\"],\n is_bot=obret[\"bot\"],\n ).to_dict()\n return satori_ret\n \n async def get_channel_list(self,platform:Optional[str],self_id:Optional[str],guild_id:str) -> [dict]:\n '''获取频道列表'''\n url = \"/channel/list?guild_id={}\".format(guild_id)\n obret = (await self._api_call(url))\n ret_list = []\n items = get_json_or(obret,\"items\",None)\n for it in items:\n channel_type = it[\"type\"]\n channel_id = \"GROUP_\" + it[\"id\"]\n channel_name = it[\"name\"]\n channel_parent = it[\"parent_id\"]\n if channel_type == 1:\n ret_list.append(SatoriChannel(\n id=channel_id,\n name=channel_name,\n type=SatoriChannel.ChannelType.TEXT,\n parent_id=channel_parent\n ).to_dict())\n page_total = get_json_or(obret,\"data\",1)\n if page_total > 1:\n for i in range(2,page_total + 1):\n url = \"/channel/list?guild_id={}&page={}\".format(guild_id,i)\n obret = (await self._api_call(url))\n items = get_json_or(obret,\"items\",None)\n for it in items:\n channel_type = it[\"type\"]\n channel_id = \"GROUP_\" + it[\"id\"]\n channel_name = it[\"name\"]\n channel_parent = it[\"parent_id\"]\n if channel_type == 1:\n ret_list.append(SatoriChannel(\n id=channel_id,\n name=channel_name,\n type=SatoriChannel.ChannelType.TEXT,\n parent=channel_parent\n ).to_dict())\n return {\"data\":ret_list}" }, { "identifier": "AdapterMihoyo", "path": "mihoyo_adapter.py", "snippet": "class AdapterMihoyo:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._http_url = \"https://bbs-api.miyoushe.com\"\n self._is_stop = False\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n self._sn = 1\n self._self_id = config[\"bot_id\"]\n self._secret = config[\"secret\"]\n self._villa_id = config[\"villa_id\"]\n\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n\n async def _send_ws_pack(self,ws,ws_dat,biztype):\n magic = 0xBABEFACE.to_bytes(length=4, byteorder='little', signed=False)\n if biztype == 7:\n pb_pack = bytes(PLogin(\n uid=int(ws_dat[\"uid\"]),\n token=self._villa_id + \".\" + self._secret + \".\" + self._self_id,\n platform=ws_dat[\"platform\"],\n app_id=ws_dat[\"app_id\"],\n device_id=ws_dat[\"device_id\"]\n ))\n elif biztype == 6:\n pb_pack = bytes(PHeartBeat(\n client_timestamp=str(int(round(time.time() * 1000)))\n ))\n else:\n raise Exception(\"unkonw biztype:{}\".format(biztype))\n \n wid = self._sn\n self._sn += 1\n\n flag = 1\n appid = 104\n headerlen = 24\n datalen = headerlen + len(pb_pack)\n\n to_send = magic\n to_send += datalen.to_bytes(length=4, byteorder='little', signed=False)\n to_send += headerlen.to_bytes(length=4, byteorder='little', signed=False)\n to_send += wid.to_bytes(length=8, byteorder='little', signed=False)\n to_send += flag.to_bytes(length=4, byteorder='little', signed=False)\n to_send += biztype.to_bytes(length=4, byteorder='little', signed=False)\n to_send += appid.to_bytes(length=4, byteorder='little', signed=True)\n to_send += pb_pack\n\n await ws.send(to_send)\n \n async def _ws_recv(self,websocket):\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n return reply\n except asyncio.TimeoutError:\n return None\n\n async def _ws_connect(self):\n self._login_status = SatoriLogin.LoginStatus.CONNECT\n ws_dat = (await self._api_call(\"/vila/api/bot/platform/getWebsocketInfo\"))\n # print(ws_dat)\n ws_url = ws_dat[\"websocket_url\"]\n async with connect(ws_url) as websocket:\n await self._send_ws_pack(websocket,ws_dat,biztype=7)\n tm = time.time()\n while not self._is_stop:\n reply = await self._ws_recv(websocket)\n if not reply:\n now_time = time.time()\n if now_time - tm > 30:\n tm = now_time\n await self._send_ws_pack(websocket,ws_dat,biztype=6)\n continue\n biztype = int.from_bytes(reply[24:28],byteorder='little',signed=False)\n if biztype == 7: # 登录返回\n login_reply = PLoginReply().parse(reply[32:])\n if login_reply.code == 0:\n print(\"mihoyo:ws连接成功\")\n self._login_status = SatoriLogin.LoginStatus.ONLINE\n continue\n else:\n print(\"mihoyo:ws连接失败\",login_reply.to_json())\n break\n elif biztype == 53:\n print(\"mihoyo:ws被踢下线\")\n pkoff = PKickOff().parse(reply[32:])\n print(\"mihoyo:\" + pkoff.reason)\n break\n elif biztype == 52:\n print(\"mihoyo:ws服务关机\")\n break\n elif biztype == 6:\n heart_reply = PHeartBeatReply().parse(reply[32:])\n if heart_reply.code != 0:\n print(\"mihoyo:ws心跳失败\")\n break\n elif biztype == 30001: # 正常处理\n evt = RobotEvent().parse(reply[32:]).to_dict()\n asyncio.create_task(self._event_deal(evt))\n\n async def _ws_server(self) -> None:\n while not self._is_stop:\n try:\n await self._ws_connect()\n except:\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n traceback.print_exc()\n await asyncio.sleep(3)\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n\n async def init_after(self) -> None:\n asyncio.create_task(self._ws_server())\n\n def _mihoyo_msg_to_satori(self,content_obj)->str:\n ret = \"\"\n entities = content_obj[\"content\"][\"entities\"]\n text = content_obj[\"content\"][\"text\"]\n l = len(text)\n i = 0\n while i < l:\n for en in entities:\n if en[\"offset\"] == i:\n print(en)\n i += en[\"length\"]\n if en[\"entity\"][\"type\"] == \"mention_all\": # 实际上收不到\n ret += \"<at type=\\\"all\\\"/>\"\n elif en[\"entity\"][\"type\"] == \"mentioned_robot\":\n ret += \"<at id=\\\"{}\\\"/>\".format(en[\"entity\"][\"bot_id\"])\n elif en[\"entity\"][\"type\"] == \"mentioned_user\":\n ret += \"<at id=\\\"{}\\\"/>\".format(en[\"entity\"][\"user_id\"])\n break\n else:\n ret += satori_to_plain(text[i])\n i += 1\n return ret\n async def _deal_group_message_event(self,data):\n extendData = data[\"extendData\"]\n\n sendMessage = extendData[\"sendMessage\"]\n user_id = sendMessage[\"fromUserId\"]\n villaId = sendMessage[\"villaId\"]\n roomId = sendMessage[\"roomId\"]\n\n villaRoomId = villaId + \"_\" + roomId\n\n content_obj = json.loads(sendMessage[\"content\"])\n\n extra_obj = json.loads(content_obj[\"user\"][\"extra\"])\n\n satori_msg = self._mihoyo_msg_to_satori(content_obj) # todo\n\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=int(data[\"sendAt\"]) * 1000,\n platform=\"mihoyo\",\n channel=SatoriChannel(\n id=villaRoomId,\n type=SatoriChannel.ChannelType.TEXT,\n ),\n message=SatoriMessage(\n id=data[\"id\"],\n content=satori_msg,\n created_at=int(sendMessage[\"sendAt\"])\n ),\n user=SatoriUser(\n id=user_id,\n name=sendMessage[\"nickname\"],\n avatar=content_obj[\"user\"][\"portraitUri\"]\n ),\n member=SatoriGuildMember(\n nick=sendMessage[\"nickname\"],\n avatar=content_obj[\"user\"][\"portraitUri\"]\n ),\n guild=SatoriGuild(\n id=villaId\n ),\n role=SatoriGuildRole(\n id=extra_obj[\"member_roles\"][\"name\"],\n name=extra_obj[\"member_roles\"][\"name\"]\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _event_deal(self,data:dict):\n try:\n event_type = data[\"type\"]\n if event_type == \"SendMessage\":\n await self._deal_group_message_event(data)\n except:\n print(traceback.format_exc())\n\n \n async def _api_call(self,path,data = None,villa_id = 0) -> dict:\n url:str = self._http_url + path\n headers = {\"x-rpc-bot_id\":self._self_id,\"x-rpc-bot_secret\":self._secret}\n if villa_id == 0:\n headers[\"x-rpc-bot_villa_id\"] = self._villa_id\n else:\n headers[\"x-rpc-bot_villa_id\"] = villa_id\n if data == None:\n async with httpx.AsyncClient() as client:\n return (await client.get(url,headers=headers)).json()[\"data\"]\n else:\n headers[\"Content-Type\"] = \"application/json\"\n async with httpx.AsyncClient() as client:\n ret = (await client.post(url,headers=headers,data=data)).json()\n if ret[\"retcode\"] != 0:\n print(\"mihoyo:\",ret)\n return ret[\"data\"]\n\n \n async def _satori_to_mihoyo(self,satori_obj,villa_id) -> [dict]:\n to_send_data = []\n last_type = 1\n for node in satori_obj:\n if isinstance(node,str):\n text = node\n if last_type == 1 and len(to_send_data) != 0:\n l = len(to_send_data)\n to_send_data[l - 1][\"text\"] += text\n else:\n to_send_data.append({\n \"type\":1,\n \"text\":text,\n \"entities\":[]\n })\n last_type = 1\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n text = \"@全体成员\"\n elif id != None:\n text = \"@\" + id\n else:\n continue\n\n if last_type != 1 or len(to_send_data) == 0:\n to_send_data.append({\n \"type\":1,\n \"text\":\"\",\n \"entities\":[]\n })\n last_type = 1\n\n l = len(to_send_data)\n ll = len(to_send_data[l - 1][\"text\"])\n to_send_data[l - 1][\"text\"] += text\n if type == \"all\":\n to_send_data[l - 1][\"entities\"].append({\n \"entity\": {\n \"type\": \"mention_all\"\n },\n \"length\":5,\n \"offset\":ll\n })\n else:\n if id.startswith(\"bot_\"):\n to_send_data[l - 1][\"entities\"].append({\n \"entity\": {\n \"type\": \"mentioned_robot\",\n \"bot_id\": id\n },\n \"length\":len(id) + 1,\n \"offset\":ll\n })\n else:\n to_send_data[l - 1][\"entities\"].append({\n \"entity\": {\n \"type\": \"mentioned_user\",\n \"user_id\": id\n },\n \"length\":len(id) + 1,\n \"offset\":ll\n })\n\n elif node[\"type\"] == \"img\":\n img_url:str = node[\"attrs\"][\"src\"]\n mihoyo_img_url = \"\"\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_content = base64.b64decode(img_url[base64_start + 7:])\n else:\n async with httpx.AsyncClient() as client:\n img_content = (await client.get(img_url)).content\n ext = imghdr.what(file = \"\",h=img_content)\n m = hashlib.md5()\n m.update(img_content)\n headers = {\"x-rpc-bot_id\":self._self_id,\"x-rpc-bot_secret\":self._secret,\"x-rpc-bot_villa_id\":villa_id}\n upload_info_url = self._http_url + \"/vila/api/bot/platform/getUploadImageParams\"\n async with httpx.AsyncClient() as client:\n req = client.build_request(\"GET\",upload_info_url,json={\n \"md5\":m.hexdigest(),\n \"ext\":ext\n },headers=headers)\n file_params = (await client.send(req)).json()[\"data\"][\"params\"]\n files = {\n \"x:extra\":file_params[\"callback_var\"][\"x:extra\"],\n \"OSSAccessKeyId\":file_params[\"accessid\"],\n \"signature\":file_params[\"signature\"],\n \"success_action_status\":file_params[\"success_action_status\"],\n \"name\":file_params[\"name\"],\n \"callback\":file_params[\"callback\"],\n \"x-oss-content-type\":file_params[\"x_oss_content_type\"],\n \"key\":file_params[\"key\"],\n \"policy\":file_params[\"policy\"],\n \"Content-Disposition\":file_params[\"content_disposition\"],\n 'file':('test',img_content)\n }\n async with httpx.AsyncClient() as client:\n ret = (await client.post(file_params[\"host\"],files=files)).json()\n mihoyo_img_url = ret[\"data\"][\"url\"]\n to_send_data.append({\n \"type\":2,\n \"url\":mihoyo_img_url,\n })\n last_type = 2\n to_send_data2 = []\n for it in to_send_data:\n type = it[\"type\"]\n if type == 1:\n to_send_data2.append({\n \"object_name\":\"MHY:Text\",\n \"msg_content\":json.dumps({\n \"content\":{\n \"text\":it[\"text\"],\n \"entities\":it[\"entities\"]\n }\n })})\n elif type == 2:\n to_send_data2.append({\n \"object_name\":\"MHY:Image\",\n \"msg_content\":json.dumps({\n \"content\":{\n \"url\":it[\"url\"]\n }\n \n })})\n \n return to_send_data2\n \n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n villa_id = channel_id.split(\"_\")[0]\n satori_obj = parse_satori_html(content)\n to_sends = await self._satori_to_mihoyo(satori_obj,villa_id)\n to_ret = []\n # print(to_sends)\n for it in to_sends:\n it[\"room_id\"] = channel_id.split(\"_\")[1]\n ret = await self._api_call(\"/vila/api/bot/platform/sendMessage\",json.dumps(it),villa_id=villa_id)\n to_ret.append(SatoriMessage(id=ret[\"bot_msg_id\"],content=\"\").to_dict())\n return to_ret\n \n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n satori_ret = SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=self._self_id,\n is_bot=True\n ),\n self_id=self._self_id,\n platform=\"mihoyo\"\n ).to_dict()\n if platform == None and self_id == None:\n return [satori_ret]\n else:\n return satori_ret\n\n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n url = self._http_url + \"/vila/api/bot/platform/getMember\"\n headers = {\"x-rpc-bot_id\":self._self_id,\"x-rpc-bot_secret\":self._secret,\"x-rpc-bot_villa_id\":guild_id}\n async with httpx.AsyncClient() as client:\n req = client.build_request(\"GET\",url,json={\n \"uid\":user_id\n },headers=headers)\n obret = (await client.send(req)).json()[\"data\"][\"member\"]\n satori_ret = SatoriGuildMember(\n user=SatoriUser(\n id=obret[\"basic\"][\"uid\"],\n name=obret[\"basic\"][\"nickname\"],\n avatar=obret[\"basic\"][\"avatar_url\"],\n is_bot=False\n ),\n nick=obret[\"basic\"][\"nickname\"],\n avatar=obret[\"basic\"][\"avatar_url\"],\n joined_at=int(obret[\"joined_at\"] + \"000\")\n ).to_dict()\n return satori_ret" }, { "identifier": "AdapterOnebot", "path": "onebot_adapter.py", "snippet": "class AdapterOnebot:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._http_url = config[\"http_url\"]\n self._ws_url = config[\"ws_url\"]\n if \"access_token\" in config:\n self._access_token = config[\"access_token\"]\n else:\n self._access_token = None\n self._is_stop = False\n self._login_status = 3 # DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n\n def _cqarr_to_satori(self,cqarr):\n ret = \"\"\n for node in cqarr:\n if node[\"type\"] == \"text\":\n ret += satori_to_plain(node[\"data\"][\"text\"])\n elif node[\"type\"] == \"at\":\n qq = node[\"data\"][\"qq\"]\n if qq == \"all\":\n ret += \"<at type=\\\"all\\\"/>\"\n else:\n ret += \"<at id={}/>\".format(json.dumps(qq))\n elif node[\"type\"] == \"image\":\n url = node[\"data\"][\"url\"]\n ret += \"<img src={}/>\".format(json.dumps(url))\n return ret\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n\n async def init_after(self) -> None:\n '''适配器创建之后会调用一次,应该在这里进行ws连接等操作,如果不需要,可以不写'''\n async def _ws_server(self:AdapterOnebot) -> None:\n while not self._is_stop:\n try:\n self._login_status = 2 # CONNECT\n async with connect(self._ws_url) as websocket:\n print(\"onebot:ws已经连接\")\n self._login_status = 1 # ONLINE\n try:\n while True:\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n await self._event_deal(json.loads(reply))\n except asyncio.TimeoutError:\n if self._is_stop:\n await websocket.close()\n except asyncio.QueueFull:\n print(\"队列满\")\n except Exception as e:\n print(e) \n except Exception as e:\n print(e)\n print(\"onebot:ws连接已经断开\")\n self._login_status = 3 # DISCONNECT\n asyncio.create_task(_ws_server(self))\n \n async def _event_deal(self,evt:dict):\n '''自己定义的事件转化函数'''\n post_type = evt[\"post_type\"]\n if post_type == \"message\":\n message_type = evt[\"message_type\"]\n sender = evt[\"sender\"]\n if message_type == \"group\":\n channel_obj = {\n \"id\":\"GROUP_\"+str(evt[\"group_id\"]),\n \"type\":0,\n \"name\":None,\n \"parent_id\":None\n }\n guild_obj = {\n \"id\":\"GROUP_\"+str(evt[\"group_id\"]),\n \"name\":None,\n \"avatar\":None\n }\n user_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"name\":get_json_or(sender,\"nickname\",None),\n \"nick\":get_json_or(sender,\"nickname\",None),\n \"avatar\":get_json_or(sender,\"avatar\",None),\n \"is_bot\":None\n }\n joined_at = get_json_or(sender,\"join_time\",None)\n if joined_at:\n joined_at = int(str(joined_at) + \"000\")\n member_obj = {\n \"nick\":get_json_or(sender,\"card\",None),\n \"avatar\":get_json_or(sender,\"avatar\",None),\n \"joined_at\":joined_at\n }\n message_obj = {\n \"id\":str(evt[\"message_id\"]),\n \"content\":self._cqarr_to_satori(_cqmsg_to_arr(evt[\"message\"])),\n \"created_at\":int(str(evt[\"time\"] ) + \"000\")\n }\n role_obj = {\n \"id\":get_json_or(sender, \"role\",\"member\"),\n \"name\":get_json_or(sender,\"role\",\"member\")\n }\n satori_evt = {\n \"id\":self._id,\n \"type\":\"message-created\",\n \"platform\":\"onebot\",\n \"self_id\":str(evt[\"self_id\"]),\n \"timestamp\":int(str(evt[\"time\"] ) + \"000\"),\n \"channel\":channel_obj,\n \"guild\":guild_obj,\n \"member\":member_obj,\n \"message\":message_obj,\n \"role\":role_obj,\n \"user\":user_obj\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n elif message_type == \"private\":\n channel_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"type\":1,\n \"name\":None,\n \"parent_id\":None\n }\n user_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"name\":get_json_or(sender,\"nickname\",None),\n \"nick\":get_json_or(sender,\"nickname\",None),\n \"avatar\":get_json_or(sender,\"avatar\",None),\n \"is_bot\":None\n }\n joined_at = get_json_or(sender,\"join_time\",None)\n if joined_at:\n joined_at = int(str(joined_at) + \"000\")\n message_obj = {\n \"id\":str(evt[\"message_id\"]),\n \"content\":self._cqarr_to_satori(_cqmsg_to_arr(evt[\"message\"])),\n \"created_at\":int(str(evt[\"time\"] ) + \"000\")\n }\n satori_evt = {\n \"id\":self._id,\n \"type\":\"message-created\",\n \"platform\":\"onebot\",\n \"self_id\":str(evt[\"self_id\"]),\n \"timestamp\":int(str(evt[\"time\"] ) + \"000\"),\n \"channel\":channel_obj,\n \"message\":message_obj,\n \"user\":user_obj\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n elif post_type == \"notice\":\n notice_type = evt[\"notice_type\"]\n if notice_type == \"group_increase\":\n guild_obj = {\n \"id\":\"GROUP_\"+str(evt[\"group_id\"]),\n \"name\":None,\n \"avatar\":None\n }\n member_obj = {\n \"nick\":None,\n \"avatar\":get_json_or(evt,\"avatar\",None),\n \"joined_at\":int(str(evt[\"time\"] ) + \"000\")\n }\n user_obj = {\n \"id\":str(evt[\"user_id\"]),\n \"name\":None,\n \"nick\":None,\n \"avatar\":None,\n \"is_bot\":None\n }\n satori_evt = {\n \"id\":self._id,\n \"type\":\"guild-member-added\",\n \"platform\":\"onebot\",\n \"self_id\":str(evt[\"self_id\"]),\n \"timestamp\":int(str(evt[\"time\"] ) + \"000\"),\n \"guild\":guild_obj,\n \"member\":member_obj,\n \"user\":user_obj\n }\n self._id += 1\n self._queue.put_nowait(satori_evt)\n\n async def _api_call(self,path,data) -> dict:\n url:str = self._http_url + path\n if self._access_token:\n headers = {\"Authorization\":\"Bearer {}\".format(self._access_token)}\n else:\n headers = {}\n async with httpx.AsyncClient() as client:\n # headers[\"Content-Type\"] = \"application/json\"\n return (await client.post(url,headers=headers,data=data)).json()\n \n async def _satori_to_cq(self,satori_obj) -> str:\n ret = \"\"\n for node in satori_obj:\n if isinstance(node,str):\n ret += _cq_text_encode(node)\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n ret += \"[CQ:at,qq=all]\"\n elif id != None:\n ret += \"[CQ:at,qq={}]\".format(_cq_params_encode(id))\n elif node[\"type\"] == \"img\":\n img_url = node[\"attrs\"][\"src\"]\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_url = \"base64://\" + img_url[base64_start + 7:]\n ret += \"[CQ:image,file={}]\".format(_cq_params_encode(img_url)) \n\n return ret\n\n\n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n satori_obj = parse_satori_html(content)\n to_send = await self._satori_to_cq(satori_obj)\n if channel_id.startswith(\"GROUP_\"):\n group_id = int(channel_id[6:])\n ret = await self._api_call(\"/send_group_msg\",{\"group_id\":group_id,\"message\":to_send})\n return [{\"id\":str(ret[\"data\"][\"message_id\"]),\"content\":\"\"}]\n else:\n user_id = int(channel_id)\n ret = await self._api_call(\"/send_private_msg\",{\"user_id\":user_id,\"message\":to_send})\n return [{\"id\":str(ret[\"data\"][\"message_id\"]),\"content\":\"\"}]\n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n obret = (await self._api_call(\"/get_login_info\",{}))[\"data\"]\n satori_ret = {\n \"user\":{\n \"id\":str(obret[\"user_id\"]),\n \"name\":obret[\"nickname\"],\n \"nick\":obret[\"nickname\"],\n \"avatar\":get_json_or(obret,\"avatar\",None),\n \"is_bot\":None\n },\n \"self_id\":str(obret[\"user_id\"]),\n \"platform\":\"onebot\",\n \"status\":self._login_status,\n }\n if platform == None and self_id == None:\n return [satori_ret]\n else:\n return satori_ret\n \n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n obret = (await self._api_call(\"/get_group_member_info\",{\n \"group_id\":int(guild_id[6:]),\n \"user_id\":int(user_id)\n }))[\"data\"]\n joined_at = get_json_or(obret,\"join_time\",None)\n if joined_at:\n joined_at = int(str(joined_at) + \"000\")\n satori_ret = {\n \"user\":{\n \"id\":str(obret[\"user_id\"]),\n \"name\":get_json_or(obret,\"nickname\",None),\n \"nick\":get_json_or(obret,\"card\",None),\n \"avatar\":get_json_or(obret,\"avatar\",None),\n \"is_bot\":None\n },\n \"nick\":get_json_or(obret,\"card\",None),\n \"avatar\":get_json_or(obret,\"avatar\",None),\n \"joined_at\":joined_at,\n }\n return satori_ret" }, { "identifier": "Config", "path": "config.py", "snippet": "class Config:\n def __init__(self) -> None:\n self.botlist:list = []\n self.web_port:int = 8080\n self.web_host:str = \"127.0.0.1\"\n self.access_token:str = \"\"\n \n async def read_config(self):\n async with aiofiles.open('config.json', mode='r') as f:\n json_dat = json5.loads(await f.read())\n self.botlist = json_dat[\"botlist\"]\n self.web_port = json_dat[\"web_port\"]\n self.web_host = json_dat[\"web_host\"]\n self.access_token = json_dat[\"access_token\"]" }, { "identifier": "AdapterQQ", "path": "qq_adapter.py", "snippet": "class AdapterQQ:\n def __init__(self,config = {}) -> None:\n '''用于初始化一些配置信息,尽量不要在这里阻塞,因为此处不具备异步环境,如果你需要读写配置文件,请在init_after中进行'''\n self._botqq = config[\"botqq\"]\n self._appid = config[\"appid\"]\n self._token = config[\"token\"]\n if \"withgroup\" in config:\n self._withgroup = config[\"withgroup\"]\n else:\n self._withgroup = None\n self._appsecret = config[\"appsecret\"]\n self._http_url = \"https://api.sgroup.qq.com\"\n self._is_stop = False\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n self._queue = Queue(maxsize=100)\n self._id = 0\n self._sn = None\n self._self_id = None\n self._access_token = None\n self._expires_in = 0\n self.msgid_map = dict()\n # self._self_name = None\n\n\n async def enable(self) -> None:\n '''适配器启用的时候会调用,可以不理,也可以没这个函数\n 配合下面的停用函数,适配器可以得到自己在整个系统中的状态,进而进行一些优化\n 如,如果适配器处于停用状态,适配器可以自行选择关闭网络连接,以节省资源,当然,也可以不理会\n '''\n pass\n\n async def disable(self) -> None:\n '''适配器停用的时候会调用,可以不理,也可以没这个函数'''\n pass\n \n async def release(self) -> None:\n '''适配器释放的时候会调用一次,应该在这里停用ws连接\n 一般认为,适配器会和真正的协议端建立连接,所以,这个函数大多数时候是需要写的\n 但是,这个函数允许资源延迟释放,只要能释放就行\n 你可以在这个函数里面进行数据保存之类的,这种用途下,请阻塞这个函数,直到保存完成\n '''\n self._is_stop = True\n\n async def get_msg(self) -> dict:\n '''阻塞并等待消息返回,如果你的适配器不具备接收消息的能力,请不要写这个函数'''\n return await self._queue.get()\n \n\n async def _ws_recv(self,websocket):\n try:\n reply = await asyncio.wait_for(websocket.recv(),0.1)\n return reply\n except asyncio.TimeoutError:\n return None\n\n async def _ws_connect(self):\n self._login_status = SatoriLogin.LoginStatus.CONNECT\n ws_url = (await self._api_call(\"/gateway\"))[\"url\"]\n async with connect(ws_url) as websocket:\n tm = time.time()\n while not self._is_stop:\n reply = await self._ws_recv(websocket)\n if not reply:\n now_time = time.time()\n if now_time - tm > 30:\n tm = now_time\n await websocket.send(json.dumps({\"op\": 1,\"d\": self._sn}))\n continue\n js = json.loads(reply)\n op = js[\"op\"]\n if op == 0: # 事件\n self._sn = js[\"s\"]\n t = js[\"t\"]\n if t == \"READY\":\n print(\"qq:ws连接成功\")\n print(json.dumps(js))\n self._login_status = SatoriLogin.LoginStatus.ONLINE\n else:\n print(json.dumps(js))\n asyncio.create_task(self._deal_event(js))\n elif op == 1: # 心跳\n await websocket.send(json.dumps({\"op\":11}))\n elif op == 7: # 重连\n print(\"qq:服务端要求重连\")\n break\n elif op == 9: # 参数错误\n print(\"qq:参数错误:\",json.dumps(js))\n break\n elif op == 10: # ws建立成功\n if self._withgroup:\n await websocket.send(json.dumps({\n \"op\":2,\n \"d\":{\n \"token\":\"QQBot {}\".format(self._access_token),\n \"intents\":0 | (1 << 0) | (1 << 1) | (1 << 30) | (1 << 25),\n \"shard\":[0, 1],\n }\n }))\n else:\n await websocket.send(json.dumps({\n \"op\":2,\n \"d\":{\n \"token\":\"QQBot {}\".format(self._access_token),\n \"intents\":0 | (1 << 0) | (1 << 1) | (1 << 30),\n \"shard\":[0, 1],\n }\n }))\n elif op == 11: # HTTP Callback ACK\n pass\n\n async def _ws_server(self) -> None:\n while not self._is_stop:\n try:\n await self._ws_connect()\n except:\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n print(traceback.format_exc())\n await asyncio.sleep(3)\n self._login_status = SatoriLogin.LoginStatus.DISCONNECT\n\n async def _token_refresh(self):\n async with httpx.AsyncClient() as client:\n if not self._expires_in or int(self._expires_in) < 60 * 5:\n url = \"https://bots.qq.com/app/getAppAccessToken\"\n ret = (await client.post(url,json={\n \"appId\":self._appid,\n \"clientSecret\":self._appsecret\n })).json()\n self._access_token = ret[\"access_token\"]\n self._expires_in = ret[\"expires_in\"]\n # print(ret)\n\n async def _qqarr_to_satori(self,qqmsg_arr):\n ret = \"\"\n for it in qqmsg_arr:\n if it[\"type\"] == \"text\":\n ret += satori_to_plain(it[\"data\"])\n else:\n if it[\"data\"].startswith(\"<@!\"):\n user_id = it[\"data\"][3:len(it[\"data\"]) - 1]\n ret += \"<at id=\\\"{}\\\">\".format(satori_to_plain(user_id))\n elif it[\"data\"].startswith(\"<@\"):\n user_id = it[\"data\"][2:len(it[\"data\"]) - 1]\n ret += \"<at id=\\\"{}\\\">\".format(satori_to_plain(user_id))\n return ret\n \n async def _deal_channel_event(self,data):\n qqmsg_arr = _qqmsg_to_arr(data[\"content\"])\n # print(\"qqmsg_arr\",qqmsg_arr)\n satori_msg = await self._qqarr_to_satori(qqmsg_arr)\n self.msgid_map[\"CHANNEL_\"+data[\"channel_id\"]] = data[\"id\"]\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._self_id,\n timestamp=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000,\n platform=\"qq_guild\",\n channel=SatoriChannel(\n id=\"CHANNEL_\"+data[\"channel_id\"],\n type=SatoriChannel.ChannelType.TEXT,\n ),\n message=SatoriMessage(\n id=data[\"id\"],\n content=satori_msg,\n created_at=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ),\n user=SatoriUser(\n id=data[\"author\"][\"id\"],\n name=data[\"author\"][\"username\"],\n avatar=data[\"author\"][\"avatar\"],\n is_bot=data[\"author\"][\"bot\"]\n ),\n member=SatoriGuildMember(\n nick=data[\"member\"][\"nick\"],\n avatar=data[\"author\"][\"avatar\"],\n joined_at=int(time.mktime(time.strptime(data[\"member\"][\"joined_at\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ),\n guild=SatoriGuild(\n id=data[\"guild_id\"]\n ),\n role=SatoriGuildRole(\n id=json.dumps(sorted(data[\"member\"][\"roles\"]))\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _deal_group_event(self,data):\n qqmsg_arr = _qqmsg_to_arr(data[\"content\"])\n # print(\"qqmsg_arr\",qqmsg_arr)\n satori_msg = await self._qqarr_to_satori(qqmsg_arr)\n self.msgid_map[\"GROUP_\"+data[\"group_id\"]] = data[\"id\"]\n satori_evt = SatoriGroupMessageCreatedEvent(\n id=self._id,\n self_id=self._botqq,\n timestamp=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000,\n platform=\"qq_group\",\n channel=SatoriChannel(\n id=\"GROUP_\"+data[\"group_id\"],\n type=SatoriChannel.ChannelType.TEXT,\n ),\n message=SatoriMessage(\n id=data[\"id\"],\n content=satori_msg,\n created_at=int(time.mktime(time.strptime(data[\"timestamp\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ),\n user=SatoriUser(\n id=data[\"author\"][\"id\"]\n ),\n member=SatoriGuildMember(\n ),\n guild=SatoriGuild(\n id=\"GROUP_\"+data[\"group_id\"]\n ),\n role=SatoriGuildRole(\n id=\"unkonw\",\n name=\"unkonw\"\n )\n )\n self._id += 1\n self._queue.put_nowait(satori_evt.to_dict())\n\n async def _deal_event(self,event):\n try:\n type = event[\"t\"]\n if type == \"AT_MESSAGE_CREATE\":\n d = event[\"d\"]\n if (\"channel_id\" in d) and d[\"channel_id\"]:\n await self._deal_channel_event(d)\n else:\n if type == \"GROUP_AT_MESSAGE_CREATE\":\n d = event[\"d\"]\n if (\"group_id\" in d) and d[\"group_id\"]:\n await self._deal_group_event(d)\n except:\n print(traceback.format_exc())\n\n async def _token_refresh_task(self):\n while True:\n try:\n await self._token_refresh()\n index = 0\n while index < 60: # 每60秒检测一次token是否过期\n await asyncio.sleep(1)\n if self._is_stop:\n break\n index += 1\n if self._is_stop:break\n except:\n print(traceback.format_exc())\n\n async def init_after(self) -> None:\n '''适配器创建之后会调用一次,应该在这里进行ws连接等操作,如果不需要,可以不写'''\n try:\n await self._token_refresh()\n except:\n print(traceback.format_exc())\n asyncio.create_task(self._token_refresh_task())\n asyncio.create_task(self._ws_server())\n\n async def _api_call(self,path,data = None) -> dict:\n url:str = self._http_url + path\n headers = {\"Authorization\":\"QQBot {}\".format(self._access_token),\"X-Union-Appid\":self._appid}\n if data == None:\n async with httpx.AsyncClient() as client:\n return (await client.get(url,headers=headers)).json()\n else:\n async with httpx.AsyncClient() as client:\n ret = (await client.post(url,headers=headers,json=data))\n # print(ret.content)\n return ret.json()\n\n def _make_qq_text(self,text:str):\n ret = text\n ret = ret.replace(\"&\",\"&amp;\")\n ret = ret.replace(\"<\",\"&lt;\")\n ret = ret.replace(\">\",\"&gt;\")\n return ret\n \n async def _satori_to_qq(self,satori_obj,platform = \"qq_guild\") -> [dict]:\n to_reply_id = None\n ret_text = \"\"\n ret_img = []\n for node in satori_obj:\n if isinstance(node,str):\n text = self._make_qq_text(node)\n ret_text += text\n else:\n if node[\"type\"] == \"at\":\n type = get_json_or(node[\"attrs\"],\"type\",None)\n id = get_json_or(node[\"attrs\"],\"id\",None)\n if type == \"all\":\n # 注意,机器人不支持at all,不能发,也不能收,这里假装at all了\n ret_text += \"@全体成员\"\n # text = \"<@everyone>\"\n elif id != None:\n ret_text += \"<@{}>\".format(self._make_qq_text(id))\n elif node[\"type\"] == \"img\":\n img_url:str = node[\"attrs\"][\"src\"]\n if img_url.startswith(\"data:image/\"):\n base64_start = img_url.find(\"base64,\")\n img_content = base64.b64decode(img_url[base64_start + 7:])\n ret_img.append(img_content)\n else:\n if platform == \"qq_guild\":\n async with httpx.AsyncClient() as client:\n img_content = (await client.get(img_url)).content\n ret_img.append(img_content)\n else:\n ret_img.append(img_url)\n elif node[\"type\"] == \"passive\":\n to_reply_id = node[\"attrs\"][\"id\"]\n \n ret_vec = []\n ret_vec.append({\n \"content\":ret_text,\n \"file_image\":None,\n \"to_reply_id\":to_reply_id\n })\n if len(ret_img) != 0:\n ret_vec[0][\"file_image\"] = ret_img[0]\n for img in ret_img[1:]:\n ret_vec.append({\n \"content\":\"\",\n \"file_image\":img,\n \"to_reply_id\":to_reply_id\n })\n return ret_vec\n \n async def create_message(self,platform:str,self_id:str,channel_id:str,content:str):\n '''发送消息'''\n to_reply_id = self.msgid_map[channel_id]\n satori_obj = parse_satori_html(content)\n to_sends = await self._satori_to_qq(satori_obj,platform)\n # print(to_sends)\n if channel_id.startswith(\"CHANNEL_\") and platform == \"qq_guild\":\n channel_id = channel_id[8:]\n to_ret = []\n for it in to_sends:\n if it[\"to_reply_id\"]:to_reply_id = it[\"to_reply_id\"]\n async with httpx.AsyncClient() as client:\n headers = {\"Authorization\":\"QQBot {}\".format(self._access_token),\"X-Union-Appid\":self._appid,\"Accept\":\"application/json\"}\n url:str = self._http_url + \"/channels/{}/messages\".format(channel_id)\n data = {\n \"msg_id\":to_reply_id,\n \"content\":it[\"content\"]\n }\n if it[\"file_image\"]:\n ret = (await client.post(url,headers=headers,data=data,files={\"file_image\":it[\"file_image\"]})).json()\n else:\n ret = (await client.post(url,headers=headers,json=data)).json()\n # print(ret)\n to_ret.append(SatoriMessage(id=ret[\"id\"],content=\"\").to_dict())\n return to_ret\n elif channel_id.startswith(\"GROUP_\") and platform == \"qq_group\":\n channel_id = channel_id[6:]\n to_ret = []\n msg_seq = 1\n for it in to_sends:\n if it[\"to_reply_id\"]:to_reply_id = it[\"to_reply_id\"]\n async with httpx.AsyncClient() as client:\n headers = {\"Authorization\":\"QQBot {}\".format(self._access_token),\"X-Union-Appid\":self._appid,\"Accept\":\"application/json\"}\n url:str = self._http_url + \"/v2/groups/{}/messages\".format(channel_id)\n data = {\n \"msg_id\":to_reply_id,\n \"content\":it[\"content\"],\n \"msg_type\":0,\n \"msg_seq\":msg_seq,\n # \"image\": 目前暂不支持\n }\n msg_seq += 1\n ret = (await client.post(url,headers=headers,json=data)).json()\n # print(ret)\n to_ret.append(SatoriMessage(id=ret[\"msg_id\"],content=\"\").to_dict())\n return to_ret\n \n async def get_login(self,platform:Optional[str],self_id:Optional[str]) -> [dict]:\n '''获取登录信息,如果platform和self_id为空,那么应该返回一个列表'''\n\n if platform == \"qq_group\":\n return SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=self._botqq,\n is_bot=True\n ),\n self_id=self._botqq,\n platform=\"qq_group\"\n ).to_dict()\n else: \n obret = (await self._api_call(\"/users/@me\"))\n satori_ret = SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=obret[\"id\"],\n name=obret[\"username\"],\n avatar=obret[\"avatar\"],\n is_bot=True\n ),\n self_id=obret[\"id\"],\n platform=\"qq_guild\"\n ).to_dict()\n self._self_id = obret[\"id\"]\n if platform == \"qq_guild\":\n return satori_ret\n elif platform == None:\n if not self._withgroup:\n return [satori_ret]\n else:\n return [satori_ret,SatoriLogin(\n status=self._login_status,\n user=SatoriUser(\n id=self._botqq,\n is_bot=True\n ),\n self_id=self._botqq,\n platform=\"qq_group\"\n ).to_dict()]\n \n async def get_guild_member(self,platform:Optional[str],self_id:Optional[str],guild_id:str,user_id:str) -> [dict]:\n '''获取群组成员信息'''\n if platform == \"qq_guild\":\n url = \"/guilds/{}/members/{}\".format(guild_id,user_id)\n obret = (await self._api_call(url))\n satori_ret = SatoriGuildMember(\n user=SatoriUser(\n id=obret[\"user\"][\"id\"],\n name=obret[\"user\"][\"username\"],\n avatar=obret[\"user\"][\"avatar\"],\n is_bot=obret[\"user\"][\"bot\"]\n ),\n nick=get_json_or(obret,\"nick\",None),\n avatar=obret[\"user\"][\"avatar\"],\n joined_at=int(time.mktime(time.strptime(obret[\"joined_at\"], \"%Y-%m-%dT%H:%M:%S%z\"))) * 1000\n ).to_dict()\n return satori_ret" }, { "identifier": "remove_json_null", "path": "tool.py", "snippet": "def remove_json_null(js) -> dict:\n '''将json中的None字段删除'''\n if isinstance(js,dict):\n st = {}\n for key in js:\n if js[key] != None:\n st[key] = remove_json_null(js[key])\n return st\n elif isinstance(js,list):\n lst = []\n for it in js:\n lst.append(remove_json_null(it))\n return lst\n else:\n return js" } ]
import asyncio import aiohttp import json import uuid from kook_adapter import AdapterKook from mihoyo_adapter import AdapterMihoyo from onebot_adapter import AdapterOnebot from config import Config from aiohttp import web from qq_adapter import AdapterQQ from tool import remove_json_null
17,893
if method == "/v1/login.get": ret = await adapter.get_login(platform,self_id) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/guild.member.get": body = await request.json() ret = await adapter.get_guild_member(platform,self_id,body["guild_id"],body["user_id"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/message.create": body = await request.json() ret = await adapter.create_message(platform,self_id,body["channel_id"],body["content"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/channel.list": body = await request.json() ret = await adapter.get_channel_list(platform,self_id,body["guild_id"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/user.get": body = await request.json() ret = await adapter.get_user(platform,self_id,body["user_id"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) return web.Response(text="method not found") async def _handle_http_admin(self,request:web.Request): print("----http admin",request) '''在这里处理管理api调用''' # 鉴权 if self._config.access_token != "": if request.headers.get("Authorization") != "Bearer " + self._config.access_token: print("token err") return web.Response(text="token err") method = request.url.path if method == "/v1/admin/login.list": ret = [] for adapter in self.adapterlist: ret += await adapter["adapter"].get_login(None,None) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) return web.Response(text="method not found") async def _handle_http_foo(self,request:web.Request): '''在这里处理其余任何api调用''' print("--------http other",request) return web.Response(text="method not found") async def _handle_events_ws(self,request:web.Request): '''在这里处理websocket''' ws_id = str(uuid.uuid4()) ws = web.WebSocketResponse() ws.can_prepare(request) await ws.prepare(request) self.wsmap[ws_id] = { "ws":ws, "is_access":False } print("--------http ws",request,ws_id) try: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: data_json = json.loads(msg.data) print("--------recv_ws",json.dumps(msg.data)) op = data_json["op"] if op == 3: if self._config.access_token != "": if data_json["body"]["token"] != self._config.access_token: raise "token err" self.wsmap[ws_id]["is_access"] = True async def get_logins(self,ws): logins = [] for adapter in self.adapterlist: logins += await adapter["adapter"].get_login(None,None) await Satori.ws_send_json(ws,{ "op":4, "body":{ "logins":logins } }) asyncio.create_task(get_logins(self,ws)) elif op == 1: async def send_pong(ws): await Satori.ws_send_json(ws,{ "op":2 }) asyncio.create_task(send_pong(ws)) elif msg.type == aiohttp.WSMsgType.ERROR: print('ws connection closed with exception %s' % ws.exception()) finally: del self.wsmap[ws_id] print("--------http ws close",ws_id) return ws async def init_after(self): async def event_loop(self:Satori,adapter:AdapterOnebot): while True: msg = await adapter.get_msg() for wsid in self.wsmap: ws = self.wsmap[wsid] if ws["is_access"]: msg["id"] = self._evt_id asyncio.create_task(Satori.ws_send_json(ws["ws"],{"op":0,"body":msg})) self._evt_id += 1 # 读取配置文件 await self._config.read_config() # 创建 adapter for botcfg in self._config.botlist: if botcfg["platform"] == "onebot": adapter = AdapterOnebot(botcfg) elif botcfg["platform"] == "kook": adapter = AdapterKook(botcfg) elif botcfg["platform"] == "mihoyo":
class Satori: def __init__(self) -> None: self._config:Config = Config() self.adapterlist = [] self.wsmap = {} self._evt_id = 100 async def _get_adapter(self,platform,self_id): ''' 用于获取适配器 ''' for adapter in self.adapterlist: info = adapter["info"] for bot in info: if self_id == bot["self_id"] and bot["platform"] == platform: return adapter["adapter"] return None async def ws_send_json(ws,js) -> None: js = remove_json_null(js) print("--------ws_send_json",json.dumps(js)) await ws.send_json(js) async def _handle_http_normal(self,request:web.Request): print("----http normal",request) '''在这里处理普通api调用''' # 鉴权 if self._config.access_token != "": if request.headers.get("Authorization") != "Bearer " + self._config.access_token: print("token err") return web.Response(text="token err") method = request.url.path platform = request.headers.get("X-Platform") self_id = request.headers.get("X-Self-ID") adapter:AdapterOnebot = await self._get_adapter(platform,self_id) if adapter == None: return web.Response(text="bot not found") if method == "/v1/login.get": ret = await adapter.get_login(platform,self_id) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/guild.member.get": body = await request.json() ret = await adapter.get_guild_member(platform,self_id,body["guild_id"],body["user_id"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/message.create": body = await request.json() ret = await adapter.create_message(platform,self_id,body["channel_id"],body["content"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/channel.list": body = await request.json() ret = await adapter.get_channel_list(platform,self_id,body["guild_id"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) elif method == "/v1/user.get": body = await request.json() ret = await adapter.get_user(platform,self_id,body["user_id"]) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) return web.Response(text="method not found") async def _handle_http_admin(self,request:web.Request): print("----http admin",request) '''在这里处理管理api调用''' # 鉴权 if self._config.access_token != "": if request.headers.get("Authorization") != "Bearer " + self._config.access_token: print("token err") return web.Response(text="token err") method = request.url.path if method == "/v1/admin/login.list": ret = [] for adapter in self.adapterlist: ret += await adapter["adapter"].get_login(None,None) return web.Response(text=json.dumps(remove_json_null(ret)),headers={ "Content-Type":"application/json; charset=utf-8" }) return web.Response(text="method not found") async def _handle_http_foo(self,request:web.Request): '''在这里处理其余任何api调用''' print("--------http other",request) return web.Response(text="method not found") async def _handle_events_ws(self,request:web.Request): '''在这里处理websocket''' ws_id = str(uuid.uuid4()) ws = web.WebSocketResponse() ws.can_prepare(request) await ws.prepare(request) self.wsmap[ws_id] = { "ws":ws, "is_access":False } print("--------http ws",request,ws_id) try: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: data_json = json.loads(msg.data) print("--------recv_ws",json.dumps(msg.data)) op = data_json["op"] if op == 3: if self._config.access_token != "": if data_json["body"]["token"] != self._config.access_token: raise "token err" self.wsmap[ws_id]["is_access"] = True async def get_logins(self,ws): logins = [] for adapter in self.adapterlist: logins += await adapter["adapter"].get_login(None,None) await Satori.ws_send_json(ws,{ "op":4, "body":{ "logins":logins } }) asyncio.create_task(get_logins(self,ws)) elif op == 1: async def send_pong(ws): await Satori.ws_send_json(ws,{ "op":2 }) asyncio.create_task(send_pong(ws)) elif msg.type == aiohttp.WSMsgType.ERROR: print('ws connection closed with exception %s' % ws.exception()) finally: del self.wsmap[ws_id] print("--------http ws close",ws_id) return ws async def init_after(self): async def event_loop(self:Satori,adapter:AdapterOnebot): while True: msg = await adapter.get_msg() for wsid in self.wsmap: ws = self.wsmap[wsid] if ws["is_access"]: msg["id"] = self._evt_id asyncio.create_task(Satori.ws_send_json(ws["ws"],{"op":0,"body":msg})) self._evt_id += 1 # 读取配置文件 await self._config.read_config() # 创建 adapter for botcfg in self._config.botlist: if botcfg["platform"] == "onebot": adapter = AdapterOnebot(botcfg) elif botcfg["platform"] == "kook": adapter = AdapterKook(botcfg) elif botcfg["platform"] == "mihoyo":
adapter = AdapterMihoyo(botcfg)
1
2023-12-03 13:53:47+00:00
24k
aliyun/pai-python-sdk
pai/model.py
[ { "identifier": "git_utils", "path": "pai/common/git_utils.py", "snippet": "def git_clone_repo(git_config: Dict[str, str], source_dir: Optional[str] = None):\ndef _validate_git_config(git_config):\ndef _build_and_run_clone_command(git_config, dest_dir):\ndef _clone_command_for_codeup(git_config, dest_dir):\ndef _clone_command_for_github(git_config, dest_dir):\ndef _clone_command_for_ssh(git_config, dest_dir):\ndef _clone_command_for_github_https(git_config, dest_dir):\ndef _clone_command_for_codeup_https(git_config, dest_dir):\ndef _clone_command(repo_url, dest_dir, branch=None):\ndef _update_url_with_token(repo_url, token):\ndef _update_url_with_username_and_password(repo_url, username, password):\ndef _checkout_commit(git_config, dest_dir):" }, { "identifier": "INSTANCE_TYPE_LOCAL_GPU", "path": "pai/common/consts.py", "snippet": "INSTANCE_TYPE_LOCAL_GPU = \"local_gpu\"" }, { "identifier": "ModelFormat", "path": "pai/common/consts.py", "snippet": "class ModelFormat(object):\n SavedModel = \"SavedModel\"\n FrozenPb = \"FrozenPb\"\n KerasH5 = \"KerasH5\"\n CaffePrototxt = \"Caffe\"\n ONNX = \"ONNX\"\n BladeModel = \"BladeModel\"\n PMML = \"PMML\"\n TorchScript = \"TorchScript\"\n TFLite = \"TFLite\"" }, { "identifier": "ContainerRun", "path": "pai/common/docker_utils.py", "snippet": "class ContainerRun(object):\n \"\"\"A class represent a container run in local.\"\"\"\n\n CONTAINER_STATUS_RUNNING = \"running\"\n CONTAINER_STATUS_EXITED = \"exited\"\n CONTAINER_STATUS_PAUSED = \"paused\"\n\n def __init__(self, container, port: Optional[int] = None):\n \"\"\"Initialize a container run.\n\n Args:\n container: A docker container object.\n port (int): The host port that container is exposed to.\n\n \"\"\"\n self.container = container\n self.port = port\n\n @property\n def status(self):\n self.container.reload()\n return self.container.status\n\n def is_running(self):\n \"\"\"Return True if container is running, otherwise False.\"\"\"\n return self.status == self.CONTAINER_STATUS_RUNNING\n\n def is_terminated(self):\n \"\"\"Return True if container is terminated, otherwise False.\"\"\"\n return self.status in [\n self.CONTAINER_STATUS_EXITED,\n self.CONTAINER_STATUS_PAUSED,\n ]\n\n def is_succeeded(self):\n \"\"\"Return True if container is succeeded, otherwise False.\"\"\"\n return (\n self.status == \"exited\" and self.container.attrs[\"State\"][\"ExitCode\"] == 0\n )\n\n def wait_for_ready(self, interval=5):\n \"\"\"Wait until container enter running state or terminated state.\"\"\"\n while True:\n status = self.status\n if status == self.CONTAINER_STATUS_RUNNING:\n break\n elif status in [self.CONTAINER_STATUS_EXITED, self.CONTAINER_STATUS_PAUSED]:\n raise RuntimeError(\n \"Container is terminated : id={} status={}\".format(\n self.container.id, self.container.status\n )\n )\n time.sleep(interval)\n\n def stop(self):\n if self.is_running():\n self.container.stop()\n\n def start(self):\n if not self.is_running():\n self.container.start()\n\n def delete(self):\n if self.is_running():\n self.container.stop()\n self.container.remove()\n\n def watch(self, show_logs: bool = True):\n \"\"\"Watch container log and wait for container to exit.\"\"\"\n if not show_logs:\n self.container.wait()\n else:\n log_iter = self.container.logs(\n stream=True,\n follow=True,\n )\n for log in log_iter:\n print(log.decode())\n\n self.container.reload()\n exit_code = self.container.attrs[\"State\"][\"ExitCode\"]\n if exit_code != 0:\n raise RuntimeError(\n \"Container run exited failed: exit_code={}\".format(exit_code)\n )" }, { "identifier": "run_container", "path": "pai/common/docker_utils.py", "snippet": "def run_container(\n image_uri: str,\n container_name: Optional[str] = None,\n port: Optional[int] = None,\n environment_variables: Optional[Dict[str, str]] = None,\n command: Optional[Union[List[str], str]] = None,\n entry_point: Optional[Union[List[str], str]] = None,\n volumes: Optional[Dict[str, Any]] = None,\n working_dir: Optional[str] = None,\n gpu_count: Optional[int] = None,\n gpu_device_ids: Optional[List[str]] = None,\n gpu_capabilities: Optional[List[List[str]]] = None,\n) -> ContainerRun:\n \"\"\"Run a container in local.\n\n Args:\n image_uri (str): A docker image uri.\n container_name (str, optional): Name of the container.\n port (int, optional): The port to expose.\n environment_variables (Dict[str, str], optional): Environment variables to set\n in the container.\n command (Union[List[str], str], optional): Command to run the container.\n entry_point (Union[List[str], str], optional): Entry point to run the container.\n volumes (Dict[str, Any], optional): Volumes to mount in the container.\n working_dir (str, optional): Working directory in the container.\n gpu_count (int, optional): Number of GPU devices to request. Set to -1 to\n request all available devices.\n To use GPU, set either ``gpu_count`` or ``gpu_device_ids``.\n gpu_device_ids (List[str], optional): List of strings for GPU device IDs,\n corresponding to `NVIDIA_VISIBLE_DEVICES` in the NVIDIA Runtime.\n To use GPU, set either ``gpu_count`` or ``gpu_device_ids``.\n gpu_capabilities (List[List[str]], optional): This parameter corresponds to\n `NVIDIA_DRIVER_CAPABILITIES` in the NVIDIA Runtime. The default value is\n ``[[\"compute\", \"utility\"]]`` if ``gpu_device_ids`` or ``gpu_count`` is set.\n Available capabilities for the NVIDIA driver can be found in\n https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/user-guide.html#driver-capabilities.\n\n Returns:\n ContainerRun: A ContainerRun object.\n\n \"\"\"\n try:\n import docker\n except ImportError:\n raise ImportError(\"Please install docker first: pip install docker\")\n\n client = docker.from_env()\n # use a random host port.\n host_port = randint(49152, 65535)\n\n if gpu_count or gpu_device_ids or gpu_capabilities:\n if not gpu_capabilities:\n gpu_capabilities = [[\"compute\", \"utility\"]]\n device_requests = [\n docker.types.DeviceRequest(\n count=gpu_count,\n device_ids=gpu_device_ids,\n capabilities=gpu_capabilities,\n )\n ]\n else:\n device_requests = []\n\n container = client.containers.run(\n name=container_name,\n entrypoint=entry_point,\n image=image_uri,\n command=command,\n environment=environment_variables,\n ports={port: host_port} if port else None,\n volumes=volumes,\n working_dir=working_dir,\n detach=True,\n device_requests=device_requests,\n )\n container_run = ContainerRun(\n container=container,\n port=host_port,\n )\n return container_run" }, { "identifier": "OssUriObj", "path": "pai/common/oss_utils.py", "snippet": "class OssUriObj(object):\n \"\"\"A class that represents an OSS URI and provides some convenient methods.\"\"\"\n\n def __init__(self, uri: str):\n \"\"\"Constructor for class OssUriObj.\n\n Args:\n uri (str): A string in OSS URI schema: oss://<bucket_name>[.endpoint]/<path/to/file>,\n endpoint in uri is optional.\n \"\"\"\n if not uri.startswith(\"oss://\"):\n raise ValueError(\n \"Invalid OSS URI schema, please provide a string starts with 'oss://'\"\n )\n bucket_name, object_key, endpoint, role_arn = self.parse(uri)\n self.bucket_name = bucket_name\n self.object_key = object_key\n self.endpoint = endpoint\n self.role_arn = role_arn\n\n @classmethod\n def from_bucket_key_endpoint(\n cls, bucket_name: str, object_key: str, endpoint: Optional[str] = None\n ) -> \"OssUriObj\":\n \"\"\"Initialize an OSSUri object from bucket_name, object_key and endpoint.\n\n Args:\n bucket_name (str): The name of the OSS bucket.\n object_key (str): OSS object key/path.\n endpoint (str, optional): Endpoint for the OSS bucket.\n\n Returns:\n OssUriObj: An OssUriObj instance represents the specified OSS object.\n\n \"\"\"\n # OSS object key could not contain leading slashes.\n # Document: https://help.aliyun.com/document_detail/273129.html\n if object_key.startswith(\"/\"):\n logger.warning(\n \"OSS object key should not contain leading slashes, the leading\"\n \" slashes will be removed.\"\n )\n object_key = object_key.lstrip(\"/\")\n\n if endpoint:\n if endpoint.startswith(\"http://\"):\n endpoint = endpoint.lstrip(\"http://\")\n elif endpoint.startswith(\"https://\"):\n endpoint = endpoint.lstrip(\"https://\")\n\n uri = f\"oss://{bucket_name}.{endpoint}/{object_key}\"\n else:\n uri = f\"oss://{bucket_name}/{object_key}\"\n return OssUriObj(uri=uri)\n\n @classmethod\n def parse(cls, oss_uri: str) -> Tuple[str, str, str, str]:\n \"\"\"Parse OSS uri string and returns a tuple of (bucket_name, object_key,\n endpoint, role_arn).\n\n Args:\n oss_uri (str): A string in OSS Uri schema: oss://{bucket_name}.{endpoint}/{object_key}.\n\n Returns:\n Tuple: An tuple of [bucket_name, object_key, endpoint, role_arn].\n\n \"\"\"\n parsed_result = urlparse(oss_uri)\n if parsed_result.scheme != \"oss\":\n raise ValueError(\n \"require OSS uri('oss://[bucket_name]/[object_key]') but \"\n \"given '{}'\".format(oss_uri)\n )\n object_key = parsed_result.path\n if object_key.startswith(\"/\"):\n object_key = object_key[1:]\n\n query = parse_qs(parsed_result.query)\n if \".\" in parsed_result.hostname:\n bucket_name, endpoint = parsed_result.hostname.split(\".\", 1)\n else:\n bucket_name = parsed_result.hostname\n # try to get OSS endpoint from url query.\n if \"endpoint\" in query:\n endpoint = query.get(\"endpoint\")[0]\n elif \"host\" in query:\n endpoint = query.get(\"host\")[0]\n else:\n endpoint = None\n role_arn = query.get(\"role_arn\")[0] if \"role_arn\" in query else None\n\n return bucket_name, object_key, endpoint, role_arn\n\n def get_uri_with_endpoint(self, endpoint: str = None) -> str:\n \"\"\"Get an OSS uri string contains endpoint.\n\n Args:\n endpoint (str): Endpoint of the OSS bucket.\n\n Returns:\n str: An string in OSS uri schema contains endpoint.\n\n \"\"\"\n if not endpoint and not self.endpoint:\n raise ValueError(\"Unknown endpoint for the OSS bucket.\")\n\n return \"oss://{bucket_name}.{endpoint}/{object_key}\".format(\n bucket_name=self.bucket_name,\n endpoint=endpoint or self.endpoint,\n object_key=self.object_key,\n )\n\n def get_dir_uri(self):\n \"\"\"Returns directory in OSS uri string format of the original object.\"\"\"\n _, dirname, _ = self.parse_object_key()\n dir_uri = f\"oss://{self.bucket_name}{dirname}\"\n return dir_uri\n\n @property\n def uri(self) -> str:\n \"\"\"Returns OSS uri in string format.\"\"\"\n return \"oss://{bucket_name}/{object_key}\".format(\n bucket_name=self.bucket_name,\n object_key=self.object_key,\n )\n\n def parse_object_key(self) -> Tuple[bool, str, str]:\n \"\"\"Parse the OSS URI object key, returns a tuple of (is_dir, dir_path, file_name).\n\n Returns:\n namedtuple: An tuple of is_dir, dir_path, file_name.\n \"\"\"\n object_key = self.object_key.strip()\n if object_key.endswith(\"/\"):\n is_dir, dir_path, file_name = True, os.path.join(\"/\", object_key), None\n else:\n idx = object_key.rfind(\"/\")\n if idx < 0:\n is_dir, dir_path, file_name = False, \"/\", object_key\n else:\n is_dir, dir_path, file_name = (\n False,\n os.path.join(\"/\", object_key[: idx + 1]),\n object_key[idx + 1 :],\n )\n return is_dir, dir_path, file_name" }, { "identifier": "download", "path": "pai/common/oss_utils.py", "snippet": "def download(\n oss_path: Union[str, OssUriObj],\n local_path: str,\n bucket: Optional[oss2.Bucket] = None,\n un_tar=False,\n):\n \"\"\"Download OSS objects to local path.\n\n Args:\n oss_path (str): Source OSS path, could be a single OSS object or a OSS\n directory.\n local_path (str): Local path used to store the data from OSS.\n bucket (oss2.Bucket, optional): OSS bucket used to store the upload data. If it\n is not provided, OSS bucket of the default session will be used.\n un_tar (bool, optional): Whether to decompress the downloaded data. It is only\n work for `oss_path` point to a single file that has a suffix \"tar.gz\".\n\n Returns:\n str: A local file path for the downloaded data.\n\n \"\"\"\n\n bucket, oss_path = _get_bucket_and_path(bucket, oss_path)\n\n if not bucket.object_exists(oss_path) or oss_path.endswith(\"/\"):\n # The `oss_path` represents a \"directory\" in the OSS bucket, download the\n # objects which object key is prefixed with `oss_path`.\n # Note: `un_tar` is not work while `oss_path` is a directory.\n\n oss_path += \"/\" if not oss_path.endswith(\"/\") else \"\"\n iterator = oss2.ObjectIteratorV2(\n bucket=bucket,\n prefix=oss_path,\n )\n keys = [obj.key for obj in iterator if not obj.key.endswith(\"/\")]\n for key in tqdm(keys, desc=f\"Downloading: {oss_path}\"):\n rel_path = os.path.relpath(key, oss_path)\n dest = os.path.join(local_path, rel_path)\n os.makedirs(os.path.dirname(dest), exist_ok=True)\n _download_with_progress(\n dest,\n object_key=key,\n oss_bucket=bucket,\n )\n return local_path\n else:\n # The `oss_path` represents a single file in OSS bucket.\n if oss_path.endswith(\".tar.gz\") and un_tar:\n # currently, only tar.gz format is supported for un_tar after downloading.\n with tempfile.TemporaryDirectory() as temp_dir:\n target_path = os.path.join(temp_dir, os.path.basename(oss_path))\n _download_with_progress(\n target_path,\n object_key=oss_path,\n oss_bucket=bucket,\n )\n with tarfile.open(name=target_path, mode=\"r\") as t:\n t.extractall(path=local_path)\n\n return local_path\n else:\n os.makedirs(local_path, exist_ok=True)\n dest = os.path.join(local_path, os.path.basename(oss_path))\n _download_with_progress(\n dest,\n object_key=oss_path,\n oss_bucket=bucket,\n )\n\n return dest" }, { "identifier": "is_oss_uri", "path": "pai/common/oss_utils.py", "snippet": "def is_oss_uri(uri: Union[str, bytes]) -> bool:\n \"\"\"Determines whether the given uri is an OSS uri.\n\n Args:\n uri (Union[str, bytes]): A string in OSS URI schema:\n oss://<bucket_name>[.endpoint]/<path/to/file>,\n\n\n Returns:\n bool: True if the given uri is an OSS uri, else False.\n\n \"\"\"\n return bool(uri and isinstance(uri, (str, bytes)) and str(uri).startswith(\"oss://\"))" }, { "identifier": "upload", "path": "pai/common/oss_utils.py", "snippet": "def upload(\n source_path: str,\n oss_path: Union[str, OssUriObj],\n bucket: Optional[oss2.Bucket] = None,\n is_tar: Optional[bool] = False,\n) -> str:\n \"\"\"Upload local source file/directory to OSS.\n\n Examples::\n\n # compress and upload local directory `./src/` to OSS\n >>> upload(source_path=\"./src/\", oss_path=\"path/to/file\",\n ... bucket=session.oss_bucket, is_tar=True)\n\n\n Args:\n source_path (str): Source file local path which needs to be uploaded, can be\n a single file or a directory.\n oss_path (Union[str, OssUriObj]): Destination OSS path.\n bucket (oss2.Bucket): OSS bucket used to store the upload data. If it is not\n provided, OSS bucket of the default session will be used.\n is_tar (bool): Whether to compress the file before uploading (default: False).\n\n Returns:\n str: A string in OSS URI format. If the source_path is directory, return the\n OSS URI representing the directory for uploaded data, else then\n returns the OSS URI points to the uploaded file.\n \"\"\"\n\n bucket, oss_path = _get_bucket_and_path(bucket, oss_path)\n\n source_path_obj = pathlib.Path(source_path)\n if not source_path_obj.exists():\n raise RuntimeError(\"Source path is not exist: {}\".format(source_path))\n\n if is_tar:\n # compress the local data and upload the compressed source data.\n with tempfile.TemporaryDirectory() as dir_name:\n temp_tar_path = _tar_file(\n source_path, os.path.join(dir_name, \"source.tar.gz\")\n )\n dest_path = (\n os.path.join(oss_path, os.path.basename(temp_tar_path))\n if oss_path.endswith(\"/\")\n else oss_path\n )\n _upload_with_progress(\n filename=temp_tar_path, object_key=dest_path, oss_bucket=bucket\n )\n return \"oss://{}/{}\".format(bucket.bucket_name, dest_path)\n elif not source_path_obj.is_dir():\n # if source path is a file, just invoke bucket.put_object.\n\n # if the oss_path is endswith slash, the file will be uploaded to\n # \"{oss_path}{filename}\", else the file will be uploaded to \"{oss_path}\".\n dest_path = (\n os.path.join(oss_path, os.path.basename(source_path))\n if oss_path.endswith(\"/\")\n else oss_path\n )\n _upload_with_progress(\n filename=source_path, object_key=dest_path, oss_bucket=bucket\n )\n return \"oss://{}/{}\".format(bucket.bucket_name, dest_path)\n else:\n # if the source path is a directory, upload all the file under the directory.\n source_files = glob.glob(\n pathname=str(source_path_obj / \"**\"),\n recursive=True,\n )\n if not oss_path.endswith(\"/\"):\n oss_path += \"/\"\n\n files = [f for f in source_files if not os.path.isdir(f)]\n for file_path in files:\n file_path_obj = pathlib.Path(file_path)\n file_relative_path = file_path_obj.relative_to(source_path_obj).as_posix()\n object_key = oss_path + file_relative_path\n _upload_with_progress(\n filename=file_path, object_key=object_key, oss_bucket=bucket\n )\n return \"oss://{}/{}\".format(bucket.bucket_name, oss_path)" }, { "identifier": "generate_repr", "path": "pai/common/utils.py", "snippet": "def generate_repr(repr_obj, *attr_names: str, **kwargs) -> str:\n \"\"\"Generate a string representation of the given object.\n\n Args:\n repr_obj: The object used to generate the string representation.\n attr_names: A list of attribute names to include in the string representation.\n\n Returns:\n str: A string representation of the object.\n\n \"\"\"\n attrs = {name: getattr(repr_obj, name) for name in attr_names}\n attrs.update(kwargs)\n attr_repr = \", \".join([\"{}={}\".format(k, v) for k, v in attrs.items()])\n cls_name = repr_obj.__class__.__name__\n\n return f\"{cls_name}({attr_repr})\"" }, { "identifier": "is_local_run_instance_type", "path": "pai/common/utils.py", "snippet": "def is_local_run_instance_type(instance_type: str) -> bool:\n \"\"\"Return True if instance_type is local run instance type.\"\"\"\n return instance_type and instance_type.strip() in [\n INSTANCE_TYPE_LOCAL_GPU,\n INSTANCE_TYPE_LOCAL,\n ]" }, { "identifier": "random_str", "path": "pai/common/utils.py", "snippet": "def random_str(n):\n \"\"\"Random string generation with lower case letters and digits.\n\n Args:\n n: Size of generated random string.\n\n Returns:\n str: generated random string.\n\n \"\"\"\n return \"\".join(\n random.choice(string.ascii_lowercase + string.digits) for _ in range(n)\n )" }, { "identifier": "to_plain_text", "path": "pai/common/utils.py", "snippet": "def to_plain_text(\n input_str: str, allowed_characters=DEFAULT_PLAIN_TEXT_ALLOW_CHARACTERS, repl_ch=\"_\"\n):\n \"\"\"Replace characters in input_str if it is not in allowed_characters.\"\"\"\n return \"\".join([c if c in allowed_characters else repl_ch for c in input_str])" }, { "identifier": "DuplicatedMountException", "path": "pai/exception.py", "snippet": "class DuplicatedMountException(PAIException):\n \"\"\"Raised if a OSS path is mounted twice.\"\"\"" }, { "identifier": "MountPathIsOccupiedException", "path": "pai/exception.py", "snippet": "class MountPathIsOccupiedException(PAIException):\n \"\"\"Raised if target mount path is already used.\"\"\"" }, { "identifier": "ImageInfo", "path": "pai/image.py", "snippet": "class ImageInfo(object):\n \"\"\"This class represents information for an image provided by PAI.\n\n Args:\n image_name (str): The name of the image.\n image_uri (str): The URI of the image.\n framework_name (str): The name of the framework installed in the image.\n framework_version (str, optional): The version of the framework (Default None).\n image_scope (str): The scope of the image, could be 'training', 'inference' or\n 'develop'.\n accelerator_type (str, optional): The type of accelerator. Defaults to None.\n python_version (str, optional): The version of Python. Defaults to None.\n \"\"\"\n\n def __repr__(self):\n return (\n \"{}(framework_name={}: framework_version={}: image_scope={}: \"\n \"accelerator_type={}: py_version={})\".format(\n self.__class__.__name__,\n self.framework_name,\n self.framework_version,\n self.image_scope,\n self.accelerator_type,\n self.python_version,\n )\n )\n\n def __init__(\n self,\n image_name: str,\n image_uri: str,\n framework_name: str,\n image_scope: str,\n framework_version: str = None,\n accelerator_type: Optional[str] = None,\n python_version: Optional[str] = None,\n ):\n self.image_name = image_name\n self.image_uri = image_uri\n self.framework_name = framework_name\n self.framework_version = framework_version\n self.accelerator_type = accelerator_type\n self.python_version = python_version\n self.image_scope = image_scope" }, { "identifier": "AsyncPredictor", "path": "pai/predictor.py", "snippet": "class AsyncPredictor(PredictorBase, _ServicePredictorMixin):\n \"\"\"A class that facilitates making predictions to asynchronous prediction service.\n\n Examples::\n\n # Initialize an AsyncPredictor object using the name of a running service.\n async_predictor = AsyncPredictor(service_name=\"example_service\")\n\n # Make a prediction with the service and get the prediction result.\n resp = async_predictor.predict(data=\"YourPredictionData\")\n result = resp.wait()\n\n # Make a prediction with async API.\n import asyncio\n result = asyncio.run(async_predictor.predict_async(data=\"YourPredictionData\"))\n\n \"\"\"\n\n def __init__(\n self,\n service_name: str,\n max_workers: Optional[int] = None,\n endpoint_type: str = EndpointType.INTERNET,\n serializer: Optional[SerializerBase] = None,\n session: Optional[Session] = None,\n ):\n \"\"\"Construct a `AsyncPredictor` object using an existing async prediction service.\n\n Args:\n service_name (str): Name of the existing prediction service.\n max_workers (int): The maximum number of threads that can be used to\n execute the given prediction calls.\n endpoint_type (str): Selects the endpoint used by the predictor, which\n should be one of `INTERNET` or `INTRANET`. The `INTERNET` endpoint type\n means that the predictor calls the service over a public endpoint, while\n the `INTRANET` endpoint type is over a VPC endpoint.\n serializer (SerializerBase, optional): A serializer object that transforms\n the input Python object for data transmission and deserialize the\n response data to Python object.\n session (Session, optional): A PAI session object used for communicating\n with PAI service.\n \"\"\"\n\n super(AsyncPredictor, self).__init__(\n service_name=service_name,\n session=session or get_default_session(),\n endpoint_type=endpoint_type,\n serializer=serializer,\n )\n self._max_workers = max_workers\n self.executor = ThreadPoolExecutor(max_workers=self._max_workers)\n self._check()\n\n @property\n def max_workers(self):\n return self._max_workers\n\n @max_workers.setter\n def max_workers(self, n: int):\n if hasattr(self, \"executor\"):\n logger.info(\"Waiting for all submitted tasks in the queue to complete...\")\n self.executor.shutdown()\n self._max_workers = n\n self.executor = ThreadPoolExecutor(max_workers=self._max_workers)\n\n def __del__(self):\n \"\"\"wait for all pending tasks to complete before exit.\"\"\"\n if hasattr(self, \"executor\"):\n logger.info(\"Waiting for all pending tasks to complete...\")\n self.executor.shutdown()\n super(AsyncPredictor, self).__del__()\n\n def _check(self):\n config = json.loads(self._service_api_object[\"ServiceConfig\"])\n if config.get(\"metadata\", {}).get(\"type\") != ServiceType.Async:\n logger.warning(\n \"AsyncPredictor is not recommended to make prediction to a standard \"\n \" prediction service.\"\n )\n\n def _get_result(\n self, request_id: str\n ) -> Optional[Tuple[int, Dict[str, str], bytes]]:\n resp = self._send_request(\n method=\"GET\",\n path=_QUEUE_SERVICE_SINK_PATH,\n params={\n \"requestId\": request_id,\n # _raw_ is false because we want to get the encapsulated prediction\n # result in response body.\n \"_raw_\": \"false\",\n },\n )\n logger.debug(\n \"Poll prediction result: request_id=%s status_code=%s, content=%s\",\n request_id,\n resp.status_code,\n resp.content,\n )\n if resp.status_code == 204:\n # Status code 204 means could not find prediction response for the specific\n # request id.\n return\n\n # Raise exception if status code is not 2xx.\n if resp.status_code // 100 != 2:\n raise RuntimeError(\n \"Pulling prediction result failed: status_code={} content={}\".format(\n resp.status_code, resp.content.decode(\"utf-8\")\n )\n )\n return self._parse_encapsulated_response(resp.json()[0])\n\n def _parse_encapsulated_response(self, data) -> Tuple[int, Dict[str, str], bytes]:\n tags = data[\"tags\"]\n # If the status code from prediction service is not 200, a tag with\n # key 'lastCode' will be added to the tags in response.\n status_code = int(tags.get(\"lastCode\", 200))\n data = base64.b64decode(data[\"data\"])\n # currently, headers are not supported in async prediction service.\n headers = dict()\n return status_code, headers, data\n\n async def _get_result_async(\n self, request_id: str\n ) -> Optional[Tuple[int, Dict[str, str], bytes]]:\n resp = await self._send_request_async(\n method=\"GET\",\n path=_QUEUE_SERVICE_SINK_PATH,\n params={\n \"requestId\": request_id,\n # _raw_ is false because we want to get the encapsulated prediction\n # result in response body.\n \"_raw_\": \"false\",\n },\n )\n status_code = resp.status\n content = await resp.read()\n logger.debug(\n \"Get prediction result: request_id=%s status_code=%s, content=%s\",\n request_id,\n status_code,\n content,\n )\n if status_code == 204:\n # Status code 204 means could not find prediction response for the specific\n # request id.\n return\n if status_code // 100 != 2:\n raise RuntimeError(\n \"Pulling prediction result failed: status_code={} content={}\".format(\n status_code, content.decode(\"utf-8\")\n )\n )\n data = (await resp.json())[0]\n return self._parse_encapsulated_response(data)\n\n def _poll_result(\n self, request_id: str, wait_config: WaitConfig\n ) -> Tuple[int, Dict[str, str], bytes]:\n # if max_attempts is negative or zero, then wait forever\n attempts = -1 if wait_config.max_attempts <= 0 else wait_config.max_attempts\n while attempts != 0:\n attempts -= 1\n result = self._get_result(request_id=request_id)\n if not result:\n time.sleep(wait_config.interval)\n continue\n status_code, headers, content = result\n # check real prediction response\n if status_code // 100 != 2:\n raise PredictionException(\n code=status_code,\n message=f\"Prediction failed: status_code={status_code}\"\n f\" content={content.decode()}\",\n )\n return status_code, headers, content\n\n # Polling prediction result timeout.\n raise RuntimeError(\n f\"Polling prediction result timeout: request_id={request_id}, \"\n f\"total_time={wait_config.max_attempts * wait_config.interval}\"\n )\n\n async def _poll_result_async(\n self, request_id, wait_config: WaitConfig\n ) -> Tuple[int, Dict[str, str], bytes]:\n # if max_attempts is negative or zero, then wait forever\n attempts = -1 if wait_config.max_attempts <= 0 else wait_config.max_attempts\n while attempts != 0:\n attempts -= 1\n result = await self._get_result_async(request_id)\n if not result:\n await asyncio.sleep(wait_config.interval)\n continue\n status_code, headers, content = result\n # check real prediction response\n if status_code // 100 != 2:\n raise PredictionException(\n f\"Prediction failed: status_code={status_code} content={content.decode()}\"\n )\n return status_code, headers, content\n\n # Polling prediction result timeout.\n raise RuntimeError(\n f\"Polling prediction result timeout: request_id={request_id}, \"\n f\"total_time={wait_config.max_attempts * wait_config.interval}\"\n )\n\n def _get_request_id(self, resp: requests.models.Response) -> str:\n if resp.status_code // 100 != 2:\n raise RuntimeError(\n f\"Send prediction request failed. status_code={resp.status_code} \"\n f\"message={resp.text}\"\n )\n\n if _QUEUE_SERVICE_REQUEST_ID_HEADER not in resp.headers:\n logger.error(\n f\"Send prediction request failed. Missing request id.\"\n f\" status_code={resp.status_code} content={resp.text}\"\n )\n raise RuntimeError(\"Missing request id in response header.\")\n\n request_id = resp.headers[_QUEUE_SERVICE_REQUEST_ID_HEADER]\n logger.debug(\n f\"Send prediction request successfully. request_id={request_id}\"\n f\" status_code={resp.status_code}\",\n )\n return request_id\n\n async def _get_request_id_async(self, resp: aiohttp.ClientResponse) -> str:\n content = await resp.read()\n if resp.status != 200:\n raise RuntimeError(\n \"Send request to async prediction service failed: status_code={} \"\n \"content={}\".format(resp.status, content.decode(\"utf-8\"))\n )\n\n if _QUEUE_SERVICE_REQUEST_ID_HEADER not in resp.headers:\n logger.error(\n f\"Send prediction request failed. Missing request id.\"\n f\" status_code={resp.status} content={content.decode()}\"\n )\n raise RuntimeError(\"Missing request id in response header.\")\n request_id = resp.headers[_QUEUE_SERVICE_REQUEST_ID_HEADER]\n logger.debug(\n f\"Send prediction request successfully. request_id={request_id}\"\n f\" status_code={resp.status}\",\n )\n return request_id\n\n def _predict_fn(\n self,\n data,\n ):\n \"\"\"Make a prediction with the async prediction service.\"\"\"\n # serialize input data\n data = self._handle_input(data)\n resp = self._send_request(data=data)\n request_id = self._get_request_id(resp)\n logger.debug(\"Async prediction RequestId: \", request_id)\n # poll prediction result\n status, headers, content = self._poll_result(\n request_id=request_id, wait_config=WaitConfig()\n )\n\n return self._handle_output(content)\n\n def _wrap_callback_fn(self, cb: Callable):\n \"\"\"Wrap the callback function to handle the prediction result.\"\"\"\n\n @functools.wraps(cb)\n def _(future: Future):\n return cb(future.result())\n\n return _\n\n def predict(\n self,\n data,\n callback: Optional[Union[Callable, List[Callable]]] = None,\n ):\n \"\"\"Make a prediction with the async prediction service.\n\n The input data is serialized using the `serializer.serialize` method before it\n is sent, and the response body is deserialized using the\n `serializer.deserialize` method the prediction result returns.\n\n Args:\n data: The input data for the prediction. It will be serialized using the\n serializer of the predictor before transmitted to the prediction\n service.\n callback (Union[Callable, List[Callable]], optional): A Callback function,\n or a list of callback functions used to process the prediction result.\n\n Returns:\n AsyncTask: The task object that can be used to retrieve the prediction\n result.\n \"\"\"\n self._post_init_serializer()\n future = self.executor.submit(self._predict_fn, data)\n\n if isinstance(callback, Callable):\n callback = [callback]\n\n if callback:\n for cb in callback:\n future.add_done_callback(self._wrap_callback_fn(cb))\n\n return AsyncTask(future=future)\n\n async def predict_async(self, data, wait_config: WaitConfig = WaitConfig()):\n \"\"\"Make a prediction with the async prediction service.\n\n The serializer object for the predictor is responsible for data transformation\n when the 'predict' method is invoked. The input data is serialized using the\n `serializer.serialize` method before it is sent, and the response is\n deserialized using the `serializer.deserialize` method before the prediction\n result returns.\n\n Args:\n data: The input data for the prediction. It will be serialized using the\n serializer of the predictor before transmitted to the prediction\n service.\n wait_config (WaitConfig): A config object that controls the behavior of\n polling the prediction result.\n\n Returns:\n Prediction result.\n\n \"\"\"\n self._post_init_serializer()\n data = self._handle_input(data)\n resp = await self._send_request_async(data=data)\n request_id = await self._get_request_id_async(resp)\n\n status_code, headers, content = await self._poll_result_async(\n request_id=request_id, wait_config=wait_config\n )\n return self._handle_output(content)\n\n def _raw_predict_fn(self, data, method, path, headers, **kwargs):\n json_data, data = self._handle_raw_input(data)\n resp = self._send_request(\n path=path,\n json=json_data,\n data=data,\n headers=self._build_headers(headers),\n method=method,\n **kwargs,\n )\n request_id = self._get_request_id(resp)\n status, headers, content = self._poll_result(\n request_id, wait_config=WaitConfig()\n )\n return RawResponse(status, headers, content)\n\n def raw_predict(\n self,\n data: Any = None,\n callback: Optional[Union[Callable, List[Callable], None]] = None,\n method: str = \"POST\",\n path: Optional[str] = None,\n headers: Optional[Dict[str, str]] = None,\n **kwargs,\n ) -> AsyncTask:\n \"\"\"Make a prediction with the online prediction service.\n\n Args:\n data (Any): Input data to be sent to the prediction service. If it is a\n file-like object, bytes, or string, it will be sent as the request body.\n Otherwise, it will be treated as a JSON serializable object and sent as\n JSON.\n callback (Union[Callable, List[Callable]], optional): A Callback function,\n or a list of callback functions used to process the prediction result.\n path (str, optional): Path for the request to be sent to. If it is provided,\n it will be appended to the endpoint URL (Default None).\n headers (dict, optional): Request headers.\n method (str, optional): Request method, default to 'POST'.\n **kwargs: Additional keyword arguments for the request.\n Returns:\n AsyncTask: The task object that can be used to retrieve the prediction\n result.\n\n Examples:\n\n from pai.predictor import AsyncPredictor, AsyncTask\n\n predictor = AsyncPredictor()\n task: AsyncTask = predictor.raw_predict(data=\"YourPredictionData\")\n print(task.result())\n\n \"\"\"\n\n future = self.executor.submit(\n self._raw_predict_fn, data, method, path, headers, **kwargs\n )\n cbs = [callback] if isinstance(callback, Callable) else callback\n if cbs:\n for cb in cbs:\n future.add_done_callback(self._wrap_callback_fn(cb))\n\n return AsyncTask(future=future)\n\n async def raw_predict_async(\n self,\n data,\n wait_config: WaitConfig = WaitConfig(),\n method: str = \"POST\",\n headers: Optional[Dict[str, str]] = None,\n path: Optional[str] = None,\n **kwargs,\n ) -> RawResponse:\n \"\"\"Make a prediction with the online prediction service.\n\n Args:\n data (Any): Input data to be sent to the prediction service. If it is a\n file-like object, bytes, or string, it will be sent as the request body.\n Otherwise, it will be treated as a JSON serializable object and sent as\n JSON.\n wait_config (WaitConfig): A config object that controls the behavior of\n polling the prediction result.\n path (str, optional): Path for the request to be sent to. If it is provided,\n it will be appended to the endpoint URL (Default None).\n headers (dict, optional): Request headers.\n method (str, optional): Request method, default to 'POST'.\n **kwargs: Additional keyword arguments for the request.\n Returns:\n RawResponse: Prediction result.\n\n \"\"\"\n if self.service_status not in ServiceStatus.completed_status():\n self.wait_for_ready()\n json_data, data = self._handle_raw_input(data)\n\n resp = await self._send_request_async(\n data=data,\n method=method,\n json=json_data,\n path=path,\n headers=headers,\n **kwargs,\n )\n request_id = await self._get_request_id_async(resp)\n # Polling the prediction result.\n status_code, headers, content = await self._poll_result_async(\n request_id=request_id, wait_config=wait_config\n )\n return self._handle_raw_output(status_code, headers, content)" }, { "identifier": "LocalPredictor", "path": "pai/predictor.py", "snippet": "class LocalPredictor(PredictorBase):\n \"\"\"Perform prediction to a local service running with docker.\"\"\"\n\n def __init__(\n self,\n port: int,\n container_id: Optional[str] = None,\n serializer: Optional[SerializerBase] = None,\n ):\n \"\"\"LocalPredictor initializer.\n\n Args:\n port (int): The port of the local service.\n container_id (str, optional): The container id of the local service.\n serializer (SerializerBase, optional): A serializer object that transforms.\n \"\"\"\n self.container_id = container_id\n self.port = port\n self.serializer = serializer or JsonSerializer()\n self._container_run = (\n self._build_container_run(container_id, port=port)\n if self.container_id\n else None\n )\n\n @classmethod\n def _build_container_run(cls, container_id, port):\n try:\n import docker\n except ImportError:\n raise ImportError(\"Please install docker first: pip install docker\")\n client = docker.from_env()\n container = client.containers.get(container_id)\n\n return ContainerRun(container=container, port=port)\n\n def predict(self, data) -> Any:\n \"\"\"Perform prediction with the given data.\n\n Args:\n data: The data to be predicted.\n \"\"\"\n request_data = self.serializer.serialize(data=data)\n response = requests.post(\n url=\"http://127.0.0.1:{port}/\".format(port=self._container_run.port),\n data=request_data,\n )\n\n if response.status_code // 100 != 2:\n raise PredictionException(\n code=response.status_code,\n message=response.content,\n )\n\n return self.serializer.deserialize(response.content)\n\n def _build_headers(\n self, headers: Optional[Dict[str, str]] = None\n ) -> Dict[str, str]:\n headers = headers or dict()\n headers[\"User-Agent\"] = http_user_agent(headers.get(\"User-Agent\"))\n return headers\n\n def _build_url(self, path: Optional[str] = None):\n url = \"http://127.0.0.1:{}\".format(self.port)\n if path:\n if path.startswith(\"/\"):\n path = path[1:]\n url = posixpath.join(url, path)\n return url\n\n def raw_predict(\n self,\n data: Any = None,\n path: Optional[str] = None,\n headers: Optional[Dict[str, str]] = None,\n method: str = \"POST\",\n timeout: Optional[Union[float, Tuple[float, float]]] = None,\n **kwargs,\n ) -> RawResponse:\n \"\"\"Make a prediction with the online prediction service.\n\n Args:\n data (Any): Input data to be sent to the prediction service. If it is a\n file-like object, bytes, or string, it will be sent as the request body.\n Otherwise, it will be treated as a JSON serializable object and sent as\n JSON.\n path (str, optional): Path for the request to be sent to. If it is provided,\n it will be appended to the endpoint URL (Default None).\n headers (dict, optional): Request headers.\n method (str, optional): Request method, default to 'POST'.\n timeout(float, tuple(float, float), optional): Timeout setting for the\n request (Default 10).\n Returns:\n RawResponse: Prediction response from the service.\n\n Raises:\n PredictionException: Raise if status code of the prediction response does\n not equal 2xx.\n \"\"\"\n if isinstance(data, (IOBase, bytes, str)):\n # if data is a file-like object, bytes, or string, it will be sent as\n # request body\n json_data, data = None, data\n else:\n # otherwise, it will be treated as a JSON serializable object and sent as\n # JSON.\n json_data, data = data, None\n header = self._build_headers(headers=headers)\n url = self._build_url(path)\n resp = requests.request(\n url=url,\n json=json_data,\n data=data,\n headers=header,\n method=method,\n timeout=timeout,\n **kwargs,\n )\n resp = RawResponse(\n status_code=resp.status_code,\n content=resp.content,\n headers=dict(resp.headers),\n )\n if resp.status_code // 100 != 2:\n raise PredictionException(resp.status_code, resp.content)\n return resp\n\n def delete_service(self):\n \"\"\"Delete the docker container that running the service.\"\"\"\n if self._container_run:\n self._container_run.stop()\n\n def wait_for_ready(self):\n self._container_run.wait_for_ready()\n # ensure the server is ready.\n self._wait_local_server_ready()\n time.sleep(5)\n\n def _wait_local_server_ready(\n self,\n interval: int = 5,\n ):\n \"\"\"Wait for the local model server to be ready.\"\"\"\n container_run = self._container_run\n while True:\n try:\n # Check whether the container is still running.\n if not container_run.is_running():\n raise RuntimeError(\n \"Container exited unexpectedly, status: {}\".format(\n container_run.status\n )\n )\n\n # Make a HEAD request to the server, just test for connection.\n requests.head(\n f\"http://127.0.0.1:{container_run.port}/\",\n )\n break\n except requests.ConnectionError:\n # ConnectionError means server is not ready.\n logging.debug(\"Waiting for the container to be ready...\")\n time.sleep(interval)\n continue" }, { "identifier": "Predictor", "path": "pai/predictor.py", "snippet": "class Predictor(PredictorBase, _ServicePredictorMixin):\n \"\"\"Predictor is responsible for making prediction to an online service.\n\n The `predictor.predict` method sends the input data to the online prediction service\n and returns the prediction result. The serializer object of the predictor is\n responsible for data transformation when the `predict` method is invoked. The input\n data is serialized using the `serializer.serialize` method before it is sent, and\n the response is deserialized using the `serializer.deserialize` method before the\n prediction result returns.\n\n Examples::\n\n # Initialize a predictor object from an existing service using PyTorch\n # processor.\n torch_predictor = Predictor(service_name=\"example_torch_service\")\n result = torch_predictor.predict(numpy.asarray([[22,33,44], [19,22,33]]))\n assert isinstance(result, numpy.ndarray)\n\n \"\"\"\n\n def __init__(\n self,\n service_name: str,\n endpoint_type: str = EndpointType.INTERNET,\n serializer: Optional[SerializerBase] = None,\n session: Optional[Session] = None,\n ):\n \"\"\"Construct a `Predictor` object using an existing prediction service.\n\n Args:\n service_name (str): Name of the existing prediction service.\n endpoint_type (str): Selects the endpoint used by the predictor, which\n should be one of `INTERNET` or `INTRANET`. The `INTERNET` endpoint type\n means that the predictor calls the service over a public endpoint, while\n the `INTRANET` endpoint type is over a VPC endpoint.\n serializer (SerializerBase, optional): A serializer object that transforms\n the input Python object for data transmission and deserialize the\n response data to Python object.\n session (Session, optional): A PAI session object used for communicating\n with PAI service.\n \"\"\"\n super(Predictor, self).__init__(\n service_name=service_name,\n session=session or get_default_session(),\n endpoint_type=endpoint_type,\n serializer=serializer,\n )\n self._check()\n\n def _check(self):\n config = json.loads(self._service_api_object[\"ServiceConfig\"])\n if config.get(\"metadata\", {}).get(\"type\") == ServiceType.Async:\n logger.warning(\n \"Predictor is not recommended to make prediction to a async\"\n \" prediction service.\"\n )\n\n def predict(self, data):\n \"\"\"Make a prediction with the online prediction service.\n\n The serializer object for the predictor is responsible for data transformation\n when the 'predict' method is invoked. The input data is serialized using the\n `serializer.serialize` method before it is sent, and the response is\n deserialized using the `serializer.deserialize` method before the prediction\n result returns.\n\n Args:\n data: The input data for the prediction. It will be serialized using the\n serializer of the predictor before transmitted to the prediction\n service.\n\n Returns:\n object: Prediction result.\n\n Raises:\n PredictionException: Raise if status code of the prediction response does\n not equal 2xx.\n \"\"\"\n self._post_init_serializer()\n data = self._handle_input(data)\n resp = self._send_request(\n data,\n )\n if resp.status_code // 100 != 2:\n raise PredictionException(resp.status_code, resp.content)\n return self._handle_output(\n resp.content,\n )\n\n def raw_predict(\n self,\n data: Any = None,\n path: Optional[str] = None,\n headers: Optional[Dict[str, str]] = None,\n method: str = \"POST\",\n timeout: Optional[Union[float, Tuple[float, float]]] = None,\n **kwargs,\n ) -> RawResponse:\n \"\"\"Make a prediction with the online prediction service.\n\n Args:\n data (Any): Input data to be sent to the prediction service. If it is a\n file-like object, bytes, or string, it will be sent as the request body.\n Otherwise, it will be treated as a JSON serializable object and sent as\n JSON.\n path (str, optional): Path for the request to be sent to. If it is provided,\n it will be appended to the endpoint URL (Default None).\n headers (dict, optional): Request headers.\n method (str, optional): Request method, default to 'POST'.\n timeout(float, tuple(float, float), optional): Timeout setting for the\n request (Default 10).\n **kwargs: Additional keyword arguments for the request.\n Returns:\n RawResponse: Prediction response from the service.\n\n Raises:\n PredictionException: Raise if status code of the prediction response does\n not equal 2xx.\n \"\"\"\n json_data, data = self._handle_raw_input(data)\n resp = self._send_request(\n data=data,\n json=json_data,\n method=method,\n path=path,\n headers=headers,\n timeout=timeout,\n **kwargs,\n )\n if resp.status_code // 100 != 2:\n raise PredictionException(resp.status_code, resp.content)\n\n resp = RawResponse(\n status_code=resp.status_code,\n content=resp.content,\n headers=dict(resp.headers),\n )\n return resp" }, { "identifier": "ServiceType", "path": "pai/predictor.py", "snippet": "class ServiceType(object):\n Standard = \"Standard\"\n Async = \"Async\"" }, { "identifier": "SerializerBase", "path": "pai/serializers.py", "snippet": "class SerializerBase(ABC):\n \"\"\"Abstract class for creating a Serializer class for predictor.\"\"\"\n\n @abstractmethod\n def serialize(self, data) -> bytes:\n \"\"\"Serialize the input data to bytes for transmitting.\"\"\"\n\n @abstractmethod\n def deserialize(self, data: bytes):\n \"\"\"Deserialize the data from raw bytes to Python object .\"\"\"\n\n def inspect_from_service(\n self, service_name: str, *, session: Optional[Session] = None\n ):\n \"\"\"Inspect the online prediction service to complete the serializer instance\n initialization.\n\n The implementation of the `inspect_from_service` method is optional. You only\n need to implement it if your serializer requires additional information from\n service metadata or if it needs to send a request to the service in order to\n be initialized.\n\n \"\"\"" }, { "identifier": "Session", "path": "pai/session.py", "snippet": "class Session(ResourceAPIsContainerMixin):\n \"\"\"A class responsible for communicating with PAI services.\"\"\"\n\n def __init__(\n self,\n region_id: str,\n workspace_id: Optional[str] = None,\n credential_config: Optional[CredentialConfig] = None,\n oss_bucket_name: Optional[str] = None,\n oss_endpoint: Optional[str] = None,\n **kwargs,\n ):\n \"\"\"PAI Session Initializer.\n\n Args:\n credential_config (:class:`alibabacloud_credentials.models.Config`, optional):\n The credential config used to access the Alibaba Cloud.\n region_id (str): The ID of the Alibaba Cloud region where the service\n is located.\n workspace_id (str, optional): ID of the workspace used in the default\n session.\n oss_bucket_name (str, optional): The name of the OSS bucket used in the\n session.\n oss_endpoint (str, optional): The endpoint for the OSS bucket.\n \"\"\"\n\n if not region_id:\n raise ValueError(\"Region ID must be provided.\")\n\n self._credential_config = credential_config\n self._region_id = region_id\n self._workspace_id = workspace_id\n self._oss_bucket_name = oss_bucket_name\n self._oss_endpoint = oss_endpoint\n\n header = kwargs.pop(\"header\", None)\n super(Session, self).__init__(header=header)\n\n @property\n def region_id(self) -> str:\n return self._region_id\n\n @property\n def is_inner(self) -> bool:\n return self._region_id in INNER_REGION_IDS\n\n @property\n def oss_bucket_name(self) -> str:\n return self._oss_bucket_name\n\n @property\n def oss_endpoint(self) -> str:\n return self._oss_endpoint\n\n @property\n def credential_config(self) -> CredentialConfig:\n return self._credential_config\n\n @property\n def workspace_name(self):\n if hasattr(self, \"_workspace_name\") and self._workspace_name:\n return self._workspace_name\n\n if not self._workspace_id:\n raise ValueError(\"Workspace id is not set.\")\n workspace_api_obj = self.workspace_api.get(workspace_id=self._workspace_id)\n self._workspace_name = workspace_api_obj[\"WorkspaceName\"]\n return self._workspace_name\n\n @property\n def provider(self) -> str:\n caller_identity = self._acs_sts_client.get_caller_identity().body\n return caller_identity.account_id\n\n @property\n def workspace_id(self) -> str:\n \"\"\"ID of the workspace used by the session.\"\"\"\n return self._workspace_id\n\n @property\n def console_uri(self) -> str:\n \"\"\"The web console URI for PAI service.\"\"\"\n if self.is_inner:\n return \"https://pai-next.alibaba-inc.com\"\n else:\n return \"https://pai.console.aliyun.com/console\"\n\n def _init_oss_config(\n self,\n ):\n \"\"\"Initialize a OssConfig instance.\"\"\"\n if not self._oss_bucket_name:\n # If OSS bucket name is not provided, use the default OSS storage URI\n # that is configured for the workspace.\n default_oss_uri = self.workspace_api.get_default_storage_uri(\n self.workspace_id\n )\n if not default_oss_uri:\n raise RuntimeError(\n \"No default OSS URI is configured for the workspace.\"\n )\n oss_uri_obj = OssUriObj(default_oss_uri)\n self._oss_bucket_name = oss_uri_obj.bucket_name\n\n if not self._oss_endpoint:\n self._oss_endpoint = self._get_default_oss_endpoint()\n\n def _get_oss_auth(self):\n auth = oss2.ProviderAuth(\n credentials_provider=CredentialProviderWrapper(\n config=self._credential_config,\n )\n )\n return auth\n\n @property\n def oss_bucket(self):\n \"\"\"A OSS2 bucket instance used by the session.\"\"\"\n if not self._oss_bucket_name or not self._oss_endpoint:\n self._init_oss_config()\n oss_bucket = oss2.Bucket(\n auth=self._get_oss_auth(),\n endpoint=self._oss_endpoint,\n bucket_name=self._oss_bucket_name,\n )\n return oss_bucket\n\n def save_config(self, config_path=None):\n \"\"\"Save the configuration of the session to a local file.\"\"\"\n attrs = {key.lstrip(\"_\"): value for key, value in vars(self).items()}\n config = {\n key: value\n for key, value in attrs.items()\n if key in _DEFAULT_CONFIG_KEYS and value is not None\n }\n\n config_path = config_path or DEFAULT_CONFIG_PATH\n os.makedirs(os.path.dirname(config_path), exist_ok=True)\n with open(config_path, \"w\") as f:\n f.write(json.dumps(config, indent=4))\n logger.info(\"Write PAI config succeed: config_path=%s\" % config_path)\n\n def patch_oss_endpoint(self, oss_uri: str):\n oss_uri_obj = OssUriObj(oss_uri)\n if oss_uri_obj.endpoint:\n return oss_uri\n\n # patch endpoint using current OSS bucket endpoint.\n endpoint = self.oss_bucket.endpoint\n if endpoint.startswith(\"http://\"):\n endpoint = endpoint.lstrip(\"http://\")\n elif endpoint.startswith(\"https://\"):\n endpoint = endpoint.lstrip(\"https://\")\n return \"oss://{bucket_name}.{endpoint}/{key}\".format(\n bucket_name=oss_uri_obj.bucket_name,\n endpoint=endpoint,\n key=oss_uri_obj.object_key,\n )\n\n def _get_default_oss_endpoint(self) -> str:\n \"\"\"Returns a default OSS endpoint.\"\"\"\n\n # OSS Endpoint document:\n # https://help.aliyun.com/document_detail/31837.html\n internet_endpoint = \"oss-{}.aliyuncs.com\".format(self.region_id)\n internal_endpoint = \"oss-{}-internal.aliyuncs.com\".format(self.region_id)\n\n return (\n internet_endpoint\n if is_domain_connectable(internal_endpoint)\n else internet_endpoint\n )\n\n def get_oss_bucket(self, bucket_name: str, endpoint: str = None) -> oss2.Bucket:\n \"\"\"Get a OSS bucket using the credentials of the session.\n\n Args:\n bucket_name (str): The name of the bucket.\n endpoint (str): Endpoint of the bucket.\n\n Returns:\n :class:`oss2.Bucket`: A OSS bucket instance.\n\n \"\"\"\n endpoint = endpoint or self._oss_endpoint or self._get_default_oss_endpoint()\n oss_bucket = oss2.Bucket(\n auth=self._get_oss_auth(),\n endpoint=endpoint,\n bucket_name=bucket_name,\n )\n return oss_bucket\n\n @classmethod\n def get_storage_path_by_category(\n cls, category: str, dir_name: Optional[str] = None\n ) -> str:\n \"\"\"Get an OSS storage path for the resource.\n\n Args:\n category (str): The category of the resource.\n dir_name (str, optional): The directory name of the resource.\n\n Returns:\n str: A OSS storage path.\n\n \"\"\"\n dir_name = dir_name or datetime.now().strftime(\"%Y%m%d_%H%M%S_%f\")\n storage_path = posixpath.join(\"pai\", category, dir_name).strip()\n\n if not storage_path.endswith(\"/\"):\n storage_path += \"/\"\n return storage_path\n\n def is_supported_training_instance(self, instance_type: str) -> bool:\n \"\"\"Check if the instance type is supported for training.\"\"\"\n instance_generator = make_list_resource_iterator(self.job_api.list_ecs_specs)\n machine_spec = next(\n (\n item\n for item in instance_generator\n if item[\"InstanceType\"] == instance_type\n ),\n None,\n )\n return bool(machine_spec)\n\n def is_gpu_training_instance(self, instance_type: str) -> bool:\n \"\"\"Check if the instance type is GPU instance for training.\"\"\"\n instance_generator = make_list_resource_iterator(self.job_api.list_ecs_specs)\n machine_spec = next(\n (\n item\n for item in instance_generator\n if item[\"InstanceType\"] == instance_type\n ),\n None,\n )\n if not machine_spec:\n raise ValueError(\n f\"Instance type {instance_type} is not supported for training job. \"\n \"Please provide a supported instance type.\"\n )\n return machine_spec[\"AcceleratorType\"] == \"GPU\"\n\n def is_supported_inference_instance(self, instance_type: str) -> bool:\n \"\"\"Check if the instance type is supported for inference.\"\"\"\n res = self.service_api.describe_machine()[\"InstanceMetas\"]\n spec = next(\n (item for item in res if item[\"InstanceType\"] == instance_type), None\n )\n return bool(spec)\n\n def is_gpu_inference_instance(self, instance_type: str) -> bool:\n \"\"\"Check if the instance type is GPU instance for inference.\"\"\"\n res = self.service_api.describe_machine()[\"InstanceMetas\"]\n spec = next(\n (item for item in res if item[\"InstanceType\"] == instance_type), None\n )\n\n if not spec:\n raise ValueError(\n f\"Instance type {instance_type} is not supported for deploying. \"\n \"Please provide a supported instance type.\"\n )\n return bool(spec[\"GPU\"])" }, { "identifier": "get_default_session", "path": "pai/session.py", "snippet": "def get_default_session() -> \"Session\":\n \"\"\"Get the default session used by the program.\n\n If the global default session is set, the function will try to initialize\n a session from config file.\n\n Returns:\n :class:`pai.session.Session`: The default session.\n\n \"\"\"\n global _default_session\n if not _default_session:\n config = load_default_config_file()\n if not config:\n return\n _default_session = Session(**config)\n return _default_session" } ]
import copy import distutils.dir_util import json import logging import os.path import posixpath import shlex import shutil import tempfile import textwrap import time import requests from typing import Any, Dict, Iterator, List, Optional, Tuple, Union from addict import Dict as AttrDict from oss2 import ObjectIterator from .common import git_utils from .common.consts import INSTANCE_TYPE_LOCAL_GPU, ModelFormat from .common.docker_utils import ContainerRun, run_container from .common.oss_utils import OssUriObj, download, is_oss_uri, upload from .common.utils import ( generate_repr, is_local_run_instance_type, random_str, to_plain_text, ) from .exception import DuplicatedMountException, MountPathIsOccupiedException from .image import ImageInfo from .predictor import AsyncPredictor, LocalPredictor, Predictor, ServiceType from .serializers import SerializerBase from .session import Session, get_default_session from .estimator import AlgorithmEstimator
17,216
else: predictor = Predictor( service_name=service_name, session=self.session, serializer=serializer, ) print( "View the service detail by accessing the console URI: \n{}".format( predictor.console_uri ) ) if wait: predictor.wait_for_ready() return predictor def _wait_service_visible(self, service_name, attempts=3, interval=2): """Wait for the service to be visible in DescribeService API. hack: https://aone.alibaba-inc.com/v2/project/1134421/bug#viewIdentifier=5dfb195e2e2b84f6b2f24718&openWorkitemIdentifier=50192431 """ while attempts > 0: obj = self.session.service_api.get(service_name) if "ServiceUid" in obj: return attempts -= 1 time.sleep(interval) logger.warning("DescribeService API failed to get the Service object.") def _build_service_config( self, service_name: str = None, instance_count: int = None, instance_type: str = None, resource_config: Union[ResourceConfig, Dict[str, Any]] = None, resource_id: str = None, service_type: str = None, options: Dict[str, Any] = None, ) -> Dict[str, Any]: """Build a service config dictionary used to create a PAI EAS service.""" self.model_data = self._upload_model_data() resource_config = ( ResourceConfig(**resource_config) if resource_config and isinstance(resource_config, dict) else None ) if resource_config and instance_type: raise ValueError( f"Only one of 'instance_type' and 'resource_config' " f"is required, but both have been provided: instance_type" f"={instance_type}, resource_config=" f"{resource_config}." ) inference_spec = InferenceSpec( self._get_inference_spec().to_dict() if self.inference_spec else dict() ) if self.model_data: if not inference_spec.is_container_serving(): # if model_data is an OSS URI with endpoint, truncate the endpoint. oss_uri_obj = OssUriObj(self.model_data) model_path_uri = "oss://{bucket_name}/{key}".format( bucket_name=oss_uri_obj.bucket_name, key=oss_uri_obj.object_key, ) inference_spec.add_option("model_path", model_path_uri) else: try: inference_spec.mount( self.model_data, mount_path=DefaultServiceConfig.model_path, ) except DuplicatedMountException as e: # ignore duplicated mount logger.info("Model is already mounted the container: %s", e) if service_type: inference_spec.add_option("metadata.type", service_type) if inference_spec.is_container_serving(): inference_spec.add_option("metadata.rpc.proxy_path", "/") if service_name: inference_spec.add_option("name", service_name) if instance_count: inference_spec.add_option("metadata.instance", instance_count) if instance_type: inference_spec.add_option("cloud.computing.instance_type", instance_type) elif resource_config: inference_spec.add_option("metadata.cpu", resource_config.cpu) inference_spec.add_option("metadata.memory", resource_config.memory) if resource_config.gpu: inference_spec.add_option("metadata.gpu", resource_config.gpu) if resource_config.gpu_memory: inference_spec.add_option( "metadata.gpu_memory", resource_config.gpu_memory ) if resource_config.gpu: logger.warning( "Parameters 'gpu' is set, the 'gpu_memory' parameter " "does not take effect." ) if resource_id: inference_spec.add_option("metadata.resource", resource_id) if options: inference_spec.merge_options(options=options) return inference_spec.to_dict() def _deploy_local( self, instance_type: str,
# Copyright 2023 Alibaba, Inc. or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.getLogger(__name__) # Reserved ports for internal use, do not use them for service _RESERVED_PORTS = [8080, 9090] class DefaultServiceConfig(object): """Default configuration used in creating prediction service.""" # Listen Port listen_port = 8000 # Default model path in container model_path = "/eas/workspace/model/" # Default user code path in container code_path = "/ml/usercode/" class ResourceConfig(object): """A class that represents the resource used by a PAI prediction service instance.""" def __init__(self, cpu: int, memory: int, gpu: int = None, gpu_memory: int = None): """ResourceConfig initializer. The public resource group does not support requesting GPU resources with `ResourceConfig`. Use the 'gpu' and 'gpu_memory' parameter only for services deployed to dedicated resource groups that provide GPU machine instances. Args: cpu (int): The number of CPUs that each instance requires. memory (int): The amount of memory that each instance requires, must be an integer, Unit: MB. gpu (int): The number of GPUs that each instance requires. gpu_memory (int): The amount of GPU memory that each instance requires. The value must be an integer, Unit: GB. PAI allows memory resources of a GPU to be allocated to multiple instances. If you want multiple instances to share the memory resources of a GPU, set the gpu parameter to 0. If you set the ``gpu`` parameter to 1, each instance occupies a GPU and the gpu_memory parameter does not take effect. .. note:: **Important** PAI does not enable the strict isolation of GPU memory. To prevent out of memory (OOM) errors, make sure that the GPU memory used by each instance does not exceed the requested amount. """ self.cpu = cpu self.memory = memory self.gpu = gpu self.gpu_memory = gpu_memory def __repr__(self): return ( f"ResourceConfig(cpu={self.cpu}, memory={self.memory}MB, gpu={self.gpu or 0}," f" gpu_memory={self.gpu_memory or 0}GB)" ) def __str__(self): return self.__repr__() def to_dict(self): """Transform the ResourceConfig instance to a dictionary. Returns: dict: """ res = { "cpu": self.cpu, "gpu": self.gpu, "gpu_memory": self.gpu_memory, "memory": self.memory, } return {k: v for k, v in res.items() if v is not None} class InferenceSpec(object): """A class used to describe how to create a prediction service. InferenceSpec is using to describe how the model is serving in PAI. To view the full supported parameters, please see the following hyperlink: `Parameters of model services <https://help.aliyun.com/document_detail/450525.htm>`_. Example of how to config a InferneceSpec:: >>> # build an inference_spec that using XGBoost processor. >>> infer_spec = InferenceSpec(processor="xgboost") >>> infer_spec.metadata.rpc.keepalive = 1000 >>> infer_spec.warm_up_data_path = "oss://bucket-name/path/to/warmup-data" >>> infer_spec.add_option("metadata.rpc.max_batch_size", 8) >>> print(infer_spec.processor) xgboost >>> print(infer_spec.metadata.rpc.keepalive) 1000 >>> print(infer_spec.metadata.rpc.max_batch_size) 8 >>> print(infer_spec.to_dict()) {'processor': 'xgboost', 'metadata': {'rpc': {'keepalive': 1000, 'max_batch_size': 8}}, 'warm_up_data_path': 'oss://bucket-name/path/to/warmup-data'} """ def __init__(self, *args, **kwargs): """InferenceSpec initializer. Args: **kwargs: Parameters of the inference spec. """ properties = kwargs.pop("__properties", []) cfg_dict = copy.deepcopy(kwargs) cfg_dict = {k: v for k, v in cfg_dict.items() if not k.startswith("_")} if args: if len(args) > 1: raise TypeError() cfg_dict.update(args[0]) super(InferenceSpec, self).__setattr__( "_cfg_dict", self._transform_value(cfg_dict) ) super(InferenceSpec, self).__setattr__("__properties", properties) def __repr__(self): return json.dumps(self.to_dict(), sort_keys=True, indent=4) def _transform_value(self, value): if isinstance(value, (List, Tuple)): return [self._transform_value(item) for item in value] elif isinstance(value, (Dict, AttrDict)): return AttrDict( {key: self._transform_value(value) for key, value in value.items()} ) return value def __missing__(self, name): return self._cfg_dict.__missing__(name) def __setitem__(self, name, value): return self._cfg_dict.__setitem__(name, self._transform_value(value)) def __setattr__(self, name, value): if name in getattr(self, "__properties"): super(InferenceSpec, self).__setattr__(name, self._transform_value(value)) else: self._cfg_dict.__setattr__(name, self._transform_value(value)) def __getattr__(self, item): if item.startswith("_"): return getattr(self, item) return self._cfg_dict.__getitem__(item) def __contains__(self, item): return item in self._cfg_dict def to_dict(self) -> Dict: """Return a dictionary that represent the InferenceSpec.""" return self._cfg_dict.to_dict() def add_option(self, name: str, value): """Add an option to the inference_spec instance. Args: name (str): Name of the option to set, represented as the JSON path of the parameter for the InferenceSpec. To view the full supported parameters, please see the following hyperlink: `Parameters of model services <https://help.aliyun.com/document_detail/450525.htm>`_. value: Value for the option. Examples: >>> infer_spec = InferenceSpec(processor="tensorflow_gpu_1.12") >>> infer_spec.add_option("metadata.rpc.keepalive", 10000) >>> infer_spec.metadata.rpc.keepalive 10000 >>> infer_spec.to_dict() {'processor': 'tensorflow_gpu_1.12', 'metadata': {'rpc': {'keepalive': 10000}}} """ src = self._transform_value(value) for k in reversed(name.split(".")): src = {k: src} self._cfg_dict.update(AttrDict(src)) def merge_options(self, options: Dict[str, Any]): """Merge options from a dictionary.""" for key, value in options.items(): self.add_option(key, value) @classmethod def from_dict(cls, config: Dict[str, Any]) -> "InferenceSpec": """Initialize a InferenceSpec from a dictionary. You can use this method to initialize a InferenceSpec instance from a dictionary. Returns: :class:`pai.model.InferenceSpec`: A InferenceSpec instance. """ config = config or dict() return cls(**config) def is_container_serving(self): return "containers" in self._cfg_dict @classmethod def _upload_source_dir(cls, source_dir, session): """Upload source files to OSS bucket.""" if not os.path.exists(source_dir): raise ValueError(f"Input source code path does not exist: {source_dir}.") if not os.path.isdir(source_dir): raise ValueError( f"Input source code path should be a directory: {source_dir}." ) target_dir = session.get_storage_path_by_category(category="inference_src") # upload local script data to the OSS bucket. uploaded_source_code = upload( source_dir, target_dir, session.oss_bucket, ) logger.debug("Uploaded source code to OSS: %s", uploaded_source_code) return uploaded_source_code def mount( self, source: str, mount_path: str, session: Session = None, ) -> Dict[str, Any]: """Mount a source storage to the running container. .. note:: If source is a local path, it will be uploaded to the OSS bucket and mounted. If source is a OSS path, it will be mounted directly. Args: source (str): The source storage to be attached, currently only support OSS path in OSS URI format and local path. mount_path (str): The mount path in the container. session (Session, optional): A PAI session instance used for communicating with PAI service. Returns: Dict[str, Any]: The storage config. Raises: DuplicateMountException: If the mount path is already used or source OSS path is mounted to the container. Examples:: # Mount a OSS storage path to the running container. >>> inference_spec.mount("oss://<YourOssBucket>/path/to/directory/model.json", ... "/ml/model/") # 'Mount' a local path to the running container. >>> inference_spec.mount("/path/to/your/data/", "/ml/model/") """ session = session or get_default_session() # TODO: supports more storages, such as NAS, PAI Dataset, PAI CodeSource, etc. if not isinstance(source, str): raise ValueError( "Parameter should be a string which represents an OSS storage path" " or a local file path." ) if "storage" in self._cfg_dict: configs = self._cfg_dict.get("storage", []) else: configs = [] uris = set() for conf in configs: # check if target mount path is already used. if conf.get("mount_path") == mount_path: raise MountPathIsOccupiedException( f"The mount path '{mount_path}' has already been used." ) mount_uri = conf.get("oss", {}).get("path") uris.add(mount_uri) if is_oss_uri(source): oss_uri_obj = OssUriObj(source) storage_config = { "mount_path": mount_path, "oss": {"path": oss_uri_obj.get_dir_uri()}, } elif os.path.exists(source): # if source is a local path, upload it to OSS bucket and use OSS URI # as storage source. oss_path = session.get_storage_path_by_category("model_data") oss_uri = upload( source_path=source, oss_path=oss_path, bucket=session.oss_bucket ) oss_uri_obj = OssUriObj(oss_uri) storage_config = { "mount_path": mount_path, "oss": {"path": oss_uri_obj.get_dir_uri()}, } else: raise ValueError( "Source path is not a valid OSS URI or a existing local path." ) # check if the source OSS Path is already mounted to the container. if oss_uri_obj.get_dir_uri() in uris: raise DuplicatedMountException( f"Source OSS path '{oss_uri_obj.get_dir_uri()}' is already " f"mounted to the container." ) configs.append(storage_config) self.storage = configs return storage_config def container_serving_spec( command: str, image_uri: Union[str, ImageInfo], source_dir: Optional[str] = None, git_config: Optional[Dict[str, Any]] = None, port: Optional[int] = None, environment_variables: Optional[Dict[str, str]] = None, requirements: Optional[List[str]] = None, requirements_path: Optional[str] = None, health_check: Optional[Dict[str, Any]] = None, session: Optional[Session] = None, ) -> InferenceSpec: """A convenient function to create an InferenceSpec instance that serving the model with given container and script. Examples:: infer_spec: InferenceSpec = container_serving_spec( command="python run.py", source_dir="./model_server/", image_uri="<ServingImageUri>", ) m = Model( model_data="oss://<YourOssBucket>/path/to/your/model", inference_spec=infer_spec, ) m.deploy( instance_type="ecs.c6.xlarge" ) Args: command (str): The command used to launch the Model server. source_dir (str): A relative path or an absolute path to the source code directory used to load model and launch the HTTP server, it will be uploaded to the OSS bucket and mounted to the container. If there is a ``requirements.txt`` file under the directory, it will be installed before the prediction server started. If 'git_config' is provided, 'source_dir' should be a relative location to a directory in the Git repo. With the following GitHub repo directory structure: .. code:: |----- README.md |----- src |----- train.py |----- test.py if you need 'src' directory as the source code directory, you can assign source_dir='./src/'. git_config (Dict[str, str]): Git configuration used to clone the repo. Including ``repo``, ``branch``, ``commit``, ``username``, ``password`` and ``token``. The ``repo`` is required. All other fields are optional. ``repo`` specifies the Git repository. If you don't provide ``branch``, the default value 'master' is used. If you don't provide ``commit``, the latest commit in the specified branch is used. ``username``, ``password`` and ``token`` are for authentication purpose. For example, the following config: .. code:: python git_config = { 'repo': 'https://github.com/modelscope/modelscope.git', 'branch': 'master', 'commit': '9bfc4a9d83c4beaf8378d0a186261ffc1cd9f960' } results in cloning the repo specified in 'repo', then checking out the 'master' branch, and checking out the specified commit. image_uri (str): The Docker image used to run the prediction service. port (int): Expose port of the server in container, the prediction request will be forward to the port. The environment variable ``LISTENING_PORT`` in the container will be set to this value. Default to 8000. environment_variables (Dict[str, str], optional): Dictionary of environment variable key-value pairs to set on the running container. requirements (List[str], optional): A list of Python package dependency, it will be installed before the serving container run. requirements_path (str, optional): A absolute path to the requirements.txt in the container. health_check (Dict[str, Any], optional): The health check configuration. If it not set, A TCP readiness probe will be used to check the health of the HTTP server. session (Session, optional): A PAI session instance used for communicating with PAI service. Returns: :class:`pai.model.InferenceSpec`: An InferenceSpec instance. """ session = session or get_default_session() if git_config: updated_args = git_utils.git_clone_repo( git_config=git_config, source_dir=source_dir, ) source_dir = updated_args["source_dir"] if not port: port = DefaultServiceConfig.listen_port elif int(port) in _RESERVED_PORTS: raise ValueError( "Reserved port {} is not allowed to use as serving port.".format(port), ) if source_dir: if not os.path.exists(source_dir): raise ValueError("Source directory {} does not exist.".format(source_dir)) if not os.path.isdir(source_dir): raise ValueError( "Source directory {} is not a directory.".format(source_dir) ) code_mount_path = DefaultServiceConfig.code_path # build the command for serving container. command = textwrap.dedent( f"""\ # change working directory to code mount path. cd {code_mount_path} {command} """ ) if not requirements_path and os.path.exists( os.path.join(source_dir, "requirements.txt") ): requirements_path = posixpath.join(code_mount_path, "requirements.txt") else: code_mount_path = None requirements_path = None if isinstance(image_uri, ImageInfo): image_uri = image_uri.image_uri environment_variables = environment_variables or dict() container_spec = { "image": image_uri, "port": port, "script": command, "env": [ {"name": key, "value": str(value)} for key, value in environment_variables.items() ] if environment_variables else [], } if health_check: container_spec["health_check"] = health_check if requirements: container_spec["prepare"] = {"pythonRequirements": requirements} if requirements_path: logger.warning( "If the parameter 'requirements' is set, the requirements_path " "parameter will be ignored." ) elif requirements_path: container_spec["prepare"] = { "pythonRequirementsPath": requirements_path, } inference_spec = InferenceSpec(containers=[container_spec]) # mount the uploaded serving scripts to the serving container. if source_dir: inference_spec.mount( source_dir, code_mount_path, session=session, ) return inference_spec class _BuiltinProcessor(object): """Helper class uses for getting the builtin processor""" PMML = "pmml" XGBoost = "xgboost" SupportedFrameworkAcceleratorVersionConfig = { "tensorflow": { "cpu": [ "1.12", "1.14", "1.15", "2.3", ], "gpu": [ "1.12", "1.14", "1.15", ], }, "pytorch": { "cpu": [ "1.6", ], "gpu": [ "1.6", ], }, } # Hard code default processor for specific model format. ModelFormatDefaultProcessorMapping = { ModelFormat.PMML: "pmml", ModelFormat.SavedModel: "tensorflow_cpu_2.3", ModelFormat.TorchScript: "pytorch_cpu_1.6", ModelFormat.FrozenPb: "pytorch_cpu_1.6", ModelFormat.CaffePrototxt: "caffe_cpu", ModelFormat.ONNX: "onnx_cu100", } @classmethod def get_default_by_model_format(cls, model_format: str) -> str: """Get the default processor for a specific model format.""" if model_format in cls.ModelFormatDefaultProcessorMapping: return cls.ModelFormatDefaultProcessorMapping[model_format] @classmethod def from_framework_version( cls, framework_name, framework_version, accelerator=None ): accelerator = accelerator or "cpu" versions = cls.SupportedFrameworkAcceleratorVersionConfig.get( framework_name, dict() ).get(accelerator, []) if framework_version in versions: return "{}_{}_{}".format(framework_name, accelerator, framework_version) else: logger.warning( "Could not find the processor for the framework_version({} {}), use the" " latest processor".format(framework_name, framework_version) ) return "{}_{}_{}".format(framework_name, accelerator, versions[-1]) class ModelBase(object): """A class represent ModelBase.""" def __init__( self, model_data: str, inference_spec: Optional[InferenceSpec] = None, session: Session = None, ): self.model_data = model_data self.inference_spec = inference_spec self.session = session or get_default_session() def download(self, target_dir: str): """Download the model data from OSS to local directory. Args: target_dir (str): The target directory to download the model data. Returns: str: Local directory path stores the model data. """ if not self.model_data: raise ValueError("Could not find the model data for this model.") if not is_oss_uri(self.model_data): raise RuntimeError("Download method only support model data stored in OSS.") self._download_model_data(target_dir) return target_dir def _download_model_data(self, target_dir): if not self.model_data: return logger.info(f"Prepare model data to local directory: {target_dir}") if self.model_data.startswith("oss://"): oss_uri = OssUriObj(self.model_data) oss_bucket = self.session.get_oss_bucket(oss_uri.bucket_name) download( oss_path=oss_uri.object_key, local_path=target_dir, bucket=oss_bucket, un_tar=True, ) else: if not os.path.exists(self.model_data): raise ValueError(f"Model data path does not exist: {self.model_data}") os.makedirs(target_dir, exist_ok=True) if os.path.isfile(self.model_data): shutil.copy( self.model_data, os.path.join(target_dir, os.path.basename(self.model_data)), ) else: distutils.dir_util.copy_tree(self.model_data, target_dir) def _upload_model_data(self): """Upload the model artifact to OSS bucket if self.model_data is a local file path. """ if not self.model_data: return elif is_oss_uri(self.model_data): return self.model_data elif not os.path.exists(self.model_data): raise RuntimeError(f"Model data path does not exist: {self.model_data}") dest_oss_path = self.session.get_storage_path_by_category(category="model_data") upload_model_data = upload( source_path=self.model_data, oss_path=dest_oss_path, bucket=self.session.oss_bucket, ) return upload_model_data def list_model_files(self, uri_format: bool = False) -> Iterator[str]: """List model files under the model path. Args: uri_format (bool): If True, return the model file path in OSS URI format. Returns: Iterator[str]: Iterator of model files. """ if not self.model_data: raise ValueError("Model data path is not specified.") if not is_oss_uri(self.model_data): raise ValueError("Method only support model data stored in OSS.") oss_uri_obj = OssUriObj(self.model_data) bucket = self.session.get_oss_bucket( bucket_name=oss_uri_obj.bucket_name, ) def _get_relative_path(obj_key: str): # if the model_data is reference an object, return the object file # name. if oss_uri_obj.object_key == obj_key: return os.path.basename(obj_key) path = obj_key[len(oss_uri_obj.object_key) :] return path.lstrip("/") if path.startswith("/") else path obj_iter = ObjectIterator(bucket=bucket, prefix=oss_uri_obj.object_key) for obj_info in obj_iter: if uri_format: yield f"oss://{bucket.bucket_name}/{obj_info.key}" else: yield _get_relative_path(obj_info.key) def _get_inference_spec(self): return self.inference_spec def deploy( self, service_name: str, instance_count: Optional[int] = 1, instance_type: Optional[str] = None, resource_config: Optional[Union[Dict[str, int], ResourceConfig]] = None, resource_id: Optional[str] = None, options: Optional[Dict[str, Any]] = None, service_type: Optional[str] = None, wait: bool = True, serializer: Optional["SerializerBase"] = None, **kwargs, ): """Deploy a prediction service with the model.""" if is_local_run_instance_type(instance_type): return self._deploy_local( instance_type=instance_type, serializer=serializer, wait=wait, ) else: return self._deploy( service_name=service_name, instance_count=instance_count, instance_type=instance_type, resource_config=resource_config, resource_id=resource_id, service_type=service_type, options=options, wait=wait, serializer=serializer, ) def _generate_service_name(self): s = os.path.basename(self.model_data.rstrip("/")) + random_str(8) return to_plain_text(s) def _deploy( self, service_name: str = None, instance_count: int = 1, instance_type: str = None, resource_config: Union[Dict[str, int], ResourceConfig] = None, resource_id: str = None, service_type: str = None, options: Dict[str, Any] = None, wait: bool = True, serializer: "SerializerBase" = None, ): """Create a prediction service.""" if not service_name: service_name = self._generate_service_name() logger.info( "Service name is not specified, using a generated service" f" name to create the service: service_name={service_name}" ) config = self._build_service_config( service_name=service_name, instance_count=instance_count, instance_type=instance_type, service_type=service_type, resource_config=resource_config, resource_id=resource_id, options=options, ) service_name = self.session.service_api.create(config=config) self._wait_service_visible(service_name) if service_type == ServiceType.Async: predictor = AsyncPredictor( service_name=service_name, session=self.session, serializer=serializer, ) else: predictor = Predictor( service_name=service_name, session=self.session, serializer=serializer, ) print( "View the service detail by accessing the console URI: \n{}".format( predictor.console_uri ) ) if wait: predictor.wait_for_ready() return predictor def _wait_service_visible(self, service_name, attempts=3, interval=2): """Wait for the service to be visible in DescribeService API. hack: https://aone.alibaba-inc.com/v2/project/1134421/bug#viewIdentifier=5dfb195e2e2b84f6b2f24718&openWorkitemIdentifier=50192431 """ while attempts > 0: obj = self.session.service_api.get(service_name) if "ServiceUid" in obj: return attempts -= 1 time.sleep(interval) logger.warning("DescribeService API failed to get the Service object.") def _build_service_config( self, service_name: str = None, instance_count: int = None, instance_type: str = None, resource_config: Union[ResourceConfig, Dict[str, Any]] = None, resource_id: str = None, service_type: str = None, options: Dict[str, Any] = None, ) -> Dict[str, Any]: """Build a service config dictionary used to create a PAI EAS service.""" self.model_data = self._upload_model_data() resource_config = ( ResourceConfig(**resource_config) if resource_config and isinstance(resource_config, dict) else None ) if resource_config and instance_type: raise ValueError( f"Only one of 'instance_type' and 'resource_config' " f"is required, but both have been provided: instance_type" f"={instance_type}, resource_config=" f"{resource_config}." ) inference_spec = InferenceSpec( self._get_inference_spec().to_dict() if self.inference_spec else dict() ) if self.model_data: if not inference_spec.is_container_serving(): # if model_data is an OSS URI with endpoint, truncate the endpoint. oss_uri_obj = OssUriObj(self.model_data) model_path_uri = "oss://{bucket_name}/{key}".format( bucket_name=oss_uri_obj.bucket_name, key=oss_uri_obj.object_key, ) inference_spec.add_option("model_path", model_path_uri) else: try: inference_spec.mount( self.model_data, mount_path=DefaultServiceConfig.model_path, ) except DuplicatedMountException as e: # ignore duplicated mount logger.info("Model is already mounted the container: %s", e) if service_type: inference_spec.add_option("metadata.type", service_type) if inference_spec.is_container_serving(): inference_spec.add_option("metadata.rpc.proxy_path", "/") if service_name: inference_spec.add_option("name", service_name) if instance_count: inference_spec.add_option("metadata.instance", instance_count) if instance_type: inference_spec.add_option("cloud.computing.instance_type", instance_type) elif resource_config: inference_spec.add_option("metadata.cpu", resource_config.cpu) inference_spec.add_option("metadata.memory", resource_config.memory) if resource_config.gpu: inference_spec.add_option("metadata.gpu", resource_config.gpu) if resource_config.gpu_memory: inference_spec.add_option( "metadata.gpu_memory", resource_config.gpu_memory ) if resource_config.gpu: logger.warning( "Parameters 'gpu' is set, the 'gpu_memory' parameter " "does not take effect." ) if resource_id: inference_spec.add_option("metadata.resource", resource_id) if options: inference_spec.merge_options(options=options) return inference_spec.to_dict() def _deploy_local( self, instance_type: str,
serializer: SerializerBase = None,
20
2023-12-01 01:40:12+00:00
24k
zerolink-io/zerolink-python
zerolink/req.py
[ { "identifier": "settings", "path": "zerolink/settings.py", "snippet": " CONFIG_FILE = os.path.join(os.environ[\"APPDATA\"], \"zerolink\", \"config\")\n CONFIG_FILE = os.path.join(os.environ[\"HOME\"], \".config\", \"zerolink\", \"config\")\n CONFIG_FILE = os.path.join(\n os.environ[\"HOME\"], \"Library\", \"Application Support\", \"zerolink\", \"config\"\n )\ndef create_config() -> None:\ndef get_config() -> configparser.ConfigParser:\ndef get_config_path() -> str:\ndef get_config_var(var: str) -> str:\ndef write_config_var(var: str, value: str):\ndef write_api_key(api_key: str):\ndef read_api_key() -> Optional[str]:" }, { "identifier": "APIError", "path": "zerolink/exc.py", "snippet": "class APIError(Exception):\n def __init__(self, message: str) -> None:\n self.message = message\n\n def __str__(self) -> str:\n return self.message" }, { "identifier": "AuthenticationError", "path": "zerolink/exc.py", "snippet": "class AuthenticationError(Exception):\n def __init__(self) -> None:\n pass\n\n def __str__(self) -> str:\n return \"No API key. Please run `zerolink key` or set the ZEROLINK_API_KEY environment variable\"" }, { "identifier": "Client", "path": "zerolink_client/client.py", "snippet": "class Client:\n \"\"\"A class for keeping track of data related to the API\n\n The following are accepted as keyword arguments and will be used to construct httpx Clients internally:\n\n ``base_url``: The base URL for the API, all requests are made to a relative path to this URL\n\n ``cookies``: A dictionary of cookies to be sent with every request\n\n ``headers``: A dictionary of headers to be sent with every request\n\n ``timeout``: The maximum amount of a time a request can take. API functions will raise\n httpx.TimeoutException if this is exceeded.\n\n ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,\n but can be set to False for testing purposes.\n\n ``follow_redirects``: Whether or not to follow redirects. Default value is False.\n\n ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.\n\n\n Attributes:\n raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a\n status code that was not documented in the source OpenAPI document. Can also be provided as a keyword\n argument to the constructor.\n \"\"\"\n\n raise_on_unexpected_status: bool = field(default=False, kw_only=True)\n _base_url: str\n _cookies: Dict[str, str] = field(factory=dict, kw_only=True)\n _headers: Dict[str, str] = field(factory=dict, kw_only=True)\n _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True)\n _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True)\n _follow_redirects: bool = field(default=False, kw_only=True)\n _httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True)\n _client: Optional[httpx.Client] = field(default=None, init=False)\n _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)\n\n def with_headers(self, headers: Dict[str, str]) -> \"Client\":\n \"\"\"Get a new client matching this one with additional headers\"\"\"\n if self._client is not None:\n self._client.headers.update(headers)\n if self._async_client is not None:\n self._async_client.headers.update(headers)\n return evolve(self, headers={**self._headers, **headers})\n\n def with_cookies(self, cookies: Dict[str, str]) -> \"Client\":\n \"\"\"Get a new client matching this one with additional cookies\"\"\"\n if self._client is not None:\n self._client.cookies.update(cookies)\n if self._async_client is not None:\n self._async_client.cookies.update(cookies)\n return evolve(self, cookies={**self._cookies, **cookies})\n\n def with_timeout(self, timeout: httpx.Timeout) -> \"Client\":\n \"\"\"Get a new client matching this one with a new timeout (in seconds)\"\"\"\n if self._client is not None:\n self._client.timeout = timeout\n if self._async_client is not None:\n self._async_client.timeout = timeout\n return evolve(self, timeout=timeout)\n\n def set_httpx_client(self, client: httpx.Client) -> \"Client\":\n \"\"\"Manually the underlying httpx.Client\n\n **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.\n \"\"\"\n self._client = client\n return self\n\n def get_httpx_client(self) -> httpx.Client:\n \"\"\"Get the underlying httpx.Client, constructing a new one if not previously set\"\"\"\n if self._client is None:\n self._client = httpx.Client(\n base_url=self._base_url,\n cookies=self._cookies,\n headers=self._headers,\n timeout=self._timeout,\n verify=self._verify_ssl,\n follow_redirects=self._follow_redirects,\n **self._httpx_args,\n )\n return self._client\n\n def __enter__(self) -> \"Client\":\n \"\"\"Enter a context manager for self.client—you cannot enter twice (see httpx docs)\"\"\"\n self.get_httpx_client().__enter__()\n return self\n\n def __exit__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Exit a context manager for internal httpx.Client (see httpx docs)\"\"\"\n self.get_httpx_client().__exit__(*args, **kwargs)\n\n def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> \"Client\":\n \"\"\"Manually the underlying httpx.AsyncClient\n\n **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.\n \"\"\"\n self._async_client = async_client\n return self\n\n def get_async_httpx_client(self) -> httpx.AsyncClient:\n \"\"\"Get the underlying httpx.AsyncClient, constructing a new one if not previously set\"\"\"\n if self._async_client is None:\n self._async_client = httpx.AsyncClient(\n base_url=self._base_url,\n cookies=self._cookies,\n headers=self._headers,\n timeout=self._timeout,\n verify=self._verify_ssl,\n follow_redirects=self._follow_redirects,\n **self._httpx_args,\n )\n return self._async_client\n\n async def __aenter__(self) -> \"Client\":\n \"\"\"Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)\"\"\"\n await self.get_async_httpx_client().__aenter__()\n return self\n\n async def __aexit__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Exit a context manager for underlying httpx.AsyncClient (see httpx docs)\"\"\"\n await self.get_async_httpx_client().__aexit__(*args, **kwargs)" }, { "identifier": "finetune", "path": "zerolink_client/api/default/finetune.py", "snippet": "def _get_kwargs(\n *,\n file: Union[File, str],\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[CreateTuneJobResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[CreateTuneJobResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n file: Union[File, str],\n) -> Response[Union[CreateTuneJobResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n file: Union[File, str],\n) -> Optional[Union[CreateTuneJobResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n file: Union[File, str],\n) -> Response[Union[CreateTuneJobResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n file: Union[File, str],\n) -> Optional[Union[CreateTuneJobResponse, HTTPValidationError]]:" }, { "identifier": "get_models_models_get", "path": "zerolink_client/api/default/get_models_models_get.py", "snippet": "def _get_kwargs() -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[ModelList]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[ModelList]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[ModelList]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[ModelList]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[ModelList]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[ModelList]:" }, { "identifier": "desc_entity_id", "path": "zerolink_client/api/entity/desc_entity_id.py", "snippet": "def _get_kwargs(\n id: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[Entity, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[Entity, HTTPValidationError]]:\ndef sync_detailed(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[Entity, HTTPValidationError]]:\ndef sync(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[Entity, HTTPValidationError]]:\nasync def asyncio_detailed(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[Entity, HTTPValidationError]]:\nasync def asyncio(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[Entity, HTTPValidationError]]:" }, { "identifier": "desc_entity_ontology", "path": "zerolink_client/api/entity/desc_entity_ontology.py", "snippet": "def _get_kwargs(\n id: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[Any, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[Any, HTTPValidationError]]:\ndef sync_detailed(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[Any, HTTPValidationError]]:\ndef sync(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[Any, HTTPValidationError]]:\nasync def asyncio_detailed(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[Any, HTTPValidationError]]:\nasync def asyncio(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[Any, HTTPValidationError]]:" }, { "identifier": "lookup_entity", "path": "zerolink_client/api/entity/lookup_entity.py", "snippet": "def _get_kwargs(\n name: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Entity\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Entity\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Entity\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Entity\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Entity\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Entity\"]]]:" }, { "identifier": "lookup_relation", "path": "zerolink_client/api/entity/lookup_relation.py", "snippet": "def _get_kwargs(\n name: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Relation\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Relation\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Relation\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Relation\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Relation\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Relation\"]]]:" }, { "identifier": "search_entity", "path": "zerolink_client/api/entity/search_entity.py", "snippet": "def _get_kwargs(\n name: str,\n *,\n limit: Union[Unset, int] = 10,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Match\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Match\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Response[Union[HTTPValidationError, List[\"Match\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Optional[Union[HTTPValidationError, List[\"Match\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Response[Union[HTTPValidationError, List[\"Match\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Optional[Union[HTTPValidationError, List[\"Match\"]]]:" }, { "identifier": "extract_text", "path": "zerolink_client/api/extract/extract_text.py", "snippet": "def _get_kwargs(\n *,\n body: TextExtract,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[AssertionResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[AssertionResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Response[Union[AssertionResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Optional[Union[AssertionResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Response[Union[AssertionResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Optional[Union[AssertionResponse, HTTPValidationError]]:" }, { "identifier": "create_userattribute", "path": "zerolink_client/api/fact/create_userattribute.py", "snippet": "def _get_kwargs(\n *,\n body: CreateAttribute,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[GenericResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[GenericResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Response[Union[GenericResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Optional[Union[GenericResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Response[Union[GenericResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Optional[Union[GenericResponse, HTTPValidationError]]:" }, { "identifier": "create_userentity", "path": "zerolink_client/api/fact/create_userentity.py", "snippet": "def _get_kwargs(\n *,\n body: CreateEntity,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[CreateEntityResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[CreateEntityResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Response[Union[CreateEntityResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Optional[Union[CreateEntityResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Response[Union[CreateEntityResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Optional[Union[CreateEntityResponse, HTTPValidationError]]:" }, { "identifier": "create_userrule", "path": "zerolink_client/api/fact/create_userrule.py", "snippet": "def _get_kwargs(\n *,\n body: CreateRule,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[CreateRuleResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[CreateRuleResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateRule,\n session_id: int,\n) -> Response[Union[CreateRuleResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateRule,\n session_id: int,\n) -> Optional[Union[CreateRuleResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateRule,\n session_id: int,\n) -> Response[Union[CreateRuleResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateRule,\n session_id: int,\n) -> Optional[Union[CreateRuleResponse, HTTPValidationError]]:" }, { "identifier": "create_usertriple", "path": "zerolink_client/api/fact/create_usertriple.py", "snippet": "def _get_kwargs(\n *,\n body: CreateTriple,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[CreateFactResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[CreateFactResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Response[Union[CreateFactResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Optional[Union[CreateFactResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Response[Union[CreateFactResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Optional[Union[CreateFactResponse, HTTPValidationError]]:" }, { "identifier": "get_triple", "path": "zerolink_client/api/kg/get_triple.py", "snippet": "def _get_kwargs(\n name: str,\n *,\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Triple\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Triple\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Response[Union[HTTPValidationError, List[\"Triple\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Optional[Union[HTTPValidationError, List[\"Triple\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Response[Union[HTTPValidationError, List[\"Triple\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Optional[Union[HTTPValidationError, List[\"Triple\"]]]:" }, { "identifier": "post_question", "path": "zerolink_client/api/question/post_question.py", "snippet": "def _get_kwargs(\n *,\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, QuestionResponse]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, QuestionResponse]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Response[Union[HTTPValidationError, QuestionResponse]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Optional[Union[HTTPValidationError, QuestionResponse]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Response[Union[HTTPValidationError, QuestionResponse]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Optional[Union[HTTPValidationError, QuestionResponse]]:" }, { "identifier": "create_session", "path": "zerolink_client/api/session/create_session.py", "snippet": "def _get_kwargs(\n user_id: str,\n *,\n name: Union[Unset, str] = UNSET,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[ChatSession, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[ChatSession, HTTPValidationError]]:\ndef sync_detailed(\n user_id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n name: Union[Unset, str] = UNSET,\n) -> Response[Union[ChatSession, HTTPValidationError]]:\ndef sync(\n user_id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n name: Union[Unset, str] = UNSET,\n) -> Optional[Union[ChatSession, HTTPValidationError]]:\nasync def asyncio_detailed(\n user_id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n name: Union[Unset, str] = UNSET,\n) -> Response[Union[ChatSession, HTTPValidationError]]:\nasync def asyncio(\n user_id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n name: Union[Unset, str] = UNSET,\n) -> Optional[Union[ChatSession, HTTPValidationError]]:" }, { "identifier": "get_session_entities", "path": "zerolink_client/api/session/get_session_entities.py", "snippet": "def _get_kwargs(\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\ndef sync_detailed(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\ndef sync(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\nasync def asyncio_detailed(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\nasync def asyncio(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"GenericEntity\"]]]:" }, { "identifier": "get_session_facts", "path": "zerolink_client/api/session/get_session_facts.py", "snippet": "def _get_kwargs(\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"GenericTriple\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"GenericTriple\"]]]:\ndef sync_detailed(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"GenericTriple\"]]]:\ndef sync(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"GenericTriple\"]]]:\nasync def asyncio_detailed(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"GenericTriple\"]]]:\nasync def asyncio(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"GenericTriple\"]]]:" }, { "identifier": "get_user_session", "path": "zerolink_client/api/session/get_user_session.py", "snippet": "def _get_kwargs(\n user_id: str,\n session_name: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[ChatSession, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[ChatSession, HTTPValidationError]]:\ndef sync_detailed(\n user_id: str,\n session_name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[ChatSession, HTTPValidationError]]:\ndef sync(\n user_id: str,\n session_name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[ChatSession, HTTPValidationError]]:\nasync def asyncio_detailed(\n user_id: str,\n session_name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[ChatSession, HTTPValidationError]]:\nasync def asyncio(\n user_id: str,\n session_name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[ChatSession, HTTPValidationError]]:" }, { "identifier": "create_user", "path": "zerolink_client/api/user/create_user.py", "snippet": "def _get_kwargs() -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[CreateUser]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[CreateUser]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[CreateUser]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[CreateUser]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[CreateUser]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[CreateUser]:" }, { "identifier": "ChatSession", "path": "zerolink_client/models/chat_session.py", "snippet": "class ChatSession:\n \"\"\"A user chat session.\n\n Attributes:\n id (int):\n name (str): The name of the chat session\n index (int):\n requests (List['Req']):\n responses (List['Rep']):\n created_on (datetime.datetime):\n \"\"\"\n\n id: int\n name: str\n index: int\n requests: List[\"Req\"]\n responses: List[\"Rep\"]\n created_on: datetime.datetime\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.rep import Rep\n from ..models.req import Req\n\n id = self.id\n\n name = self.name\n\n index = self.index\n\n requests = []\n for requests_item_data in self.requests:\n requests_item = requests_item_data.to_dict()\n requests.append(requests_item)\n\n responses = []\n for responses_item_data in self.responses:\n responses_item = responses_item_data.to_dict()\n responses.append(responses_item)\n\n created_on = self.created_on.isoformat()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"id\": id,\n \"name\": name,\n \"index\": index,\n \"requests\": requests,\n \"responses\": responses,\n \"created_on\": created_on,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.rep import Rep\n from ..models.req import Req\n\n d = src_dict.copy()\n id = d.pop(\"id\")\n\n name = d.pop(\"name\")\n\n index = d.pop(\"index\")\n\n requests = []\n _requests = d.pop(\"requests\")\n for requests_item_data in _requests:\n requests_item = Req.from_dict(requests_item_data)\n\n requests.append(requests_item)\n\n responses = []\n _responses = d.pop(\"responses\")\n for responses_item_data in _responses:\n responses_item = Rep.from_dict(responses_item_data)\n\n responses.append(responses_item)\n\n created_on = isoparse(d.pop(\"created_on\"))\n\n chat_session = cls(\n id=id,\n name=name,\n index=index,\n requests=requests,\n responses=responses,\n created_on=created_on,\n )\n\n chat_session.additional_properties = d\n return chat_session\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "CreateAttribute", "path": "zerolink_client/models/create_attribute.py", "snippet": "class CreateAttribute:\n \"\"\"\n Attributes:\n subject (str): EID of a builtin entity\n predicate (str): Name of attribute\n attribute (Attribute):\n \"\"\"\n\n subject: str\n predicate: str\n attribute: \"Attribute\"\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.attribute import Attribute\n\n subject = self.subject\n\n predicate = self.predicate\n\n attribute = self.attribute.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"subject\": subject,\n \"predicate\": predicate,\n \"attribute\": attribute,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.attribute import Attribute\n\n d = src_dict.copy()\n subject = d.pop(\"subject\")\n\n predicate = d.pop(\"predicate\")\n\n attribute = Attribute.from_dict(d.pop(\"attribute\"))\n\n create_attribute = cls(\n subject=subject,\n predicate=predicate,\n attribute=attribute,\n )\n\n create_attribute.additional_properties = d\n return create_attribute\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "CreateEntity", "path": "zerolink_client/models/create_entity.py", "snippet": "class CreateEntity:\n \"\"\"\n Attributes:\n entity (str): Name of entity\n entity_type (Union[Unset, EntityType]): Entity types are entities that map to base ontological entities in\n Foundation.\n entity_str (Union[Unset, str]): User specified type\n is_class (Union[Unset, bool]): Whether the entity is a class or instance Default: False.\n \"\"\"\n\n entity: str\n entity_type: Union[Unset, EntityType] = UNSET\n entity_str: Union[Unset, str] = UNSET\n is_class: Union[Unset, bool] = False\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n entity = self.entity\n\n entity_type: Union[Unset, str] = UNSET\n if not isinstance(self.entity_type, Unset):\n entity_type = self.entity_type.value\n\n entity_str = self.entity_str\n\n is_class = self.is_class\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"entity\": entity,\n }\n )\n if entity_type is not UNSET:\n field_dict[\"entity_type\"] = entity_type\n if entity_str is not UNSET:\n field_dict[\"entity_str\"] = entity_str\n if is_class is not UNSET:\n field_dict[\"is_class\"] = is_class\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n entity = d.pop(\"entity\")\n\n _entity_type = d.pop(\"entity_type\", UNSET)\n entity_type: Union[Unset, EntityType]\n if isinstance(_entity_type, Unset):\n entity_type = UNSET\n else:\n entity_type = EntityType(_entity_type)\n\n entity_str = d.pop(\"entity_str\", UNSET)\n\n is_class = d.pop(\"is_class\", UNSET)\n\n create_entity = cls(\n entity=entity,\n entity_type=entity_type,\n entity_str=entity_str,\n is_class=is_class,\n )\n\n create_entity.additional_properties = d\n return create_entity\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "CreateRule", "path": "zerolink_client/models/create_rule.py", "snippet": "class CreateRule:\n \"\"\"\n Attributes:\n rule (str): Textual representation of the rule to parse\n context (Union[Unset, CreateRuleContext]): Context of entities to use for parsing the rule\n \"\"\"\n\n rule: str\n context: Union[Unset, \"CreateRuleContext\"] = UNSET\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.create_rule_context import CreateRuleContext\n\n rule = self.rule\n\n context: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.context, Unset):\n context = self.context.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"rule\": rule,\n }\n )\n if context is not UNSET:\n field_dict[\"context\"] = context\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.create_rule_context import CreateRuleContext\n\n d = src_dict.copy()\n rule = d.pop(\"rule\")\n\n _context = d.pop(\"context\", UNSET)\n context: Union[Unset, CreateRuleContext]\n if isinstance(_context, Unset):\n context = UNSET\n else:\n context = CreateRuleContext.from_dict(_context)\n\n create_rule = cls(\n rule=rule,\n context=context,\n )\n\n create_rule.additional_properties = d\n return create_rule\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "CreateRuleResponse", "path": "zerolink_client/models/create_rule_response.py", "snippet": "class CreateRuleResponse:\n \"\"\"\n Attributes:\n id (str):\n \"\"\"\n\n id: str\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n id = self.id\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"id\": id,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n id = d.pop(\"id\")\n\n create_rule_response = cls(\n id=id,\n )\n\n create_rule_response.additional_properties = d\n return create_rule_response\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "CreateTriple", "path": "zerolink_client/models/create_triple.py", "snippet": "class CreateTriple:\n \"\"\"\n Attributes:\n predicate (str): Name of predicate relation\n user_subject (Union[Unset, str]): EID of a user entity\n subject (Union[Unset, str]): EID of a builtin entity\n user_object (Union[Unset, str]): EID of a user entity\n object_ (Union[Unset, str]): EID of a builtin entity\n \"\"\"\n\n predicate: str\n user_subject: Union[Unset, str] = UNSET\n subject: Union[Unset, str] = UNSET\n user_object: Union[Unset, str] = UNSET\n object_: Union[Unset, str] = UNSET\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n predicate = self.predicate\n\n user_subject = self.user_subject\n\n subject = self.subject\n\n user_object = self.user_object\n\n object_ = self.object_\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"predicate\": predicate,\n }\n )\n if user_subject is not UNSET:\n field_dict[\"user_subject\"] = user_subject\n if subject is not UNSET:\n field_dict[\"subject\"] = subject\n if user_object is not UNSET:\n field_dict[\"user_object\"] = user_object\n if object_ is not UNSET:\n field_dict[\"object\"] = object_\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n predicate = d.pop(\"predicate\")\n\n user_subject = d.pop(\"user_subject\", UNSET)\n\n subject = d.pop(\"subject\", UNSET)\n\n user_object = d.pop(\"user_object\", UNSET)\n\n object_ = d.pop(\"object\", UNSET)\n\n create_triple = cls(\n predicate=predicate,\n user_subject=user_subject,\n subject=subject,\n user_object=user_object,\n object_=object_,\n )\n\n create_triple.additional_properties = d\n return create_triple\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "CreateTuneJobResponse", "path": "zerolink_client/models/create_tune_job_response.py", "snippet": "class CreateTuneJobResponse:\n \"\"\"\n Attributes:\n id (str):\n status (str):\n \"\"\"\n\n id: str\n status: str\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n id = self.id\n\n status = self.status\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"id\": id,\n \"status\": status,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n id = d.pop(\"id\")\n\n status = d.pop(\"status\")\n\n create_tune_job_response = cls(\n id=id,\n status=status,\n )\n\n create_tune_job_response.additional_properties = d\n return create_tune_job_response\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "Entity", "path": "zerolink_client/models/entity.py", "snippet": "class Entity:\n \"\"\"\n Attributes:\n id (str):\n entity (str):\n description (Union[Unset, str]):\n source (Union[Unset, str]):\n source_url (Union[Unset, str]):\n ontology (Union[Unset, Graph]):\n source_id (Union[Unset, str]):\n \"\"\"\n\n id: str\n entity: str\n description: Union[Unset, str] = UNSET\n source: Union[Unset, str] = UNSET\n source_url: Union[Unset, str] = UNSET\n ontology: Union[Unset, \"Graph\"] = UNSET\n source_id: Union[Unset, str] = UNSET\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.graph import Graph\n\n id = self.id\n\n entity = self.entity\n\n description = self.description\n\n source = self.source\n\n source_url = self.source_url\n\n ontology: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.ontology, Unset):\n ontology = self.ontology.to_dict()\n\n source_id = self.source_id\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"id\": id,\n \"entity\": entity,\n }\n )\n if description is not UNSET:\n field_dict[\"description\"] = description\n if source is not UNSET:\n field_dict[\"source\"] = source\n if source_url is not UNSET:\n field_dict[\"source_url\"] = source_url\n if ontology is not UNSET:\n field_dict[\"ontology\"] = ontology\n if source_id is not UNSET:\n field_dict[\"source_id\"] = source_id\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.graph import Graph\n\n d = src_dict.copy()\n id = d.pop(\"id\")\n\n entity = d.pop(\"entity\")\n\n description = d.pop(\"description\", UNSET)\n\n source = d.pop(\"source\", UNSET)\n\n source_url = d.pop(\"source_url\", UNSET)\n\n _ontology = d.pop(\"ontology\", UNSET)\n ontology: Union[Unset, Graph]\n if isinstance(_ontology, Unset):\n ontology = UNSET\n else:\n ontology = Graph.from_dict(_ontology)\n\n source_id = d.pop(\"source_id\", UNSET)\n\n entity = cls(\n id=id,\n entity=entity,\n description=description,\n source=source,\n source_url=source_url,\n ontology=ontology,\n source_id=source_id,\n )\n\n entity.additional_properties = d\n return entity\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "HTTPValidationError", "path": "zerolink_client/models/http_validation_error.py", "snippet": "class HTTPValidationError:\n \"\"\"\n Attributes:\n detail (Union[Unset, List['ValidationError']]):\n \"\"\"\n\n detail: Union[Unset, List[\"ValidationError\"]] = UNSET\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.validation_error import ValidationError\n\n detail: Union[Unset, List[Dict[str, Any]]] = UNSET\n if not isinstance(self.detail, Unset):\n detail = []\n for detail_item_data in self.detail:\n detail_item = detail_item_data.to_dict()\n detail.append(detail_item)\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if detail is not UNSET:\n field_dict[\"detail\"] = detail\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.validation_error import ValidationError\n\n d = src_dict.copy()\n detail = []\n _detail = d.pop(\"detail\", UNSET)\n for detail_item_data in _detail or []:\n detail_item = ValidationError.from_dict(detail_item_data)\n\n detail.append(detail_item)\n\n http_validation_error = cls(\n detail=detail,\n )\n\n http_validation_error.additional_properties = d\n return http_validation_error\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "Question", "path": "zerolink_client/models/question.py", "snippet": "class Question:\n \"\"\"A question to be answered by querying the knowledge graph and reasoner.\n\n Attributes:\n body (str): The body of the question\n world (Union[Unset, WorldAssumption]): The world assumption is the assumption about the world that the reasoner\n makes. This is used to determine the answer to a query. For example, if\n the world assumption is \"closed\" then the reasoner will assume that the\n answer to the query is \"no\" if it cannot find a triple to satisfy the\n query. Default: WorldAssumption.CLOSED.\n spatial (Union[Unset, SpatialAssumption]): The spatial assumption is the assumption about space that the\n reasoner\n makes. This is used to determine the answer to a query. For example, if the\n spatial assumption is \"earth\" then the reasoner will only consider\n geographic locations on Earth and will assume all instances of 'location'\n are on Earth. If the spatial assumption is \"universe\" then the reasoner\n then this restriction is lifted and the reasoner will consider all\n locations in the universe. Default: SpatialAssumption.EARTH.\n temporal (Union[Unset, TemporalAssumption]): The temporal assumption is the assumption about time that the\n reasoner\n makes. This is used to determine the answer to a query. For example, if\n the temporal assumption is \"current\" then the reasoner will only consider\n triples that refer to entities that are non-historical. Excluding things\n like the Roman Empire and Francoist Spain. Default: TemporalAssumption.CURRENT.\n context (Union[Unset, ContextAssumption]): The context assumption is the assumption about the context that the\n reasoner makes. This is used to determine the answer to a query. For\n example, if the context assumption is \"none\" then the reasoner will only\n consider basic triples like instance_of and subclass_of. If the context\n assumption is \"local\" then the reasoner will consider triples that are\n defined by the user. If the context assumption is \"global\" then the\n reasoner will consider all queryable triples. Default: ContextAssumption.GLOBAL.\n \"\"\"\n\n body: str\n world: Union[Unset, WorldAssumption] = WorldAssumption.CLOSED\n spatial: Union[Unset, SpatialAssumption] = SpatialAssumption.EARTH\n temporal: Union[Unset, TemporalAssumption] = TemporalAssumption.CURRENT\n context: Union[Unset, ContextAssumption] = ContextAssumption.GLOBAL\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n body = self.body\n\n world: Union[Unset, str] = UNSET\n if not isinstance(self.world, Unset):\n world = self.world.value\n\n spatial: Union[Unset, str] = UNSET\n if not isinstance(self.spatial, Unset):\n spatial = self.spatial.value\n\n temporal: Union[Unset, str] = UNSET\n if not isinstance(self.temporal, Unset):\n temporal = self.temporal.value\n\n context: Union[Unset, str] = UNSET\n if not isinstance(self.context, Unset):\n context = self.context.value\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"body\": body,\n }\n )\n if world is not UNSET:\n field_dict[\"world\"] = world\n if spatial is not UNSET:\n field_dict[\"spatial\"] = spatial\n if temporal is not UNSET:\n field_dict[\"temporal\"] = temporal\n if context is not UNSET:\n field_dict[\"context\"] = context\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n body = d.pop(\"body\")\n\n _world = d.pop(\"world\", UNSET)\n world: Union[Unset, WorldAssumption]\n if isinstance(_world, Unset):\n world = UNSET\n else:\n world = WorldAssumption(_world)\n\n _spatial = d.pop(\"spatial\", UNSET)\n spatial: Union[Unset, SpatialAssumption]\n if isinstance(_spatial, Unset):\n spatial = UNSET\n else:\n spatial = SpatialAssumption(_spatial)\n\n _temporal = d.pop(\"temporal\", UNSET)\n temporal: Union[Unset, TemporalAssumption]\n if isinstance(_temporal, Unset):\n temporal = UNSET\n else:\n temporal = TemporalAssumption(_temporal)\n\n _context = d.pop(\"context\", UNSET)\n context: Union[Unset, ContextAssumption]\n if isinstance(_context, Unset):\n context = UNSET\n else:\n context = ContextAssumption(_context)\n\n question = cls(\n body=body,\n world=world,\n spatial=spatial,\n temporal=temporal,\n context=context,\n )\n\n question.additional_properties = d\n return question\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "QuestionResponse", "path": "zerolink_client/models/question_response.py", "snippet": "class QuestionResponse:\n \"\"\"A response to a question request.\n\n Attributes:\n id (int): The ID of the question\n msg (str): A message describing the result of the question\n status (ResultStatus): The status of a result.\n answers (List[str]): The answers to the question\n methods (List[str]): The methods used to answer the question\n reasoners (List[str]): The reasoners used to answer the question\n query (Union[Unset, QuestionResponseQuery]): The query used to answer the question\n \"\"\"\n\n id: int\n msg: str\n status: ResultStatus\n answers: List[str]\n methods: List[str]\n reasoners: List[str]\n query: Union[Unset, \"QuestionResponseQuery\"] = UNSET\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.question_response_query import QuestionResponseQuery\n\n id = self.id\n\n msg = self.msg\n\n status = self.status.value\n\n answers = self.answers\n\n methods = self.methods\n\n reasoners = self.reasoners\n\n query: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.query, Unset):\n query = self.query.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"id\": id,\n \"msg\": msg,\n \"status\": status,\n \"answers\": answers,\n \"methods\": methods,\n \"reasoners\": reasoners,\n }\n )\n if query is not UNSET:\n field_dict[\"query\"] = query\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.question_response_query import QuestionResponseQuery\n\n d = src_dict.copy()\n id = d.pop(\"id\")\n\n msg = d.pop(\"msg\")\n\n status = ResultStatus(d.pop(\"status\"))\n\n answers = cast(List[str], d.pop(\"answers\"))\n\n methods = cast(List[str], d.pop(\"methods\"))\n\n reasoners = cast(List[str], d.pop(\"reasoners\"))\n\n _query = d.pop(\"query\", UNSET)\n query: Union[Unset, QuestionResponseQuery]\n if isinstance(_query, Unset):\n query = UNSET\n else:\n query = QuestionResponseQuery.from_dict(_query)\n\n question_response = cls(\n id=id,\n msg=msg,\n status=status,\n answers=answers,\n methods=methods,\n reasoners=reasoners,\n query=query,\n )\n\n question_response.additional_properties = d\n return question_response\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "TextExtract", "path": "zerolink_client/models/text_extract.py", "snippet": "class TextExtract:\n \"\"\"\n Attributes:\n text (str): Text to extract from\n extraction_model (Union[Unset, ExtractModel]): An enumeration. Default: ExtractModel.BASE.\n \"\"\"\n\n text: str\n extraction_model: Union[Unset, ExtractModel] = ExtractModel.BASE\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n text = self.text\n\n extraction_model: Union[Unset, str] = UNSET\n if not isinstance(self.extraction_model, Unset):\n extraction_model = self.extraction_model.value\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"text\": text,\n }\n )\n if extraction_model is not UNSET:\n field_dict[\"extraction_model\"] = extraction_model\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n text = d.pop(\"text\")\n\n _extraction_model = d.pop(\"extraction_model\", UNSET)\n extraction_model: Union[Unset, ExtractModel]\n if isinstance(_extraction_model, Unset):\n extraction_model = UNSET\n else:\n extraction_model = ExtractModel(_extraction_model)\n\n text_extract = cls(\n text=text,\n extraction_model=extraction_model,\n )\n\n text_extract.additional_properties = d\n return text_extract\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties" }, { "identifier": "File", "path": "zerolink_client/types.py", "snippet": "class File:\n \"\"\"Contains information for file uploads\"\"\"\n\n payload: BinaryIO\n file_name: Optional[str] = None\n mime_type: Optional[str] = None\n\n def to_tuple(self) -> FileJsonType:\n \"\"\"Return a tuple representation that httpx will accept for multipart/form-data\"\"\"\n return self.file_name, self.payload, self.mime_type" }, { "identifier": "UNSET", "path": "zerolink_client/types.py", "snippet": "UNSET: Unset = Unset()" } ]
from typing import Any, Optional, cast from zerolink import settings from zerolink.exc import APIError, AuthenticationError from zerolink_client import Client from zerolink_client.api.default import finetune, get_models_models_get from zerolink_client.api.entity import ( desc_entity_id, desc_entity_ontology, lookup_entity, lookup_relation, search_entity, ) from zerolink_client.api.extract import extract_text from zerolink_client.api.fact import ( create_userattribute, create_userentity, create_userrule, create_usertriple, ) from zerolink_client.api.kg import get_triple from zerolink_client.api.question import post_question from zerolink_client.api.session import ( create_session, get_session_entities, get_session_facts, get_user_session, ) from zerolink_client.api.user import create_user from zerolink_client.models import ( ChatSession, CreateAttribute, CreateEntity, CreateRule, CreateRuleResponse, CreateTriple, CreateTuneJobResponse, Entity, HTTPValidationError, Question, QuestionResponse, TextExtract, ) from zerolink_client.types import File, UNSET
17,429
rep = lookup_relation.sync_detailed( client=client, name=name, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_ontology(name: str, **kwargs) -> dict[str, Any]: """ Get the ontology of an entity. """ check_api_key() rep = desc_entity_ontology.sync_detailed( client=client, id=name, **kwargs, ) if rep.status_code == 200: return cast(dict[str, Any], rep.parsed) else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_triples(name: str, **kwargs): """ Get the triples of a session. """ check_api_key() rep = get_triple.sync_detailed( client=client, name=name, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_reasoners(name: str, **kwargs): """ Get the reasoners available. """ check_api_key() rep = get_models_models_get.sync_detailed( client=client, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") raise APIError(err) def add_entity(session_id: int, body: CreateEntity, **kwargs): """ Add a user entity to a session. """ check_api_key() rep = create_userentity.sync_detailed( client=client, session_id=session_id, body=body, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def add_triple(session_id: int, body: CreateTriple, **kwargs): """ Add a user triple to a session. """ check_api_key() rep = create_usertriple.sync_detailed( client=client, session_id=session_id, body=body, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") raise APIError(err) def add_attribute(session_id: int, body: CreateAttribute, **kwargs): """ Add a user attribute to a session. """ check_api_key() rep = create_userattribute.sync_detailed( client=client, session_id=session_id, body=body, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") raise APIError(err)
# ------------------------------------------------------------------------ # Endpoints # ------------------------------------------------------------------------ client = Client( base_url=settings.server_url, raise_on_unexpected_status=False, ) def check_api_key() -> None: """ Check if the API key is set. """ if settings.api_key is None: raise AuthenticationError() else: pass def get_user_id() -> str: """ Get the user ID from the server. Only used for Demo server. """ client._headers["Authorization"] = settings.api_key rep = create_user.sync(client=client) if rep is None: raise Exception("Failed to authenticate.") settings.api_key = rep.user_id if isinstance(rep, HTTPValidationError): raise APIError(str(rep)) return rep.user_id def post_session(user_id: str, **kwargs) -> Optional[ChatSession]: """ Create a new session. """ check_api_key() if user_id is None: user_id = settings.api_key rep = create_session.sync(client=client, user_id=user_id, **kwargs) if isinstance(rep, HTTPValidationError): raise APIError(str(rep)) return rep def get_session_name(user_id: str, session_name: str, **kwargs): """ Lookup a session by user and name. """ check_api_key() rep = get_user_session.sync_detailed(user_id, session_name, client=client, **kwargs) if rep.status_code == 200: return rep.parsed elif rep.status_code == 404: return None else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_session_entities_list(session_id: int, **kwargs): """ Get the entities of a session. """ check_api_key() rep = get_session_entities.sync_detailed(session_id, client=client, **kwargs) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_session_facts_list(session_id: int, **kwargs): """ Get the facts of a session. """ check_api_key() rep = get_session_facts.sync_detailed(session_id, client=client, **kwargs) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def ask_question( session_id: Optional[int], body: str, assumps: Optional[dict[str, Any]] = None, **kwargs, ) -> QuestionResponse: """ Ask a question. """ check_api_key() rep = post_question.sync_detailed( client=client, session_id=(session_id or UNSET), body=Question(body=body, **(assumps or {})), **kwargs, ) if rep.status_code == 200: return cast(QuestionResponse, rep.parsed) else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_entity_id(id: str, **kwargs) -> Entity: """ Get the description of an entity by eid. """ check_api_key() rep = desc_entity_id.sync_detailed( client=client, id=id, **kwargs, ) if rep.status_code == 200: return cast(Entity, rep.parsed) else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_desc_entity(name: str, **kwargs): """ Get the description of an entity by eid. """ check_api_key() rep = lookup_entity.sync_detailed( client=client, name=name, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_search_entity(name: str, **kwargs): """ Search for an entity. """ check_api_key() rep = search_entity.sync_detailed( client=client, name=name, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_search_relation(name: str, **kwargs): """ Search for a relation. """ check_api_key() rep = lookup_relation.sync_detailed( client=client, name=name, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_ontology(name: str, **kwargs) -> dict[str, Any]: """ Get the ontology of an entity. """ check_api_key() rep = desc_entity_ontology.sync_detailed( client=client, id=name, **kwargs, ) if rep.status_code == 200: return cast(dict[str, Any], rep.parsed) else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_triples(name: str, **kwargs): """ Get the triples of a session. """ check_api_key() rep = get_triple.sync_detailed( client=client, name=name, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def get_reasoners(name: str, **kwargs): """ Get the reasoners available. """ check_api_key() rep = get_models_models_get.sync_detailed( client=client, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") raise APIError(err) def add_entity(session_id: int, body: CreateEntity, **kwargs): """ Add a user entity to a session. """ check_api_key() rep = create_userentity.sync_detailed( client=client, session_id=session_id, body=body, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") print(err) raise APIError(err) def add_triple(session_id: int, body: CreateTriple, **kwargs): """ Add a user triple to a session. """ check_api_key() rep = create_usertriple.sync_detailed( client=client, session_id=session_id, body=body, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") raise APIError(err) def add_attribute(session_id: int, body: CreateAttribute, **kwargs): """ Add a user attribute to a session. """ check_api_key() rep = create_userattribute.sync_detailed( client=client, session_id=session_id, body=body, **kwargs, ) if rep.status_code == 200: return rep.parsed else: err = rep.content.decode("utf-8") raise APIError(err)
def post_rule(session_id: int, body: CreateRule, **kwargs) -> CreateRuleResponse:
26
2023-12-03 07:50:04+00:00
24k
JunMa11/UHNSeg-Quiz
nnunetv2/training/nnUNetTrainer/variants/network_architecture/nnUNetTrainerNoDeepSupervision.py
[ { "identifier": "DC_and_BCE_loss", "path": "nnunetv2/training/loss/compound_losses.py", "snippet": "class DC_and_BCE_loss(nn.Module):\n def __init__(self, bce_kwargs, soft_dice_kwargs, weight_ce=1, weight_dice=1, use_ignore_label: bool = False,\n dice_class=MemoryEfficientSoftDiceLoss):\n \"\"\"\n DO NOT APPLY NONLINEARITY IN YOUR NETWORK!\n\n target mut be one hot encoded\n IMPORTANT: We assume use_ignore_label is located in target[:, -1]!!!\n\n :param soft_dice_kwargs:\n :param bce_kwargs:\n :param aggregate:\n \"\"\"\n super(DC_and_BCE_loss, self).__init__()\n if use_ignore_label:\n bce_kwargs['reduction'] = 'none'\n\n self.weight_dice = weight_dice\n self.weight_ce = weight_ce\n self.use_ignore_label = use_ignore_label\n\n self.ce = nn.BCEWithLogitsLoss(**bce_kwargs)\n self.dc = dice_class(apply_nonlin=torch.sigmoid, **soft_dice_kwargs)\n\n def forward(self, net_output: torch.Tensor, target: torch.Tensor):\n if self.use_ignore_label:\n # target is one hot encoded here. invert it so that it is True wherever we can compute the loss\n mask = (1 - target[:, -1:]).bool()\n # remove ignore channel now that we have the mask\n target_regions = torch.clone(target[:, :-1])\n else:\n target_regions = target\n mask = None\n\n dc_loss = self.dc(net_output, target_regions, loss_mask=mask)\n if mask is not None:\n ce_loss = (self.ce(net_output, target_regions) * mask).sum() / torch.clip(mask.sum(), min=1e-8)\n else:\n ce_loss = self.ce(net_output, target_regions)\n result = self.weight_ce * ce_loss + self.weight_dice * dc_loss\n return result" }, { "identifier": "DC_and_CE_loss", "path": "nnunetv2/training/loss/compound_losses.py", "snippet": "class DC_and_CE_loss(nn.Module):\n def __init__(self, soft_dice_kwargs, ce_kwargs, weight_ce=1, weight_dice=1, ignore_label=None,\n dice_class=SoftDiceLoss):\n \"\"\"\n Weights for CE and Dice do not need to sum to one. You can set whatever you want.\n :param soft_dice_kwargs:\n :param ce_kwargs:\n :param aggregate:\n :param square_dice:\n :param weight_ce:\n :param weight_dice:\n \"\"\"\n super(DC_and_CE_loss, self).__init__()\n if ignore_label is not None:\n ce_kwargs['ignore_index'] = ignore_label\n\n self.weight_dice = weight_dice\n self.weight_ce = weight_ce\n self.ignore_label = ignore_label\n\n self.ce = RobustCrossEntropyLoss(**ce_kwargs)\n self.dc = dice_class(apply_nonlin=softmax_helper_dim1, **soft_dice_kwargs)\n\n def forward(self, net_output: torch.Tensor, target: torch.Tensor):\n \"\"\"\n target must be b, c, x, y(, z) with c=1\n :param net_output:\n :param target:\n :return:\n \"\"\"\n if self.ignore_label is not None:\n assert target.shape[1] == 1, 'ignore label is not implemented for one hot encoded target variables ' \\\n '(DC_and_CE_loss)'\n mask = (target != self.ignore_label).bool()\n # remove ignore label from target, replace with one of the known labels. It doesn't matter because we\n # ignore gradients in those areas anyway\n target_dice = torch.clone(target)\n target_dice[target == self.ignore_label] = 0\n num_fg = mask.sum()\n else:\n target_dice = target\n mask = None\n\n dc_loss = self.dc(net_output, target_dice, loss_mask=mask) \\\n if self.weight_dice != 0 else 0\n ce_loss = self.ce(net_output, target[:, 0].long()) \\\n if self.weight_ce != 0 and (self.ignore_label is None or num_fg > 0) else 0\n\n result = self.weight_ce * ce_loss + self.weight_dice * dc_loss\n return result" }, { "identifier": "get_tp_fp_fn_tn", "path": "nnunetv2/training/loss/dice.py", "snippet": "def get_tp_fp_fn_tn(net_output, gt, axes=None, mask=None, square=False):\n \"\"\"\n net_output must be (b, c, x, y(, z)))\n gt must be a label map (shape (b, 1, x, y(, z)) OR shape (b, x, y(, z))) or one hot encoding (b, c, x, y(, z))\n if mask is provided it must have shape (b, 1, x, y(, z)))\n :param net_output:\n :param gt:\n :param axes: can be (, ) = no summation\n :param mask: mask must be 1 for valid pixels and 0 for invalid pixels\n :param square: if True then fp, tp and fn will be squared before summation\n :return:\n \"\"\"\n if axes is None:\n axes = tuple(range(2, len(net_output.size())))\n\n shp_x = net_output.shape\n shp_y = gt.shape\n\n with torch.no_grad():\n if len(shp_x) != len(shp_y):\n gt = gt.view((shp_y[0], 1, *shp_y[1:]))\n\n if net_output.shape == gt.shape:\n # if this is the case then gt is probably already a one hot encoding\n y_onehot = gt\n else:\n gt = gt.long()\n y_onehot = torch.zeros(shp_x, device=net_output.device)\n y_onehot.scatter_(1, gt, 1)\n\n tp = net_output * y_onehot\n fp = net_output * (1 - y_onehot)\n fn = (1 - net_output) * y_onehot\n tn = (1 - net_output) * (1 - y_onehot)\n\n if mask is not None:\n with torch.no_grad():\n mask_here = torch.tile(mask, (1, tp.shape[1], *[1 for i in range(2, len(tp.shape))]))\n tp *= mask_here\n fp *= mask_here\n fn *= mask_here\n tn *= mask_here\n # benchmark whether tiling the mask would be faster (torch.tile). It probably is for large batch sizes\n # OK it barely makes a difference but the implementation above is a tiny bit faster + uses less vram\n # (using nnUNetv2_train 998 3d_fullres 0)\n # tp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tp, dim=1)), dim=1)\n # fp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fp, dim=1)), dim=1)\n # fn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fn, dim=1)), dim=1)\n # tn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tn, dim=1)), dim=1)\n\n if square:\n tp = tp ** 2\n fp = fp ** 2\n fn = fn ** 2\n tn = tn ** 2\n\n if len(axes) > 0:\n tp = tp.sum(dim=axes, keepdim=False)\n fp = fp.sum(dim=axes, keepdim=False)\n fn = fn.sum(dim=axes, keepdim=False)\n tn = tn.sum(dim=axes, keepdim=False)\n\n return tp, fp, fn, tn" }, { "identifier": "MemoryEfficientSoftDiceLoss", "path": "nnunetv2/training/loss/dice.py", "snippet": "class MemoryEfficientSoftDiceLoss(nn.Module):\n def __init__(self, apply_nonlin: Callable = None, batch_dice: bool = False, do_bg: bool = True, smooth: float = 1.,\n ddp: bool = True):\n \"\"\"\n saves 1.6 GB on Dataset017 3d_lowres\n \"\"\"\n super(MemoryEfficientSoftDiceLoss, self).__init__()\n\n self.do_bg = do_bg\n self.batch_dice = batch_dice\n self.apply_nonlin = apply_nonlin\n self.smooth = smooth\n self.ddp = ddp\n\n def forward(self, x, y, loss_mask=None):\n if self.apply_nonlin is not None:\n x = self.apply_nonlin(x)\n\n # make everything shape (b, c)\n axes = list(range(2, len(x.shape)))\n with torch.no_grad():\n if len(x.shape) != len(y.shape):\n y = y.view((y.shape[0], 1, *y.shape[1:]))\n\n if x.shape == y.shape:\n # if this is the case then gt is probably already a one hot encoding\n y_onehot = y\n else:\n gt = y.long()\n y_onehot = torch.zeros(x.shape, device=x.device, dtype=torch.bool)\n y_onehot.scatter_(1, gt, 1)\n\n if not self.do_bg:\n y_onehot = y_onehot[:, 1:]\n\n sum_gt = y_onehot.sum(axes) if loss_mask is None else (y_onehot * loss_mask).sum(axes)\n\n # this one MUST be outside the with torch.no_grad(): context. Otherwise no gradients for you\n if not self.do_bg:\n x = x[:, 1:]\n\n intersect = (x * y_onehot).sum(axes) if loss_mask is None else (x * y_onehot * loss_mask).sum(axes)\n sum_pred = x.sum(axes) if loss_mask is None else (x * loss_mask).sum(axes)\n\n if self.ddp and self.batch_dice:\n intersect = AllGatherGrad.apply(intersect).sum(0)\n sum_pred = AllGatherGrad.apply(sum_pred).sum(0)\n sum_gt = AllGatherGrad.apply(sum_gt).sum(0)\n\n if self.batch_dice:\n intersect = intersect.sum(0)\n sum_pred = sum_pred.sum(0)\n sum_gt = sum_gt.sum(0)\n\n dc = (2 * intersect + self.smooth) / (torch.clip(sum_gt + sum_pred + self.smooth, 1e-8))\n\n dc = dc.mean()\n return -dc" }, { "identifier": "nnUNetTrainer", "path": "nnunetv2/training/nnUNetTrainer/nnUNetTrainer.py", "snippet": "class nnUNetTrainer(object):\n def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool = True,\n device: torch.device = torch.device('cuda')):\n # From https://grugbrain.dev/. Worth a read ya big brains ;-)\n\n # apex predator of grug is complexity\n # complexity bad\n # say again:\n # complexity very bad\n # you say now:\n # complexity very, very bad\n # given choice between complexity or one on one against t-rex, grug take t-rex: at least grug see t-rex\n # complexity is spirit demon that enter codebase through well-meaning but ultimately very clubbable non grug-brain developers and project managers who not fear complexity spirit demon or even know about sometime\n # one day code base understandable and grug can get work done, everything good!\n # next day impossible: complexity demon spirit has entered code and very dangerous situation!\n\n # OK OK I am guilty. But I tried.\n # https://www.osnews.com/images/comics/wtfm.jpg\n # https://i.pinimg.com/originals/26/b2/50/26b250a738ea4abc7a5af4d42ad93af0.jpg\n\n self.is_ddp = dist.is_available() and dist.is_initialized()\n self.local_rank = 0 if not self.is_ddp else dist.get_rank()\n\n self.device = device\n\n # print what device we are using\n if self.is_ddp: # implicitly it's clear that we use cuda in this case\n print(f\"I am local rank {self.local_rank}. {device_count()} GPUs are available. The world size is \"\n f\"{dist.get_world_size()}.\"\n f\"Setting device to {self.device}\")\n self.device = torch.device(type='cuda', index=self.local_rank)\n else:\n if self.device.type == 'cuda':\n # we might want to let the user pick this but for now please pick the correct GPU with CUDA_VISIBLE_DEVICES=X\n self.device = torch.device(type='cuda', index=0)\n print(f\"Using device: {self.device}\")\n\n # loading and saving this class for continuing from checkpoint should not happen based on pickling. This\n # would also pickle the network etc. Bad, bad. Instead we just reinstantiate and then load the checkpoint we\n # need. So let's save the init args\n self.my_init_kwargs = {}\n for k in inspect.signature(self.__init__).parameters.keys():\n self.my_init_kwargs[k] = locals()[k]\n\n ### Saving all the init args into class variables for later access\n self.plans_manager = PlansManager(plans)\n self.configuration_manager = self.plans_manager.get_configuration(configuration)\n self.configuration_name = configuration\n self.dataset_json = dataset_json\n self.fold = fold\n self.unpack_dataset = unpack_dataset\n\n ### Setting all the folder names. We need to make sure things don't crash in case we are just running\n # inference and some of the folders may not be defined!\n self.preprocessed_dataset_folder_base = join(nnUNet_preprocessed, self.plans_manager.dataset_name) \\\n if nnUNet_preprocessed is not None else None\n self.output_folder_base = join(nnUNet_results, self.plans_manager.dataset_name,\n self.__class__.__name__ + '__' + self.plans_manager.plans_name + \"__\" + configuration) \\\n if nnUNet_results is not None else None\n self.output_folder = join(self.output_folder_base, f'fold_{fold}')\n\n self.preprocessed_dataset_folder = join(self.preprocessed_dataset_folder_base,\n self.configuration_manager.data_identifier)\n # unlike the previous nnunet folder_with_segs_from_previous_stage is now part of the plans. For now it has to\n # be a different configuration in the same plans\n # IMPORTANT! the mapping must be bijective, so lowres must point to fullres and vice versa (using\n # \"previous_stage\" and \"next_stage\"). Otherwise it won't work!\n self.is_cascaded = self.configuration_manager.previous_stage_name is not None\n self.folder_with_segs_from_previous_stage = \\\n join(nnUNet_results, self.plans_manager.dataset_name,\n self.__class__.__name__ + '__' + self.plans_manager.plans_name + \"__\" +\n self.configuration_manager.previous_stage_name, 'predicted_next_stage', self.configuration_name) \\\n if self.is_cascaded else None\n\n ### Some hyperparameters for you to fiddle with\n self.initial_lr = 1e-2\n self.weight_decay = 3e-5\n self.oversample_foreground_percent = 0.33\n self.num_iterations_per_epoch = 250\n self.num_val_iterations_per_epoch = 50\n self.num_epochs = 1000\n self.current_epoch = 0\n\n ### Dealing with labels/regions\n self.label_manager = self.plans_manager.get_label_manager(dataset_json)\n # labels can either be a list of int (regular training) or a list of tuples of int (region-based training)\n # needed for predictions. We do sigmoid in case of (overlapping) regions\n\n self.num_input_channels = None # -> self.initialize()\n self.network = None # -> self._get_network()\n self.optimizer = self.lr_scheduler = None # -> self.initialize\n self.grad_scaler = GradScaler() if self.device.type == 'cuda' else None\n self.loss = None # -> self.initialize\n\n ### Simple logging. Don't take that away from me!\n # initialize log file. This is just our log for the print statements etc. Not to be confused with lightning\n # logging\n timestamp = datetime.now()\n maybe_mkdir_p(self.output_folder)\n self.log_file = join(self.output_folder, \"training_log_%d_%d_%d_%02.0d_%02.0d_%02.0d.txt\" %\n (timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute,\n timestamp.second))\n self.logger = nnUNetLogger()\n\n ### placeholders\n self.dataloader_train = self.dataloader_val = None # see on_train_start\n\n ### initializing stuff for remembering things and such\n self._best_ema = None\n\n ### inference things\n self.inference_allowed_mirroring_axes = None # this variable is set in\n # self.configure_rotation_dummyDA_mirroring_and_inital_patch_size and will be saved in checkpoints\n\n ### checkpoint saving stuff\n self.save_every = 50\n self.disable_checkpointing = False\n\n ## DDP batch size and oversampling can differ between workers and needs adaptation\n # we need to change the batch size in DDP because we don't use any of those distributed samplers\n self._set_batch_size_and_oversample()\n\n self.was_initialized = False\n\n self.print_to_log_file(\"\\n#######################################################################\\n\"\n \"Please cite the following paper when using nnU-Net:\\n\"\n \"Isensee, F., Jaeger, P. F., Kohl, S. A., Petersen, J., & Maier-Hein, K. H. (2021). \"\n \"nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation. \"\n \"Nature methods, 18(2), 203-211.\\n\"\n \"#######################################################################\\n\",\n also_print_to_console=True, add_timestamp=False)\n\n def initialize(self):\n if not self.was_initialized:\n self.num_input_channels = determine_num_input_channels(self.plans_manager, self.configuration_manager,\n self.dataset_json)\n\n self.network = self.build_network_architecture(self.plans_manager, self.dataset_json,\n self.configuration_manager,\n self.num_input_channels,\n enable_deep_supervision=True).to(self.device)\n # compile network for free speedup\n if self._do_i_compile():\n self.print_to_log_file('Compiling network...')\n self.network = torch.compile(self.network)\n\n self.optimizer, self.lr_scheduler = self.configure_optimizers()\n # if ddp, wrap in DDP wrapper\n if self.is_ddp:\n self.network = torch.nn.SyncBatchNorm.convert_sync_batchnorm(self.network)\n self.network = DDP(self.network, device_ids=[self.local_rank])\n\n self.loss = self._build_loss()\n self.was_initialized = True\n else:\n raise RuntimeError(\"You have called self.initialize even though the trainer was already initialized. \"\n \"That should not happen.\")\n\n def _do_i_compile(self):\n return ('nnUNet_compile' in os.environ.keys()) and (os.environ['nnUNet_compile'].lower() in ('true', '1', 't'))\n\n def _save_debug_information(self):\n # saving some debug information\n if self.local_rank == 0:\n dct = {}\n for k in self.__dir__():\n if not k.startswith(\"__\"):\n if not callable(getattr(self, k)) or k in ['loss', ]:\n dct[k] = str(getattr(self, k))\n elif k in ['network', ]:\n dct[k] = str(getattr(self, k).__class__.__name__)\n else:\n # print(k)\n pass\n if k in ['dataloader_train', 'dataloader_val']:\n if hasattr(getattr(self, k), 'generator'):\n dct[k + '.generator'] = str(getattr(self, k).generator)\n if hasattr(getattr(self, k), 'num_processes'):\n dct[k + '.num_processes'] = str(getattr(self, k).num_processes)\n if hasattr(getattr(self, k), 'transform'):\n dct[k + '.transform'] = str(getattr(self, k).transform)\n import subprocess\n hostname = subprocess.getoutput(['hostname'])\n dct['hostname'] = hostname\n torch_version = torch.__version__\n if self.device.type == 'cuda':\n gpu_name = torch.cuda.get_device_name()\n dct['gpu_name'] = gpu_name\n cudnn_version = torch.backends.cudnn.version()\n else:\n cudnn_version = 'None'\n dct['device'] = str(self.device)\n dct['torch_version'] = torch_version\n dct['cudnn_version'] = cudnn_version\n save_json(dct, join(self.output_folder, \"debug.json\"))\n\n @staticmethod\n def build_network_architecture(plans_manager: PlansManager,\n dataset_json,\n configuration_manager: ConfigurationManager,\n num_input_channels,\n enable_deep_supervision: bool = True) -> nn.Module:\n \"\"\"\n his is where you build the architecture according to the plans. There is no obligation to use\n get_network_from_plans, this is just a utility we use for the nnU-Net default architectures. You can do what\n you want. Even ignore the plans and just return something static (as long as it can process the requested\n patch size)\n but don't bug us with your bugs arising from fiddling with this :-P\n This is the function that is called in inference as well! This is needed so that all network architecture\n variants can be loaded at inference time (inference will use the same nnUNetTrainer that was used for\n training, so if you change the network architecture during training by deriving a new trainer class then\n inference will know about it).\n\n If you need to know how many segmentation outputs your custom architecture needs to have, use the following snippet:\n > label_manager = plans_manager.get_label_manager(dataset_json)\n > label_manager.num_segmentation_heads\n (why so complicated? -> We can have either classical training (classes) or regions. If we have regions,\n the number of outputs is != the number of classes. Also there is the ignore label for which no output\n should be generated. label_manager takes care of all that for you.)\n\n \"\"\"\n return get_network_from_plans(plans_manager, dataset_json, configuration_manager,\n num_input_channels, deep_supervision=enable_deep_supervision)\n\n def _get_deep_supervision_scales(self):\n deep_supervision_scales = list(list(i) for i in 1 / np.cumprod(np.vstack(\n self.configuration_manager.pool_op_kernel_sizes), axis=0))[:-1]\n return deep_supervision_scales\n\n def _set_batch_size_and_oversample(self):\n if not self.is_ddp:\n # set batch size to what the plan says, leave oversample untouched\n self.batch_size = self.configuration_manager.batch_size\n else:\n # batch size is distributed over DDP workers and we need to change oversample_percent for each worker\n batch_sizes = []\n oversample_percents = []\n\n world_size = dist.get_world_size()\n my_rank = dist.get_rank()\n\n global_batch_size = self.configuration_manager.batch_size\n assert global_batch_size >= world_size, 'Cannot run DDP if the batch size is smaller than the number of ' \\\n 'GPUs... Duh.'\n\n batch_size_per_GPU = np.ceil(global_batch_size / world_size).astype(int)\n\n for rank in range(world_size):\n if (rank + 1) * batch_size_per_GPU > global_batch_size:\n batch_size = batch_size_per_GPU - ((rank + 1) * batch_size_per_GPU - global_batch_size)\n else:\n batch_size = batch_size_per_GPU\n\n batch_sizes.append(batch_size)\n\n sample_id_low = 0 if len(batch_sizes) == 0 else np.sum(batch_sizes[:-1])\n sample_id_high = np.sum(batch_sizes)\n\n if sample_id_high / global_batch_size < (1 - self.oversample_foreground_percent):\n oversample_percents.append(0.0)\n elif sample_id_low / global_batch_size > (1 - self.oversample_foreground_percent):\n oversample_percents.append(1.0)\n else:\n percent_covered_by_this_rank = sample_id_high / global_batch_size - sample_id_low / global_batch_size\n oversample_percent_here = 1 - (((1 - self.oversample_foreground_percent) -\n sample_id_low / global_batch_size) / percent_covered_by_this_rank)\n oversample_percents.append(oversample_percent_here)\n\n print(\"worker\", my_rank, \"oversample\", oversample_percents[my_rank])\n print(\"worker\", my_rank, \"batch_size\", batch_sizes[my_rank])\n # self.print_to_log_file(\"worker\", my_rank, \"oversample\", oversample_percents[my_rank])\n # self.print_to_log_file(\"worker\", my_rank, \"batch_size\", batch_sizes[my_rank])\n\n self.batch_size = batch_sizes[my_rank]\n self.oversample_foreground_percent = oversample_percents[my_rank]\n\n def _build_loss(self):\n if self.label_manager.has_regions:\n loss = DC_and_BCE_loss({},\n {'batch_dice': self.configuration_manager.batch_dice,\n 'do_bg': True, 'smooth': 1e-5, 'ddp': self.is_ddp},\n use_ignore_label=self.label_manager.ignore_label is not None,\n dice_class=MemoryEfficientSoftDiceLoss)\n else:\n loss = DC_and_CE_loss({'batch_dice': self.configuration_manager.batch_dice,\n 'smooth': 1e-5, 'do_bg': False, 'ddp': self.is_ddp}, {}, weight_ce=1, weight_dice=1,\n ignore_label=self.label_manager.ignore_label, dice_class=MemoryEfficientSoftDiceLoss)\n\n deep_supervision_scales = self._get_deep_supervision_scales()\n\n # we give each output a weight which decreases exponentially (division by 2) as the resolution decreases\n # this gives higher resolution outputs more weight in the loss\n weights = np.array([1 / (2 ** i) for i in range(len(deep_supervision_scales))])\n weights[-1] = 0\n\n # we don't use the lowest 2 outputs. Normalize weights so that they sum to 1\n weights = weights / weights.sum()\n # now wrap the loss\n loss = DeepSupervisionWrapper(loss, weights)\n return loss\n\n def configure_rotation_dummyDA_mirroring_and_inital_patch_size(self):\n \"\"\"\n This function is stupid and certainly one of the weakest spots of this implementation. Not entirely sure how we can fix it.\n \"\"\"\n patch_size = self.configuration_manager.patch_size\n dim = len(patch_size)\n # todo rotation should be defined dynamically based on patch size (more isotropic patch sizes = more rotation)\n if dim == 2:\n do_dummy_2d_data_aug = False\n # todo revisit this parametrization\n if max(patch_size) / min(patch_size) > 1.5:\n rotation_for_DA = {\n 'x': (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi),\n 'y': (0, 0),\n 'z': (0, 0)\n }\n else:\n rotation_for_DA = {\n 'x': (-180. / 360 * 2. * np.pi, 180. / 360 * 2. * np.pi),\n 'y': (0, 0),\n 'z': (0, 0)\n }\n mirror_axes = (0, 1)\n elif dim == 3:\n # todo this is not ideal. We could also have patch_size (64, 16, 128) in which case a full 180deg 2d rot would be bad\n # order of the axes is determined by spacing, not image size\n do_dummy_2d_data_aug = (max(patch_size) / patch_size[0]) > ANISO_THRESHOLD\n if do_dummy_2d_data_aug:\n # why do we rotate 180 deg here all the time? We should also restrict it\n rotation_for_DA = {\n 'x': (-180. / 360 * 2. * np.pi, 180. / 360 * 2. * np.pi),\n 'y': (0, 0),\n 'z': (0, 0)\n }\n else:\n rotation_for_DA = {\n 'x': (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi),\n 'y': (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi),\n 'z': (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi),\n }\n mirror_axes = (0, 1, 2)\n else:\n raise RuntimeError()\n\n # todo this function is stupid. It doesn't even use the correct scale range (we keep things as they were in the\n # old nnunet for now)\n initial_patch_size = get_patch_size(patch_size[-dim:],\n *rotation_for_DA.values(),\n (0.85, 1.25))\n if do_dummy_2d_data_aug:\n initial_patch_size[0] = patch_size[0]\n\n self.print_to_log_file(f'do_dummy_2d_data_aug: {do_dummy_2d_data_aug}')\n self.inference_allowed_mirroring_axes = mirror_axes\n\n return rotation_for_DA, do_dummy_2d_data_aug, initial_patch_size, mirror_axes\n\n def print_to_log_file(self, *args, also_print_to_console=True, add_timestamp=True):\n if self.local_rank == 0:\n timestamp = time()\n dt_object = datetime.fromtimestamp(timestamp)\n\n if add_timestamp:\n args = (f\"{dt_object}:\", *args)\n\n successful = False\n max_attempts = 5\n ctr = 0\n while not successful and ctr < max_attempts:\n try:\n with open(self.log_file, 'a+') as f:\n for a in args:\n f.write(str(a))\n f.write(\" \")\n f.write(\"\\n\")\n successful = True\n except IOError:\n print(f\"{datetime.fromtimestamp(timestamp)}: failed to log: \", sys.exc_info())\n sleep(0.5)\n ctr += 1\n if also_print_to_console:\n print(*args)\n elif also_print_to_console:\n print(*args)\n\n def print_plans(self):\n if self.local_rank == 0:\n dct = deepcopy(self.plans_manager.plans)\n del dct['configurations']\n self.print_to_log_file(f\"\\nThis is the configuration used by this \"\n f\"training:\\nConfiguration name: {self.configuration_name}\\n\",\n self.configuration_manager, '\\n', add_timestamp=False)\n self.print_to_log_file('These are the global plan.json settings:\\n', dct, '\\n', add_timestamp=False)\n\n def configure_optimizers(self):\n optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay,\n momentum=0.99, nesterov=True)\n lr_scheduler = PolyLRScheduler(optimizer, self.initial_lr, self.num_epochs)\n return optimizer, lr_scheduler\n\n def plot_network_architecture(self):\n if self._do_i_compile():\n self.print_to_log_file(\"Unable to plot network architecture: nnUNet_compile is enabled!\")\n return\n\n if self.local_rank == 0:\n try:\n # raise NotImplementedError('hiddenlayer no longer works and we do not have a viable alternative :-(')\n # pip install git+https://github.com/saugatkandel/hiddenlayer.git\n\n # from torchviz import make_dot\n # # not viable.\n # make_dot(tuple(self.network(torch.rand((1, self.num_input_channels,\n # *self.configuration_manager.patch_size),\n # device=self.device)))).render(\n # join(self.output_folder, \"network_architecture.pdf\"), format='pdf')\n # self.optimizer.zero_grad()\n\n # broken.\n\n import hiddenlayer as hl\n g = hl.build_graph(self.network,\n torch.rand((1, self.num_input_channels,\n *self.configuration_manager.patch_size),\n device=self.device),\n transforms=None)\n g.save(join(self.output_folder, \"network_architecture.pdf\"))\n del g\n except Exception as e:\n self.print_to_log_file(\"Unable to plot network architecture:\")\n self.print_to_log_file(e)\n\n # self.print_to_log_file(\"\\nprinting the network instead:\\n\")\n # self.print_to_log_file(self.network)\n # self.print_to_log_file(\"\\n\")\n finally:\n empty_cache(self.device)\n\n def do_split(self):\n \"\"\"\n The default split is a 5 fold CV on all available training cases. nnU-Net will create a split (it is seeded,\n so always the same) and save it as splits_final.pkl file in the preprocessed data directory.\n Sometimes you may want to create your own split for various reasons. For this you will need to create your own\n splits_final.pkl file. If this file is present, nnU-Net is going to use it and whatever splits are defined in\n it. You can create as many splits in this file as you want. Note that if you define only 4 splits (fold 0-3)\n and then set fold=4 when training (that would be the fifth split), nnU-Net will print a warning and proceed to\n use a random 80:20 data split.\n :return:\n \"\"\"\n if self.fold == \"all\":\n # if fold==all then we use all images for training and validation\n case_identifiers = get_case_identifiers(self.preprocessed_dataset_folder)\n tr_keys = case_identifiers\n val_keys = tr_keys\n else:\n splits_file = join(self.preprocessed_dataset_folder_base, \"splits_final.json\")\n dataset = nnUNetDataset(self.preprocessed_dataset_folder, case_identifiers=None,\n num_images_properties_loading_threshold=0,\n folder_with_segs_from_previous_stage=self.folder_with_segs_from_previous_stage)\n # if the split file does not exist we need to create it\n if not isfile(splits_file):\n self.print_to_log_file(\"Creating new 5-fold cross-validation split...\")\n splits = []\n all_keys_sorted = np.sort(list(dataset.keys()))\n kfold = KFold(n_splits=5, shuffle=True, random_state=12345)\n for i, (train_idx, test_idx) in enumerate(kfold.split(all_keys_sorted)):\n train_keys = np.array(all_keys_sorted)[train_idx]\n test_keys = np.array(all_keys_sorted)[test_idx]\n splits.append({})\n splits[-1]['train'] = list(train_keys)\n splits[-1]['val'] = list(test_keys)\n save_json(splits, splits_file)\n\n else:\n self.print_to_log_file(\"Using splits from existing split file:\", splits_file)\n splits = load_json(splits_file)\n self.print_to_log_file(f\"The split file contains {len(splits)} splits.\")\n\n self.print_to_log_file(\"Desired fold for training: %d\" % self.fold)\n if self.fold < len(splits):\n tr_keys = splits[self.fold]['train']\n val_keys = splits[self.fold]['val']\n self.print_to_log_file(\"This split has %d training and %d validation cases.\"\n % (len(tr_keys), len(val_keys)))\n else:\n self.print_to_log_file(\"INFO: You requested fold %d for training but splits \"\n \"contain only %d folds. I am now creating a \"\n \"random (but seeded) 80:20 split!\" % (self.fold, len(splits)))\n # if we request a fold that is not in the split file, create a random 80:20 split\n rnd = np.random.RandomState(seed=12345 + self.fold)\n keys = np.sort(list(dataset.keys()))\n idx_tr = rnd.choice(len(keys), int(len(keys) * 0.8), replace=False)\n idx_val = [i for i in range(len(keys)) if i not in idx_tr]\n tr_keys = [keys[i] for i in idx_tr]\n val_keys = [keys[i] for i in idx_val]\n self.print_to_log_file(\"This random 80:20 split has %d training and %d validation cases.\"\n % (len(tr_keys), len(val_keys)))\n if any([i in val_keys for i in tr_keys]):\n self.print_to_log_file('WARNING: Some validation cases are also in the training set. Please check the '\n 'splits.json or ignore if this is intentional.')\n return tr_keys, val_keys\n\n def get_tr_and_val_datasets(self):\n # create dataset split\n tr_keys, val_keys = self.do_split()\n\n # load the datasets for training and validation. Note that we always draw random samples so we really don't\n # care about distributing training cases across GPUs.\n dataset_tr = nnUNetDataset(self.preprocessed_dataset_folder, tr_keys,\n folder_with_segs_from_previous_stage=self.folder_with_segs_from_previous_stage,\n num_images_properties_loading_threshold=0)\n dataset_val = nnUNetDataset(self.preprocessed_dataset_folder, val_keys,\n folder_with_segs_from_previous_stage=self.folder_with_segs_from_previous_stage,\n num_images_properties_loading_threshold=0)\n return dataset_tr, dataset_val\n\n def get_dataloaders(self):\n # we use the patch size to determine whether we need 2D or 3D dataloaders. We also use it to determine whether\n # we need to use dummy 2D augmentation (in case of 3D training) and what our initial patch size should be\n patch_size = self.configuration_manager.patch_size\n dim = len(patch_size)\n\n # needed for deep supervision: how much do we need to downscale the segmentation targets for the different\n # outputs?\n deep_supervision_scales = self._get_deep_supervision_scales()\n\n rotation_for_DA, do_dummy_2d_data_aug, initial_patch_size, mirror_axes = \\\n self.configure_rotation_dummyDA_mirroring_and_inital_patch_size()\n\n # training pipeline\n tr_transforms = self.get_training_transforms(\n patch_size, rotation_for_DA, deep_supervision_scales, mirror_axes, do_dummy_2d_data_aug,\n order_resampling_data=3, order_resampling_seg=1,\n use_mask_for_norm=self.configuration_manager.use_mask_for_norm,\n is_cascaded=self.is_cascaded, foreground_labels=self.label_manager.foreground_labels,\n regions=self.label_manager.foreground_regions if self.label_manager.has_regions else None,\n ignore_label=self.label_manager.ignore_label)\n\n # validation pipeline\n val_transforms = self.get_validation_transforms(deep_supervision_scales,\n is_cascaded=self.is_cascaded,\n foreground_labels=self.label_manager.foreground_labels,\n regions=self.label_manager.foreground_regions if\n self.label_manager.has_regions else None,\n ignore_label=self.label_manager.ignore_label)\n\n dl_tr, dl_val = self.get_plain_dataloaders(initial_patch_size, dim)\n\n allowed_num_processes = get_allowed_n_proc_DA()\n if allowed_num_processes == 0:\n mt_gen_train = SingleThreadedAugmenter(dl_tr, tr_transforms)\n mt_gen_val = SingleThreadedAugmenter(dl_val, val_transforms)\n else:\n mt_gen_train = LimitedLenWrapper(self.num_iterations_per_epoch, data_loader=dl_tr, transform=tr_transforms,\n num_processes=allowed_num_processes, num_cached=6, seeds=None,\n pin_memory=self.device.type == 'cuda', wait_time=0.02)\n mt_gen_val = LimitedLenWrapper(self.num_val_iterations_per_epoch, data_loader=dl_val,\n transform=val_transforms, num_processes=max(1, allowed_num_processes // 2),\n num_cached=3, seeds=None, pin_memory=self.device.type == 'cuda',\n wait_time=0.02)\n return mt_gen_train, mt_gen_val\n\n def get_plain_dataloaders(self, initial_patch_size: Tuple[int, ...], dim: int):\n dataset_tr, dataset_val = self.get_tr_and_val_datasets()\n\n if dim == 2:\n dl_tr = nnUNetDataLoader2D(dataset_tr, self.batch_size,\n initial_patch_size,\n self.configuration_manager.patch_size,\n self.label_manager,\n oversample_foreground_percent=self.oversample_foreground_percent,\n sampling_probabilities=None, pad_sides=None)\n dl_val = nnUNetDataLoader2D(dataset_val, self.batch_size,\n self.configuration_manager.patch_size,\n self.configuration_manager.patch_size,\n self.label_manager,\n oversample_foreground_percent=self.oversample_foreground_percent,\n sampling_probabilities=None, pad_sides=None)\n else:\n dl_tr = nnUNetDataLoader3D(dataset_tr, self.batch_size,\n initial_patch_size,\n self.configuration_manager.patch_size,\n self.label_manager,\n oversample_foreground_percent=self.oversample_foreground_percent,\n sampling_probabilities=None, pad_sides=None)\n dl_val = nnUNetDataLoader3D(dataset_val, self.batch_size,\n self.configuration_manager.patch_size,\n self.configuration_manager.patch_size,\n self.label_manager,\n oversample_foreground_percent=self.oversample_foreground_percent,\n sampling_probabilities=None, pad_sides=None)\n return dl_tr, dl_val\n\n @staticmethod\n def get_training_transforms(patch_size: Union[np.ndarray, Tuple[int]],\n rotation_for_DA: dict,\n deep_supervision_scales: Union[List, Tuple],\n mirror_axes: Tuple[int, ...],\n do_dummy_2d_data_aug: bool,\n order_resampling_data: int = 3,\n order_resampling_seg: int = 1,\n border_val_seg: int = -1,\n use_mask_for_norm: List[bool] = None,\n is_cascaded: bool = False,\n foreground_labels: Union[Tuple[int, ...], List[int]] = None,\n regions: List[Union[List[int], Tuple[int, ...], int]] = None,\n ignore_label: int = None) -> AbstractTransform:\n tr_transforms = []\n if do_dummy_2d_data_aug:\n ignore_axes = (0,)\n tr_transforms.append(Convert3DTo2DTransform())\n patch_size_spatial = patch_size[1:]\n else:\n patch_size_spatial = patch_size\n ignore_axes = None\n\n tr_transforms.append(SpatialTransform(\n patch_size_spatial, patch_center_dist_from_border=None,\n do_elastic_deform=False, alpha=(0, 0), sigma=(0, 0),\n do_rotation=True, angle_x=rotation_for_DA['x'], angle_y=rotation_for_DA['y'], angle_z=rotation_for_DA['z'],\n p_rot_per_axis=1, # todo experiment with this\n do_scale=True, scale=(0.7, 1.4),\n border_mode_data=\"constant\", border_cval_data=0, order_data=order_resampling_data,\n border_mode_seg=\"constant\", border_cval_seg=border_val_seg, order_seg=order_resampling_seg,\n random_crop=False, # random cropping is part of our dataloaders\n p_el_per_sample=0, p_scale_per_sample=0.2, p_rot_per_sample=0.2,\n independent_scale_for_each_axis=False # todo experiment with this\n ))\n\n if do_dummy_2d_data_aug:\n tr_transforms.append(Convert2DTo3DTransform())\n\n tr_transforms.append(GaussianNoiseTransform(p_per_sample=0.1))\n tr_transforms.append(GaussianBlurTransform((0.5, 1.), different_sigma_per_channel=True, p_per_sample=0.2,\n p_per_channel=0.5))\n tr_transforms.append(BrightnessMultiplicativeTransform(multiplier_range=(0.75, 1.25), p_per_sample=0.15))\n tr_transforms.append(ContrastAugmentationTransform(p_per_sample=0.15))\n tr_transforms.append(SimulateLowResolutionTransform(zoom_range=(0.5, 1), per_channel=True,\n p_per_channel=0.5,\n order_downsample=0, order_upsample=3, p_per_sample=0.25,\n ignore_axes=ignore_axes))\n tr_transforms.append(GammaTransform((0.7, 1.5), True, True, retain_stats=True, p_per_sample=0.1))\n tr_transforms.append(GammaTransform((0.7, 1.5), False, True, retain_stats=True, p_per_sample=0.3))\n\n if mirror_axes is not None and len(mirror_axes) > 0:\n tr_transforms.append(MirrorTransform(mirror_axes))\n\n if use_mask_for_norm is not None and any(use_mask_for_norm):\n tr_transforms.append(MaskTransform([i for i in range(len(use_mask_for_norm)) if use_mask_for_norm[i]],\n mask_idx_in_seg=0, set_outside_to=0))\n\n tr_transforms.append(RemoveLabelTransform(-1, 0))\n\n if is_cascaded:\n assert foreground_labels is not None, 'We need foreground_labels for cascade augmentations'\n tr_transforms.append(MoveSegAsOneHotToData(1, foreground_labels, 'seg', 'data'))\n tr_transforms.append(ApplyRandomBinaryOperatorTransform(\n channel_idx=list(range(-len(foreground_labels), 0)),\n p_per_sample=0.4,\n key=\"data\",\n strel_size=(1, 8),\n p_per_label=1))\n tr_transforms.append(\n RemoveRandomConnectedComponentFromOneHotEncodingTransform(\n channel_idx=list(range(-len(foreground_labels), 0)),\n key=\"data\",\n p_per_sample=0.2,\n fill_with_other_class_p=0,\n dont_do_if_covers_more_than_x_percent=0.15))\n\n tr_transforms.append(RenameTransform('seg', 'target', True))\n\n if regions is not None:\n # the ignore label must also be converted\n tr_transforms.append(ConvertSegmentationToRegionsTransform(list(regions) + [ignore_label]\n if ignore_label is not None else regions,\n 'target', 'target'))\n\n if deep_supervision_scales is not None:\n tr_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, input_key='target',\n output_key='target'))\n tr_transforms.append(NumpyToTensor(['data', 'target'], 'float'))\n tr_transforms = Compose(tr_transforms)\n return tr_transforms\n\n @staticmethod\n def get_validation_transforms(deep_supervision_scales: Union[List, Tuple],\n is_cascaded: bool = False,\n foreground_labels: Union[Tuple[int, ...], List[int]] = None,\n regions: List[Union[List[int], Tuple[int, ...], int]] = None,\n ignore_label: int = None) -> AbstractTransform:\n val_transforms = []\n val_transforms.append(RemoveLabelTransform(-1, 0))\n\n if is_cascaded:\n val_transforms.append(MoveSegAsOneHotToData(1, foreground_labels, 'seg', 'data'))\n\n val_transforms.append(RenameTransform('seg', 'target', True))\n\n if regions is not None:\n # the ignore label must also be converted\n val_transforms.append(ConvertSegmentationToRegionsTransform(list(regions) + [ignore_label]\n if ignore_label is not None else regions,\n 'target', 'target'))\n\n if deep_supervision_scales is not None:\n val_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, input_key='target',\n output_key='target'))\n\n val_transforms.append(NumpyToTensor(['data', 'target'], 'float'))\n val_transforms = Compose(val_transforms)\n return val_transforms\n\n def set_deep_supervision_enabled(self, enabled: bool):\n \"\"\"\n This function is specific for the default architecture in nnU-Net. If you change the architecture, there are\n chances you need to change this as well!\n \"\"\"\n if self.is_ddp:\n self.network.module.decoder.deep_supervision = enabled\n else:\n self.network.decoder.deep_supervision = enabled\n\n def on_train_start(self):\n if not self.was_initialized:\n self.initialize()\n\n maybe_mkdir_p(self.output_folder)\n\n # make sure deep supervision is on in the network\n self.set_deep_supervision_enabled(True)\n\n self.print_plans()\n empty_cache(self.device)\n\n # maybe unpack\n if self.unpack_dataset and self.local_rank == 0:\n self.print_to_log_file('unpacking dataset...')\n unpack_dataset(self.preprocessed_dataset_folder, unpack_segmentation=True, overwrite_existing=False,\n num_processes=max(1, round(get_allowed_n_proc_DA() // 2)))\n self.print_to_log_file('unpacking done...')\n\n if self.is_ddp:\n dist.barrier()\n\n # dataloaders must be instantiated here because they need access to the training data which may not be present\n # when doing inference\n self.dataloader_train, self.dataloader_val = self.get_dataloaders()\n\n # copy plans and dataset.json so that they can be used for restoring everything we need for inference\n save_json(self.plans_manager.plans, join(self.output_folder_base, 'plans.json'), sort_keys=False)\n save_json(self.dataset_json, join(self.output_folder_base, 'dataset.json'), sort_keys=False)\n\n # we don't really need the fingerprint but its still handy to have it with the others\n shutil.copy(join(self.preprocessed_dataset_folder_base, 'dataset_fingerprint.json'),\n join(self.output_folder_base, 'dataset_fingerprint.json'))\n\n # produces a pdf in output folder\n self.plot_network_architecture()\n\n self._save_debug_information()\n\n # print(f\"batch size: {self.batch_size}\")\n # print(f\"oversample: {self.oversample_foreground_percent}\")\n\n def on_train_end(self):\n # dirty hack because on_epoch_end increments the epoch counter and this is executed afterwards.\n # This will lead to the wrong current epoch to be stored\n self.current_epoch -= 1\n self.save_checkpoint(join(self.output_folder, \"checkpoint_final.pth\"))\n self.current_epoch += 1\n\n # now we can delete latest\n if self.local_rank == 0 and isfile(join(self.output_folder, \"checkpoint_latest.pth\")):\n os.remove(join(self.output_folder, \"checkpoint_latest.pth\"))\n\n # shut down dataloaders\n old_stdout = sys.stdout\n with open(os.devnull, 'w') as f:\n sys.stdout = f\n if self.dataloader_train is not None:\n self.dataloader_train._finish()\n if self.dataloader_val is not None:\n self.dataloader_val._finish()\n sys.stdout = old_stdout\n\n empty_cache(self.device)\n self.print_to_log_file(\"Training done.\")\n\n def on_train_epoch_start(self):\n self.network.train()\n self.lr_scheduler.step(self.current_epoch)\n self.print_to_log_file('')\n self.print_to_log_file(f'Epoch {self.current_epoch}')\n self.print_to_log_file(\n f\"Current learning rate: {np.round(self.optimizer.param_groups[0]['lr'], decimals=5)}\")\n # lrs are the same for all workers so we don't need to gather them in case of DDP training\n self.logger.log('lrs', self.optimizer.param_groups[0]['lr'], self.current_epoch)\n\n def train_step(self, batch: dict) -> dict:\n data = batch['data']\n target = batch['target']\n\n data = data.to(self.device, non_blocking=True)\n if isinstance(target, list):\n target = [i.to(self.device, non_blocking=True) for i in target]\n else:\n target = target.to(self.device, non_blocking=True)\n\n self.optimizer.zero_grad(set_to_none=True)\n # Autocast is a little bitch.\n # If the device_type is 'cpu' then it's slow as heck and needs to be disabled.\n # If the device_type is 'mps' then it will complain that mps is not implemented, even if enabled=False is set. Whyyyyyyy. (this is why we don't make use of enabled=False)\n # So autocast will only be active if we have a cuda device.\n with autocast(self.device.type, enabled=True) if self.device.type == 'cuda' else dummy_context():\n output = self.network(data)\n # del data\n l = self.loss(output, target)\n\n if self.grad_scaler is not None:\n self.grad_scaler.scale(l).backward()\n self.grad_scaler.unscale_(self.optimizer)\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.grad_scaler.step(self.optimizer)\n self.grad_scaler.update()\n else:\n l.backward()\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.optimizer.step()\n return {'loss': l.detach().cpu().numpy()}\n\n def on_train_epoch_end(self, train_outputs: List[dict]):\n outputs = collate_outputs(train_outputs)\n\n if self.is_ddp:\n losses_tr = [None for _ in range(dist.get_world_size())]\n dist.all_gather_object(losses_tr, outputs['loss'])\n loss_here = np.vstack(losses_tr).mean()\n else:\n loss_here = np.mean(outputs['loss'])\n\n self.logger.log('train_losses', loss_here, self.current_epoch)\n\n def on_validation_epoch_start(self):\n self.network.eval()\n\n def validation_step(self, batch: dict) -> dict:\n data = batch['data']\n target = batch['target']\n\n data = data.to(self.device, non_blocking=True)\n if isinstance(target, list):\n target = [i.to(self.device, non_blocking=True) for i in target]\n else:\n target = target.to(self.device, non_blocking=True)\n\n # Autocast is a little bitch.\n # If the device_type is 'cpu' then it's slow as heck and needs to be disabled.\n # If the device_type is 'mps' then it will complain that mps is not implemented, even if enabled=False is set. Whyyyyyyy. (this is why we don't make use of enabled=False)\n # So autocast will only be active if we have a cuda device.\n with autocast(self.device.type, enabled=True) if self.device.type == 'cuda' else dummy_context():\n output = self.network(data)\n del data\n l = self.loss(output, target)\n\n # we only need the output with the highest output resolution\n output = output[0]\n target = target[0]\n\n # the following is needed for online evaluation. Fake dice (green line)\n axes = [0] + list(range(2, output.ndim))\n\n if self.label_manager.has_regions:\n predicted_segmentation_onehot = (torch.sigmoid(output) > 0.5).long()\n else:\n # no need for softmax\n output_seg = output.argmax(1)[:, None]\n predicted_segmentation_onehot = torch.zeros(output.shape, device=output.device, dtype=torch.float32)\n predicted_segmentation_onehot.scatter_(1, output_seg, 1)\n del output_seg\n\n if self.label_manager.has_ignore_label:\n if not self.label_manager.has_regions:\n mask = (target != self.label_manager.ignore_label).float()\n # CAREFUL that you don't rely on target after this line!\n target[target == self.label_manager.ignore_label] = 0\n else:\n mask = 1 - target[:, -1:]\n # CAREFUL that you don't rely on target after this line!\n target = target[:, :-1]\n else:\n mask = None\n\n tp, fp, fn, _ = get_tp_fp_fn_tn(predicted_segmentation_onehot, target, axes=axes, mask=mask)\n\n tp_hard = tp.detach().cpu().numpy()\n fp_hard = fp.detach().cpu().numpy()\n fn_hard = fn.detach().cpu().numpy()\n if not self.label_manager.has_regions:\n # if we train with regions all segmentation heads predict some kind of foreground. In conventional\n # (softmax training) there needs tobe one output for the background. We are not interested in the\n # background Dice\n # [1:] in order to remove background\n tp_hard = tp_hard[1:]\n fp_hard = fp_hard[1:]\n fn_hard = fn_hard[1:]\n\n return {'loss': l.detach().cpu().numpy(), 'tp_hard': tp_hard, 'fp_hard': fp_hard, 'fn_hard': fn_hard}\n\n def on_validation_epoch_end(self, val_outputs: List[dict]):\n outputs_collated = collate_outputs(val_outputs)\n tp = np.sum(outputs_collated['tp_hard'], 0)\n fp = np.sum(outputs_collated['fp_hard'], 0)\n fn = np.sum(outputs_collated['fn_hard'], 0)\n\n if self.is_ddp:\n world_size = dist.get_world_size()\n\n tps = [None for _ in range(world_size)]\n dist.all_gather_object(tps, tp)\n tp = np.vstack([i[None] for i in tps]).sum(0)\n\n fps = [None for _ in range(world_size)]\n dist.all_gather_object(fps, fp)\n fp = np.vstack([i[None] for i in fps]).sum(0)\n\n fns = [None for _ in range(world_size)]\n dist.all_gather_object(fns, fn)\n fn = np.vstack([i[None] for i in fns]).sum(0)\n\n losses_val = [None for _ in range(world_size)]\n dist.all_gather_object(losses_val, outputs_collated['loss'])\n loss_here = np.vstack(losses_val).mean()\n else:\n loss_here = np.mean(outputs_collated['loss'])\n\n global_dc_per_class = [i for i in [2 * i / (2 * i + j + k) for i, j, k in\n zip(tp, fp, fn)]]\n mean_fg_dice = np.nanmean(global_dc_per_class)\n self.logger.log('mean_fg_dice', mean_fg_dice, self.current_epoch)\n self.logger.log('dice_per_class_or_region', global_dc_per_class, self.current_epoch)\n self.logger.log('val_losses', loss_here, self.current_epoch)\n\n def on_epoch_start(self):\n self.logger.log('epoch_start_timestamps', time(), self.current_epoch)\n\n def on_epoch_end(self):\n self.logger.log('epoch_end_timestamps', time(), self.current_epoch)\n\n # todo find a solution for this stupid shit\n self.print_to_log_file('train_loss', np.round(self.logger.my_fantastic_logging['train_losses'][-1], decimals=4))\n self.print_to_log_file('val_loss', np.round(self.logger.my_fantastic_logging['val_losses'][-1], decimals=4))\n self.print_to_log_file('Pseudo dice', [np.round(i, decimals=4) for i in\n self.logger.my_fantastic_logging['dice_per_class_or_region'][-1]])\n self.print_to_log_file(\n f\"Epoch time: {np.round(self.logger.my_fantastic_logging['epoch_end_timestamps'][-1] - self.logger.my_fantastic_logging['epoch_start_timestamps'][-1], decimals=2)} s\")\n\n # handling periodic checkpointing\n current_epoch = self.current_epoch\n if (current_epoch + 1) % self.save_every == 0 and current_epoch != (self.num_epochs - 1):\n self.save_checkpoint(join(self.output_folder, 'checkpoint_latest.pth'))\n\n # handle 'best' checkpointing. ema_fg_dice is computed by the logger and can be accessed like this\n if self._best_ema is None or self.logger.my_fantastic_logging['ema_fg_dice'][-1] > self._best_ema:\n self._best_ema = self.logger.my_fantastic_logging['ema_fg_dice'][-1]\n self.print_to_log_file(f\"Yayy! New best EMA pseudo Dice: {np.round(self._best_ema, decimals=4)}\")\n self.save_checkpoint(join(self.output_folder, 'checkpoint_best.pth'))\n\n if self.local_rank == 0:\n self.logger.plot_progress_png(self.output_folder)\n\n self.current_epoch += 1\n\n def save_checkpoint(self, filename: str) -> None:\n if self.local_rank == 0:\n if not self.disable_checkpointing:\n if self.is_ddp:\n mod = self.network.module\n else:\n mod = self.network\n if isinstance(mod, OptimizedModule):\n mod = mod._orig_mod\n\n checkpoint = {\n 'network_weights': mod.state_dict(),\n 'optimizer_state': self.optimizer.state_dict(),\n 'grad_scaler_state': self.grad_scaler.state_dict() if self.grad_scaler is not None else None,\n 'logging': self.logger.get_checkpoint(),\n '_best_ema': self._best_ema,\n 'current_epoch': self.current_epoch + 1,\n 'init_args': self.my_init_kwargs,\n 'trainer_name': self.__class__.__name__,\n 'inference_allowed_mirroring_axes': self.inference_allowed_mirroring_axes,\n }\n torch.save(checkpoint, filename)\n else:\n self.print_to_log_file('No checkpoint written, checkpointing is disabled')\n\n def load_checkpoint(self, filename_or_checkpoint: Union[dict, str]) -> None:\n if not self.was_initialized:\n self.initialize()\n\n if isinstance(filename_or_checkpoint, str):\n checkpoint = torch.load(filename_or_checkpoint, map_location=self.device)\n # if state dict comes from nn.DataParallel but we use non-parallel model here then the state dict keys do not\n # match. Use heuristic to make it match\n new_state_dict = {}\n for k, value in checkpoint['network_weights'].items():\n key = k\n if key not in self.network.state_dict().keys() and key.startswith('module.'):\n key = key[7:]\n new_state_dict[key] = value\n\n self.my_init_kwargs = checkpoint['init_args']\n self.current_epoch = checkpoint['current_epoch']\n self.logger.load_checkpoint(checkpoint['logging'])\n self._best_ema = checkpoint['_best_ema']\n self.inference_allowed_mirroring_axes = checkpoint[\n 'inference_allowed_mirroring_axes'] if 'inference_allowed_mirroring_axes' in checkpoint.keys() else self.inference_allowed_mirroring_axes\n\n # messing with state dict naming schemes. Facepalm.\n if self.is_ddp:\n if isinstance(self.network.module, OptimizedModule):\n self.network.module._orig_mod.load_state_dict(new_state_dict)\n else:\n self.network.module.load_state_dict(new_state_dict)\n else:\n if isinstance(self.network, OptimizedModule):\n self.network._orig_mod.load_state_dict(new_state_dict)\n else:\n self.network.load_state_dict(new_state_dict)\n self.optimizer.load_state_dict(checkpoint['optimizer_state'])\n if self.grad_scaler is not None:\n if checkpoint['grad_scaler_state'] is not None:\n self.grad_scaler.load_state_dict(checkpoint['grad_scaler_state'])\n\n def perform_actual_validation(self, save_probabilities: bool = False):\n self.set_deep_supervision_enabled(False)\n self.network.eval()\n\n predictor = nnUNetPredictor(tile_step_size=0.5, use_gaussian=True, use_mirroring=True,\n perform_everything_on_gpu=True, device=self.device, verbose=False,\n verbose_preprocessing=False, allow_tqdm=False)\n predictor.manual_initialization(self.network, self.plans_manager, self.configuration_manager, None,\n self.dataset_json, self.__class__.__name__,\n self.inference_allowed_mirroring_axes)\n\n with multiprocessing.get_context(\"spawn\").Pool(default_num_processes) as segmentation_export_pool:\n worker_list = [i for i in segmentation_export_pool._pool]\n validation_output_folder = join(self.output_folder, 'validation')\n maybe_mkdir_p(validation_output_folder)\n\n # we cannot use self.get_tr_and_val_datasets() here because we might be DDP and then we have to distribute\n # the validation keys across the workers.\n _, val_keys = self.do_split()\n if self.is_ddp:\n val_keys = val_keys[self.local_rank:: dist.get_world_size()]\n\n dataset_val = nnUNetDataset(self.preprocessed_dataset_folder, val_keys,\n folder_with_segs_from_previous_stage=self.folder_with_segs_from_previous_stage,\n num_images_properties_loading_threshold=0)\n\n next_stages = self.configuration_manager.next_stage_names\n\n if next_stages is not None:\n _ = [maybe_mkdir_p(join(self.output_folder_base, 'predicted_next_stage', n)) for n in next_stages]\n\n results = []\n\n for k in dataset_val.keys():\n proceed = not check_workers_alive_and_busy(segmentation_export_pool, worker_list, results,\n allowed_num_queued=2)\n while not proceed:\n sleep(0.1)\n proceed = not check_workers_alive_and_busy(segmentation_export_pool, worker_list, results,\n allowed_num_queued=2)\n\n self.print_to_log_file(f\"predicting {k}\")\n data, seg, properties = dataset_val.load_case(k)\n\n if self.is_cascaded:\n data = np.vstack((data, convert_labelmap_to_one_hot(seg[-1], self.label_manager.foreground_labels,\n output_dtype=data.dtype)))\n with warnings.catch_warnings():\n # ignore 'The given NumPy array is not writable' warning\n warnings.simplefilter(\"ignore\")\n data = torch.from_numpy(data)\n\n output_filename_truncated = join(validation_output_folder, k)\n\n try:\n prediction = predictor.predict_sliding_window_return_logits(data)\n except RuntimeError:\n predictor.perform_everything_on_gpu = False\n prediction = predictor.predict_sliding_window_return_logits(data)\n predictor.perform_everything_on_gpu = True\n\n prediction = prediction.cpu()\n\n # this needs to go into background processes\n results.append(\n segmentation_export_pool.starmap_async(\n export_prediction_from_logits, (\n (prediction, properties, self.configuration_manager, self.plans_manager,\n self.dataset_json, output_filename_truncated, save_probabilities),\n )\n )\n )\n # for debug purposes\n # export_prediction(prediction_for_export, properties, self.configuration, self.plans, self.dataset_json,\n # output_filename_truncated, save_probabilities)\n\n # if needed, export the softmax prediction for the next stage\n if next_stages is not None:\n for n in next_stages:\n next_stage_config_manager = self.plans_manager.get_configuration(n)\n expected_preprocessed_folder = join(nnUNet_preprocessed, self.plans_manager.dataset_name,\n next_stage_config_manager.data_identifier)\n\n try:\n # we do this so that we can use load_case and do not have to hard code how loading training cases is implemented\n tmp = nnUNetDataset(expected_preprocessed_folder, [k],\n num_images_properties_loading_threshold=0)\n d, s, p = tmp.load_case(k)\n except FileNotFoundError:\n self.print_to_log_file(\n f\"Predicting next stage {n} failed for case {k} because the preprocessed file is missing! \"\n f\"Run the preprocessing for this configuration first!\")\n continue\n\n target_shape = d.shape[1:]\n output_folder = join(self.output_folder_base, 'predicted_next_stage', n)\n output_file = join(output_folder, k + '.npz')\n\n # resample_and_save(prediction, target_shape, output_file, self.plans_manager, self.configuration_manager, properties,\n # self.dataset_json)\n results.append(segmentation_export_pool.starmap_async(\n resample_and_save, (\n (prediction, target_shape, output_file, self.plans_manager,\n self.configuration_manager,\n properties,\n self.dataset_json),\n )\n ))\n\n _ = [r.get() for r in results]\n\n if self.is_ddp:\n dist.barrier()\n\n if self.local_rank == 0:\n metrics = compute_metrics_on_folder(join(self.preprocessed_dataset_folder_base, 'gt_segmentations'),\n validation_output_folder,\n join(validation_output_folder, 'summary.json'),\n self.plans_manager.image_reader_writer_class(),\n self.dataset_json[\"file_ending\"],\n self.label_manager.foreground_regions if self.label_manager.has_regions else\n self.label_manager.foreground_labels,\n self.label_manager.ignore_label, chill=True)\n self.print_to_log_file(\"Validation complete\", also_print_to_console=True)\n self.print_to_log_file(\"Mean Validation Dice: \", (metrics['foreground_mean'][\"Dice\"]), also_print_to_console=True)\n\n self.set_deep_supervision_enabled(True)\n compute_gaussian.cache_clear()\n\n def run_training(self):\n self.on_train_start()\n\n for epoch in range(self.current_epoch, self.num_epochs):\n self.on_epoch_start()\n\n self.on_train_epoch_start()\n train_outputs = []\n for batch_id in range(self.num_iterations_per_epoch):\n train_outputs.append(self.train_step(next(self.dataloader_train)))\n self.on_train_epoch_end(train_outputs)\n\n with torch.no_grad():\n self.on_validation_epoch_start()\n val_outputs = []\n for batch_id in range(self.num_val_iterations_per_epoch):\n val_outputs.append(self.validation_step(next(self.dataloader_val)))\n self.on_validation_epoch_end(val_outputs)\n\n self.on_epoch_end()\n\n self.on_train_end()" }, { "identifier": "dummy_context", "path": "nnunetv2/utilities/helpers.py", "snippet": "class dummy_context(object):\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass" }, { "identifier": "determine_num_input_channels", "path": "nnunetv2/utilities/label_handling/label_handling.py", "snippet": "def determine_num_input_channels(plans_manager: PlansManager,\n configuration_or_config_manager: Union[str, ConfigurationManager],\n dataset_json: dict) -> int:\n if isinstance(configuration_or_config_manager, str):\n config_manager = plans_manager.get_configuration(configuration_or_config_manager)\n else:\n config_manager = configuration_or_config_manager\n\n label_manager = plans_manager.get_label_manager(dataset_json)\n num_modalities = len(dataset_json['modality']) if 'modality' in dataset_json.keys() else len(dataset_json['channel_names'])\n\n # cascade has different number of input channels\n if config_manager.previous_stage_name is not None:\n num_label_inputs = len(label_manager.foreground_labels)\n num_input_channels = num_modalities + num_label_inputs\n else:\n num_input_channels = num_modalities\n return num_input_channels" } ]
import torch from torch import autocast from nnunetv2.training.loss.compound_losses import DC_and_BCE_loss, DC_and_CE_loss from nnunetv2.training.loss.dice import get_tp_fp_fn_tn, MemoryEfficientSoftDiceLoss from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer from nnunetv2.utilities.helpers import dummy_context from nnunetv2.utilities.label_handling.label_handling import determine_num_input_channels from torch.nn.parallel import DistributedDataParallel as DDP
17,293
class nnUNetTrainerNoDeepSupervision(nnUNetTrainer): def _build_loss(self): if self.label_manager.has_regions: loss = DC_and_BCE_loss({}, {'batch_dice': self.configuration_manager.batch_dice, 'do_bg': True, 'smooth': 1e-5, 'ddp': self.is_ddp}, use_ignore_label=self.label_manager.ignore_label is not None, dice_class=MemoryEfficientSoftDiceLoss) else: loss = DC_and_CE_loss({'batch_dice': self.configuration_manager.batch_dice, 'smooth': 1e-5, 'do_bg': False, 'ddp': self.is_ddp}, {}, weight_ce=1, weight_dice=1, ignore_label=self.label_manager.ignore_label, dice_class=MemoryEfficientSoftDiceLoss) return loss def _get_deep_supervision_scales(self): return None def initialize(self): if not self.was_initialized:
class nnUNetTrainerNoDeepSupervision(nnUNetTrainer): def _build_loss(self): if self.label_manager.has_regions: loss = DC_and_BCE_loss({}, {'batch_dice': self.configuration_manager.batch_dice, 'do_bg': True, 'smooth': 1e-5, 'ddp': self.is_ddp}, use_ignore_label=self.label_manager.ignore_label is not None, dice_class=MemoryEfficientSoftDiceLoss) else: loss = DC_and_CE_loss({'batch_dice': self.configuration_manager.batch_dice, 'smooth': 1e-5, 'do_bg': False, 'ddp': self.is_ddp}, {}, weight_ce=1, weight_dice=1, ignore_label=self.label_manager.ignore_label, dice_class=MemoryEfficientSoftDiceLoss) return loss def _get_deep_supervision_scales(self): return None def initialize(self): if not self.was_initialized:
self.num_input_channels = determine_num_input_channels(self.plans_manager, self.configuration_manager,
6
2023-12-04 19:43:14+00:00
24k
opisaac9001/TTS-With-ooba-and-voice
TTS/tts/models/glow_tts.py
[ { "identifier": "GlowTTSConfig", "path": "TTS/tts/configs/glow_tts_config.py", "snippet": "class GlowTTSConfig(BaseTTSConfig):\n \"\"\"Defines parameters for GlowTTS model.\n\n Example:\n\n >>> from TTS.tts.configs.glow_tts_config import GlowTTSConfig\n >>> config = GlowTTSConfig()\n\n Args:\n model(str):\n Model name used for selecting the right model at initialization. Defaults to `glow_tts`.\n encoder_type (str):\n Type of the encoder used by the model. Look at `TTS.tts.layers.glow_tts.encoder` for more details.\n Defaults to `rel_pos_transformers`.\n encoder_params (dict):\n Parameters used to define the encoder network. Look at `TTS.tts.layers.glow_tts.encoder` for more details.\n Defaults to `{\"kernel_size\": 3, \"dropout_p\": 0.1, \"num_layers\": 6, \"num_heads\": 2, \"hidden_channels_ffn\": 768}`\n use_encoder_prenet (bool):\n enable / disable the use of a prenet for the encoder. Defaults to True.\n hidden_channels_enc (int):\n Number of base hidden channels used by the encoder network. It defines the input and the output channel sizes,\n and for some encoder types internal hidden channels sizes too. Defaults to 192.\n hidden_channels_dec (int):\n Number of base hidden channels used by the decoder WaveNet network. Defaults to 192 as in the original work.\n hidden_channels_dp (int):\n Number of layer channels of the duration predictor network. Defaults to 256 as in the original work.\n mean_only (bool):\n If true predict only the mean values by the decoder flow. Defaults to True.\n out_channels (int):\n Number of channels of the model output tensor. Defaults to 80.\n num_flow_blocks_dec (int):\n Number of decoder blocks. Defaults to 12.\n inference_noise_scale (float):\n Noise scale used at inference. Defaults to 0.33.\n kernel_size_dec (int):\n Decoder kernel size. Defaults to 5\n dilation_rate (int):\n Rate to increase dilation by each layer in a decoder block. Defaults to 1.\n num_block_layers (int):\n Number of decoder layers in each decoder block. Defaults to 4.\n dropout_p_dec (float):\n Dropout rate for decoder. Defaults to 0.1.\n num_speaker (int):\n Number of speaker to define the size of speaker embedding layer. Defaults to 0.\n c_in_channels (int):\n Number of speaker embedding channels. It is set to 512 if embeddings are learned. Defaults to 0.\n num_splits (int):\n Number of split levels in inversible conv1x1 operation. Defaults to 4.\n num_squeeze (int):\n Number of squeeze levels. When squeezing channels increases and time steps reduces by the factor\n 'num_squeeze'. Defaults to 2.\n sigmoid_scale (bool):\n enable/disable sigmoid scaling in decoder. Defaults to False.\n mean_only (bool):\n If True, encoder only computes mean value and uses constant variance for each time step. Defaults to true.\n encoder_type (str):\n Encoder module type. Possible values are`[\"rel_pos_transformer\", \"gated_conv\", \"residual_conv_bn\", \"time_depth_separable\"]`\n Check `TTS.tts.layers.glow_tts.encoder` for more details. Defaults to `rel_pos_transformers` as in the original paper.\n encoder_params (dict):\n Encoder module parameters. Defaults to None.\n d_vector_dim (int):\n Channels of external speaker embedding vectors. Defaults to 0.\n data_dep_init_steps (int):\n Number of steps used for computing normalization parameters at the beginning of the training. GlowTTS uses\n Activation Normalization that pre-computes normalization stats at the beginning and use the same values\n for the rest. Defaults to 10.\n style_wav_for_test (str):\n Path to the wav file used for changing the style of the speech. Defaults to None.\n inference_noise_scale (float):\n Variance used for sampling the random noise added to the decoder's input at inference. Defaults to 0.0.\n length_scale (float):\n Multiply the predicted durations with this value to change the speech speed. Defaults to 1.\n use_speaker_embedding (bool):\n enable / disable using speaker embeddings for multi-speaker models. If set True, the model is\n in the multi-speaker mode. Defaults to False.\n use_d_vector_file (bool):\n enable /disable using external speaker embeddings in place of the learned embeddings. Defaults to False.\n d_vector_file (str):\n Path to the file including pre-computed speaker embeddings. Defaults to None.\n noam_schedule (bool):\n enable / disable the use of Noam LR scheduler. Defaults to False.\n warmup_steps (int):\n Number of warm-up steps for the Noam scheduler. Defaults 4000.\n lr (float):\n Initial learning rate. Defaults to `1e-3`.\n wd (float):\n Weight decay coefficient. Defaults to `1e-7`.\n min_seq_len (int):\n Minimum input sequence length to be used at training.\n max_seq_len (int):\n Maximum input sequence length to be used at training. Larger values result in more VRAM usage.\n \"\"\"\n\n model: str = \"glow_tts\"\n\n # model params\n num_chars: int = None\n encoder_type: str = \"rel_pos_transformer\"\n encoder_params: dict = field(\n default_factory=lambda: {\n \"kernel_size\": 3,\n \"dropout_p\": 0.1,\n \"num_layers\": 6,\n \"num_heads\": 2,\n \"hidden_channels_ffn\": 768,\n }\n )\n use_encoder_prenet: bool = True\n hidden_channels_enc: int = 192\n hidden_channels_dec: int = 192\n hidden_channels_dp: int = 256\n dropout_p_dp: float = 0.1\n dropout_p_dec: float = 0.05\n mean_only: bool = True\n out_channels: int = 80\n num_flow_blocks_dec: int = 12\n inference_noise_scale: float = 0.33\n kernel_size_dec: int = 5\n dilation_rate: int = 1\n num_block_layers: int = 4\n num_speakers: int = 0\n c_in_channels: int = 0\n num_splits: int = 4\n num_squeeze: int = 2\n sigmoid_scale: bool = False\n encoder_type: str = \"rel_pos_transformer\"\n encoder_params: dict = field(\n default_factory=lambda: {\n \"kernel_size\": 3,\n \"dropout_p\": 0.1,\n \"num_layers\": 6,\n \"num_heads\": 2,\n \"hidden_channels_ffn\": 768,\n \"input_length\": None,\n }\n )\n d_vector_dim: int = 0\n\n # training params\n data_dep_init_steps: int = 10\n\n # inference params\n style_wav_for_test: str = None\n inference_noise_scale: float = 0.0\n length_scale: float = 1.0\n\n # multi-speaker settings\n use_speaker_embedding: bool = False\n speakers_file: str = None\n use_d_vector_file: bool = False\n d_vector_file: str = False\n\n # optimizer parameters\n optimizer: str = \"RAdam\"\n optimizer_params: dict = field(default_factory=lambda: {\"betas\": [0.9, 0.998], \"weight_decay\": 1e-6})\n lr_scheduler: str = \"NoamLR\"\n lr_scheduler_params: dict = field(default_factory=lambda: {\"warmup_steps\": 4000})\n grad_clip: float = 5.0\n lr: float = 1e-3\n\n # overrides\n min_seq_len: int = 3\n max_seq_len: int = 500\n r: int = 1 # DO NOT CHANGE - TODO: make this immutable once coqpit implements it.\n\n # testing\n test_sentences: List[str] = field(\n default_factory=lambda: [\n \"It took me quite a long time to develop a voice, and now that I have it I'm not going to be silent.\",\n \"Be a voice, not an echo.\",\n \"I'm sorry Dave. I'm afraid I can't do that.\",\n \"This cake is great. It's so delicious and moist.\",\n \"Prior to November 22, 1963.\",\n ]\n )" }, { "identifier": "Decoder", "path": "TTS/tts/layers/glow_tts/decoder.py", "snippet": "class Decoder(nn.Module):\n \"\"\"Stack of Glow Decoder Modules.\n\n ::\n\n Squeeze -> ActNorm -> InvertibleConv1x1 -> AffineCoupling -> Unsqueeze\n\n Args:\n in_channels (int): channels of input tensor.\n hidden_channels (int): hidden decoder channels.\n kernel_size (int): Coupling block kernel size. (Wavenet filter kernel size.)\n dilation_rate (int): rate to increase dilation by each layer in a decoder block.\n num_flow_blocks (int): number of decoder blocks.\n num_coupling_layers (int): number coupling layers. (number of wavenet layers.)\n dropout_p (float): wavenet dropout rate.\n sigmoid_scale (bool): enable/disable sigmoid scaling in coupling layer.\n \"\"\"\n\n def __init__(\n self,\n in_channels,\n hidden_channels,\n kernel_size,\n dilation_rate,\n num_flow_blocks,\n num_coupling_layers,\n dropout_p=0.0,\n num_splits=4,\n num_squeeze=2,\n sigmoid_scale=False,\n c_in_channels=0,\n ):\n super().__init__()\n\n self.in_channels = in_channels\n self.hidden_channels = hidden_channels\n self.kernel_size = kernel_size\n self.dilation_rate = dilation_rate\n self.num_flow_blocks = num_flow_blocks\n self.num_coupling_layers = num_coupling_layers\n self.dropout_p = dropout_p\n self.num_splits = num_splits\n self.num_squeeze = num_squeeze\n self.sigmoid_scale = sigmoid_scale\n self.c_in_channels = c_in_channels\n\n self.flows = nn.ModuleList()\n for _ in range(num_flow_blocks):\n self.flows.append(ActNorm(channels=in_channels * num_squeeze))\n self.flows.append(InvConvNear(channels=in_channels * num_squeeze, num_splits=num_splits))\n self.flows.append(\n CouplingBlock(\n in_channels * num_squeeze,\n hidden_channels,\n kernel_size=kernel_size,\n dilation_rate=dilation_rate,\n num_layers=num_coupling_layers,\n c_in_channels=c_in_channels,\n dropout_p=dropout_p,\n sigmoid_scale=sigmoid_scale,\n )\n )\n\n def forward(self, x, x_mask, g=None, reverse=False):\n \"\"\"\n Shapes:\n - x: :math:`[B, C, T]`\n - x_mask: :math:`[B, 1 ,T]`\n - g: :math:`[B, C]`\n \"\"\"\n if not reverse:\n flows = self.flows\n logdet_tot = 0\n else:\n flows = reversed(self.flows)\n logdet_tot = None\n\n if self.num_squeeze > 1:\n x, x_mask = squeeze(x, x_mask, self.num_squeeze)\n for f in flows:\n if not reverse:\n x, logdet = f(x, x_mask, g=g, reverse=reverse)\n logdet_tot += logdet\n else:\n x, logdet = f(x, x_mask, g=g, reverse=reverse)\n if self.num_squeeze > 1:\n x, x_mask = unsqueeze(x, x_mask, self.num_squeeze)\n return x, logdet_tot\n\n def store_inverse(self):\n for f in self.flows:\n f.store_inverse()" }, { "identifier": "Encoder", "path": "TTS/tts/layers/glow_tts/encoder.py", "snippet": "class Encoder(nn.Module):\n \"\"\"Glow-TTS encoder module.\n\n ::\n\n embedding -> <prenet> -> encoder_module -> <postnet> --> proj_mean\n |\n |-> proj_var\n |\n |-> concat -> duration_predictor\n ↑\n speaker_embed\n\n Args:\n num_chars (int): number of characters.\n out_channels (int): number of output channels.\n hidden_channels (int): encoder's embedding size.\n hidden_channels_ffn (int): transformer's feed-forward channels.\n kernel_size (int): kernel size for conv layers and duration predictor.\n dropout_p (float): dropout rate for any dropout layer.\n mean_only (bool): if True, output only mean values and use constant std.\n use_prenet (bool): if True, use pre-convolutional layers before transformer layers.\n c_in_channels (int): number of channels in conditional input.\n\n Shapes:\n - input: (B, T, C)\n\n ::\n\n suggested encoder params...\n\n for encoder_type == 'rel_pos_transformer'\n encoder_params={\n 'kernel_size':3,\n 'dropout_p': 0.1,\n 'num_layers': 6,\n 'num_heads': 2,\n 'hidden_channels_ffn': 768, # 4 times the hidden_channels\n 'input_length': None\n }\n\n for encoder_type == 'gated_conv'\n encoder_params={\n 'kernel_size':5,\n 'dropout_p': 0.1,\n 'num_layers': 9,\n }\n\n for encoder_type == 'residual_conv_bn'\n encoder_params={\n \"kernel_size\": 4,\n \"dilations\": [1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1],\n \"num_conv_blocks\": 2,\n \"num_res_blocks\": 13\n }\n\n for encoder_type == 'time_depth_separable'\n encoder_params={\n \"kernel_size\": 5,\n 'num_layers': 9,\n }\n \"\"\"\n\n def __init__(\n self,\n num_chars,\n out_channels,\n hidden_channels,\n hidden_channels_dp,\n encoder_type,\n encoder_params,\n dropout_p_dp=0.1,\n mean_only=False,\n use_prenet=True,\n c_in_channels=0,\n ):\n super().__init__()\n # class arguments\n self.num_chars = num_chars\n self.out_channels = out_channels\n self.hidden_channels = hidden_channels\n self.hidden_channels_dp = hidden_channels_dp\n self.dropout_p_dp = dropout_p_dp\n self.mean_only = mean_only\n self.use_prenet = use_prenet\n self.c_in_channels = c_in_channels\n self.encoder_type = encoder_type\n # embedding layer\n self.emb = nn.Embedding(num_chars, hidden_channels)\n nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)\n # init encoder module\n if encoder_type.lower() == \"rel_pos_transformer\":\n if use_prenet:\n self.prenet = ResidualConv1dLayerNormBlock(\n hidden_channels, hidden_channels, hidden_channels, kernel_size=5, num_layers=3, dropout_p=0.5\n )\n self.encoder = RelativePositionTransformer(\n hidden_channels, hidden_channels, hidden_channels, **encoder_params\n )\n elif encoder_type.lower() == \"gated_conv\":\n self.encoder = GatedConvBlock(hidden_channels, **encoder_params)\n elif encoder_type.lower() == \"residual_conv_bn\":\n if use_prenet:\n self.prenet = nn.Sequential(nn.Conv1d(hidden_channels, hidden_channels, 1), nn.ReLU())\n self.encoder = ResidualConv1dBNBlock(hidden_channels, hidden_channels, hidden_channels, **encoder_params)\n self.postnet = nn.Sequential(\n nn.Conv1d(self.hidden_channels, self.hidden_channels, 1), nn.BatchNorm1d(self.hidden_channels)\n )\n elif encoder_type.lower() == \"time_depth_separable\":\n if use_prenet:\n self.prenet = ResidualConv1dLayerNormBlock(\n hidden_channels, hidden_channels, hidden_channels, kernel_size=5, num_layers=3, dropout_p=0.5\n )\n self.encoder = TimeDepthSeparableConvBlock(\n hidden_channels, hidden_channels, hidden_channels, **encoder_params\n )\n else:\n raise ValueError(\" [!] Unkown encoder type.\")\n\n # final projection layers\n self.proj_m = nn.Conv1d(hidden_channels, out_channels, 1)\n if not mean_only:\n self.proj_s = nn.Conv1d(hidden_channels, out_channels, 1)\n # duration predictor\n self.duration_predictor = DurationPredictor(\n hidden_channels + c_in_channels, hidden_channels_dp, 3, dropout_p_dp\n )\n\n def forward(self, x, x_lengths, g=None):\n \"\"\"\n Shapes:\n - x: :math:`[B, C, T]`\n - x_lengths: :math:`[B]`\n - g (optional): :math:`[B, 1, T]`\n \"\"\"\n # embedding layer\n # [B ,T, D]\n x = self.emb(x) * math.sqrt(self.hidden_channels)\n # [B, D, T]\n x = torch.transpose(x, 1, -1)\n # compute input sequence mask\n x_mask = torch.unsqueeze(sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)\n # prenet\n if hasattr(self, \"prenet\") and self.use_prenet:\n x = self.prenet(x, x_mask)\n # encoder\n x = self.encoder(x, x_mask)\n # postnet\n if hasattr(self, \"postnet\"):\n x = self.postnet(x) * x_mask\n # set duration predictor input\n if g is not None:\n g_exp = g.expand(-1, -1, x.size(-1))\n x_dp = torch.cat([x.detach(), g_exp], 1)\n else:\n x_dp = x.detach()\n # final projection layer\n x_m = self.proj_m(x) * x_mask\n if not self.mean_only:\n x_logs = self.proj_s(x) * x_mask\n else:\n x_logs = torch.zeros_like(x_m)\n # duration predictor\n logw = self.duration_predictor(x_dp, x_mask)\n return x_m, x_logs, logw, x_mask" }, { "identifier": "BaseTTS", "path": "TTS/tts/models/base_tts.py", "snippet": "class BaseTTS(BaseTrainerModel):\n \"\"\"Base `tts` class. Every new `tts` model must inherit this.\n\n It defines common `tts` specific functions on top of `Model` implementation.\n \"\"\"\n\n MODEL_TYPE = \"tts\"\n\n def __init__(\n self,\n config: Coqpit,\n ap: \"AudioProcessor\",\n tokenizer: \"TTSTokenizer\",\n speaker_manager: SpeakerManager = None,\n language_manager: LanguageManager = None,\n ):\n super().__init__()\n self.config = config\n self.ap = ap\n self.tokenizer = tokenizer\n self.speaker_manager = speaker_manager\n self.language_manager = language_manager\n self._set_model_args(config)\n\n def _set_model_args(self, config: Coqpit):\n \"\"\"Setup model args based on the config type (`ModelConfig` or `ModelArgs`).\n\n `ModelArgs` has all the fields reuqired to initialize the model architecture.\n\n `ModelConfig` has all the fields required for training, inference and containes `ModelArgs`.\n\n If the config is for training with a name like \"*Config\", then the model args are embeded in the\n config.model_args\n\n If the config is for the model with a name like \"*Args\", then we assign the directly.\n \"\"\"\n # don't use isintance not to import recursively\n if \"Config\" in config.__class__.__name__:\n config_num_chars = (\n self.config.model_args.num_chars if hasattr(self.config, \"model_args\") else self.config.num_chars\n )\n num_chars = config_num_chars if self.tokenizer is None else self.tokenizer.characters.num_chars\n if \"characters\" in config:\n self.config.num_chars = num_chars\n if hasattr(self.config, \"model_args\"):\n config.model_args.num_chars = num_chars\n self.args = self.config.model_args\n else:\n self.config = config\n self.args = config.model_args\n elif \"Args\" in config.__class__.__name__:\n self.args = config\n else:\n raise ValueError(\"config must be either a *Config or *Args\")\n\n def init_multispeaker(self, config: Coqpit, data: List = None):\n \"\"\"Initialize a speaker embedding layer if needen and define expected embedding channel size for defining\n `in_channels` size of the connected layers.\n\n This implementation yields 3 possible outcomes:\n\n 1. If `config.use_speaker_embedding` and `config.use_d_vector_file are False, do nothing.\n 2. If `config.use_d_vector_file` is True, set expected embedding channel size to `config.d_vector_dim` or 512.\n 3. If `config.use_speaker_embedding`, initialize a speaker embedding layer with channel size of\n `config.d_vector_dim` or 512.\n\n You can override this function for new models.\n\n Args:\n config (Coqpit): Model configuration.\n \"\"\"\n # set number of speakers\n if self.speaker_manager is not None:\n self.num_speakers = self.speaker_manager.num_speakers\n elif hasattr(config, \"num_speakers\"):\n self.num_speakers = config.num_speakers\n\n # set ultimate speaker embedding size\n if config.use_speaker_embedding or config.use_d_vector_file:\n self.embedded_speaker_dim = (\n config.d_vector_dim if \"d_vector_dim\" in config and config.d_vector_dim is not None else 512\n )\n # init speaker embedding layer\n if config.use_speaker_embedding and not config.use_d_vector_file:\n print(\" > Init speaker_embedding layer.\")\n self.speaker_embedding = nn.Embedding(self.num_speakers, self.embedded_speaker_dim)\n self.speaker_embedding.weight.data.normal_(0, 0.3)\n\n def get_aux_input(self, **kwargs) -> Dict:\n \"\"\"Prepare and return `aux_input` used by `forward()`\"\"\"\n return {\"speaker_id\": None, \"style_wav\": None, \"d_vector\": None, \"language_id\": None}\n\n def get_aux_input_from_test_sentences(self, sentence_info):\n if hasattr(self.config, \"model_args\"):\n config = self.config.model_args\n else:\n config = self.config\n\n # extract speaker and language info\n text, speaker_name, style_wav, language_name = None, None, None, None\n\n if isinstance(sentence_info, list):\n if len(sentence_info) == 1:\n text = sentence_info[0]\n elif len(sentence_info) == 2:\n text, speaker_name = sentence_info\n elif len(sentence_info) == 3:\n text, speaker_name, style_wav = sentence_info\n elif len(sentence_info) == 4:\n text, speaker_name, style_wav, language_name = sentence_info\n else:\n text = sentence_info\n\n # get speaker id/d_vector\n speaker_id, d_vector, language_id = None, None, None\n if self.speaker_manager is not None:\n if config.use_d_vector_file:\n if speaker_name is None:\n d_vector = self.speaker_manager.get_random_embedding()\n else:\n d_vector = self.speaker_manager.get_d_vector_by_name(speaker_name)\n elif config.use_speaker_embedding:\n if speaker_name is None:\n speaker_id = self.speaker_manager.get_random_id()\n else:\n speaker_id = self.speaker_manager.name_to_id[speaker_name]\n\n # get language id\n if self.language_manager is not None and config.use_language_embedding and language_name is not None:\n language_id = self.language_manager.name_to_id[language_name]\n\n return {\n \"text\": text,\n \"speaker_id\": speaker_id,\n \"style_wav\": style_wav,\n \"d_vector\": d_vector,\n \"language_id\": language_id,\n }\n\n def format_batch(self, batch: Dict) -> Dict:\n \"\"\"Generic batch formatting for `TTSDataset`.\n\n You must override this if you use a custom dataset.\n\n Args:\n batch (Dict): [description]\n\n Returns:\n Dict: [description]\n \"\"\"\n # setup input batch\n text_input = batch[\"token_id\"]\n text_lengths = batch[\"token_id_lengths\"]\n speaker_names = batch[\"speaker_names\"]\n linear_input = batch[\"linear\"]\n mel_input = batch[\"mel\"]\n mel_lengths = batch[\"mel_lengths\"]\n stop_targets = batch[\"stop_targets\"]\n item_idx = batch[\"item_idxs\"]\n d_vectors = batch[\"d_vectors\"]\n speaker_ids = batch[\"speaker_ids\"]\n attn_mask = batch[\"attns\"]\n waveform = batch[\"waveform\"]\n pitch = batch[\"pitch\"]\n energy = batch[\"energy\"]\n language_ids = batch[\"language_ids\"]\n max_text_length = torch.max(text_lengths.float())\n max_spec_length = torch.max(mel_lengths.float())\n\n # compute durations from attention masks\n durations = None\n if attn_mask is not None:\n durations = torch.zeros(attn_mask.shape[0], attn_mask.shape[2])\n for idx, am in enumerate(attn_mask):\n # compute raw durations\n c_idxs = am[:, : text_lengths[idx], : mel_lengths[idx]].max(1)[1]\n # c_idxs, counts = torch.unique_consecutive(c_idxs, return_counts=True)\n c_idxs, counts = torch.unique(c_idxs, return_counts=True)\n dur = torch.ones([text_lengths[idx]]).to(counts.dtype)\n dur[c_idxs] = counts\n # smooth the durations and set any 0 duration to 1\n # by cutting off from the largest duration indeces.\n extra_frames = dur.sum() - mel_lengths[idx]\n largest_idxs = torch.argsort(-dur)[:extra_frames]\n dur[largest_idxs] -= 1\n assert (\n dur.sum() == mel_lengths[idx]\n ), f\" [!] total duration {dur.sum()} vs spectrogram length {mel_lengths[idx]}\"\n durations[idx, : text_lengths[idx]] = dur\n\n # set stop targets wrt reduction factor\n stop_targets = stop_targets.view(text_input.shape[0], stop_targets.size(1) // self.config.r, -1)\n stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float().squeeze(2)\n stop_target_lengths = torch.divide(mel_lengths, self.config.r).ceil_()\n\n return {\n \"text_input\": text_input,\n \"text_lengths\": text_lengths,\n \"speaker_names\": speaker_names,\n \"mel_input\": mel_input,\n \"mel_lengths\": mel_lengths,\n \"linear_input\": linear_input,\n \"stop_targets\": stop_targets,\n \"stop_target_lengths\": stop_target_lengths,\n \"attn_mask\": attn_mask,\n \"durations\": durations,\n \"speaker_ids\": speaker_ids,\n \"d_vectors\": d_vectors,\n \"max_text_length\": float(max_text_length),\n \"max_spec_length\": float(max_spec_length),\n \"item_idx\": item_idx,\n \"waveform\": waveform,\n \"pitch\": pitch,\n \"energy\": energy,\n \"language_ids\": language_ids,\n \"audio_unique_names\": batch[\"audio_unique_names\"],\n }\n\n def get_sampler(self, config: Coqpit, dataset: TTSDataset, num_gpus=1):\n weights = None\n data_items = dataset.samples\n\n if getattr(config, \"use_language_weighted_sampler\", False):\n alpha = getattr(config, \"language_weighted_sampler_alpha\", 1.0)\n print(\" > Using Language weighted sampler with alpha:\", alpha)\n weights = get_language_balancer_weights(data_items) * alpha\n\n if getattr(config, \"use_speaker_weighted_sampler\", False):\n alpha = getattr(config, \"speaker_weighted_sampler_alpha\", 1.0)\n print(\" > Using Speaker weighted sampler with alpha:\", alpha)\n if weights is not None:\n weights += get_speaker_balancer_weights(data_items) * alpha\n else:\n weights = get_speaker_balancer_weights(data_items) * alpha\n\n if getattr(config, \"use_length_weighted_sampler\", False):\n alpha = getattr(config, \"length_weighted_sampler_alpha\", 1.0)\n print(\" > Using Length weighted sampler with alpha:\", alpha)\n if weights is not None:\n weights += get_length_balancer_weights(data_items) * alpha\n else:\n weights = get_length_balancer_weights(data_items) * alpha\n\n if weights is not None:\n sampler = WeightedRandomSampler(weights, len(weights))\n else:\n sampler = None\n\n # sampler for DDP\n if sampler is None:\n sampler = DistributedSampler(dataset) if num_gpus > 1 else None\n else: # If a sampler is already defined use this sampler and DDP sampler together\n sampler = DistributedSamplerWrapper(sampler) if num_gpus > 1 else sampler\n\n return sampler\n\n def get_data_loader(\n self,\n config: Coqpit,\n assets: Dict,\n is_eval: bool,\n samples: Union[List[Dict], List[List]],\n verbose: bool,\n num_gpus: int,\n rank: int = None,\n ) -> \"DataLoader\":\n if is_eval and not config.run_eval:\n loader = None\n else:\n # setup multi-speaker attributes\n if self.speaker_manager is not None:\n if hasattr(config, \"model_args\"):\n speaker_id_mapping = (\n self.speaker_manager.name_to_id if config.model_args.use_speaker_embedding else None\n )\n d_vector_mapping = self.speaker_manager.embeddings if config.model_args.use_d_vector_file else None\n config.use_d_vector_file = config.model_args.use_d_vector_file\n else:\n speaker_id_mapping = self.speaker_manager.name_to_id if config.use_speaker_embedding else None\n d_vector_mapping = self.speaker_manager.embeddings if config.use_d_vector_file else None\n else:\n speaker_id_mapping = None\n d_vector_mapping = None\n\n # setup multi-lingual attributes\n if self.language_manager is not None:\n language_id_mapping = self.language_manager.name_to_id if self.args.use_language_embedding else None\n else:\n language_id_mapping = None\n\n # init dataloader\n dataset = TTSDataset(\n outputs_per_step=config.r if \"r\" in config else 1,\n compute_linear_spec=config.model.lower() == \"tacotron\" or config.compute_linear_spec,\n compute_f0=config.get(\"compute_f0\", False),\n f0_cache_path=config.get(\"f0_cache_path\", None),\n compute_energy=config.get(\"compute_energy\", False),\n energy_cache_path=config.get(\"energy_cache_path\", None),\n samples=samples,\n ap=self.ap,\n return_wav=config.return_wav if \"return_wav\" in config else False,\n batch_group_size=0 if is_eval else config.batch_group_size * config.batch_size,\n min_text_len=config.min_text_len,\n max_text_len=config.max_text_len,\n min_audio_len=config.min_audio_len,\n max_audio_len=config.max_audio_len,\n phoneme_cache_path=config.phoneme_cache_path,\n precompute_num_workers=config.precompute_num_workers,\n use_noise_augment=False if is_eval else config.use_noise_augment,\n verbose=verbose,\n speaker_id_mapping=speaker_id_mapping,\n d_vector_mapping=d_vector_mapping if config.use_d_vector_file else None,\n tokenizer=self.tokenizer,\n start_by_longest=config.start_by_longest,\n language_id_mapping=language_id_mapping,\n )\n\n # wait all the DDP process to be ready\n if num_gpus > 1:\n dist.barrier()\n\n # sort input sequences from short to long\n dataset.preprocess_samples()\n\n # get samplers\n sampler = self.get_sampler(config, dataset, num_gpus)\n\n loader = DataLoader(\n dataset,\n batch_size=config.eval_batch_size if is_eval else config.batch_size,\n shuffle=config.shuffle if sampler is None else False, # if there is no other sampler\n collate_fn=dataset.collate_fn,\n drop_last=config.drop_last, # setting this False might cause issues in AMP training.\n sampler=sampler,\n num_workers=config.num_eval_loader_workers if is_eval else config.num_loader_workers,\n pin_memory=False,\n )\n return loader\n\n def _get_test_aux_input(\n self,\n ) -> Dict:\n d_vector = None\n if self.config.use_d_vector_file:\n d_vector = [self.speaker_manager.embeddings[name][\"embedding\"] for name in self.speaker_manager.embeddings]\n d_vector = (random.sample(sorted(d_vector), 1),)\n\n aux_inputs = {\n \"speaker_id\": None\n if not self.config.use_speaker_embedding\n else random.sample(sorted(self.speaker_manager.name_to_id.values()), 1),\n \"d_vector\": d_vector,\n \"style_wav\": None, # TODO: handle GST style input\n }\n return aux_inputs\n\n def test_run(self, assets: Dict) -> Tuple[Dict, Dict]:\n \"\"\"Generic test run for `tts` models used by `Trainer`.\n\n You can override this for a different behaviour.\n\n Args:\n assets (dict): A dict of training assets. For `tts` models, it must include `{'audio_processor': ap}`.\n\n Returns:\n Tuple[Dict, Dict]: Test figures and audios to be projected to Tensorboard.\n \"\"\"\n print(\" | > Synthesizing test sentences.\")\n test_audios = {}\n test_figures = {}\n test_sentences = self.config.test_sentences\n aux_inputs = self._get_test_aux_input()\n for idx, sen in enumerate(test_sentences):\n if isinstance(sen, list):\n aux_inputs = self.get_aux_input_from_test_sentences(sen)\n sen = aux_inputs[\"text\"]\n outputs_dict = synthesis(\n self,\n sen,\n self.config,\n \"cuda\" in str(next(self.parameters()).device),\n speaker_id=aux_inputs[\"speaker_id\"],\n d_vector=aux_inputs[\"d_vector\"],\n style_wav=aux_inputs[\"style_wav\"],\n use_griffin_lim=True,\n do_trim_silence=False,\n )\n test_audios[\"{}-audio\".format(idx)] = outputs_dict[\"wav\"]\n test_figures[\"{}-prediction\".format(idx)] = plot_spectrogram(\n outputs_dict[\"outputs\"][\"model_outputs\"], self.ap, output_fig=False\n )\n test_figures[\"{}-alignment\".format(idx)] = plot_alignment(\n outputs_dict[\"outputs\"][\"alignments\"], output_fig=False\n )\n return test_figures, test_audios\n\n def on_init_start(self, trainer):\n \"\"\"Save the speaker.pth and language_ids.json at the beginning of the training. Also update both paths.\"\"\"\n if self.speaker_manager is not None:\n output_path = os.path.join(trainer.output_path, \"speakers.pth\")\n self.speaker_manager.save_ids_to_file(output_path)\n trainer.config.speakers_file = output_path\n # some models don't have `model_args` set\n if hasattr(trainer.config, \"model_args\"):\n trainer.config.model_args.speakers_file = output_path\n trainer.config.save_json(os.path.join(trainer.output_path, \"config.json\"))\n print(f\" > `speakers.pth` is saved to {output_path}.\")\n print(\" > `speakers_file` is updated in the config.json.\")\n\n if self.language_manager is not None:\n output_path = os.path.join(trainer.output_path, \"language_ids.json\")\n self.language_manager.save_ids_to_file(output_path)\n trainer.config.language_ids_file = output_path\n if hasattr(trainer.config, \"model_args\"):\n trainer.config.model_args.language_ids_file = output_path\n trainer.config.save_json(os.path.join(trainer.output_path, \"config.json\"))\n print(f\" > `language_ids.json` is saved to {output_path}.\")\n print(\" > `language_ids_file` is updated in the config.json.\")" }, { "identifier": "generate_path", "path": "TTS/tts/utils/helpers.py", "snippet": "def generate_path(duration, mask):\n \"\"\"\n Shapes:\n - duration: :math:`[B, T_en]`\n - mask: :math:'[B, T_en, T_de]`\n - path: :math:`[B, T_en, T_de]`\n \"\"\"\n b, t_x, t_y = mask.shape\n cum_duration = torch.cumsum(duration, 1)\n\n cum_duration_flat = cum_duration.view(b * t_x)\n path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)\n path = path.view(b, t_x, t_y)\n path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]\n path = path * mask\n return path" }, { "identifier": "maximum_path", "path": "TTS/tts/utils/helpers.py", "snippet": "def maximum_path(value, mask):\n if CYTHON:\n return maximum_path_cython(value, mask)\n return maximum_path_numpy(value, mask)" }, { "identifier": "sequence_mask", "path": "TTS/tts/utils/helpers.py", "snippet": "def sequence_mask(sequence_length, max_len=None):\n \"\"\"Create a sequence mask for filtering padding in a sequence tensor.\n\n Args:\n sequence_length (torch.tensor): Sequence lengths.\n max_len (int, Optional): Maximum sequence length. Defaults to None.\n\n Shapes:\n - mask: :math:`[B, T_max]`\n \"\"\"\n if max_len is None:\n max_len = sequence_length.max()\n seq_range = torch.arange(max_len, dtype=sequence_length.dtype, device=sequence_length.device)\n # B x T_max\n return seq_range.unsqueeze(0) < sequence_length.unsqueeze(1)" }, { "identifier": "SpeakerManager", "path": "TTS/tts/utils/speakers.py", "snippet": "class SpeakerManager(EmbeddingManager):\n \"\"\"Manage the speakers for multi-speaker 🐸TTS models. Load a datafile and parse the information\n in a way that can be queried by speaker or clip.\n\n There are 3 different scenarios considered:\n\n 1. Models using speaker embedding layers. The datafile only maps speaker names to ids used by the embedding layer.\n 2. Models using d-vectors. The datafile includes a dictionary in the following format.\n\n ::\n\n {\n 'clip_name.wav':{\n 'name': 'speakerA',\n 'embedding'[<d_vector_values>]\n },\n ...\n }\n\n\n 3. Computing the d-vectors by the speaker encoder. It loads the speaker encoder model and\n computes the d-vectors for a given clip or speaker.\n\n Args:\n d_vectors_file_path (str, optional): Path to the metafile including x vectors. Defaults to \"\".\n speaker_id_file_path (str, optional): Path to the metafile that maps speaker names to ids used by\n TTS models. Defaults to \"\".\n encoder_model_path (str, optional): Path to the speaker encoder model file. Defaults to \"\".\n encoder_config_path (str, optional): Path to the spealer encoder config file. Defaults to \"\".\n\n Examples:\n >>> # load audio processor and speaker encoder\n >>> ap = AudioProcessor(**config.audio)\n >>> manager = SpeakerManager(encoder_model_path=encoder_model_path, encoder_config_path=encoder_config_path)\n >>> # load a sample audio and compute embedding\n >>> waveform = ap.load_wav(sample_wav_path)\n >>> mel = ap.melspectrogram(waveform)\n >>> d_vector = manager.compute_embeddings(mel.T)\n \"\"\"\n\n def __init__(\n self,\n data_items: List[List[Any]] = None,\n d_vectors_file_path: str = \"\",\n speaker_id_file_path: str = \"\",\n encoder_model_path: str = \"\",\n encoder_config_path: str = \"\",\n use_cuda: bool = False,\n ):\n super().__init__(\n embedding_file_path=d_vectors_file_path,\n id_file_path=speaker_id_file_path,\n encoder_model_path=encoder_model_path,\n encoder_config_path=encoder_config_path,\n use_cuda=use_cuda,\n )\n\n if data_items:\n self.set_ids_from_data(data_items, parse_key=\"speaker_name\")\n\n @property\n def num_speakers(self):\n return len(self.name_to_id)\n\n @property\n def speaker_names(self):\n return list(self.name_to_id.keys())\n\n def get_speakers(self) -> List:\n return self.name_to_id\n\n @staticmethod\n def init_from_config(config: \"Coqpit\", samples: Union[List[List], List[Dict]] = None) -> \"SpeakerManager\":\n \"\"\"Initialize a speaker manager from config\n\n Args:\n config (Coqpit): Config object.\n samples (Union[List[List], List[Dict]], optional): List of data samples to parse out the speaker names.\n Defaults to None.\n\n Returns:\n SpeakerEncoder: Speaker encoder object.\n \"\"\"\n speaker_manager = None\n if get_from_config_or_model_args_with_default(config, \"use_speaker_embedding\", False):\n if samples:\n speaker_manager = SpeakerManager(data_items=samples)\n if get_from_config_or_model_args_with_default(config, \"speaker_file\", None):\n speaker_manager = SpeakerManager(\n speaker_id_file_path=get_from_config_or_model_args_with_default(config, \"speaker_file\", None)\n )\n if get_from_config_or_model_args_with_default(config, \"speakers_file\", None):\n speaker_manager = SpeakerManager(\n speaker_id_file_path=get_from_config_or_model_args_with_default(config, \"speakers_file\", None)\n )\n\n if get_from_config_or_model_args_with_default(config, \"use_d_vector_file\", False):\n speaker_manager = SpeakerManager()\n if get_from_config_or_model_args_with_default(config, \"d_vector_file\", None):\n speaker_manager = SpeakerManager(\n d_vectors_file_path=get_from_config_or_model_args_with_default(config, \"d_vector_file\", None)\n )\n return speaker_manager" }, { "identifier": "synthesis", "path": "TTS/tts/utils/synthesis.py", "snippet": "def synthesis(\n model,\n text,\n CONFIG,\n use_cuda,\n speaker_id=None,\n style_wav=None,\n style_text=None,\n use_griffin_lim=False,\n do_trim_silence=False,\n d_vector=None,\n language_id=None,\n):\n \"\"\"Synthesize voice for the given text using Griffin-Lim vocoder or just compute output features to be passed to\n the vocoder model.\n\n Args:\n model (TTS.tts.models):\n The TTS model to synthesize audio with.\n\n text (str):\n The input text to convert to speech.\n\n CONFIG (Coqpit):\n Model configuration.\n\n use_cuda (bool):\n Enable/disable CUDA.\n\n speaker_id (int):\n Speaker ID passed to the speaker embedding layer in multi-speaker model. Defaults to None.\n\n style_wav (str | Dict[str, float]):\n Path or tensor to/of a waveform used for computing the style embedding based on GST or Capacitron.\n Defaults to None, meaning that Capacitron models will sample from the prior distribution to\n generate random but realistic prosody.\n\n style_text (str):\n Transcription of style_wav for Capacitron models. Defaults to None.\n\n enable_eos_bos_chars (bool):\n enable special chars for end of sentence and start of sentence. Defaults to False.\n\n do_trim_silence (bool):\n trim silence after synthesis. Defaults to False.\n\n d_vector (torch.Tensor):\n d-vector for multi-speaker models in share :math:`[1, D]`. Defaults to None.\n\n language_id (int):\n Language ID passed to the language embedding layer in multi-langual model. Defaults to None.\n \"\"\"\n # device\n device = next(model.parameters()).device\n if use_cuda:\n device = \"cuda\"\n\n # GST or Capacitron processing\n # TODO: need to handle the case of setting both gst and capacitron to true somewhere\n style_mel = None\n if CONFIG.has(\"gst\") and CONFIG.gst and style_wav is not None:\n if isinstance(style_wav, dict):\n style_mel = style_wav\n else:\n style_mel = compute_style_mel(style_wav, model.ap, device=device)\n\n if CONFIG.has(\"capacitron_vae\") and CONFIG.use_capacitron_vae and style_wav is not None:\n style_mel = compute_style_mel(style_wav, model.ap, device=device)\n style_mel = style_mel.transpose(1, 2) # [1, time, depth]\n\n language_name = None\n if language_id is not None:\n language = [k for k, v in model.language_manager.name_to_id.items() if v == language_id]\n assert len(language) == 1, \"language_id must be a valid language\"\n language_name = language[0]\n\n # convert text to sequence of token IDs\n text_inputs = np.asarray(\n model.tokenizer.text_to_ids(text, language=language_name),\n dtype=np.int32,\n )\n # pass tensors to backend\n if speaker_id is not None:\n speaker_id = id_to_torch(speaker_id, device=device)\n\n if d_vector is not None:\n d_vector = embedding_to_torch(d_vector, device=device)\n\n if language_id is not None:\n language_id = id_to_torch(language_id, device=device)\n\n if not isinstance(style_mel, dict):\n # GST or Capacitron style mel\n style_mel = numpy_to_torch(style_mel, torch.float, device=device)\n if style_text is not None:\n style_text = np.asarray(\n model.tokenizer.text_to_ids(style_text, language=language_id),\n dtype=np.int32,\n )\n style_text = numpy_to_torch(style_text, torch.long, device=device)\n style_text = style_text.unsqueeze(0)\n\n text_inputs = numpy_to_torch(text_inputs, torch.long, device=device)\n text_inputs = text_inputs.unsqueeze(0)\n # synthesize voice\n outputs = run_model_torch(\n model,\n text_inputs,\n speaker_id,\n style_mel,\n style_text,\n d_vector=d_vector,\n language_id=language_id,\n )\n model_outputs = outputs[\"model_outputs\"]\n model_outputs = model_outputs[0].data.cpu().numpy()\n alignments = outputs[\"alignments\"]\n\n # convert outputs to numpy\n # plot results\n wav = None\n model_outputs = model_outputs.squeeze()\n if model_outputs.ndim == 2: # [T, C_spec]\n if use_griffin_lim:\n wav = inv_spectrogram(model_outputs, model.ap, CONFIG)\n # trim silence\n if do_trim_silence:\n wav = trim_silence(wav, model.ap)\n else: # [T,]\n wav = model_outputs\n return_dict = {\n \"wav\": wav,\n \"alignments\": alignments,\n \"text_inputs\": text_inputs,\n \"outputs\": outputs,\n }\n return return_dict" }, { "identifier": "TTSTokenizer", "path": "TTS/tts/utils/text/tokenizer.py", "snippet": "class TTSTokenizer:\n \"\"\"🐸TTS tokenizer to convert input characters to token IDs and back.\n\n Token IDs for OOV chars are discarded but those are stored in `self.not_found_characters` for later.\n\n Args:\n use_phonemes (bool):\n Whether to use phonemes instead of characters. Defaults to False.\n\n characters (Characters):\n A Characters object to use for character-to-ID and ID-to-character mappings.\n\n text_cleaner (callable):\n A function to pre-process the text before tokenization and phonemization. Defaults to None.\n\n phonemizer (Phonemizer):\n A phonemizer object or a dict that maps language codes to phonemizer objects. Defaults to None.\n\n Example:\n\n >>> from TTS.tts.utils.text.tokenizer import TTSTokenizer\n >>> tokenizer = TTSTokenizer(use_phonemes=False, characters=Graphemes())\n >>> text = \"Hello world!\"\n >>> ids = tokenizer.text_to_ids(text)\n >>> text_hat = tokenizer.ids_to_text(ids)\n >>> assert text == text_hat\n \"\"\"\n\n def __init__(\n self,\n use_phonemes=False,\n text_cleaner: Callable = None,\n characters: \"BaseCharacters\" = None,\n phonemizer: Union[\"Phonemizer\", Dict] = None,\n add_blank: bool = False,\n use_eos_bos=False,\n ):\n self.text_cleaner = text_cleaner\n self.use_phonemes = use_phonemes\n self.add_blank = add_blank\n self.use_eos_bos = use_eos_bos\n self.characters = characters\n self.not_found_characters = []\n self.phonemizer = phonemizer\n\n @property\n def characters(self):\n return self._characters\n\n @characters.setter\n def characters(self, new_characters):\n self._characters = new_characters\n self.pad_id = self.characters.char_to_id(self.characters.pad) if self.characters.pad else None\n self.blank_id = self.characters.char_to_id(self.characters.blank) if self.characters.blank else None\n\n def encode(self, text: str) -> List[int]:\n \"\"\"Encodes a string of text as a sequence of IDs.\"\"\"\n token_ids = []\n for char in text:\n try:\n idx = self.characters.char_to_id(char)\n token_ids.append(idx)\n except KeyError:\n # discard but store not found characters\n if char not in self.not_found_characters:\n self.not_found_characters.append(char)\n print(text)\n print(f\" [!] Character {repr(char)} not found in the vocabulary. Discarding it.\")\n return token_ids\n\n def decode(self, token_ids: List[int]) -> str:\n \"\"\"Decodes a sequence of IDs to a string of text.\"\"\"\n text = \"\"\n for token_id in token_ids:\n text += self.characters.id_to_char(token_id)\n return text\n\n def text_to_ids(self, text: str, language: str = None) -> List[int]: # pylint: disable=unused-argument\n \"\"\"Converts a string of text to a sequence of token IDs.\n\n Args:\n text(str):\n The text to convert to token IDs.\n\n language(str):\n The language code of the text. Defaults to None.\n\n TODO:\n - Add support for language-specific processing.\n\n 1. Text normalizatin\n 2. Phonemization (if use_phonemes is True)\n 3. Add blank char between characters\n 4. Add BOS and EOS characters\n 5. Text to token IDs\n \"\"\"\n # TODO: text cleaner should pick the right routine based on the language\n if self.text_cleaner is not None:\n text = self.text_cleaner(text)\n if self.use_phonemes:\n text = self.phonemizer.phonemize(text, separator=\"\", language=language)\n text = self.encode(text)\n if self.add_blank:\n text = self.intersperse_blank_char(text, True)\n if self.use_eos_bos:\n text = self.pad_with_bos_eos(text)\n return text\n\n def ids_to_text(self, id_sequence: List[int]) -> str:\n \"\"\"Converts a sequence of token IDs to a string of text.\"\"\"\n return self.decode(id_sequence)\n\n def pad_with_bos_eos(self, char_sequence: List[str]):\n \"\"\"Pads a sequence with the special BOS and EOS characters.\"\"\"\n return [self.characters.bos_id] + list(char_sequence) + [self.characters.eos_id]\n\n def intersperse_blank_char(self, char_sequence: List[str], use_blank_char: bool = False):\n \"\"\"Intersperses the blank character between characters in a sequence.\n\n Use the ```blank``` character if defined else use the ```pad``` character.\n \"\"\"\n char_to_use = self.characters.blank_id if use_blank_char else self.characters.pad\n result = [char_to_use] * (len(char_sequence) * 2 + 1)\n result[1::2] = char_sequence\n return result\n\n def print_logs(self, level: int = 0):\n indent = \"\\t\" * level\n print(f\"{indent}| > add_blank: {self.add_blank}\")\n print(f\"{indent}| > use_eos_bos: {self.use_eos_bos}\")\n print(f\"{indent}| > use_phonemes: {self.use_phonemes}\")\n if self.use_phonemes:\n print(f\"{indent}| > phonemizer:\")\n self.phonemizer.print_logs(level + 1)\n if len(self.not_found_characters) > 0:\n print(f\"{indent}| > {len(self.not_found_characters)} not found characters:\")\n for char in self.not_found_characters:\n print(f\"{indent}| > {char}\")\n\n @staticmethod\n def init_from_config(config: \"Coqpit\", characters: \"BaseCharacters\" = None):\n \"\"\"Init Tokenizer object from config\n\n Args:\n config (Coqpit): Coqpit model config.\n characters (BaseCharacters): Defines the model character set. If not set, use the default options based on\n the config values. Defaults to None.\n \"\"\"\n # init cleaners\n text_cleaner = None\n if isinstance(config.text_cleaner, (str, list)):\n text_cleaner = getattr(cleaners, config.text_cleaner)\n\n # init characters\n if characters is None:\n # set characters based on defined characters class\n if config.characters and config.characters.characters_class:\n CharactersClass = import_class(config.characters.characters_class)\n characters, new_config = CharactersClass.init_from_config(config)\n # set characters based on config\n else:\n if config.use_phonemes:\n # init phoneme set\n characters, new_config = IPAPhonemes().init_from_config(config)\n else:\n # init character set\n characters, new_config = Graphemes().init_from_config(config)\n\n else:\n characters, new_config = characters.init_from_config(config)\n\n # set characters class\n new_config.characters.characters_class = get_import_path(characters)\n\n # init phonemizer\n phonemizer = None\n if config.use_phonemes:\n if \"phonemizer\" in config and config.phonemizer == \"multi_phonemizer\":\n lang_to_phonemizer_name = {}\n for dataset in config.datasets:\n if dataset.language != \"\":\n lang_to_phonemizer_name[dataset.language] = dataset.phonemizer\n else:\n raise ValueError(\"Multi phonemizer requires language to be set for each dataset.\")\n phonemizer = MultiPhonemizer(lang_to_phonemizer_name)\n else:\n phonemizer_kwargs = {\"language\": config.phoneme_language}\n if \"phonemizer\" in config and config.phonemizer:\n phonemizer = get_phonemizer_by_name(config.phonemizer, **phonemizer_kwargs)\n else:\n try:\n phonemizer = get_phonemizer_by_name(\n DEF_LANG_TO_PHONEMIZER[config.phoneme_language], **phonemizer_kwargs\n )\n new_config.phonemizer = phonemizer.name()\n except KeyError as e:\n raise ValueError(\n f\"\"\"No phonemizer found for language {config.phoneme_language}.\n You may need to install a third party library for this language.\"\"\"\n ) from e\n\n return (\n TTSTokenizer(\n config.use_phonemes, text_cleaner, characters, phonemizer, config.add_blank, config.enable_eos_bos_chars\n ),\n new_config,\n )" }, { "identifier": "plot_alignment", "path": "TTS/tts/utils/visual.py", "snippet": "def plot_alignment(alignment, info=None, fig_size=(16, 10), title=None, output_fig=False, plot_log=False):\n if isinstance(alignment, torch.Tensor):\n alignment_ = alignment.detach().cpu().numpy().squeeze()\n else:\n alignment_ = alignment\n alignment_ = alignment_.astype(np.float32) if alignment_.dtype == np.float16 else alignment_\n fig, ax = plt.subplots(figsize=fig_size)\n im = ax.imshow(\n alignment_.T, aspect=\"auto\", origin=\"lower\", interpolation=\"none\", norm=LogNorm() if plot_log else None\n )\n fig.colorbar(im, ax=ax)\n xlabel = \"Decoder timestep\"\n if info is not None:\n xlabel += \"\\n\\n\" + info\n plt.xlabel(xlabel)\n plt.ylabel(\"Encoder timestep\")\n # plt.yticks(range(len(text)), list(text))\n plt.tight_layout()\n if title is not None:\n plt.title(title)\n if not output_fig:\n plt.close()\n return fig" }, { "identifier": "plot_spectrogram", "path": "TTS/tts/utils/visual.py", "snippet": "def plot_spectrogram(spectrogram, ap=None, fig_size=(16, 10), output_fig=False):\n if isinstance(spectrogram, torch.Tensor):\n spectrogram_ = spectrogram.detach().cpu().numpy().squeeze().T\n else:\n spectrogram_ = spectrogram.T\n spectrogram_ = spectrogram_.astype(np.float32) if spectrogram_.dtype == np.float16 else spectrogram_\n if ap is not None:\n spectrogram_ = ap.denormalize(spectrogram_) # pylint: disable=protected-access\n fig = plt.figure(figsize=fig_size)\n plt.imshow(spectrogram_, aspect=\"auto\", origin=\"lower\")\n plt.colorbar()\n plt.tight_layout()\n if not output_fig:\n plt.close()\n return fig" }, { "identifier": "load_fsspec", "path": "TTS/utils/io.py", "snippet": "def load_fsspec(\n path: str,\n map_location: Union[str, Callable, torch.device, Dict[Union[str, torch.device], Union[str, torch.device]]] = None,\n cache: bool = True,\n **kwargs,\n) -> Any:\n \"\"\"Like torch.load but can load from other locations (e.g. s3:// , gs://).\n\n Args:\n path: Any path or url supported by fsspec.\n map_location: torch.device or str.\n cache: If True, cache a remote file locally for subsequent calls. It is cached under `get_user_data_dir()/tts_cache`. Defaults to True.\n **kwargs: Keyword arguments forwarded to torch.load.\n\n Returns:\n Object stored in path.\n \"\"\"\n is_local = os.path.isdir(path) or os.path.isfile(path)\n if cache and not is_local:\n with fsspec.open(\n f\"filecache::{path}\",\n filecache={\"cache_storage\": str(get_user_data_dir(\"tts_cache\"))},\n mode=\"rb\",\n ) as f:\n return torch.load(f, map_location=map_location, **kwargs)\n else:\n with fsspec.open(path, \"rb\") as f:\n return torch.load(f, map_location=map_location, **kwargs)" } ]
import math import torch from typing import Dict, List, Tuple, Union from coqpit import Coqpit from torch import nn from torch.cuda.amp.autocast_mode import autocast from torch.nn import functional as F from TTS.tts.configs.glow_tts_config import GlowTTSConfig from TTS.tts.layers.glow_tts.decoder import Decoder from TTS.tts.layers.glow_tts.encoder import Encoder from TTS.tts.models.base_tts import BaseTTS from TTS.tts.utils.helpers import generate_path, maximum_path, sequence_mask from TTS.tts.utils.speakers import SpeakerManager from TTS.tts.utils.synthesis import synthesis from TTS.tts.utils.text.tokenizer import TTSTokenizer from TTS.tts.utils.visual import plot_alignment, plot_spectrogram from TTS.utils.io import load_fsspec from TTS.tts.layers.losses import GlowTTSLoss # pylint: disable=import-outside-toplevel from TTS.utils.audio import AudioProcessor
15,207
class GlowTTS(BaseTTS): """GlowTTS model. Paper:: https://arxiv.org/abs/2005.11129 Paper abstract:: Recently, text-to-speech (TTS) models such as FastSpeech and ParaNet have been proposed to generate mel-spectrograms from text in parallel. Despite the advantage, the parallel TTS models cannot be trained without guidance from autoregressive TTS models as their external aligners. In this work, we propose Glow-TTS, a flow-based generative model for parallel TTS that does not require any external aligner. By combining the properties of flows and dynamic programming, the proposed model searches for the most probable monotonic alignment between text and the latent representation of speech on its own. We demonstrate that enforcing hard monotonic alignments enables robust TTS, which generalizes to long utterances, and employing generative flows enables fast, diverse, and controllable speech synthesis. Glow-TTS obtains an order-of-magnitude speed-up over the autoregressive model, Tacotron 2, at synthesis with comparable speech quality. We further show that our model can be easily extended to a multi-speaker setting. Check :class:`TTS.tts.configs.glow_tts_config.GlowTTSConfig` for class arguments. Examples: Init only model layers. >>> from TTS.tts.configs.glow_tts_config import GlowTTSConfig >>> from TTS.tts.models.glow_tts import GlowTTS >>> config = GlowTTSConfig(num_chars=2) >>> model = GlowTTS(config) Fully init a model ready for action. All the class attributes and class members (e.g Tokenizer, AudioProcessor, etc.). are initialized internally based on config values. >>> from TTS.tts.configs.glow_tts_config import GlowTTSConfig >>> from TTS.tts.models.glow_tts import GlowTTS >>> config = GlowTTSConfig() >>> model = GlowTTS.init_from_config(config, verbose=False) """ def __init__( self, config: GlowTTSConfig, ap: "AudioProcessor" = None, tokenizer: "TTSTokenizer" = None, speaker_manager: SpeakerManager = None, ): super().__init__(config, ap, tokenizer, speaker_manager) # pass all config fields to `self` # for fewer code change self.config = config for key in config: setattr(self, key, config[key]) self.decoder_output_dim = config.out_channels # init multi-speaker layers if necessary self.init_multispeaker(config) self.run_data_dep_init = config.data_dep_init_steps > 0
class GlowTTS(BaseTTS): """GlowTTS model. Paper:: https://arxiv.org/abs/2005.11129 Paper abstract:: Recently, text-to-speech (TTS) models such as FastSpeech and ParaNet have been proposed to generate mel-spectrograms from text in parallel. Despite the advantage, the parallel TTS models cannot be trained without guidance from autoregressive TTS models as their external aligners. In this work, we propose Glow-TTS, a flow-based generative model for parallel TTS that does not require any external aligner. By combining the properties of flows and dynamic programming, the proposed model searches for the most probable monotonic alignment between text and the latent representation of speech on its own. We demonstrate that enforcing hard monotonic alignments enables robust TTS, which generalizes to long utterances, and employing generative flows enables fast, diverse, and controllable speech synthesis. Glow-TTS obtains an order-of-magnitude speed-up over the autoregressive model, Tacotron 2, at synthesis with comparable speech quality. We further show that our model can be easily extended to a multi-speaker setting. Check :class:`TTS.tts.configs.glow_tts_config.GlowTTSConfig` for class arguments. Examples: Init only model layers. >>> from TTS.tts.configs.glow_tts_config import GlowTTSConfig >>> from TTS.tts.models.glow_tts import GlowTTS >>> config = GlowTTSConfig(num_chars=2) >>> model = GlowTTS(config) Fully init a model ready for action. All the class attributes and class members (e.g Tokenizer, AudioProcessor, etc.). are initialized internally based on config values. >>> from TTS.tts.configs.glow_tts_config import GlowTTSConfig >>> from TTS.tts.models.glow_tts import GlowTTS >>> config = GlowTTSConfig() >>> model = GlowTTS.init_from_config(config, verbose=False) """ def __init__( self, config: GlowTTSConfig, ap: "AudioProcessor" = None, tokenizer: "TTSTokenizer" = None, speaker_manager: SpeakerManager = None, ): super().__init__(config, ap, tokenizer, speaker_manager) # pass all config fields to `self` # for fewer code change self.config = config for key in config: setattr(self, key, config[key]) self.decoder_output_dim = config.out_channels # init multi-speaker layers if necessary self.init_multispeaker(config) self.run_data_dep_init = config.data_dep_init_steps > 0
self.encoder = Encoder(
2
2023-11-29 08:15:06+00:00
24k
magic-research/magic-animate
magicanimate/pipelines/pipeline_animation.py
[ { "identifier": "UNet3DConditionModel", "path": "magicanimate/models/unet_controlnet.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in_channels: int = 4,\n out_channels: int = 4,\n center_input_sample: bool = False,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0, \n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\",\n ),\n mid_block_type: str = \"UNetMidBlock3DCrossAttn\",\n up_block_types: Tuple[str] = (\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: int = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n dual_cross_attention: bool = False,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n \n # Additional\n use_motion_module = False,\n motion_module_resolutions = ( 1,2,4,8 ),\n motion_module_mid_block = False,\n motion_module_decoder_only = False,\n motion_module_type = None,\n motion_module_kwargs = {},\n unet_use_cross_frame_attention = None,\n unet_use_temporal_attention = None,\n ):\n super().__init__()\n\n self.sample_size = sample_size\n time_embed_dim = block_out_channels[0] * 4\n\n # input\n self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))\n\n # time\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n self.down_blocks = nn.ModuleList([])\n self.mid_block = None\n self.up_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n for i, down_block_type in enumerate(down_block_types):\n res = 2 ** i\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[i],\n downsample_padding=downsample_padding,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n \n use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.down_blocks.append(down_block)\n\n # mid\n if mid_block_type == \"UNetMidBlock3DCrossAttn\":\n self.mid_block = UNetMidBlock3DCrossAttn(\n in_channels=block_out_channels[-1],\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n \n use_motion_module=use_motion_module and motion_module_mid_block,\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n else:\n raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n \n # count how many layers upsample the videos\n self.num_upsamplers = 0\n\n # up\n reversed_block_out_channels = list(reversed(block_out_channels))\n reversed_attention_head_dim = list(reversed(attention_head_dim))\n only_cross_attention = list(reversed(only_cross_attention))\n output_channel = reversed_block_out_channels[0]\n for i, up_block_type in enumerate(up_block_types):\n res = 2 ** (3 - i)\n is_final_block = i == len(block_out_channels) - 1\n\n prev_output_channel = output_channel\n output_channel = reversed_block_out_channels[i]\n input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n # add upsample block for all BUT final layer\n if not is_final_block:\n add_upsample = True\n self.num_upsamplers += 1\n else:\n add_upsample = False\n\n up_block = get_up_block(\n up_block_type,\n num_layers=layers_per_block + 1,\n in_channels=input_channel,\n out_channels=output_channel,\n prev_output_channel=prev_output_channel,\n temb_channels=time_embed_dim,\n add_upsample=add_upsample,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n attn_num_head_channels=reversed_attention_head_dim[i],\n dual_cross_attention=dual_cross_attention,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n\n unet_use_cross_frame_attention=unet_use_cross_frame_attention,\n unet_use_temporal_attention=unet_use_temporal_attention,\n\n use_motion_module=use_motion_module and (res in motion_module_resolutions),\n motion_module_type=motion_module_type,\n motion_module_kwargs=motion_module_kwargs,\n )\n self.up_blocks.append(up_block)\n prev_output_channel = output_channel\n\n # out\n self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)\n self.conv_act = nn.SiLU()\n self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1)\n\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maxium amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_slicable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_slicable_dims(module)\n\n num_slicable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_slicable_layers * [1]\n\n slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n class_labels: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n # for controlnet\n down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n mid_block_additional_residual: Optional[torch.Tensor] = None,\n return_dict: bool = True,\n ) -> Union[UNet3DConditionOutput, Tuple]:\n r\"\"\"\n Args:\n sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor\n timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps\n encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states\n return_dict (`bool`, *optional*, defaults to `True`):\n Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.\n\n Returns:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:\n [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When\n returning a tuple, the first element is the sample tensor.\n \"\"\"\n # By default samples have to be AT least a multiple of the overall upsampling factor.\n # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).\n # However, the upsampling interpolation output size can be forced to fit any upsampling size\n # on the fly if necessary.\n default_overall_up_factor = 2**self.num_upsamplers\n\n # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n forward_upsample_size = False\n upsample_size = None\n\n if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):\n logger.info(\"Forward upsample size to force interpolation output size.\")\n forward_upsample_size = True\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # center input if necessary\n if self.config.center_input_sample:\n sample = 2 * sample - 1.0\n\n # time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n emb = self.time_embedding(t_emb)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # pre-process\n sample = self.conv_in(sample)\n\n # down\n is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None\n\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb, encoder_hidden_states=encoder_hidden_states)\n\n down_block_res_samples += res_samples\n\n if is_controlnet:\n new_down_block_res_samples = ()\n\n for down_block_res_sample, down_block_additional_residual in zip(\n down_block_res_samples, down_block_additional_residuals\n ):\n down_block_res_sample = down_block_res_sample + down_block_additional_residual\n new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)\n\n down_block_res_samples = new_down_block_res_samples\n\n # mid\n sample = self.mid_block(\n sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n\n if is_controlnet:\n sample = sample + mid_block_additional_residual\n\n # up\n for i, upsample_block in enumerate(self.up_blocks):\n is_final_block = i == len(self.up_blocks) - 1\n\n res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n # if we have not reached the final block and need to forward the\n # upsample size, we do it here\n if not is_final_block and forward_upsample_size:\n upsample_size = down_block_res_samples[-1].shape[2:]\n\n if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n sample = upsample_block(\n hidden_states=sample,\n temb=emb,\n res_hidden_states_tuple=res_samples,\n encoder_hidden_states=encoder_hidden_states,\n upsample_size=upsample_size,\n attention_mask=attention_mask,\n )\n else:\n sample = upsample_block(\n hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size, encoder_hidden_states=encoder_hidden_states,\n )\n\n # post-process\n sample = self.conv_norm_out(sample)\n sample = self.conv_act(sample)\n sample = self.conv_out(sample)\n\n if not return_dict:\n return (sample,)\n\n return UNet3DConditionOutput(sample=sample)\n\n @classmethod\n def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, unet_additional_kwargs=None):\n if subfolder is not None:\n pretrained_model_path = os.path.join(pretrained_model_path, subfolder)\n print(f\"loaded temporal unet's pretrained weights from {pretrained_model_path} ...\")\n\n config_file = os.path.join(pretrained_model_path, 'config.json')\n if not os.path.isfile(config_file):\n raise RuntimeError(f\"{config_file} does not exist\")\n with open(config_file, \"r\") as f:\n config = json.load(f)\n config[\"_class_name\"] = cls.__name__\n config[\"down_block_types\"] = [\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"CrossAttnDownBlock3D\",\n \"DownBlock3D\"\n ]\n config[\"up_block_types\"] = [\n \"UpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\",\n \"CrossAttnUpBlock3D\"\n ]\n # config[\"mid_block_type\"] = \"UNetMidBlock3DCrossAttn\"\n\n from diffusers.utils import WEIGHTS_NAME\n model = cls.from_config(config, **unet_additional_kwargs)\n model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)\n if not os.path.isfile(model_file):\n raise RuntimeError(f\"{model_file} does not exist\")\n state_dict = torch.load(model_file, map_location=\"cpu\")\n\n m, u = model.load_state_dict(state_dict, strict=False)\n print(f\"### missing keys: {len(m)}; \\n### unexpected keys: {len(u)};\")\n # print(f\"### missing keys:\\n{m}\\n### unexpected keys:\\n{u}\\n\")\n \n params = [p.numel() if \"temporal\" in n else 0 for n, p in model.named_parameters()]\n print(f\"### Temporal Module Parameters: {sum(params) / 1e6} M\")\n \n return model" }, { "identifier": "ControlNetModel", "path": "magicanimate/models/controlnet.py", "snippet": "class ControlNetModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n in_channels: int = 4,\n flip_sin_to_cos: bool = True,\n freq_shift: int = 0,\n down_block_types: Tuple[str] = (\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"CrossAttnDownBlock2D\",\n \"DownBlock2D\",\n ),\n only_cross_attention: Union[bool, Tuple[bool]] = False,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n layers_per_block: int = 2,\n downsample_padding: int = 1,\n mid_block_scale_factor: float = 1,\n act_fn: str = \"silu\",\n norm_num_groups: Optional[int] = 32,\n norm_eps: float = 1e-5,\n cross_attention_dim: int = 1280,\n attention_head_dim: Union[int, Tuple[int]] = 8,\n use_linear_projection: bool = False,\n class_embed_type: Optional[str] = None,\n num_class_embeds: Optional[int] = None,\n upcast_attention: bool = False,\n resnet_time_scale_shift: str = \"default\",\n projection_class_embeddings_input_dim: Optional[int] = None,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n ):\n super().__init__()\n\n # Check inputs\n if len(block_out_channels) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n )\n\n if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n raise ValueError(\n f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n )\n\n # input\n conv_in_kernel = 3\n conv_in_padding = (conv_in_kernel - 1) // 2\n self.conv_in = nn.Conv2d(\n in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n )\n\n # time\n time_embed_dim = block_out_channels[0] * 4\n\n self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n timestep_input_dim = block_out_channels[0]\n\n self.time_embedding = TimestepEmbedding(\n timestep_input_dim,\n time_embed_dim,\n act_fn=act_fn,\n )\n\n # class embedding\n if class_embed_type is None and num_class_embeds is not None:\n self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n elif class_embed_type == \"timestep\":\n self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)\n elif class_embed_type == \"identity\":\n self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n elif class_embed_type == \"projection\":\n if projection_class_embeddings_input_dim is None:\n raise ValueError(\n \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n )\n # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n # 2. it projects from an arbitrary input dimension.\n #\n # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n else:\n self.class_embedding = None\n\n # control net conditioning embedding\n self.controlnet_cond_embedding = ControlNetConditioningEmbedding(\n conditioning_embedding_channels=block_out_channels[0],\n block_out_channels=conditioning_embedding_out_channels,\n )\n\n self.down_blocks = nn.ModuleList([])\n self.controlnet_down_blocks = nn.ModuleList([])\n\n if isinstance(only_cross_attention, bool):\n only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n if isinstance(attention_head_dim, int):\n attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n # down\n output_channel = block_out_channels[0]\n\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n for i, down_block_type in enumerate(down_block_types):\n input_channel = output_channel\n output_channel = block_out_channels[i]\n is_final_block = i == len(block_out_channels) - 1\n\n down_block = get_down_block(\n down_block_type,\n num_layers=layers_per_block,\n in_channels=input_channel,\n out_channels=output_channel,\n temb_channels=time_embed_dim,\n add_downsample=not is_final_block,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n resnet_groups=norm_num_groups,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[i],\n downsample_padding=downsample_padding,\n use_linear_projection=use_linear_projection,\n only_cross_attention=only_cross_attention[i],\n upcast_attention=upcast_attention,\n resnet_time_scale_shift=resnet_time_scale_shift,\n )\n self.down_blocks.append(down_block)\n\n for _ in range(layers_per_block):\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n if not is_final_block:\n controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_down_blocks.append(controlnet_block)\n\n # mid\n mid_block_channel = block_out_channels[-1]\n\n controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)\n controlnet_block = zero_module(controlnet_block)\n self.controlnet_mid_block = controlnet_block\n\n self.mid_block = UNetMidBlock2DCrossAttn(\n in_channels=mid_block_channel,\n temb_channels=time_embed_dim,\n resnet_eps=norm_eps,\n resnet_act_fn=act_fn,\n output_scale_factor=mid_block_scale_factor,\n resnet_time_scale_shift=resnet_time_scale_shift,\n cross_attention_dim=cross_attention_dim,\n num_attention_heads=attention_head_dim[-1],\n resnet_groups=norm_num_groups,\n use_linear_projection=use_linear_projection,\n upcast_attention=upcast_attention,\n )\n\n @classmethod\n def from_unet(\n cls,\n unet: UNet2DConditionModel,\n controlnet_conditioning_channel_order: str = \"rgb\",\n conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),\n load_weights_from_unet: bool = True,\n ):\n r\"\"\"\n Instantiate Controlnet class from UNet2DConditionModel.\n\n Parameters:\n unet (`UNet2DConditionModel`):\n UNet model which weights are copied to the ControlNet. Note that all configuration options are also\n copied where applicable.\n \"\"\"\n controlnet = cls(\n in_channels=unet.config.in_channels,\n flip_sin_to_cos=unet.config.flip_sin_to_cos,\n freq_shift=unet.config.freq_shift,\n down_block_types=unet.config.down_block_types,\n only_cross_attention=unet.config.only_cross_attention,\n block_out_channels=unet.config.block_out_channels,\n layers_per_block=unet.config.layers_per_block,\n downsample_padding=unet.config.downsample_padding,\n mid_block_scale_factor=unet.config.mid_block_scale_factor,\n act_fn=unet.config.act_fn,\n norm_num_groups=unet.config.norm_num_groups,\n norm_eps=unet.config.norm_eps,\n cross_attention_dim=unet.config.cross_attention_dim,\n attention_head_dim=unet.config.attention_head_dim,\n use_linear_projection=unet.config.use_linear_projection,\n class_embed_type=unet.config.class_embed_type,\n num_class_embeds=unet.config.num_class_embeds,\n upcast_attention=unet.config.upcast_attention,\n resnet_time_scale_shift=unet.config.resnet_time_scale_shift,\n projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,\n controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,\n conditioning_embedding_out_channels=conditioning_embedding_out_channels,\n )\n\n if load_weights_from_unet:\n controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())\n controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())\n controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())\n\n if controlnet.class_embedding:\n controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())\n\n controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())\n controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())\n\n return controlnet\n\n # @property\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors\n # def attn_processors(self) -> Dict[str, AttentionProcessor]:\n # r\"\"\"\n # Returns:\n # `dict` of attention processors: A dictionary containing all attention processors used in the model with\n # indexed by its weight name.\n # \"\"\"\n # # set recursively\n # processors = {}\n\n # def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):\n # if hasattr(module, \"set_processor\"):\n # processors[f\"{name}.processor\"] = module.processor\n\n # for sub_name, child in module.named_children():\n # fn_recursive_add_processors(f\"{name}.{sub_name}\", child, processors)\n\n # return processors\n\n # for name, module in self.named_children():\n # fn_recursive_add_processors(name, module, processors)\n\n # return processors\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor\n # def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):\n # r\"\"\"\n # Parameters:\n # `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`):\n # The instantiated processor class or a dictionary of processor classes that will be set as the processor\n # of **all** `Attention` layers.\n # In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.:\n\n # \"\"\"\n # count = len(self.attn_processors.keys())\n\n # if isinstance(processor, dict) and len(processor) != count:\n # raise ValueError(\n # f\"A dict of processors was passed, but the number of processors {len(processor)} does not match the\"\n # f\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\n # )\n\n # def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):\n # if hasattr(module, \"set_processor\"):\n # if not isinstance(processor, dict):\n # module.set_processor(processor)\n # else:\n # module.set_processor(processor.pop(f\"{name}.processor\"))\n\n # for sub_name, child in module.named_children():\n # fn_recursive_attn_processor(f\"{name}.{sub_name}\", child, processor)\n\n # for name, module in self.named_children():\n # fn_recursive_attn_processor(name, module, processor)\n\n # # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor\n # def set_default_attn_processor(self):\n # \"\"\"\n # Disables custom attention processors and sets the default attention implementation.\n # \"\"\"\n # self.set_attn_processor(AttnProcessor())\n\n # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice\n def set_attention_slice(self, slice_size):\n r\"\"\"\n Enable sliced attention computation.\n\n When this option is enabled, the attention module will split the input tensor in slices, to compute attention\n in several steps. This is useful to save some memory in exchange for a small speed decrease.\n\n Args:\n slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n When `\"auto\"`, halves the input to the attention heads, so attention will be computed in two steps. If\n `\"max\"`, maximum amount of memory will be saved by running only one slice at a time. If a number is\n provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n must be a multiple of `slice_size`.\n \"\"\"\n sliceable_head_dims = []\n\n def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):\n if hasattr(module, \"set_attention_slice\"):\n sliceable_head_dims.append(module.sliceable_head_dim)\n\n for child in module.children():\n fn_recursive_retrieve_sliceable_dims(child)\n\n # retrieve number of attention layers\n for module in self.children():\n fn_recursive_retrieve_sliceable_dims(module)\n\n num_sliceable_layers = len(sliceable_head_dims)\n\n if slice_size == \"auto\":\n # half the attention head size is usually a good trade-off between\n # speed and memory\n slice_size = [dim // 2 for dim in sliceable_head_dims]\n elif slice_size == \"max\":\n # make smallest slice possible\n slice_size = num_sliceable_layers * [1]\n\n slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n if len(slice_size) != len(sliceable_head_dims):\n raise ValueError(\n f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n )\n\n for i in range(len(slice_size)):\n size = slice_size[i]\n dim = sliceable_head_dims[i]\n if size is not None and size > dim:\n raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n # Recursively walk through all the children.\n # Any children which exposes the set_attention_slice method\n # gets the message\n def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n if hasattr(module, \"set_attention_slice\"):\n module.set_attention_slice(slice_size.pop())\n\n for child in module.children():\n fn_recursive_set_attention_slice(child, slice_size)\n\n reversed_slice_size = list(reversed(slice_size))\n for module in self.children():\n fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):\n module.gradient_checkpointing = value\n\n def forward(\n self,\n sample: torch.FloatTensor,\n timestep: Union[torch.Tensor, float, int],\n encoder_hidden_states: torch.Tensor,\n controlnet_cond: torch.FloatTensor,\n conditioning_scale: float = 1.0,\n class_labels: Optional[torch.Tensor] = None,\n timestep_cond: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n return_dict: bool = True,\n ) -> Union[ControlNetOutput, Tuple]:\n # check channel order\n channel_order = self.config.controlnet_conditioning_channel_order\n\n if channel_order == \"rgb\":\n # in rgb order by default\n ...\n elif channel_order == \"bgr\":\n controlnet_cond = torch.flip(controlnet_cond, dims=[1])\n else:\n raise ValueError(f\"unknown `controlnet_conditioning_channel_order`: {channel_order}\")\n\n # prepare attention_mask\n if attention_mask is not None:\n attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n attention_mask = attention_mask.unsqueeze(1)\n\n # 1. time\n timesteps = timestep\n if not torch.is_tensor(timesteps):\n # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n # This would be a good case for the `match` statement (Python 3.10+)\n is_mps = sample.device.type == \"mps\"\n if isinstance(timestep, float):\n dtype = torch.float32 if is_mps else torch.float64\n else:\n dtype = torch.int32 if is_mps else torch.int64\n timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n elif len(timesteps.shape) == 0:\n timesteps = timesteps[None].to(sample.device)\n\n # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n timesteps = timesteps.expand(sample.shape[0])\n\n t_emb = self.time_proj(timesteps)\n\n # timesteps does not contain any weights and will always return f32 tensors\n # but time_embedding might actually be running in fp16. so we need to cast here.\n # there might be better ways to encapsulate this.\n t_emb = t_emb.to(dtype=self.dtype)\n\n emb = self.time_embedding(t_emb, timestep_cond)\n\n if self.class_embedding is not None:\n if class_labels is None:\n raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n if self.config.class_embed_type == \"timestep\":\n class_labels = self.time_proj(class_labels)\n\n class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)\n emb = emb + class_emb\n\n # 2. pre-process\n sample = self.conv_in(sample)\n\n controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)\n\n sample += controlnet_cond\n\n # 3. down\n down_block_res_samples = (sample,)\n for downsample_block in self.down_blocks:\n if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n sample, res_samples = downsample_block(\n hidden_states=sample,\n temb=emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n else:\n sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n\n down_block_res_samples += res_samples\n\n # 4. mid\n if self.mid_block is not None:\n sample = self.mid_block(\n sample,\n emb,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=attention_mask,\n # cross_attention_kwargs=cross_attention_kwargs,\n )\n\n # 5. Control net blocks\n\n controlnet_down_block_res_samples = ()\n\n for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):\n down_block_res_sample = controlnet_block(down_block_res_sample)\n controlnet_down_block_res_samples += (down_block_res_sample,)\n\n down_block_res_samples = controlnet_down_block_res_samples\n\n mid_block_res_sample = self.controlnet_mid_block(sample)\n\n # 6. scaling\n down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]\n mid_block_res_sample *= conditioning_scale\n\n if not return_dict:\n return (down_block_res_samples, mid_block_res_sample)\n\n return ControlNetOutput(\n down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample\n )" }, { "identifier": "ReferenceAttentionControl", "path": "magicanimate/models/mutual_self_attention.py", "snippet": "class ReferenceAttentionControl():\n \n def __init__(self, \n unet,\n mode=\"write\",\n do_classifier_free_guidance=False,\n attention_auto_machine_weight = float('inf'),\n gn_auto_machine_weight = 1.0,\n style_fidelity = 1.0,\n reference_attn=True,\n reference_adain=False,\n fusion_blocks=\"midup\",\n batch_size=1, \n ) -> None:\n # 10. Modify self attention and group norm\n self.unet = unet\n assert mode in [\"read\", \"write\"]\n assert fusion_blocks in [\"midup\", \"full\"]\n self.reference_attn = reference_attn\n self.reference_adain = reference_adain\n self.fusion_blocks = fusion_blocks\n self.register_reference_hooks(\n mode, \n do_classifier_free_guidance,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n fusion_blocks,\n batch_size=batch_size, \n )\n\n def register_reference_hooks(\n self, \n mode, \n do_classifier_free_guidance,\n attention_auto_machine_weight,\n gn_auto_machine_weight,\n style_fidelity,\n reference_attn,\n reference_adain,\n dtype=torch.float16,\n batch_size=1, \n num_images_per_prompt=1, \n device=torch.device(\"cpu\"), \n fusion_blocks='midup',\n ):\n MODE = mode\n do_classifier_free_guidance = do_classifier_free_guidance\n attention_auto_machine_weight = attention_auto_machine_weight\n gn_auto_machine_weight = gn_auto_machine_weight\n style_fidelity = style_fidelity\n reference_attn = reference_attn\n reference_adain = reference_adain\n fusion_blocks = fusion_blocks\n num_images_per_prompt = num_images_per_prompt\n dtype=dtype\n if do_classifier_free_guidance:\n uc_mask = (\n torch.Tensor([1] * batch_size * num_images_per_prompt * 16 + [0] * batch_size * num_images_per_prompt * 16)\n .to(device)\n .bool()\n )\n else:\n uc_mask = (\n torch.Tensor([0] * batch_size * num_images_per_prompt * 2)\n .to(device)\n .bool()\n )\n \n def hacked_basic_transformer_inner_forward(\n self,\n hidden_states: torch.FloatTensor,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n timestep: Optional[torch.LongTensor] = None,\n cross_attention_kwargs: Dict[str, Any] = None,\n class_labels: Optional[torch.LongTensor] = None,\n video_length=None,\n ):\n if self.use_ada_layer_norm:\n norm_hidden_states = self.norm1(hidden_states, timestep)\n elif self.use_ada_layer_norm_zero:\n norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(\n hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype\n )\n else:\n norm_hidden_states = self.norm1(hidden_states)\n\n # 1. Self-Attention\n cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}\n if self.only_cross_attention:\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n else:\n if MODE == \"write\":\n self.bank.append(norm_hidden_states.clone())\n attn_output = self.attn1(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,\n attention_mask=attention_mask,\n **cross_attention_kwargs,\n )\n if MODE == \"read\":\n self.bank = [rearrange(d.unsqueeze(1).repeat(1, video_length, 1, 1), \"b t l c -> (b t) l c\")[:hidden_states.shape[0]] for d in self.bank]\n hidden_states_uc = self.attn1(norm_hidden_states, \n encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),\n attention_mask=attention_mask) + hidden_states\n hidden_states_c = hidden_states_uc.clone()\n _uc_mask = uc_mask.clone()\n if do_classifier_free_guidance:\n if hidden_states.shape[0] != _uc_mask.shape[0]:\n _uc_mask = (\n torch.Tensor([1] * (hidden_states.shape[0]//2) + [0] * (hidden_states.shape[0]//2))\n .to(device)\n .bool()\n )\n hidden_states_c[_uc_mask] = self.attn1(\n norm_hidden_states[_uc_mask],\n encoder_hidden_states=norm_hidden_states[_uc_mask],\n attention_mask=attention_mask,\n ) + hidden_states[_uc_mask]\n hidden_states = hidden_states_c.clone()\n \n self.bank.clear()\n if self.attn2 is not None:\n # Cross-Attention\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n hidden_states = (\n self.attn2(\n norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask\n )\n + hidden_states\n )\n\n # Feed-forward\n hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states\n\n # Temporal-Attention\n if self.unet_use_temporal_attention:\n d = hidden_states.shape[1]\n hidden_states = rearrange(hidden_states, \"(b f) d c -> (b d) f c\", f=video_length)\n norm_hidden_states = (\n self.norm_temp(hidden_states, timestep) if self.use_ada_layer_norm else self.norm_temp(hidden_states)\n )\n hidden_states = self.attn_temp(norm_hidden_states) + hidden_states\n hidden_states = rearrange(hidden_states, \"(b d) f c -> (b f) d c\", d=d)\n\n return hidden_states\n \n if self.use_ada_layer_norm_zero:\n attn_output = gate_msa.unsqueeze(1) * attn_output\n hidden_states = attn_output + hidden_states\n\n if self.attn2 is not None:\n norm_hidden_states = (\n self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)\n )\n\n # 2. Cross-Attention\n attn_output = self.attn2(\n norm_hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n attention_mask=encoder_attention_mask,\n **cross_attention_kwargs,\n )\n hidden_states = attn_output + hidden_states\n\n # 3. Feed-forward\n norm_hidden_states = self.norm3(hidden_states)\n\n if self.use_ada_layer_norm_zero:\n norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]\n\n ff_output = self.ff(norm_hidden_states)\n\n if self.use_ada_layer_norm_zero:\n ff_output = gate_mlp.unsqueeze(1) * ff_output\n\n hidden_states = ff_output + hidden_states\n\n return hidden_states\n\n def hacked_mid_forward(self, *args, **kwargs):\n eps = 1e-6\n x = self.original_forward(*args, **kwargs)\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append(mean)\n self.var_bank.append(var)\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))\n var_acc = sum(self.var_bank) / float(len(self.var_bank))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n x_uc = (((x - mean) / std) * std_acc) + mean_acc\n x_c = x_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n x_c[uc_mask] = x[uc_mask]\n x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc\n self.mean_bank = []\n self.var_bank = []\n return x\n\n def hack_CrossAttnDownBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n\n # TODO(Patrick, William) - attention mask is not used\n output_states = ()\n\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_DownBlock2D_forward(self, hidden_states, temb=None):\n eps = 1e-6\n\n output_states = ()\n\n for i, resnet in enumerate(self.resnets):\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n output_states = output_states + (hidden_states,)\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.downsamplers is not None:\n for downsampler in self.downsamplers:\n hidden_states = downsampler(hidden_states)\n\n output_states = output_states + (hidden_states,)\n\n return hidden_states, output_states\n\n def hacked_CrossAttnUpBlock2D_forward(\n self,\n hidden_states: torch.FloatTensor,\n res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],\n temb: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.FloatTensor] = None,\n cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n upsample_size: Optional[int] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n ):\n eps = 1e-6\n # TODO(Patrick, William) - attention mask is not used\n for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n hidden_states = attn(\n hidden_states,\n encoder_hidden_states=encoder_hidden_states,\n cross_attention_kwargs=cross_attention_kwargs,\n attention_mask=attention_mask,\n encoder_attention_mask=encoder_attention_mask,\n return_dict=False,\n )[0]\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):\n eps = 1e-6\n for i, resnet in enumerate(self.resnets):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n hidden_states = resnet(hidden_states, temb)\n\n if MODE == \"write\":\n if gn_auto_machine_weight >= self.gn_weight:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n self.mean_bank.append([mean])\n self.var_bank.append([var])\n if MODE == \"read\":\n if len(self.mean_bank) > 0 and len(self.var_bank) > 0:\n var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)\n std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5\n mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))\n var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))\n std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5\n hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc\n hidden_states_c = hidden_states_uc.clone()\n if do_classifier_free_guidance and style_fidelity > 0:\n hidden_states_c[uc_mask] = hidden_states[uc_mask].to(hidden_states_c.dtype)\n hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc\n\n if MODE == \"read\":\n self.mean_bank = []\n self.var_bank = []\n\n if self.upsamplers is not None:\n for upsampler in self.upsamplers:\n hidden_states = upsampler(hidden_states, upsample_size)\n\n return hidden_states\n\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)] \n attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n\n for i, module in enumerate(attn_modules):\n module._original_inner_forward = module.forward\n module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)\n module.bank = []\n module.attn_weight = float(i) / float(len(attn_modules))\n\n if self.reference_adain:\n gn_modules = [self.unet.mid_block]\n self.unet.mid_block.gn_weight = 0\n\n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n module.gn_weight = 1.0 - float(w) / float(len(down_blocks))\n gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n module.gn_weight = float(w) / float(len(up_blocks))\n gn_modules.append(module)\n\n for i, module in enumerate(gn_modules):\n if getattr(module, \"original_forward\", None) is None:\n module.original_forward = module.forward\n if i == 0:\n # mid_block\n module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)\n elif isinstance(module, CrossAttnDownBlock2D):\n module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)\n elif isinstance(module, DownBlock2D):\n module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)\n elif isinstance(module, CrossAttnUpBlock2D):\n module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)\n elif isinstance(module, UpBlock2D):\n module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)\n module.mean_bank = []\n module.var_bank = []\n module.gn_weight *= 2\n \n def update(self, writer, dtype=torch.float16):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in (torch_dfs(writer.unet.mid_block)+torch_dfs(writer.unet.up_blocks)) if isinstance(module, BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, _BasicTransformerBlock)]\n writer_attn_modules = [module for module in torch_dfs(writer.unet) if isinstance(module, BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]) \n writer_attn_modules = sorted(writer_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r, w in zip(reader_attn_modules, writer_attn_modules):\n r.bank = [v.clone().to(dtype) for v in w.bank]\n # w.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n writer_gn_modules = [writer.unet.mid_block]\n \n down_blocks = writer.unet.down_blocks\n for w, module in enumerate(down_blocks):\n writer_gn_modules.append(module)\n\n up_blocks = writer.unet.up_blocks\n for w, module in enumerate(up_blocks):\n writer_gn_modules.append(module)\n \n for r, w in zip(reader_gn_modules, writer_gn_modules):\n if len(w.mean_bank) > 0 and isinstance(w.mean_bank[0], list):\n r.mean_bank = [[v.clone().to(dtype) for v in vl] for vl in w.mean_bank]\n r.var_bank = [[v.clone().to(dtype) for v in vl] for vl in w.var_bank]\n else:\n r.mean_bank = [v.clone().to(dtype) for v in w.mean_bank]\n r.var_bank = [v.clone().to(dtype) for v in w.var_bank]\n \n def clear(self):\n if self.reference_attn:\n if self.fusion_blocks == \"midup\":\n reader_attn_modules = [module for module in (torch_dfs(self.unet.mid_block)+torch_dfs(self.unet.up_blocks)) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n elif self.fusion_blocks == \"full\":\n reader_attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock) or isinstance(module, _BasicTransformerBlock)]\n reader_attn_modules = sorted(reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0])\n for r in reader_attn_modules:\n r.bank.clear()\n if self.reference_adain:\n reader_gn_modules = [self.unet.mid_block]\n \n down_blocks = self.unet.down_blocks\n for w, module in enumerate(down_blocks):\n reader_gn_modules.append(module)\n\n up_blocks = self.unet.up_blocks\n for w, module in enumerate(up_blocks):\n reader_gn_modules.append(module)\n \n for r in reader_gn_modules:\n r.mean_bank.clear()\n r.var_bank.clear()" }, { "identifier": "get_context_scheduler", "path": "magicanimate/pipelines/context.py", "snippet": "def get_context_scheduler(name: str) -> Callable:\n if name == \"uniform\":\n return uniform\n else:\n raise ValueError(f\"Unknown context_overlap policy {name}\")" }, { "identifier": "get_total_steps", "path": "magicanimate/pipelines/context.py", "snippet": "def get_total_steps(\n scheduler,\n timesteps: List[int],\n num_steps: Optional[int] = None,\n num_frames: int = ...,\n context_size: Optional[int] = None,\n context_stride: int = 3,\n context_overlap: int = 4,\n closed_loop: bool = True,\n):\n return sum(\n len(\n list(\n scheduler(\n i,\n num_steps,\n num_frames,\n context_size,\n context_stride,\n context_overlap,\n )\n )\n )\n for i in range(len(timesteps))\n )" }, { "identifier": "get_tensor_interpolation_method", "path": "magicanimate/utils/util.py", "snippet": "def get_tensor_interpolation_method():\n return tensor_interpolation" } ]
import inspect, math import numpy as np import torch import torch.distributed as dist from typing import Callable, List, Optional, Union from dataclasses import dataclass from PIL import Image from tqdm import tqdm from diffusers.utils import is_accelerate_available from packaging import version from transformers import CLIPTextModel, CLIPTokenizer from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL from diffusers.pipeline_utils import DiffusionPipeline from diffusers.schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from diffusers.utils import deprecate, logging, BaseOutput from einops import rearrange from magicanimate.models.unet_controlnet import UNet3DConditionModel from magicanimate.models.controlnet import ControlNetModel from magicanimate.models.mutual_self_attention import ReferenceAttentionControl from magicanimate.pipelines.context import ( get_context_scheduler, get_total_steps ) from magicanimate.utils.util import get_tensor_interpolation_method from accelerate import cpu_offload
16,739
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TODO: 1. support multi-controlnet 2. [DONE] support DDIM inversion 3. support Prompt-to-prompt """ logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] class AnimationPipeline(DiffusionPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer,
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TODO: 1. support multi-controlnet 2. [DONE] support DDIM inversion 3. support Prompt-to-prompt """ logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] class AnimationPipeline(DiffusionPipeline): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer,
unet: UNet3DConditionModel,
0
2023-11-21 08:33:54+00:00
24k
HeliosZhao/Animate124
dnerf/utils.py
[ { "identifier": "save_tensor2image", "path": "nerf/utils.py", "snippet": "def save_tensor2image(x: torch.Tensor, path, channel_last=False, quality=75, **kwargs):\n # assume the input x is channel last\n # ipdb.set_trace()\n # if x.ndim == 4:\n # if channel_last:\n # x = x.permute(0, 3, 1, 2) \n # TF.to_pil_image(make_grid(x, value_range=(0, 1), **kwargs)).save(path, quality=quality)\n if x.ndim == 5:\n ## video\n # ipdb.set_trace()\n path = os.path.splitext(path)[0] + '.mp4' # convert image to mp4\n # B,F,C,H,W or B,F,H,W,C\n if channel_last: # B,F,H,W,C\n x = rearrange(x, \"b f h w c -> b f c h w\")\n save_videos_grid(x, path, **kwargs)\n else:\n if channel_last:\n x = x.permute(0, 3, 1, 2) \n TF.to_pil_image(make_grid(x, value_range=(0, 1), **kwargs)).save(path, quality=quality)" }, { "identifier": "nonzero_normalize_depth", "path": "nerf/utils.py", "snippet": "def nonzero_normalize_depth(depth, mask=None):\n if mask is not None:\n if (depth[mask]>0).sum() > 0:\n nonzero_depth_min = depth[mask][depth[mask]>0].min()\n else:\n nonzero_depth_min = 0\n else:\n if (depth>0).sum() > 0:\n nonzero_depth_min = depth[depth>0].min()\n else:\n nonzero_depth_min = 0\n if nonzero_depth_min == 0:\n return depth\n else:\n depth = (depth - nonzero_depth_min) \n depth = depth / (depth.max()+1e-6)\n return depth.clamp(0, 1)" }, { "identifier": "Trainer", "path": "nerf/utils.py", "snippet": "class Trainer(object):\n def __init__(self,\n\t\t argv, # command line args\n name, # name of this experiment\n opt, # extra conf\n model, # network\n guidance, # guidance network\n criterion=None, # loss function, if None, assume inline implementation in train_step\n optimizer=None, # optimizer\n ema_decay=None, # if use EMA, set the decay\n lr_scheduler=None, # scheduler\n metrics=[], # metrics for evaluation, if None, use val_loss to measure performance, else use the first metric.\n local_rank=0, # which GPU am I\n world_size=1, # total num of GPUs\n device=None, # device to use, usually setting to None is OK. (auto choose device)\n mute=False, # whether to mute all print\n fp16=False, # amp optimize level\n max_keep_ckpt=1, # max num of saved ckpts in disk\n workspace='workspace', # workspace to save logs & ckpts\n best_mode='min', # the smaller/larger result, the better\n use_loss_as_metric=True, # use loss as the first metric\n report_metric_at_train=False, # also report metrics at training\n use_checkpoint=\"latest\", # which ckpt to use at init time\n use_tensorboard=True, # whether to use tensorboard for logging\n scheduler_update_every_step=False, # whether to call scheduler.step() after every train step\n **kwargs\n ):\n\n self.argv = argv\n self.name = name\n self.opt = opt\n self.mute = mute\n self.metrics = metrics\n self.local_rank = local_rank\n self.world_size = world_size\n self.workspace = workspace\n self.ema_decay = ema_decay\n self.fp16 = fp16\n self.best_mode = best_mode\n self.use_loss_as_metric = use_loss_as_metric\n self.report_metric_at_train = report_metric_at_train\n self.max_keep_ckpt = opt.get(\"max_keep_ckpt\", max_keep_ckpt)\n self.use_checkpoint = use_checkpoint\n self.use_tensorboard = use_tensorboard\n self.time_stamp = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n self.scheduler_update_every_step = scheduler_update_every_step\n self.device = device if device is not None else torch.device(f'cuda:{local_rank}' if torch.cuda.is_available() else 'cpu')\n self.console = Console()\n\n model.to(self.device)\n if self.world_size > 1:\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank])\n self.model = model\n\n # guide model\n self.guidance = guidance\n self.embeddings = {}\n\n # text prompt / images\n if self.guidance is not None:\n for key in self.guidance:\n for p in self.guidance[key].parameters():\n p.requires_grad = False\n self.embeddings[key] = {}\n self.prepare_embeddings()\n\n if isinstance(criterion, nn.Module):\n criterion.to(self.device)\n self.criterion = criterion\n\n if optimizer is None:\n self.optimizer = optim.Adam(self.model.parameters(), lr=0.001, weight_decay=5e-4) # naive adam\n else:\n self.optimizer = optimizer(self.model)\n\n if lr_scheduler is None: ## scheduler is all one, for nerf model other than vanilla nerf\n self.lr_scheduler = optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lambda epoch: 1) # fake scheduler\n else:\n self.lr_scheduler = lr_scheduler(self.optimizer) \n\n if ema_decay:\n self.ema = ExponentialMovingAverage(\n self.model.parameters(), decay=ema_decay)\n else:\n self.ema = None\n\n self.scaler = torch.cuda.amp.GradScaler(enabled=self.fp16)\n\n # variable init\n self.total_train_t = 0\n self.epoch = 0\n self.global_step = 0\n self.local_step = 0\n self.novel_view_step = 0\n self.stats = {\n \"loss\": [],\n \"valid_loss\": [],\n \"results\": [], # metrics[0], or valid_loss\n \"checkpoints\": [], # record path of saved ckpt, to automatically remove old ckpt\n \"best_result\": None,\n }\n self.loss_meter = AverageMeters()\n # auto fix\n if len(metrics) == 0 or self.use_loss_as_metric:\n self.best_mode = 'min'\n\n logger.info(f'[INFO] cmdline: {self.argv}')\n logger.info(f'args:\\n{self.opt}')\n logger.info(\n f'[INFO] Trainer: {self.name} | {self.time_stamp} | {self.device} | {\"fp16\" if self.fp16 else \"fp32\"} | {self.workspace}')\n logger.info(\n f'[INFO] #parameters: {sum([p.numel() for p in model.parameters() if p.requires_grad])}')\n logger.info(f'[INFO] #Optimizer: \\n{self.optimizer}')\n logger.info(f'[INFO] #Scheduler: \\n{self.lr_scheduler}')\n\n if self.workspace is not None:\n if self.use_checkpoint == \"scratch\":\n logger.info(\"[INFO] Training from scratch ...\")\n elif self.use_checkpoint == \"latest\":\n logger.info(\"[INFO] Loading latest checkpoint ...\")\n self.load_checkpoint()\n elif self.use_checkpoint == \"latest_model\":\n logger.info(\"[INFO] Loading latest checkpoint (model only)...\")\n self.load_checkpoint(model_only=True)\n elif self.use_checkpoint == \"best\":\n if os.path.exists(self.opt.best_path):\n logger.info(\"[INFO] Loading best checkpoint ...\")\n self.load_checkpoint(self.opt.best_path)\n else:\n logger.info(\n f\"[INFO] {self.opt.best_path} not found, loading latest ...\")\n self.load_checkpoint()\n else: # path to ckpt\n logger.info(f\"[INFO] Loading {self.use_checkpoint} ...\")\n self.load_checkpoint(self.use_checkpoint)\n\n # calculate the text embs.\n @torch.no_grad()\n def prepare_embeddings(self):\n\n # text embeddings (stable-diffusion)\n if self.opt.text is not None:\n assert not self.opt.text_emb_all\n dir_texts = ['front', 'side', 'back']\n if 'SD' in self.guidance:\n if self.opt.text_emb_all:\n self.embeddings['SD']['default'] = self.guidance['SD'].get_all_text_embeds([self.opt.text])\n neg_embedding = self.guidance['SD'].get_all_text_embeds([self.opt.negative])\n else:\n self.embeddings['SD']['default'] = self.guidance['SD'].get_text_embeds([self.opt.text])\n neg_embedding = self.guidance['SD'].get_text_embeds([self.opt.negative])\n \n self.embeddings['SD']['default'] = torch.cat((neg_embedding, self.embeddings['SD']['default']), dim=0)\n\n for idx, d in enumerate(dir_texts):\n text = f\"{self.opt.text}, {d} view\"\n if self.opt.text_emb_all:\n self.embeddings['SD'][d] = self.guidance['SD'].get_all_text_embeds([text])\n else:\n self.embeddings['SD'][d] = self.guidance['SD'].get_text_embeds([text])\n if self.opt.dir_texts_neg:\n text_neg = self.opt.negative + ', '.join([text+' view' for i, text in enumerate(dir_texts) if i != idx]) \n logger.info(f'dir_texts of {d}\\n postive text: {text},\\n negative text: {text_neg}')\n if self.opt.text_emb_all:\n neg_embedding= self.guidance['SD'].get_all_text_embeds([text_neg])\n else:\n neg_embedding= self.guidance['SD'].get_text_embeds([text_neg])\n self.embeddings['SD'][d] = torch.cat((neg_embedding, self.embeddings['SD'][d]), dim=0)\n\n\n if 'IF' in self.guidance:\n self.embeddings['IF']['default'] = self.guidance['IF'].get_text_embeds([self.opt.text])\n neg_embedding = self.guidance['IF'].get_text_embeds([self.opt.negative])\n\n for idx, d in enumerate(dir_texts):\n text = f\"{self.opt.text}, {d} view\"\n self.embeddings['IF'][d] = self.guidance['IF'].get_text_embeds([text])\n if self.opt.dir_texts_neg:\n text_neg = self.opt.negative + ', '.join([text+' view' for i, text in enumerate(dir_texts) if i != idx]) \n logger.info(f'dir_texts of {d}\\n postive text: {text},\\n negative text: {text_neg}')\n neg_embedding= self.guidance['IF'].get_text_embeds([text_neg])\n self.embeddings['IF'][d] = torch.cat((neg_embedding, self.embeddings['IF'][d]), dim=0)\n \n # if 'clip' in self.guidance:\n # self.embeddings['clip']['text'] = self.guidance['clip'].get_text_embeds(self.opt.text)\n\n if self.opt.cn_text is not None:\n # ipdb.set_trace()\n assert 'CN' in self.guidance\n dir_texts = ['front', 'side', 'back']\n self.embeddings['CN']['default'] = self.guidance['CN'].get_text_embeds([self.opt.cn_text])\n neg_embedding = self.guidance['CN'].get_text_embeds([self.opt.negative])\n self.embeddings['CN']['default'] = torch.cat((neg_embedding, self.embeddings['CN']['default']), dim=0)\n\n ## embedding for controlnet -> best quality\n self.embeddings['CN']['CN'] = self.guidance['CN'].get_text_embeds([self.opt.cn_cn_text])\n self.embeddings['CN']['CN'] = torch.cat((neg_embedding, self.embeddings['CN']['CN']), dim=0)\n\n for idx, d in enumerate(dir_texts):\n text = f\"{self.opt.cn_text}, {d} view\"\n self.embeddings['CN'][d] = self.guidance['CN'].get_text_embeds([text])\n if self.opt.dir_texts_neg:\n text_neg = self.opt.negative + ', '.join([text+' view' for i, text in enumerate(dir_texts) if i != idx]) \n logger.info(f'dir_texts of {d}\\n postive text: {text},\\n negative text: {text_neg}')\n neg_embedding= self.guidance['CN'].get_text_embeds([text_neg])\n self.embeddings['CN'][d] = torch.cat((neg_embedding, self.embeddings['CN'][d]), dim=0)\n\n\n if self.opt.images is not None:\n\n h = int(self.opt.known_view_scale * self.opt.h)\n w = int(self.opt.known_view_scale * self.opt.w)\n\n # load processed image and remove edges\n rgbas = []\n rgbas_hw = []\n mask_no_edges = []\n for image in self.opt.images:\n rgba = cv2.cvtColor(cv2.imread(image, cv2.IMREAD_UNCHANGED), cv2.COLOR_BGRA2RGBA)\n rgbas.append(rgba)\n rgba_hw = cv2.resize(rgba, (w, h), interpolation=cv2.INTER_AREA).astype(np.float32) / 255\n rgbas_hw.append(rgba_hw)\n if self.opt.rm_edge:\n alpha = np.uint8(rgba_hw[..., 3] * 255.)\n dilate = cv2.dilate(alpha, np.ones((self.opt.edge_width, self.opt.edge_width), np.uint8))\n edge = cv2.absdiff(alpha, dilate).astype(np.float32) / 255\n mask_no_edge = rgba_hw[..., 3] > 0.5\n mask_no_edge[edge>self.opt.edge_threshold] = False\n mask_no_edges.append(mask_no_edge)\n rgba_hw = np.stack(rgbas_hw)\n mask = rgba_hw[..., 3] > 0.5\n if len(mask_no_edges) > 0:\n mask_no_edge = np.stack(mask_no_edges)\n else:\n mask_no_edge = mask\n \n # breakpoint() \n # rgb\n rgb_hw = rgba_hw[..., :3] * rgba_hw[..., 3:] + (1 - rgba_hw[..., 3:]) \n self.rgb = torch.from_numpy(rgb_hw).permute(0,3,1,2).contiguous().to(self.device)\n self.mask = torch.from_numpy(mask).to(self.device)\n self.opacity = torch.from_numpy(mask_no_edge).to(self.device).to(torch.float32).unsqueeze(0)\n print(f'[INFO] dataset: load image prompt {self.opt.images} {self.rgb.shape}')\n\n # load depth\n depth_paths = [image.replace('rgba', 'depth') for image in self.opt.images]\n if os.path.exists(depth_paths[0]):\n depths = [cv2.imread(depth_path, cv2.IMREAD_UNCHANGED) for depth_path in depth_paths]\n depth = np.stack([cv2.resize(depth, (w, h), interpolation=cv2.INTER_AREA) for depth in depths])\n self.depth = 1 - torch.from_numpy(depth.astype(np.float32) / 255).to(self.device) ## why use inverse?? MiDas predict depth larger value, more close, while nerf should be small value more close\n # self.depth = torch.from_numpy(depth.astype(np.float32) / 255).to(self.device)\n # ipdb.set_trace()\n if len(self.depth.shape) == 4 and self.depth.shape[-1] > 1:\n self.depth = self.depth[..., 0]\n logger.info(f'[WARN] dataset: {depth_paths[0]} has more than one channel, only use the first channel')\n if self.opt.normalize_depth:\n self.depth = nonzero_normalize_depth(self.depth, self.mask)\n save_tensor2image(self.depth, os.path.join(self.workspace, 'depth_resized.jpg'))\n self.depth = self.depth[self.mask]\n print(f'[INFO] dataset: load depth prompt {depth_paths} {self.depth.shape}')\n else:\n self.depth = None\n logger.info(f'[WARN] dataset: {depth_paths[0]} is not found')\n \n # load normal\n normal_paths = [image.replace('rgba', 'normal') for image in self.opt.images]\n if os.path.exists(normal_paths[0]):\n normals = []\n for normal_path in normal_paths:\n normal = cv2.imread(normal_path, cv2.IMREAD_UNCHANGED)\n if normal.shape[-1] == 4:\n normal = cv2.cvtColor(normal, cv2.COLOR_BGRA2RGB)\n normals.append(normal)\n normal = np.stack([cv2.resize(normal, (w, h), interpolation=cv2.INTER_AREA) for normal in normals])\n self.normal = torch.from_numpy(normal.astype(np.float32) / 255).to(self.device)\n save_tensor2image(self.normal, os.path.join(self.workspace, 'normal_resized.jpg'), channel_last=True)\n print(f'[INFO] dataset: load normal prompt {normal_paths} {self.normal.shape}')\n self.normal = self.normal[self.mask]\n else:\n self.normal = None\n logger.info(f'[WARN] dataset: {normal_paths[0]} is not found')\n\n # save for debug\n save_tensor2image(self.rgb, os.path.join(self.workspace, 'rgb_resized.png'), channel_last=False)\n save_tensor2image(self.opacity, os.path.join(self.workspace, 'opacity_resized.png'), channel_last=False)\n\n # encode embeddings for zero123\n if 'zero123' in self.guidance:\n rgba_256 = np.stack([cv2.resize(rgba, (256, 256), interpolation=cv2.INTER_AREA).astype(np.float32) / 255 for rgba in rgbas])\n rgbs_256 = rgba_256[..., :3] * rgba_256[..., 3:] + (1 - rgba_256[..., 3:])\n rgb_256 = torch.from_numpy(rgbs_256).permute(0,3,1,2).contiguous().to(self.device)\n # import ipdb\n # ipdb.set_trace()\n guidance_embeds = self.guidance['zero123'].get_img_embeds(rgb_256)\n self.embeddings['zero123']['default'] = {\n 'zero123_ws' : self.opt.zero123_ws,\n 'c_crossattn' : guidance_embeds[0],\n 'c_concat' : guidance_embeds[1],\n 'ref_polars' : self.opt.ref_polars,\n 'ref_azimuths' : self.opt.ref_azimuths,\n 'ref_radii' : self.opt.ref_radii,\n }\n\n # if 'clip' in self.guidance:\n # self.embeddings['clip']['image'] = self.guidance['clip'].get_img_embeds(self.rgb)\n # encoder image for clip\n if self.opt.use_clip:\n self.rgb_clip_embed = self.guidance.get_clip_img_embeds(self.rgb)\n # debug.\n scaler = torch.cuda.amp.GradScaler()\n image = torch.randn((1,3,512,512), device=self.device, requires_grad=True)\n with torch.autocast(device_type='cuda', dtype=torch.float16):\n loss = self.guidance.clip_loss(self.rgb_clip_embed, image)\n scaler.scale(loss).backward()\n else:\n self.rgb_clip_embed = None\n\n\n # ------------------------------\n @torch.no_grad()\n def match_known(self, **kwargs):\n self.model.eval()\n data = self.default_view_data\n rays_o = data['rays_o'] # [B, N, 3]\n rays_d = data['rays_d'] # [B, N, 3]\n mvp = data['mvp'] # [B, 4, 4]\n\n B, N = rays_o.shape[:2]\n H, W = data['H'], data['W']\n\n ambient_ratio = 1.0\n shading = self.opt.known_shading\n binarize = False\n bg_color = self.get_bg_color(\n self.opt.bg_color_known, B*N, rays_o.device)\n\n # add camera noise to avoid grid-like artifect\n # * (1 - self.global_step / self.opt.iters)\n noise_scale = self.opt.known_view_noise_scale\n rays_o = rays_o + torch.randn(3, device=self.device) * noise_scale\n rays_d = rays_d + torch.randn(3, device=self.device) * noise_scale\n\n outputs = self.model.render(rays_o, rays_d, mvp, H, W, staged=False, perturb=True,\n bg_color=bg_color, ambient_ratio=ambient_ratio, shading=shading, binarize=binarize)\n pred_rgb = outputs['image'].reshape(B, H, W, 3).permute(\n 0, 3, 1, 2).contiguous() # [1, 3, H, W]\n pred_mask = outputs['weights_sum'].reshape(B, 1, H, W)\n\n rgb_loss = self.opt.lambda_rgb * \\\n F.mse_loss(pred_rgb*self.opacity,\n self.rgb*self.opacity)\n mask_loss = self.opt.lambda_mask * \\\n F.mse_loss(pred_mask, self.mask.to(torch.float32).unsqueeze(0))\n return pred_rgb, pred_mask, rgb_loss, mask_loss\n\n def get_bg_color(self, bg_type, N, device):\n if bg_type is None:\n return None\n elif isinstance(bg_type, str):\n if bg_type == 'pixelnoise':\n bg_color = torch.rand((N, 3), device=device)\n elif bg_type == 'noise':\n bg_color = torch.rand((1, 3), device=device).repeat(N, 1)\n elif bg_type == 'white':\n bg_color = torch.ones((N, 3), device=device)\n return bg_color\n elif isinstance(bg_type, Tensor):\n bg_color = bg_color.to(device)\n return bg_color\n else:\n raise NotImplementedError(f\"{bg_type} is not implemented\")\n\n def train_step(self, data):\n # perform RGBD loss instead of SDS if is image-conditioned\n do_rgbd_loss = self.opt.images is not None and \\\n ((self.global_step < self.opt.known_iters) or (self.global_step % self.opt.known_view_interval == 0))\n\n # override random camera with fixed known camera\n if do_rgbd_loss:\n data = self.default_view_data\n\n # progressively relaxing view range\n if self.opt.progressive_view:\n r = min(1.0, 0.2 + self.global_step / (0.5 * self.opt.iters))\n self.opt.phi_range = [self.opt.default_azimuth * (1 - r) + self.opt.full_phi_range[0] * r,\n self.opt.default_azimuth * (1 - r) + self.opt.full_phi_range[1] * r]\n self.opt.theta_range = [self.opt.default_polar * (1 - r) + self.opt.full_theta_range[0] * r,\n self.opt.default_polar * (1 - r) + self.opt.full_theta_range[1] * r]\n self.opt.radius_range = [self.opt.default_radius * (1 - r) + self.opt.full_radius_range[0] * r,\n self.opt.default_radius * (1 - r) + self.opt.full_radius_range[1] * r]\n self.opt.fovy_range = [self.opt.default_fovy * (1 - r) + self.opt.full_fovy_range[0] * r,\n self.opt.default_fovy * (1 - r) + self.opt.full_fovy_range[1] * r]\n\n # progressively increase max_level\n if self.opt.progressive_level:\n self.model.max_level = min(1.0, 0.25 + self.global_step / (0.5 * self.opt.iters))\n\n rays_o = data['rays_o'] # [B, N, 3]\n rays_d = data['rays_d'] # [B, N, 3]\n mvp = data['mvp'] # [B, 4, 4]\n\n B, N = rays_o.shape[:2]\n H, W = data['H'], data['W']\n\n # When ref_data has B images > opt.batch_size\n if B > self.opt.batch_size:\n # choose batch_size images out of those B images\n choice = torch.randperm(B)[:self.opt.batch_size]\n B = self.opt.batch_size\n rays_o = rays_o[choice]\n rays_d = rays_d[choice]\n mvp = mvp[choice]\n\n if do_rgbd_loss:\n ambient_ratio = 1.0\n shading = 'lambertian' # use lambertian instead of albedo to get normal\n as_latent = False\n binarize = False\n bg_color = self.get_bg_color(\n self.opt.bg_color_known, B*N, rays_o.device)\n\n # add camera noise to avoid grid-like artifact\n if self.opt.known_view_noise_scale > 0:\n noise_scale = self.opt.known_view_noise_scale #* (1 - self.global_step / self.opt.iters)\n rays_o = rays_o + torch.randn(3, device=self.device) * noise_scale\n rays_d = rays_d + torch.randn(3, device=self.device) * noise_scale\n\n elif self.global_step < (self.opt.latent_iter_ratio * self.opt.iters): ## 0\n ambient_ratio = 1.0\n shading = 'normal'\n as_latent = True\n binarize = False\n bg_color = None\n\n else:\n if self.global_step < (self.opt.normal_iter_ratio * self.opt.iters): # 0.2\n ambient_ratio = 1.0\n shading = 'normal'\n elif self.global_step < (self.opt.textureless_iter_ratio * self.opt.iters): # 0\n ambient_ratio = 0.1 + 0.9 * random.random()\n shading = 'textureless'\n elif self.global_step < (self.opt.albedo_iter_ratio * self.opt.iters): # 0\n ambient_ratio = 1.0\n shading = 'albedo'\n else:\n # random shading\n ambient_ratio = 0.1 + 0.9 * random.random()\n rand = random.random()\n if rand > 0.8:\n shading = 'textureless'\n else:\n shading = 'lambertian'\n\n as_latent = False\n\n # random weights binarization (like mobile-nerf) [NOT WORKING NOW]\n # binarize_thresh = min(0.5, -0.5 + self.global_step / self.opt.iters)\n # binarize = random.random() < binarize_thresh\n binarize = False\n\n # random background\n rand = random.random()\n # ipdb.set_trace()\n if self.opt.bg_radius > 0 and rand > 0.5:\n bg_color = None # use bg_net\n else:\n bg_color = torch.rand(3).to(self.device) # single color random bg\n\n outputs = self.model.render(rays_o, rays_d, mvp, H, W, staged=False, perturb=True, bg_color=bg_color, ambient_ratio=ambient_ratio, shading=shading, binarize=binarize)\n pred_depth = outputs['depth'].reshape(B, 1, H, W)\n if self.opt.normalize_depth: \n pred_depth = nonzero_normalize_depth(pred_depth)\n pred_mask = outputs['weights_sum'].reshape(B, 1, H, W)\n if 'normal_image' in outputs:\n pred_normal = outputs['normal_image'].reshape(B, H, W, 3)\n else:\n pred_normal = None \n\n if as_latent:\n # abuse normal & mask as latent code for faster geometry initialization (ref: fantasia3D)\n pred_rgb = torch.cat([outputs['image'], outputs['weights_sum'].unsqueeze(-1)], dim=-1).reshape(B, H, W, 4).permute(0, 3, 1, 2).contiguous() # [B, 4, H, W]\n else:\n pred_rgb = outputs['image'].reshape(B, H, W, 3).permute(0, 3, 1, 2).contiguous() # [B, 3, H, W]\n \n # ipdb.set_trace()\n if 'image_wo_bg' in outputs:\n image_wo_bg = outputs['image_wo_bg'] + (1 - outputs['weights_sum']).unsqueeze(-1) * 1 # B,1,N,3\n if as_latent:\n # abuse normal & mask as latent code for faster geometry initialization (ref: fantasia3D)\n pred_rgb_wobg = torch.cat([image_wo_bg, outputs['weights_sum'].unsqueeze(-1)], dim=-1).reshape(B, H, W, 4).permute(0, 3, 1, 2).contiguous() # [B, 4, H, W]\n else:\n pred_rgb_wobg = image_wo_bg.reshape(B, H, W, 3).permute(0, 3, 1, 2).contiguous() # [B, 3, H, W]\n\n out_dict = {\n 'rgb': pred_rgb,\n 'depth': pred_depth,\n 'mask': pred_mask,\n 'normal': pred_normal,\n 'pred_rgb_wobg': pred_rgb_wobg,\n }\n\n # Loss\n # known view loss\n loss_rgb, loss_mask, loss_normal, loss_depth, loss_sds, loss_if, loss_zero123, loss_clip, loss_entropy, loss_opacity, loss_orient, loss_smooth, loss_smooth2d, loss_smooth3d, loss_mesh_normal, loss_mesh_lap = torch.zeros(16, device=self.device)\n # known view loss\n if do_rgbd_loss:\n gt_mask = self.mask # [B, H, W]\n gt_rgb = self.rgb # [B, 3, H, W]\n gt_opacity = self.opacity # [B, 1, H, W]\n gt_normal = self.normal # [B, H, W, 3]\n gt_depth = self.depth # [B, H, W]\n\n if len(gt_rgb) > self.opt.batch_size:\n gt_mask = gt_mask[choice]\n gt_rgb = gt_rgb[choice]\n gt_opacity = gt_opacity[choice]\n gt_normal = gt_normal[choice]\n gt_depth = gt_depth[choice]\n\n # color loss\n loss_rgb = self.opt.lambda_rgb * \\\n F.mse_loss(pred_rgb*gt_opacity, gt_rgb*gt_opacity)\n\n # mask loss\n loss_mask = self.opt.lambda_mask * F.mse_loss(pred_mask, gt_mask.to(torch.float32).unsqueeze(0))\n\n # normal loss\n if self.opt.lambda_normal > 0 and 'normal_image' in outputs and self.normal is not None:\n pred_normal = pred_normal[self.mask]\n lambda_normal = self.opt.lambda_normal * \\\n min(1, self.global_step / self.opt.iters) \n loss_normal = lambda_normal * \\\n (1 - F.cosine_similarity(pred_normal, self.normal).mean())/2\n\n # relative depth loss\n if self.opt.lambda_depth > 0 and self.depth is not None:\n valid_pred_depth = pred_depth[:, 0][self.mask]\n loss_depth = self.opt.lambda_depth * (1 - pearson_corrcoef(valid_pred_depth, self.depth))/2\n \n loss = loss_rgb + loss_mask + loss_normal + loss_depth\n # novel view loss\n else:\n save_guidance_path = os.path.join(self.opt.workspace, 'guidance', f'train_step{self.global_step}_guidance.jpg') if self.opt.save_guidance_every > 0 and self.global_step % self.opt.save_guidance_every ==0 else None\n if 'SD' in self.guidance:\n # interpolate text_z\n azimuth = data['azimuth'] # [-180, 180]\n\n # ENHANCE: remove loop to handle batch size > 1\n text_z = [] \n for b in range(azimuth.shape[0]):\n if azimuth[b] >= -90 and azimuth[b] < 90:\n if azimuth[b] >= 0:\n r = 1 - azimuth[b] / 90\n else:\n r = 1 + azimuth[b] / 90\n start_z = self.embeddings['SD']['front']\n end_z = self.embeddings['SD']['side']\n else:\n if azimuth[b] >= 0:\n r = 1 - (azimuth[b] - 90) / 90\n else:\n r = 1 + (azimuth[b] + 90) / 90\n start_z = self.embeddings['SD']['side']\n end_z = self.embeddings['SD']['back']\n text_z.append(r * start_z + (1 - r) * end_z)\n text_z = torch.stack(text_z, dim=0).transpose(0, 1).flatten(0, 1)\n # text_z_sds = text_z[:, :-1]\n text_z_sds = text_z \n loss_sds, _ = self.guidance['SD'].train_step(text_z_sds, pred_rgb, as_latent=as_latent, guidance_scale=self.opt.guidance_scale['SD'], grad_scale=self.opt.lambda_guidance['SD'],\n density=pred_mask if self.opt.gudiance_spatial_weighting else None, \n save_guidance_path=save_guidance_path\n )\n\n \n if 'IF' in self.guidance:\n # interpolate text_z\n azimuth = data['azimuth'] # [-180, 180]\n\n # ENHANCE: remove loop to handle batch size > 1\n # ENHANCE: remove loop to handle batch size > 1\n text_z = [] \n for b in range(azimuth.shape[0]):\n if azimuth[b] >= -90 and azimuth[b] < 90:\n if azimuth[b] >= 0:\n r = 1 - azimuth[b] / 90\n else:\n r = 1 + azimuth[b] / 90\n start_z = self.embeddings['IF']['front']\n end_z = self.embeddings['IF']['side']\n else:\n if azimuth[b] >= 0:\n r = 1 - (azimuth[b] - 90) / 90\n else:\n r = 1 + (azimuth[b] + 90) / 90\n start_z = self.embeddings['IF']['side']\n end_z = self.embeddings['IF']['back']\n text_z.append(r * start_z + (1 - r) * end_z)\n text_z = torch.stack(text_z, dim=0).transpose(0, 1).flatten(0, 1)\n text_z = torch.cat(text_z, dim=1).reshape(B, 2, start_z.shape[-2]-1, start_z.shape[-1]).transpose(0, 1).flatten(0, 1)\n loss_if = self.guidance['IF'].train_step(text_z, pred_rgb, guidance_scale=self.opt.guidance_scale['IF'], grad_scale=self.opt.lambda_guidance['IF'])\n\n if 'zero123' in self.guidance:\n\n polar = data['polar']\n azimuth = data['azimuth']\n radius = data['radius']\n\n # ipdb.set_trace()\n input_3dprior = pred_rgb\n loss_zero123 = self.guidance['zero123'].train_step(self.embeddings['zero123']['default'], input_3dprior, polar, azimuth, radius, guidance_scale=self.opt.guidance_scale['zero123'],\n as_latent=as_latent, grad_scale=self.opt.lambda_guidance['zero123'], save_guidance_path=save_guidance_path)\n\n if 'clip' in self.guidance:\n\n # empirical, far view should apply smaller CLIP loss\n lambda_guidance = 10 * (1 - abs(azimuth) / 180) * self.opt.lambda_guidance['clip']\n loss_clip = self.guidance['clip'].train_step(self.embeddings['clip'], pred_rgb, grad_scale=lambda_guidance)\n loss = loss_sds + loss_if + loss_zero123 + loss_clip\n\n # regularizations\n if not self.opt.dmtet:\n\n if self.opt.lambda_opacity > 0: # 0\n loss_opacity = self.opt.lambda_opacity * (outputs['weights_sum'] ** 2).mean()\n\n if self.opt.lambda_entropy > 0: # 1e-3\n lambda_entropy = self.opt.lambda_entropy * \\\n min(1, 2 * self.global_step / self.opt.iters)\n alphas = outputs['weights'].clamp(1e-5, 1 - 1e-5)\n # alphas = alphas ** 2 # skewed entropy, favors 0 over 1\n loss_entropy = lambda_entropy * (- alphas * torch.log2(alphas) -\n (1 - alphas) * torch.log2(1 - alphas)).mean()\n\n if self.opt.lambda_normal_smooth > 0 and 'normal_image' in outputs: # 0.5 # no image in sd-dreamfusion should be 0\n pred_vals = outputs['normal_image'].reshape(B, H, W, 3)\n # total-variation\n loss_smooth = (pred_vals[:, 1:, :, :] - pred_vals[:, :-1, :, :]).square().mean() + \\\n (pred_vals[:, :, 1:, :] -\n pred_vals[:, :, :-1, :]).square().mean()\n loss_smooth = self.opt.lambda_normal_smooth * loss_smooth\n\n if self.opt.lambda_normal_smooth2d > 0 and 'normal_image' in outputs: # 0.5 # no image in sd-dreamfusion should be 0\n pred_vals = outputs['normal_image'].reshape(\n B, H, W, 3).permute(0, 3, 1, 2).contiguous()\n smoothed_vals = TF.gaussian_blur(pred_vals, kernel_size=9)\n loss_smooth2d = self.opt.lambda_normal_smooth2d * F.mse_loss(pred_vals, smoothed_vals)\n\n if self.opt.lambda_orient > 0 and 'loss_orient' in outputs: # 1e-2\n loss_orient = self.opt.lambda_orient * outputs['loss_orient']\n \n if self.opt.lambda_3d_normal_smooth > 0 and 'loss_normal_perturb' in outputs: # 0\n loss_smooth3d = self.opt.lambda_3d_normal_smooth * outputs['loss_normal_perturb']\n\n loss += loss_opacity + loss_entropy + loss_smooth + loss_smooth2d + loss_orient + loss_smooth3d\n \n else:\n if self.opt.lambda_mesh_normal > 0:\n loss_mesh_normal = self.opt.lambda_mesh_normal * \\\n outputs['loss_normal']\n\n if self.opt.lambda_mesh_lap > 0:\n loss_mesh_lap = self.opt.lambda_mesh_lap * outputs['loss_lap']\n loss += loss_mesh_normal + loss_mesh_lap\n\n losses_dict = {\n 'loss': loss.item(),\n 'loss_sds': loss_sds.item(),\n 'loss_if': loss_if.item(),\n 'loss_zero123': loss_zero123.item(),\n 'loss_clip': loss_clip.item(),\n 'loss_rgb': loss_rgb.item(),\n 'loss_mask': loss_mask.item(),\n 'loss_normal': loss_normal.item(),\n 'loss_depth': loss_depth.item(),\n 'loss_opacity': loss_opacity.item(),\n 'loss_entropy': loss_entropy.item(),\n 'loss_smooth': loss_smooth.item(),\n 'loss_smooth2d': loss_smooth2d.item(),\n 'loss_smooth3d': loss_smooth3d.item(),\n 'loss_orient': loss_orient.item(),\n 'loss_mesh_normal': loss_mesh_normal.item(),\n 'loss_mesh_lap': loss_mesh_lap.item(),\n }\n\n \n if 'normal' in out_dict:\n out_dict['normal'] = out_dict['normal'].permute(0, 3, 1, 2).contiguous()\n\n # save for debug purpose\n if self.opt.save_train_every > 0 and self.global_step % self.opt.save_train_every == 0:\n image_save_path = os.path.join(self.workspace, 'train_debug',)\n os.makedirs(image_save_path, exist_ok=True)\n for key, value in out_dict.items():\n if value is not None:\n value = ((value - value.min()) / (value.max() - value.min() + 1e-6)).detach().mul(255).to(torch.uint8)\n try:\n save_tensor2image(value, os.path.join(image_save_path, f'train_{self.global_step:06d}_{key}.jpg'), channel_last=False) \n except:\n pass\n return loss, losses_dict, out_dict \n\n def post_train_step(self):\n\n # unscale grad before modifying it!\n # ref: https://pytorch.org/docs/stable/notes/amp_examples.html#gradient-clipping\n self.scaler.unscale_(self.optimizer)\n\n # clip grad\n if self.opt.grad_clip >= 0:\n torch.nn.utils.clip_grad_value_(self.model.parameters(), self.opt.grad_clip)\n\n if not self.opt.dmtet and self.opt.backbone == 'grid':\n\n if self.opt.lambda_tv > 0:\n lambda_tv = min(1.0, self.global_step / (0.5 * self.opt.iters)) * self.opt.lambda_tv\n self.model.encoder.grad_total_variation(lambda_tv, None, self.model.bound)\n if self.opt.lambda_wd > 0:\n self.model.encoder.grad_weight_decay(self.opt.lambda_wd)\n\n\n def eval_step(self, data):\n\n rays_o = data['rays_o'] # [B, N, 3]\n rays_d = data['rays_d'] # [B, N, 3]\n mvp = data['mvp']\n\n B, N = rays_o.shape[:2]\n H, W = data['H'], data['W']\n\n shading = data['shading'] if 'shading' in data else 'lambertian' \n ambient_ratio = data['ambient_ratio'] if 'ambient_ratio' in data else 1.0\n light_d = data['light_d'] if 'light_d' in data else None\n\n outputs = self.model.render(rays_o, rays_d, mvp, H, W, staged=True, perturb=False, bg_color=None, light_d=light_d, ambient_ratio=ambient_ratio, shading=shading)\n pred_rgb = outputs['image'].reshape(B, H, W, 3)\n pred_depth = outputs['depth'].reshape(B, H, W, 1)\n if self.opt.normalize_depth: \n pred_depth = nonzero_normalize_depth(pred_depth)\n if 'normal_image' in outputs:\n pred_normal = outputs['normal_image'].reshape(B, H, W, 3)\n else:\n pred_normal = None \n out_dict = {\n shading: pred_rgb,\n 'depth': pred_depth,\n 'normal_image': pred_normal,\n }\n # dummy\n loss = torch.zeros([1], device=pred_rgb.device, dtype=pred_rgb.dtype)\n return out_dict, loss\n\n def test_step(self, data, bg_color=None, perturb=False, shading='lambertian'):\n rays_o = data['rays_o'] # [B, N, 3]\n rays_d = data['rays_d'] # [B, N, 3]\n mvp = data['mvp']\n\n B, N = rays_o.shape[:2]\n H, W = data['H'], data['W']\n\n bg_color = self.get_bg_color(bg_color, B*N, rays_o.device)\n\n shading = data['shading'] if 'shading' in data else shading \n ambient_ratio = data['ambient_ratio'] if 'ambient_ratio' in data else 1.0\n light_d = data['light_d'] if 'light_d' in data else None\n\n outputs = self.model.render(rays_o, rays_d, mvp, H, W, staged=True, perturb=perturb, light_d=light_d, ambient_ratio=ambient_ratio, shading=shading, bg_color=bg_color)\n\n pred_rgb = outputs['image'].reshape(B, H, W, 3)\n pred_depth = outputs['depth'].reshape(B, H, W, 1)\n pred_mask = outputs['weights_sum'].reshape(B, H, W, 1)\n # if self.opt.normalize_depth: \n pred_depth = nonzero_normalize_depth(pred_depth)\n if 'normal_image' in outputs:\n pred_normal = outputs['normal_image'].reshape(B, H, W, 3)\n pred_normal = pred_normal * pred_mask + (1.0 - pred_mask) \n else:\n pred_normal = None \n out_dict = {\n shading: pred_rgb,\n 'depth': pred_depth,\n 'normal_image': pred_normal,\n 'mask': pred_mask,\n }\n return out_dict\n\n def save_mesh(self, loader=None, save_path=None):\n\n if save_path is None:\n save_path = os.path.join(self.workspace, 'mesh')\n\n logger.info(f\"==> Saving mesh to {save_path}\")\n\n os.makedirs(save_path, exist_ok=True)\n\n self.model.export_mesh(save_path, resolution=self.opt.mcubes_resolution, decimate_target=self.opt.decimate_target)\n\n logger.info(f\"==> Finished saving mesh.\")\n\n ### ------------------------------\n\n def train(self, train_loader, valid_loader, test_loader, max_epochs):\n\n if self.use_tensorboard and self.local_rank == 0:\n self.writer = SummaryWriter(\n os.path.join(self.workspace, \"run\", self.name))\n\n # init from nerf should be performed after Shap-E, since Shap-E will rescale dmtet\n if self.opt.dmtet and (self.opt.init_ckpt and os.path.exists(self.opt.init_ckpt)):\n reset_scale = False if self.opt.use_shape else True\n old_sdf = self.model.get_sdf_from_nerf(reset_scale)\n if not self.opt.tet_mlp:\n self.model.dmtet.init_tet_from_sdf(old_sdf)\n self.test(valid_loader, name=f'init_ckpt', write_video=False, save_each_frame=False, subfolder='check_init')\n else:\n old_sdf = None\n \n if self.opt.use_shape and self.opt.dmtet:\n os.makedirs(os.path.join(self.opt.workspace, 'shape'), exist_ok=True)\n best_loss = torch.inf\n best_idx = 0\n for idx, (sdf, color) in enumerate(zip(self.opt.rpsts, self.opt.colors)):\n self.model.init_tet_from_sdf_color(sdf)\n pred_rgb, pred_mask, rgb_loss, mask_loss = self.match_known()\n best_loss = min(best_loss, mask_loss)\n if best_loss == mask_loss:\n best_idx = idx\n logger.info(f\"==> Current best match shape known sdf idx: {best_idx}\")\n save_tensor2image(pred_mask, os.path.join(self.opt.workspace, 'shape', f\"match_shape_known_{idx}_rgb.jpg\"), channel_last=False)\n self.test(valid_loader, name=f'idx_{idx}', write_video=False, save_each_frame=False, subfolder='check_init')\n \n sdf = self.opt.rpsts[best_idx]\n self.model.init_tet_from_sdf_color(sdf, self.opt.colors[best_idx])\n self.test(valid_loader, name=f'shape_only', write_video=False, save_each_frame=False, subfolder='check_init')\n\n # Enable mixture model\n if self.opt.base_mesh:\n logger.info(f\"==> Enable mixture model with base mesh {self.opt.base_mesh}\")\n mesh_sdf = self.model.dmtet.get_sdf_from_mesh(self.opt.base_mesh)\n sdf = (mesh_sdf.clamp(0, 1) + sdf.clamp(0,1) ).clamp(0, 1)\n\n if old_sdf is not None:\n sdf = (sdf.clamp(0, 1) + old_sdf.clamp(0, 1)).clamp(0, 1)\n\n self.model.init_tet_from_sdf_color(sdf, self.opt.colors[best_idx])\n self.test(valid_loader, name=f'shape_merge', write_video=False, save_each_frame=False, subfolder='check_init')\n\n del best_loss, best_idx, pred_rgb, pred_mask, rgb_loss, mask_loss\n self.opt.rpsts = None\n gc.collect()\n torch.cuda.empty_cache()\n\n\n start_t = time.time()\n\n for epoch in range(self.epoch + 1, max_epochs + 1):\n self.epoch = epoch\n\n self.train_one_epoch(train_loader, max_epochs)\n\n if self.workspace is not None and self.local_rank == 0:\n if self.epoch % self.opt.save_interval == 0:\n self.save_checkpoint(full=True, best=False)\n\n if self.epoch % self.opt.eval_interval == 0:\n self.evaluate_one_epoch(valid_loader) \n # best_save = True if self.epoch % self.opt.save_interval else False\n self.save_checkpoint(full=False, best=True)\n\n if self.epoch % self.opt.test_interval == 0 or self.epoch == max_epochs:\n self.test(test_loader, img_folder='images' if self.epoch == max_epochs else f'images_ep{self.epoch:04d}')\n\n end_t = time.time()\n\n self.total_train_t = end_t - start_t + self.total_train_t\n\n logger.info(f\"[INFO] training takes {(self.total_train_t)/ 60:.4f} minutes.\")\n\n if self.use_tensorboard and self.local_rank == 0:\n self.writer.close()\n\n def evaluate(self, loader, name=None):\n self.use_tensorboard, use_tensorboard = False, self.use_tensorboard\n self.evaluate_one_epoch(loader, name)\n self.use_tensorboard = use_tensorboard\n\n def test(self, loader, save_path=None, name=None, \n write_video=True, save_each_frame=True, shading='lambertian', \n subfolder='results', img_folder='images'\n ):\n\n if save_path is None:\n save_path = os.path.join(self.workspace, subfolder)\n image_save_path = os.path.join(self.workspace, subfolder, img_folder)\n\n if name is None:\n name = f'{self.name}_ep{self.epoch:04d}'\n\n os.makedirs(save_path, exist_ok=True)\n os.makedirs(image_save_path, exist_ok=True)\n\n logger.info(f\"==> Start Test, saving {shading} results to {save_path}\")\n\n pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')\n self.model.eval()\n\n all_outputs = {} \n with torch.no_grad():\n for i, data in enumerate(loader):\n # if i > 20:\n # break\n with torch.cuda.amp.autocast(enabled=self.fp16):\n outputs = self.test_step(data, bg_color=self.opt.bg_color_test, shading=shading)\n for key, value in outputs.items():\n if value is not None:\n value = ((value - value.min()) / (value.max() - value.min() + 1e-6)).detach().mul(255).to(torch.uint8)\n if save_each_frame:\n save_tensor2image(value, os.path.join(image_save_path, f'{name}_{i:04d}_{key}.jpg'), channel_last=True) \n if key not in all_outputs.keys():\n all_outputs[key] = []\n all_outputs[key].append(value)\n pbar.update(loader.batch_size)\n\n for key, value in all_outputs.items():\n all_outputs[key] = torch.cat(value, dim=0) # B,H,W,C, B is all the pose results\n # if video -> B,F,H,W,C \n \n if write_video:\n for key, value in all_outputs.items():\n # current version torchvision does not support writing a single-channel video\n # torchvision.io.write_video(os.path.join(save_path, f'{name}_{key}.mp4'), all_outputs[key].detach().cpu(), fps=25)\n # imageio.mimwrite(os.path.join(save_path, f'{name}_{key}.mp4'), all_outputs[key].detach().cpu().numpy(), fps=25, quality=8, macro_block_size=1)\n one_video_save(os.path.join(save_path, f'{name}_{key}.mp4'), all_outputs[key])\n\n for key, value in all_outputs.items():\n save_tensor2image(value, os.path.join(save_path, f'{name}_{key}_grid.jpg'), channel_last=True)\n logger.info(f\"==> Finished Test.\")\n\n # [GUI] train text step.\n def train_gui(self, train_loader, step=16):\n\n self.model.train()\n\n total_loss = torch.tensor([0], dtype=torch.float32, device=self.device)\n\n loader = iter(train_loader)\n\n for _ in range(step):\n\n # mimic an infinite loop dataloader (in case the total dataset is smaller than step)\n try:\n data = next(loader)\n except StopIteration:\n loader = iter(train_loader)\n data = next(loader)\n\n # update grid every 16 steps\n if self.model.cuda_ray and self.global_step % self.opt.update_extra_interval == 0:\n with torch.cuda.amp.autocast(enabled=self.fp16):\n self.model.update_extra_state()\n\n self.global_step += 1\n\n self.optimizer.zero_grad()\n\n with torch.cuda.amp.autocast(enabled=self.fp16):\n loss, loss_dicts, outputs = self.train_step(data)\n\n self.scaler.scale(loss).backward()\n self.post_train_step()\n self.scaler.step(self.optimizer)\n self.scaler.update()\n\n if self.scheduler_update_every_step:\n self.lr_scheduler.step()\n\n self.loss_meter.update(loss_dicts)\n \n if self.ema is not None:\n self.ema.update()\n\n average_loss = self.loss_meter.meters['loss'].avg\n\n if not self.scheduler_update_every_step:\n if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):\n self.lr_scheduler.step(average_loss)\n else:\n self.lr_scheduler.step()\n\n outputs = {\n 'loss': average_loss,\n 'lr': self.optimizer.param_groups[0]['lr'],\n }\n\n return outputs\n\n\n # [GUI] test on a single image\n def test_gui(self, pose, intrinsics, mvp, W, H, bg_color=None, spp=1, downscale=1, light_d=None, ambient_ratio=1.0, shading='albedo'):\n\n # render resolution (may need downscale to for better frame rate)\n rH = int(H * downscale)\n rW = int(W * downscale)\n intrinsics = intrinsics * downscale\n\n pose = torch.from_numpy(pose).unsqueeze(0).to(self.device)\n mvp = torch.from_numpy(mvp).unsqueeze(0).to(self.device)\n\n rays = get_rays(pose, intrinsics, rH, rW, -1)\n\n # from degree theta/phi to 3D normalized vec\n light_d = np.deg2rad(light_d)\n light_d = np.array([\n np.sin(light_d[0]) * np.sin(light_d[1]),\n np.cos(light_d[0]),\n np.sin(light_d[0]) * np.cos(light_d[1]),\n ], dtype=np.float32)\n light_d = torch.from_numpy(light_d).to(self.device)\n\n data = {\n 'rays_o': rays['rays_o'],\n 'rays_d': rays['rays_d'],\n 'mvp': mvp,\n 'H': rH,\n 'W': rW,\n 'light_d': light_d,\n 'ambient_ratio': ambient_ratio,\n 'shading': shading,\n }\n\n self.model.eval()\n\n if self.ema is not None:\n self.ema.store()\n self.ema.copy_to()\n\n with torch.no_grad():\n with torch.cuda.amp.autocast(enabled=self.fp16):\n # here spp is used as perturb random seed!\n outputs = self.test_step(\n data, bg_color=bg_color, perturb=False if spp == 1 else spp)\n\n if self.ema is not None:\n self.ema.restore()\n\n # interpolation to the original resolution\n if downscale != 1:\n # have to permute twice with torch...\n outputs[shading] = F.interpolate(outputs[shading].permute(0, 3, 1, 2), size=(\n H, W), mode='nearest').permute(0, 2, 3, 1).contiguous()\n outputs['depth'] = F.interpolate(outputs['depth'].unsqueeze(\n 1), size=(H, W), mode='nearest').squeeze(1)\n\n if outputs['normal_imagea'] is not None:\n outputs['normal_image'] = F.interpolate(outputs['normal_image'].unsqueeze(1), size=(H, W), mode='nearest').squeeze(1)\n\n return outputs\n\n def train_one_epoch(self, loader, max_epochs):\n logger.info(f\"==> [{time.strftime('%Y-%m-%d_%H-%M-%S')}] Start Training {self.workspace} Epoch {self.epoch}/{max_epochs}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...\")\n\n if self.local_rank == 0 and self.report_metric_at_train:\n for metric in self.metrics:\n metric.clear()\n\n self.model.train()\n\n # distributedSampler: must call set_epoch() to shuffle indices across multiple epochs\n # ref: https://pytorch.org/docs/stable/data.html\n if self.world_size > 1:\n loader.sampler.set_epoch(self.epoch)\n\n self.local_step = 0\n\n for data in loader:\n\n # update grid every 16 steps\n if (self.model.cuda_ray or self.model.taichi_ray) and self.global_step % self.opt.update_extra_interval == 0:\n with torch.cuda.amp.autocast(enabled=self.fp16):\n self.model.update_extra_state()\n \n # Update grid\n if self.opt.grid_levels_mask > 0:\n if self.global_step > self.opt.grid_levels_mask_iters:\n self.model.grid_levels_mask = 0\n else:\n self.model.grid_levels_mask = self.opt.grid_levels_mask\n\n self.local_step += 1\n self.global_step += 1\n\n ## update optimizer\n if self.global_step == self.opt.lr_time_iter:\n # ipdb.set_trace()\n grad_vars = self.model.get_params(self.opt.lr, self.opt.lr_scale_time)\n self.optimizer = torch.optim.Adam(\n grad_vars, betas=(0.9, 0.99), eps=1e-15\n )\n self.lr_scheduler.optimizer = self.optimizer\n\n self.optimizer.zero_grad()\n # ipdb.set_trace()\n with torch.cuda.amp.autocast(enabled=self.fp16):\n loss, losses_dict, outputs = self.train_step(data)\n\n # hooked grad clipping for RGB space\n if self.opt.grad_clip_rgb >= 0:\n def _hook(grad):\n if self.opt.fp16:\n # correctly handle the scale\n grad_scale = self.scaler._get_scale_async()\n return grad.clamp(grad_scale * -self.opt.grad_clip_rgb, grad_scale * self.opt.grad_clip_rgb)\n else:\n return grad.clamp(-self.opt.grad_clip_rgb, self.opt.grad_clip_rgb)\n outputs['rgb'].register_hook(_hook)\n # if (self.global_step <= self.opt.known_iters or self.global_step % self.opt.known_view_interval == 0) and self.opt.image is not None and self.opt.joint_known_unknown and known_rgbs is not None:\n # known_rgbs.register_hook(_hook)\n # pred_rgbs.retain_grad()\n\n self.scaler.scale(loss).backward()\n # ipdb.set_trace()\n self.post_train_step()\n self.scaler.step(self.optimizer)\n self.scaler.update()\n\n if self.scheduler_update_every_step:\n self.lr_scheduler.step()\n \n\n self.loss_meter.update(losses_dict)\n\n # last_losses_dict = losses_dict\n # last_grad = [layer.weight.grad.data.detach() for layer in self.model.deformation_net.net]\n\n if self.local_rank == 0:\n # if self.report_metric_at_train:\n # for metric in self.metrics:\n # metric.update(preds, truths)\n\n if self.use_tensorboard:\n\n for key, val in losses_dict.items():\n self.writer.add_scalar(\n f\"train/{key}\", val, self.global_step) \n\n self.writer.add_scalar(\n \"train/lr\", self.optimizer.param_groups[0]['lr'], self.global_step)\n\n if self.global_step % self.opt.log_every == 0:\n strings = f\"==> Train [Step] {self.global_step}/{self.opt.iters}\"\n for key, value in losses_dict.items():\n strings += f\", {key}={value:.4f}\"\n logger.info(strings)\n strings = f\"==> Train [Avg] {self.global_step}/{self.opt.iters}\"\n for key in self.loss_meter.meters.keys():\n strings += f\", {key}={self.loss_meter.meters[key].avg:.4f}\"\n logger.info(strings)\n\n if self.ema is not None:\n self.ema.update()\n \n average_loss = self.loss_meter.meters['loss'].avg\n self.stats[\"loss\"].append(average_loss)\n\n if self.local_rank == 0:\n # pbar.close()\n if self.report_metric_at_train:\n for metric in self.metrics:\n logger.info(metric.report(), style=\"red\")\n if self.use_tensorboard:\n metric.write(self.writer, self.epoch, prefix=\"train\")\n metric.clear()\n\n if not self.scheduler_update_every_step:\n if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):\n self.lr_scheduler.step(average_loss)\n else:\n self.lr_scheduler.step()\n\n\n # Visualize Training\n if self.local_rank == 0:\n # save image\n save_path = os.path.join(\n self.workspace, 'training')\n os.makedirs(save_path, exist_ok=True)\n name = f'train_{self.name}_ep{self.epoch:04d}'\n for key, value in outputs.items():\n value = ((value - value.min()) / (value.max() - value.min() + 1e-6)).detach().mul(255).to(torch.uint8)\n save_tensor2image(value, os.path.join(save_path, f'{name}_{key}.jpg'), channel_last=False) \n gpu_mem = get_GPU_mem()[0]\n logger.info(f\"==> [Finished Epoch {self.epoch}/{max_epochs}. GPU={gpu_mem:.1f}GB.\")\n\n def evaluate_one_epoch(self, loader, name=None):\n logger.info(f\"++> Evaluate {self.workspace} at epoch {self.epoch} ...\")\n\n if name is None:\n name = f'{self.name}_ep{self.epoch:04d}'\n\n total_loss = 0\n if self.local_rank == 0:\n for metric in self.metrics:\n metric.clear()\n\n self.model.eval()\n \n if self.ema is not None:\n self.ema.store()\n self.ema.copy_to()\n\n if self.local_rank == 0:\n pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{desc}: {percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')\n\n with torch.no_grad():\n self.local_step = 0\n \n all_outputs = {} \n for data in loader:\n self.local_step += 1\n\n with torch.cuda.amp.autocast(enabled=self.fp16):\n outputs, loss = self.eval_step(data)\n\n # all_gather/reduce the statistics (NCCL only support all_*)\n if self.world_size > 1:\n dist.all_reduce(loss, op=dist.ReduceOp.SUM)\n loss = loss / self.world_size\n \n for key, value in outputs.items():\n if value is not None:\n dist.all_gather(outputs[key])\n outputs[key] = torch.cat(outputs[key], dim=0)\n \n loss_val = loss.item()\n total_loss += loss_val\n\n # only rank = 0 will perform evaluation.\n if self.local_rank == 0:\n\n # save image\n save_path = os.path.join(\n self.workspace, 'validation')\n\n # logger.info(f\"==> Saving validation image to {save_path}\")\n os.makedirs(save_path, exist_ok=True)\n\n for key, value in outputs.items():\n if value is not None:\n value = ((value - value.min()) / (value.max() - value.min() + 1e-6)).detach().mul(255).to(torch.uint8)\n # save_tensor2image(value, os.path.join(save_path, f'{name}_{self.local_step:04d}_{key}.jpg')) \n if key not in all_outputs.keys():\n all_outputs[key] = []\n all_outputs[key].append(value)\n\n pbar.set_description(\n f\"loss={loss_val:.4f} ({total_loss/self.local_step:.4f})\")\n pbar.update(loader.batch_size)\n\n\n average_loss = total_loss / self.local_step\n self.stats[\"valid_loss\"].append(average_loss)\n\n if self.local_rank == 0:\n pbar.close()\n if not self.use_loss_as_metric and len(self.metrics) > 0:\n result = self.metrics[0].measure()\n self.stats[\"results\"].append(result if self.best_mode == 'min' else - result) # if max mode, use -result\n else:\n self.stats[\"results\"].append(average_loss) # if no metric, choose best by min loss\n\n for metric in self.metrics:\n logger.info(metric.report(), style=\"blue\")\n if self.use_tensorboard:\n metric.write(self.writer, self.epoch, prefix=\"evaluate\")\n metric.clear()\n \n for key, value in all_outputs.items():\n all_outputs[key] = torch.cat(value, dim=0)\n save_tensor2image(all_outputs[key], os.path.join(save_path, f'{name}_{key}.jpg'), channel_last=True)\n if self.ema is not None:\n self.ema.restore()\n\n logger.info(f\"++> Evaluate epoch {self.epoch} Finished.\")\n\n def save_checkpoint(self, name=None, full=False, best=False):\n\n if name is None:\n name = f'{self.name}_ep{self.epoch:04d}'\n\n state = {\n 'epoch': self.epoch,\n 'global_step': self.global_step,\n 'stats': self.stats,\n }\n\n if self.model.cuda_ray:\n state['mean_density'] = self.model.mean_density\n\n if self.opt.dmtet:\n state['tet_scale'] = self.model.dmtet.tet_scale.cpu().numpy()\n\n if full:\n state['optimizer'] = self.optimizer.state_dict()\n state['lr_scheduler'] = self.lr_scheduler.state_dict()\n state['scaler'] = self.scaler.state_dict()\n if self.ema is not None:\n state['ema'] = self.ema.state_dict()\n\n if not best:\n\n state['model'] = self.model.state_dict()\n\n file_path = f\"{name}.pth\"\n\n self.stats[\"checkpoints\"].append(file_path)\n\n if len(self.stats[\"checkpoints\"]) > self.max_keep_ckpt:\n old_ckpt = os.path.join(\n self.opt.ckpt_path, self.stats[\"checkpoints\"].pop(0))\n if os.path.exists(old_ckpt):\n os.remove(old_ckpt)\n\n torch.save(state, os.path.join(self.opt.ckpt_path, file_path))\n\n \n \n\n else:\n if len(self.stats[\"results\"]) > 0:\n # always save best since loss cannot reflect performance.\n if True:\n # logger.info(f\"[INFO] New best result: {self.stats['best_result']} --> {self.stats['results'][-1]}\")\n # self.stats[\"best_result\"] = self.stats[\"results\"][-1]\n\n # save ema results\n if self.ema is not None:\n self.ema.store()\n self.ema.copy_to()\n\n state['model'] = self.model.state_dict()\n\n if self.ema is not None:\n self.ema.restore()\n\n torch.save(state, self.opt.best_path)\n\n\n else:\n logger.info(\n f\"[WARN] no evaluated results found, skip saving best checkpoint.\")\n\n def load_checkpoint(self, checkpoint=None, model_only=False):\n if checkpoint is None:\n checkpoint_list = sorted(glob.glob(f'{self.opt.ckpt_path}/*.pth'))\n if checkpoint_list:\n checkpoint = checkpoint_list[-1]\n logger.info(f\"[INFO] Latest checkpoint is {checkpoint}\")\n else:\n logger.info(\n \"[WARN] No checkpoint found, model randomly initialized.\")\n return\n\n checkpoint_dict = torch.load(checkpoint, map_location=self.device)\n\n if 'model' not in checkpoint_dict:\n self.model.load_state_dict(checkpoint_dict)\n logger.info(\"[INFO] loaded model.\")\n return\n\n missing_keys, unexpected_keys = self.model.load_state_dict(checkpoint_dict['model'], strict=False)\n logger.info(\"[INFO] loaded model.\")\n if len(missing_keys) > 0:\n logger.info(f\"[WARN] missing keys: {missing_keys}\")\n if len(unexpected_keys) > 0:\n logger.info(f\"[WARN] unexpected keys: {unexpected_keys}\")\n\n if self.ema is not None and 'ema' in checkpoint_dict:\n try:\n self.ema.load_state_dict(checkpoint_dict['ema'])\n logger.info(\"[INFO] loaded EMA.\")\n except:\n logger.info(\"[WARN] failed to loaded EMA.\")\n\n if self.model.cuda_ray:\n if 'mean_density' in checkpoint_dict:\n self.model.mean_density = checkpoint_dict['mean_density']\n\n if self.opt.dmtet:\n if 'tet_scale' in checkpoint_dict:\n new_scale = torch.from_numpy(\n checkpoint_dict['tet_scale']).to(self.device)\n self.model.dmtet.verts *= new_scale / self.model.dmtet.tet_scale\n self.model.dmtet.tet_scale = new_scale\n # self.model.init_tet() \n if model_only:\n return\n\n self.stats = checkpoint_dict['stats']\n self.epoch = checkpoint_dict['epoch']\n self.global_step = checkpoint_dict['global_step']\n logger.info(\n f\"[INFO] load at epoch {self.epoch}, global step {self.global_step}\")\n\n if self.optimizer and 'optimizer' in checkpoint_dict:\n try:\n self.optimizer.load_state_dict(checkpoint_dict['optimizer'])\n logger.info(\"[INFO] loaded optimizer.\")\n except:\n logger.info(\"[WARN] Failed to load optimizer.\")\n\n if self.lr_scheduler and 'lr_scheduler' in checkpoint_dict:\n try:\n self.lr_scheduler.load_state_dict(checkpoint_dict['lr_scheduler'])\n logger.info(\"[INFO] loaded scheduler.\")\n except:\n logger.info(\"[WARN] Failed to load scheduler.\")\n\n if self.scaler and 'scaler' in checkpoint_dict:\n try:\n self.scaler.load_state_dict(checkpoint_dict['scaler'])\n logger.info(\"[INFO] loaded scaler.\")\n except:\n logger.info(\"[WARN] Failed to load scaler.\")" }, { "identifier": "custom_meshgrid", "path": "nerf/utils.py", "snippet": "def custom_meshgrid(*args):\n # ref: https://pytorch.org/docs/stable/generated/torch.meshgrid.html?highlight=meshgrid#torch.meshgrid\n if pver.parse(torch.__version__) < pver.parse('1.10'):\n return torch.meshgrid(*args)\n else:\n return torch.meshgrid(*args, indexing='ij')" }, { "identifier": "safe_normalize", "path": "nerf/utils.py", "snippet": "def safe_normalize(x, eps=1e-20):\n return x / torch.sqrt(torch.clamp(torch.sum(x * x, -1, keepdim=True), min=eps))" } ]
import os import glob import tqdm import random import logging import gc import numpy as np import imageio, imageio_ffmpeg import time import cv2 import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.distributed as dist import torchvision.transforms.functional as TF import ipdb import copy from torch import Tensor from torch.utils.tensorboard import SummaryWriter from torchvision.utils import make_grid from torchmetrics.functional import pearson_corrcoef from nerf.utils import save_tensor2image, nonzero_normalize_depth, Trainer from einops import rearrange from nerf.utils import custom_meshgrid, safe_normalize from dnerf.network_4dgrid import NeRFNetwork
18,060
logger = logging.getLogger(__name__) class DTrainer(Trainer): def __init__(self, argv, name, opt, model, guidance, criterion=None, optimizer=None, ema_decay=None, lr_scheduler=None, metrics=[], local_rank=0, world_size=1, device=None, mute=False, fp16=False, max_keep_ckpt=1, workspace='workspace', best_mode='min', use_loss_as_metric=True, report_metric_at_train=False, use_checkpoint="latest", use_tensorboard=True, scheduler_update_every_step=False, **kwargs): super().__init__(argv, name, opt, model, guidance, criterion, optimizer, ema_decay, lr_scheduler, metrics, local_rank, world_size, device, mute, fp16, max_keep_ckpt, workspace, best_mode, use_loss_as_metric, report_metric_at_train, use_checkpoint, use_tensorboard, scheduler_update_every_step, **kwargs) self.rgbd_scale = opt.get("rgbd_scale", 1.0) self.fix_dynamic = opt.fix_dynamic if self.fix_dynamic: assert opt.backbone == 'grid4d' self.dynamic_model = NeRFNetwork(opt) # ipdb.set_trace() model_state_dict = self.model.state_dict() self.dynamic_model.load_state_dict(model_state_dict) for p in self.dynamic_model.parameters(): p.requires_grad = False self.dynamic_model.train() self.dynamic_model.to(opt.device) @torch.no_grad() def eval_static_step(self, data, shading): rays_o = data['rays_o'] # [B, N, 3] / B,F,N,3 rays_d = data['rays_d'] # [B, N, 3] / B,F,N,3 mvp = data['mvp'] # B,4,4 / B,F,4,4 if rays_o.ndim == 4: rays_o = rays_o[:, 0] rays_d = rays_d[:, 0] mvp = mvp[:, 0] B, N = rays_o.shape[:2] H, W = data['H'], data['W'] ambient_ratio = data['ambient_ratio'] if 'ambient_ratio' in data else 1.0 light_d = data['light_d'] if 'light_d' in data else None # ipdb.set_trace() outputs = self.static_model.render(rays_o, rays_d, mvp, H, W, staged=True, perturb=False, bg_color=None, light_d=light_d, ambient_ratio=ambient_ratio, shading=shading) pred_rgb = outputs['image'].reshape(B, H, W, 3) pred_depth = outputs['depth'].reshape(B, H, W, 1) if self.opt.normalize_depth:
logger = logging.getLogger(__name__) class DTrainer(Trainer): def __init__(self, argv, name, opt, model, guidance, criterion=None, optimizer=None, ema_decay=None, lr_scheduler=None, metrics=[], local_rank=0, world_size=1, device=None, mute=False, fp16=False, max_keep_ckpt=1, workspace='workspace', best_mode='min', use_loss_as_metric=True, report_metric_at_train=False, use_checkpoint="latest", use_tensorboard=True, scheduler_update_every_step=False, **kwargs): super().__init__(argv, name, opt, model, guidance, criterion, optimizer, ema_decay, lr_scheduler, metrics, local_rank, world_size, device, mute, fp16, max_keep_ckpt, workspace, best_mode, use_loss_as_metric, report_metric_at_train, use_checkpoint, use_tensorboard, scheduler_update_every_step, **kwargs) self.rgbd_scale = opt.get("rgbd_scale", 1.0) self.fix_dynamic = opt.fix_dynamic if self.fix_dynamic: assert opt.backbone == 'grid4d' self.dynamic_model = NeRFNetwork(opt) # ipdb.set_trace() model_state_dict = self.model.state_dict() self.dynamic_model.load_state_dict(model_state_dict) for p in self.dynamic_model.parameters(): p.requires_grad = False self.dynamic_model.train() self.dynamic_model.to(opt.device) @torch.no_grad() def eval_static_step(self, data, shading): rays_o = data['rays_o'] # [B, N, 3] / B,F,N,3 rays_d = data['rays_d'] # [B, N, 3] / B,F,N,3 mvp = data['mvp'] # B,4,4 / B,F,4,4 if rays_o.ndim == 4: rays_o = rays_o[:, 0] rays_d = rays_d[:, 0] mvp = mvp[:, 0] B, N = rays_o.shape[:2] H, W = data['H'], data['W'] ambient_ratio = data['ambient_ratio'] if 'ambient_ratio' in data else 1.0 light_d = data['light_d'] if 'light_d' in data else None # ipdb.set_trace() outputs = self.static_model.render(rays_o, rays_d, mvp, H, W, staged=True, perturb=False, bg_color=None, light_d=light_d, ambient_ratio=ambient_ratio, shading=shading) pred_rgb = outputs['image'].reshape(B, H, W, 3) pred_depth = outputs['depth'].reshape(B, H, W, 1) if self.opt.normalize_depth:
pred_depth = nonzero_normalize_depth(pred_depth)
1
2023-11-23 10:34:08+00:00
24k
alexzhou907/DreamPropeller
threestudio/models/geometry/tetrahedra_sdf_grid.py
[ { "identifier": "BaseExplicitGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseExplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n\n cfg: Config\n\n def configure(self) -> None:\n self.bbox: Float[Tensor, \"2 3\"]\n self.register_buffer(\n \"bbox\",\n torch.as_tensor(\n [\n [-self.cfg.radius, -self.cfg.radius, -self.cfg.radius],\n [self.cfg.radius, self.cfg.radius, self.cfg.radius],\n ],\n dtype=torch.float32,\n ),\n )" }, { "identifier": "BaseGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseGeometry(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n @staticmethod\n def create_from(\n other: \"BaseGeometry\", cfg: Optional[Union[dict, DictConfig]] = None, **kwargs\n ) -> \"BaseGeometry\":\n raise TypeError(\n f\"Cannot create {BaseGeometry.__name__} from {other.__class__.__name__}\"\n )\n\n def export(self, *args, **kwargs) -> Dict[str, Any]:\n return {}" }, { "identifier": "contract_to_unisphere", "path": "threestudio/models/geometry/base.py", "snippet": "def contract_to_unisphere(\n x: Float[Tensor, \"... 3\"], bbox: Float[Tensor, \"2 3\"], unbounded: bool = False\n) -> Float[Tensor, \"... 3\"]:\n if unbounded:\n x = scale_tensor(x, bbox, (0, 1))\n x = x * 2 - 1 # aabb is at [-1, 1]\n mag = x.norm(dim=-1, keepdim=True)\n mask = mag.squeeze(-1) > 1\n x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask])\n x = x / 4 + 0.5 # [-inf, inf] is at [0, 1]\n else:\n x = scale_tensor(x, bbox, (0, 1))\n return x" }, { "identifier": "ImplicitSDF", "path": "threestudio/models/geometry/implicit_sdf.py", "snippet": "class ImplicitSDF(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: Union[\n float, str\n ] = 0.01 # in [float, \"progressive\"]\n shape_init: Optional[str] = None\n shape_init_params: Optional[Any] = None\n shape_init_mesh_up: str = \"+z\"\n shape_init_mesh_front: str = \"+x\"\n force_shape_init: bool = False\n sdf_bias: Union[float, str] = 0.0\n sdf_bias_params: Optional[Any] = None\n\n # no need to removal outlier for SDF\n isosurface_remove_outliers: bool = False\n\n cfg: Config\n\n def configure(self, *args, **kwargs) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.sdf_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n if self.cfg.isosurface_deformable_grid:\n assert (\n self.cfg.isosurface_method == \"mt\"\n ), \"isosurface_deformable_grid only works with mt\"\n self.deformation_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n self.finite_difference_normal_eps: Optional[float] = None\n\n def initialize_shape(self) -> None:\n if self.cfg.shape_init is None and not self.cfg.force_shape_init:\n return\n\n # do not initialize shape if weights are provided\n if self.cfg.weights is not None and not self.cfg.force_shape_init:\n return\n\n if self.cfg.sdf_bias != 0.0:\n threestudio.warn(\n \"shape_init and sdf_bias are both specified, which may lead to unexpected results.\"\n )\n\n get_gt_sdf: Callable[[Float[Tensor, \"N 3\"]], Float[Tensor, \"N 1\"]]\n assert isinstance(self.cfg.shape_init, str)\n if self.cfg.shape_init == \"ellipsoid\":\n assert (\n isinstance(self.cfg.shape_init_params, Sized)\n and len(self.cfg.shape_init_params) == 3\n )\n size = torch.as_tensor(self.cfg.shape_init_params).to(self.device)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return ((points_rand / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n\n get_gt_sdf = func\n elif self.cfg.shape_init == \"sphere\":\n assert isinstance(self.cfg.shape_init_params, float)\n radius = self.cfg.shape_init_params\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius\n\n get_gt_sdf = func\n elif self.cfg.shape_init.startswith(\"mesh:\"):\n assert isinstance(self.cfg.shape_init_params, float)\n mesh_path = self.cfg.shape_init[5:]\n if not os.path.exists(mesh_path):\n raise ValueError(f\"Mesh file {mesh_path} does not exist.\")\n\n import trimesh\n\n scene = trimesh.load(mesh_path)\n if isinstance(scene, trimesh.Trimesh):\n mesh = scene\n elif isinstance(scene, trimesh.scene.Scene):\n mesh = trimesh.Trimesh()\n for obj in scene.geometry.values():\n mesh = trimesh.util.concatenate([mesh, obj])\n else:\n raise ValueError(f\"Unknown mesh type at {mesh_path}.\")\n\n # move to center\n centroid = mesh.vertices.mean(0)\n mesh.vertices = mesh.vertices - centroid\n\n # align to up-z and front-x\n dirs = [\"+x\", \"+y\", \"+z\", \"-x\", \"-y\", \"-z\"]\n dir2vec = {\n \"+x\": np.array([1, 0, 0]),\n \"+y\": np.array([0, 1, 0]),\n \"+z\": np.array([0, 0, 1]),\n \"-x\": np.array([-1, 0, 0]),\n \"-y\": np.array([0, -1, 0]),\n \"-z\": np.array([0, 0, -1]),\n }\n if (\n self.cfg.shape_init_mesh_up not in dirs\n or self.cfg.shape_init_mesh_front not in dirs\n ):\n raise ValueError(\n f\"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}.\"\n )\n if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]:\n raise ValueError(\n \"shape_init_mesh_up and shape_init_mesh_front must be orthogonal.\"\n )\n z_, x_ = (\n dir2vec[self.cfg.shape_init_mesh_up],\n dir2vec[self.cfg.shape_init_mesh_front],\n )\n y_ = np.cross(z_, x_)\n std2mesh = np.stack([x_, y_, z_], axis=0).T\n mesh2std = np.linalg.inv(std2mesh)\n\n # scaling\n scale = np.abs(mesh.vertices).max()\n mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params\n mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T\n\n from pysdf import SDF\n\n sdf = SDF(mesh.vertices, mesh.faces)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n # add a negative signed here\n # as in pysdf the inside of the shape has positive signed distance\n return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to(\n points_rand\n )[..., None]\n\n get_gt_sdf = func\n\n else:\n raise ValueError(\n f\"Unknown shape initialization type: {self.cfg.shape_init}\"\n )\n\n # Initialize SDF to a given shape when no weights are provided or force_shape_init is True\n optim = torch.optim.Adam(self.parameters(), lr=1e-3)\n from tqdm import tqdm\n\n for _ in tqdm(\n range(1000),\n desc=f\"Initializing SDF to a(n) {self.cfg.shape_init}:\",\n disable=get_rank() != 0,\n ):\n points_rand = (\n torch.rand((10000, 3), dtype=torch.float32).to(self.device) * 2.0 - 1.0\n )\n sdf_gt = get_gt_sdf(points_rand)\n sdf_pred = self.forward_sdf(points_rand)\n loss = F.mse_loss(sdf_pred, sdf_gt)\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n # explicit broadcast to ensure param consistency across ranks\n for param in self.parameters():\n broadcast(param, src=0)\n\n def get_shifted_sdf(\n self, points: Float[Tensor, \"*N Di\"], sdf: Float[Tensor, \"*N 1\"]\n ) -> Float[Tensor, \"*N 1\"]:\n sdf_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.sdf_bias == \"ellipsoid\":\n assert (\n isinstance(self.cfg.sdf_bias_params, Sized)\n and len(self.cfg.sdf_bias_params) == 3\n )\n size = torch.as_tensor(self.cfg.sdf_bias_params).to(points)\n sdf_bias = ((points / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n elif self.cfg.sdf_bias == \"sphere\":\n assert isinstance(self.cfg.sdf_bias_params, float)\n radius = self.cfg.sdf_bias_params\n sdf_bias = (points**2).sum(dim=-1, keepdim=True).sqrt() - radius\n elif isinstance(self.cfg.sdf_bias, float):\n sdf_bias = self.cfg.sdf_bias\n else:\n raise ValueError(f\"Unknown sdf bias {self.cfg.sdf_bias}\")\n return sdf + sdf_bias\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).view(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n output = {\"sdf\": sdf}\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n assert self.finite_difference_normal_eps is not None\n eps: float = self.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 6 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (\n 0.5\n * (sdf_offset[..., 0::2, 0] - sdf_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 3 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (sdf_offset[..., 0::1, 0] - sdf) / eps\n normal = F.normalize(sdf_grad, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n sdf_grad = normal\n elif self.cfg.normal_type == \"analytic\":\n sdf_grad = -torch.autograd.grad(\n sdf,\n points_unscaled,\n grad_outputs=torch.ones_like(sdf),\n create_graph=True,\n )[0]\n normal = F.normalize(sdf_grad, dim=-1)\n if not grad_enabled:\n sdf_grad = sdf_grad.detach()\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update(\n {\"normal\": normal, \"shading_normal\": normal, \"sdf_grad\": sdf_grad}\n )\n return output\n\n def forward_sdf(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n sdf = self.sdf_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n return sdf\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n deformation: Optional[Float[Tensor, \"*N 3\"]] = None\n if self.cfg.isosurface_deformable_grid:\n deformation = self.deformation_network(enc).reshape(*points.shape[:-1], 3)\n return sdf, deformation\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return field - threshold\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n if isinstance(self.cfg.finite_difference_normal_eps, float):\n self.finite_difference_normal_eps = (\n self.cfg.finite_difference_normal_eps\n )\n elif self.cfg.finite_difference_normal_eps == \"progressive\":\n # progressive finite difference eps from Neuralangelo\n # https://arxiv.org/abs/2306.03092\n hg_conf: Any = self.cfg.pos_encoding_config\n assert (\n hg_conf.otype == \"ProgressiveBandHashGrid\"\n ), \"finite_difference_normal_eps=progressive only works with ProgressiveBandHashGrid\"\n current_level = min(\n hg_conf.start_level\n + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps,\n hg_conf.n_levels,\n )\n grid_res = hg_conf.base_resolution * hg_conf.per_level_scale ** (\n current_level - 1\n )\n grid_size = 2 * self.cfg.radius / grid_res\n if grid_size != self.finite_difference_normal_eps:\n threestudio.info(\n f\"Update finite_difference_normal_eps to {grid_size}\"\n )\n self.finite_difference_normal_eps = grid_size\n else:\n raise ValueError(\n f\"Unknown finite_difference_normal_eps={self.cfg.finite_difference_normal_eps}\"\n )" }, { "identifier": "ImplicitVolume", "path": "threestudio/models/geometry/implicit_volume.py", "snippet": "class ImplicitVolume(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n density_activation: Optional[str] = \"softplus\"\n density_bias: Union[float, str] = \"blob_magic3d\"\n density_blob_scale: float = 10.0\n density_blob_std: float = 0.5\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: float = 0.01\n\n # automatically determine the threshold\n isosurface_threshold: Union[float, str] = 25.0\n\n cfg: Config\n\n def configure(self, *args, **kwargs) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.density_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n \n def get_activated_density(\n self, points: Float[Tensor, \"*N Di\"], density: Float[Tensor, \"*N 1\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Float[Tensor, \"*N 1\"]]:\n density_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.density_bias == \"blob_dreamfusion\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * torch.exp(\n -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2\n )[..., None]\n )\n elif self.cfg.density_bias == \"blob_magic3d\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * (\n 1\n - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std\n )[..., None]\n )\n elif isinstance(self.cfg.density_bias, float):\n density_bias = self.cfg.density_bias\n else:\n raise ValueError(f\"Unknown density bias {self.cfg.density_bias}\")\n raw_density: Float[Tensor, \"*N 1\"] = density + density_bias\n density = get_activation(self.cfg.density_activation)(raw_density)\n # density = self.density_act(raw_density)\n return raw_density, density\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n density = self.density_network(enc).view(*points.shape[:-1], 1)\n raw_density, density = self.get_activated_density(points_unscaled, density)\n\n output = {\n \"density\": density,\n }\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n # TODO: use raw density\n eps = self.cfg.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 6 1\"] = self.forward_density(\n points_offset\n )\n normal = (\n -0.5\n * (density_offset[..., 0::2, 0] - density_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 3 1\"] = self.forward_density(\n points_offset\n )\n normal = -(density_offset[..., 0::1, 0] - density) / eps\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"analytic\":\n normal = -torch.autograd.grad(\n density,\n points_unscaled,\n grad_outputs=torch.ones_like(density),\n create_graph=True,\n )[0]\n normal = F.normalize(normal, dim=-1)\n if not grad_enabled:\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update({\"normal\": normal, \"shading_normal\": normal})\n\n torch.set_grad_enabled(grad_enabled)\n return output\n\n def forward_density(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n density = self.density_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n\n _, density = self.get_activated_density(points_unscaled, density)\n return density\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n if self.cfg.isosurface_deformable_grid:\n threestudio.warn(\n f\"{self.__class__.__name__} does not support isosurface_deformable_grid. Ignoring.\"\n )\n density = self.forward_density(points)\n return density, None\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return -(field - threshold)\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n @staticmethod\n @torch.no_grad()\n def create_from(\n other: BaseGeometry,\n cfg: Optional[Union[dict, DictConfig]] = None,\n copy_net: bool = True,\n **kwargs,\n ) -> \"ImplicitVolume\":\n if isinstance(other, ImplicitVolume):\n instance = ImplicitVolume(cfg, **kwargs)\n instance.encoding.load_state_dict(other.encoding.state_dict())\n instance.density_network.load_state_dict(other.density_network.state_dict())\n if copy_net:\n if (\n instance.cfg.n_feature_dims > 0\n and other.cfg.n_feature_dims == instance.cfg.n_feature_dims\n ):\n instance.feature_network.load_state_dict(\n other.feature_network.state_dict()\n )\n if (\n instance.cfg.normal_type == \"pred\"\n and other.cfg.normal_type == \"pred\"\n ):\n instance.normal_network.load_state_dict(\n other.normal_network.state_dict()\n )\n return instance\n else:\n raise TypeError(\n f\"Cannot create {ImplicitVolume.__name__} from {other.__class__.__name__}\"\n )" }, { "identifier": "MarchingTetrahedraHelper", "path": "threestudio/models/isosurface.py", "snippet": "class MarchingTetrahedraHelper(IsosurfaceHelper):\n def __init__(self, resolution: int, tets_path: str):\n super().__init__()\n self.resolution = resolution\n self.tets_path = tets_path\n\n self.triangle_table: Float[Tensor, \"...\"]\n self.register_buffer(\n \"triangle_table\",\n torch.as_tensor(\n [\n [-1, -1, -1, -1, -1, -1],\n [1, 0, 2, -1, -1, -1],\n [4, 0, 3, -1, -1, -1],\n [1, 4, 2, 1, 3, 4],\n [3, 1, 5, -1, -1, -1],\n [2, 3, 0, 2, 5, 3],\n [1, 4, 0, 1, 5, 4],\n [4, 2, 5, -1, -1, -1],\n [4, 5, 2, -1, -1, -1],\n [4, 1, 0, 4, 5, 1],\n [3, 2, 0, 3, 5, 2],\n [1, 3, 5, -1, -1, -1],\n [4, 1, 2, 4, 3, 1],\n [3, 0, 4, -1, -1, -1],\n [2, 0, 1, -1, -1, -1],\n [-1, -1, -1, -1, -1, -1],\n ],\n dtype=torch.long,\n ),\n persistent=False,\n )\n self.num_triangles_table: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"num_triangles_table\",\n torch.as_tensor(\n [0, 1, 1, 2, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 0], dtype=torch.long\n ),\n persistent=False,\n )\n self.base_tet_edges: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"base_tet_edges\",\n torch.as_tensor([0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3], dtype=torch.long),\n persistent=False,\n )\n\n tets = np.load(self.tets_path)\n self._grid_vertices: Float[Tensor, \"...\"]\n self.register_buffer(\n \"_grid_vertices\",\n torch.from_numpy(tets[\"vertices\"]).float(),\n persistent=False,\n )\n self.indices: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"indices\", torch.from_numpy(tets[\"indices\"]).long(), persistent=False\n )\n\n self._all_edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n\n def normalize_grid_deformation(\n self, grid_vertex_offsets: Float[Tensor, \"Nv 3\"]\n ) -> Float[Tensor, \"Nv 3\"]:\n return (\n (self.points_range[1] - self.points_range[0])\n / (self.resolution) # half tet size is approximately 1 / self.resolution\n * torch.tanh(grid_vertex_offsets)\n ) # FIXME: hard-coded activation\n\n @property\n def grid_vertices(self) -> Float[Tensor, \"Nv 3\"]:\n return self._grid_vertices\n\n @property\n def all_edges(self) -> Integer[Tensor, \"Ne 2\"]:\n if self._all_edges is None:\n # compute edges on GPU, or it would be VERY SLOW (basically due to the unique operation)\n edges = torch.tensor(\n [0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],\n dtype=torch.long,\n device=self.indices.device,\n )\n _all_edges = self.indices[:, edges].reshape(-1, 2)\n _all_edges_sorted = torch.sort(_all_edges, dim=1)[0]\n _all_edges = torch.unique(_all_edges_sorted, dim=0)\n self._all_edges = _all_edges\n return self._all_edges\n\n def sort_edges(self, edges_ex2):\n with torch.no_grad():\n order = (edges_ex2[:, 0] > edges_ex2[:, 1]).long()\n order = order.unsqueeze(dim=1)\n\n a = torch.gather(input=edges_ex2, index=order, dim=1)\n b = torch.gather(input=edges_ex2, index=1 - order, dim=1)\n\n return torch.stack([a, b], -1)\n\n def _forward(self, pos_nx3, sdf_n, tet_fx4):\n with torch.no_grad():\n occ_n = sdf_n > 0\n occ_fx4 = occ_n[tet_fx4.reshape(-1)].reshape(-1, 4)\n occ_sum = torch.sum(occ_fx4, -1)\n valid_tets = (occ_sum > 0) & (occ_sum < 4)\n occ_sum = occ_sum[valid_tets]\n\n # find all vertices\n all_edges = tet_fx4[valid_tets][:, self.base_tet_edges].reshape(-1, 2)\n all_edges = self.sort_edges(all_edges)\n unique_edges, idx_map = torch.unique(all_edges, dim=0, return_inverse=True)\n\n unique_edges = unique_edges.long()\n mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1\n mapping = (\n torch.ones(\n (unique_edges.shape[0]), dtype=torch.long, device=pos_nx3.device\n )\n * -1\n )\n mapping[mask_edges] = torch.arange(\n mask_edges.sum(), dtype=torch.long, device=pos_nx3.device\n )\n idx_map = mapping[idx_map] # map edges to verts\n\n interp_v = unique_edges[mask_edges]\n edges_to_interp = pos_nx3[interp_v.reshape(-1)].reshape(-1, 2, 3)\n edges_to_interp_sdf = sdf_n[interp_v.reshape(-1)].reshape(-1, 2, 1)\n edges_to_interp_sdf[:, -1] *= -1\n\n denominator = edges_to_interp_sdf.sum(1, keepdim=True)\n\n edges_to_interp_sdf = torch.flip(edges_to_interp_sdf, [1]) / denominator\n verts = (edges_to_interp * edges_to_interp_sdf).sum(1)\n\n idx_map = idx_map.reshape(-1, 6)\n\n v_id = torch.pow(2, torch.arange(4, dtype=torch.long, device=pos_nx3.device))\n tetindex = (occ_fx4[valid_tets] * v_id.unsqueeze(0)).sum(-1)\n num_triangles = self.num_triangles_table[tetindex]\n\n # Generate triangle indices\n faces = torch.cat(\n (\n torch.gather(\n input=idx_map[num_triangles == 1],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 1]][:, :3],\n ).reshape(-1, 3),\n torch.gather(\n input=idx_map[num_triangles == 2],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 2]][:, :6],\n ).reshape(-1, 3),\n ),\n dim=0,\n )\n\n return verts, faces\n\n def forward(\n self,\n level: Float[Tensor, \"N3 1\"],\n deformation: Optional[Float[Tensor, \"N3 3\"]] = None,\n ) -> Mesh:\n if deformation is not None:\n grid_vertices = self.grid_vertices + self.normalize_grid_deformation(\n deformation\n )\n else:\n grid_vertices = self.grid_vertices\n\n v_pos, t_pos_idx = self._forward(grid_vertices, level, self.indices)\n\n mesh = Mesh(\n v_pos=v_pos,\n t_pos_idx=t_pos_idx,\n # extras\n grid_vertices=grid_vertices,\n tet_edges=self.all_edges,\n grid_level=level,\n grid_deformation=deformation,\n )\n\n return mesh" }, { "identifier": "Mesh", "path": "threestudio/models/mesh.py", "snippet": "class Mesh:\n def __init__(\n self, v_pos: Float[Tensor, \"Nv 3\"], t_pos_idx: Integer[Tensor, \"Nf 3\"], **kwargs\n ) -> None:\n self.v_pos: Float[Tensor, \"Nv 3\"] = v_pos\n self.t_pos_idx: Integer[Tensor, \"Nf 3\"] = t_pos_idx\n self._v_nrm: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tng: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tex: Optional[Float[Tensor, \"Nt 3\"]] = None\n self._t_tex_idx: Optional[Float[Tensor, \"Nf 3\"]] = None\n self._v_rgb: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n self.extras: Dict[str, Any] = {}\n for k, v in kwargs.items():\n self.add_extra(k, v)\n\n def add_extra(self, k, v) -> None:\n self.extras[k] = v\n\n def remove_outlier(self, outlier_n_faces_threshold: Union[int, float]) -> Mesh:\n if self.requires_grad:\n threestudio.debug(\"Mesh is differentiable, not removing outliers\")\n return self\n\n # use trimesh to first split the mesh into connected components\n # then remove the components with less than n_face_threshold faces\n import trimesh\n\n # construct a trimesh object\n mesh = trimesh.Trimesh(\n vertices=self.v_pos.detach().cpu().numpy(),\n faces=self.t_pos_idx.detach().cpu().numpy(),\n )\n\n # split the mesh into connected components\n components = mesh.split(only_watertight=False)\n # log the number of faces in each component\n threestudio.debug(\n \"Mesh has {} components, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n\n n_faces_threshold: int\n if isinstance(outlier_n_faces_threshold, float):\n # set the threshold to the number of faces in the largest component multiplied by outlier_n_faces_threshold\n n_faces_threshold = int(\n max([c.faces.shape[0] for c in components]) * outlier_n_faces_threshold\n )\n else:\n # set the threshold directly to outlier_n_faces_threshold\n n_faces_threshold = outlier_n_faces_threshold\n\n # log the threshold\n threestudio.debug(\n \"Removing components with less than {} faces\".format(n_faces_threshold)\n )\n\n # remove the components with less than n_face_threshold faces\n components = [c for c in components if c.faces.shape[0] >= n_faces_threshold]\n\n # log the number of faces in each component after removing outliers\n threestudio.debug(\n \"Mesh has {} components after removing outliers, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n # merge the components\n mesh = trimesh.util.concatenate(components)\n\n # convert back to our mesh format\n v_pos = torch.from_numpy(mesh.vertices).to(self.v_pos)\n t_pos_idx = torch.from_numpy(mesh.faces).to(self.t_pos_idx)\n\n clean_mesh = Mesh(v_pos, t_pos_idx)\n # keep the extras unchanged\n\n if len(self.extras) > 0:\n clean_mesh.extras = self.extras\n threestudio.debug(\n f\"The following extra attributes are inherited from the original mesh unchanged: {list(self.extras.keys())}\"\n )\n return clean_mesh\n\n @property\n def requires_grad(self):\n return self.v_pos.requires_grad\n\n @property\n def v_nrm(self):\n if self._v_nrm is None:\n self._v_nrm = self._compute_vertex_normal()\n return self._v_nrm\n\n @property\n def v_tng(self):\n if self._v_tng is None:\n self._v_tng = self._compute_vertex_tangent()\n return self._v_tng\n\n @property\n def v_tex(self):\n if self._v_tex is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._v_tex\n\n @property\n def t_tex_idx(self):\n if self._t_tex_idx is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._t_tex_idx\n\n @property\n def v_rgb(self):\n return self._v_rgb\n\n @property\n def edges(self):\n if self._edges is None:\n self._edges = self._compute_edges()\n return self._edges\n\n def _compute_vertex_normal(self):\n i0 = self.t_pos_idx[:, 0]\n i1 = self.t_pos_idx[:, 1]\n i2 = self.t_pos_idx[:, 2]\n\n v0 = self.v_pos[i0, :]\n v1 = self.v_pos[i1, :]\n v2 = self.v_pos[i2, :]\n\n face_normals = torch.cross(v1 - v0, v2 - v0)\n\n # Splat face normals to vertices\n v_nrm = torch.zeros_like(self.v_pos)\n v_nrm.scatter_add_(0, i0[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i1[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i2[:, None].repeat(1, 3), face_normals)\n\n # Normalize, replace zero (degenerated) normals with some default value\n v_nrm = torch.where(\n dot(v_nrm, v_nrm) > 1e-20, v_nrm, torch.as_tensor([0.0, 0.0, 1.0]).to(v_nrm)\n )\n v_nrm = F.normalize(v_nrm, dim=1)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(v_nrm))\n\n return v_nrm\n\n def _compute_vertex_tangent(self):\n vn_idx = [None] * 3\n pos = [None] * 3\n tex = [None] * 3\n for i in range(0, 3):\n pos[i] = self.v_pos[self.t_pos_idx[:, i]]\n tex[i] = self.v_tex[self.t_tex_idx[:, i]]\n # t_nrm_idx is always the same as t_pos_idx\n vn_idx[i] = self.t_pos_idx[:, i]\n\n tangents = torch.zeros_like(self.v_nrm)\n tansum = torch.zeros_like(self.v_nrm)\n\n # Compute tangent space for each triangle\n uve1 = tex[1] - tex[0]\n uve2 = tex[2] - tex[0]\n pe1 = pos[1] - pos[0]\n pe2 = pos[2] - pos[0]\n\n nom = pe1 * uve2[..., 1:2] - pe2 * uve1[..., 1:2]\n denom = uve1[..., 0:1] * uve2[..., 1:2] - uve1[..., 1:2] * uve2[..., 0:1]\n\n # Avoid division by zero for degenerated texture coordinates\n tang = nom / torch.where(\n denom > 0.0, torch.clamp(denom, min=1e-6), torch.clamp(denom, max=-1e-6)\n )\n\n # Update all 3 vertices\n for i in range(0, 3):\n idx = vn_idx[i][:, None].repeat(1, 3)\n tangents.scatter_add_(0, idx, tang) # tangents[n_i] = tangents[n_i] + tang\n tansum.scatter_add_(\n 0, idx, torch.ones_like(tang)\n ) # tansum[n_i] = tansum[n_i] + 1\n tangents = tangents / tansum\n\n # Normalize and make sure tangent is perpendicular to normal\n tangents = F.normalize(tangents, dim=1)\n tangents = F.normalize(tangents - dot(tangents, self.v_nrm) * self.v_nrm)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(tangents))\n\n return tangents\n\n def _unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n threestudio.info(\"Using xatlas to perform UV unwrapping, may take a while ...\")\n\n import xatlas\n\n atlas = xatlas.Atlas()\n atlas.add_mesh(\n self.v_pos.detach().cpu().numpy(),\n self.t_pos_idx.cpu().numpy(),\n )\n co = xatlas.ChartOptions()\n po = xatlas.PackOptions()\n for k, v in xatlas_chart_options.items():\n setattr(co, k, v)\n for k, v in xatlas_pack_options.items():\n setattr(po, k, v)\n atlas.generate(co, po)\n vmapping, indices, uvs = atlas.get_mesh(0)\n vmapping = (\n torch.from_numpy(\n vmapping.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n uvs = torch.from_numpy(uvs).to(self.v_pos.device).float()\n indices = (\n torch.from_numpy(\n indices.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n return uvs, indices\n\n def unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n self._v_tex, self._t_tex_idx = self._unwrap_uv(\n xatlas_chart_options, xatlas_pack_options\n )\n\n def set_vertex_color(self, v_rgb):\n assert v_rgb.shape[0] == self.v_pos.shape[0]\n self._v_rgb = v_rgb\n\n def _compute_edges(self):\n # Compute edges\n edges = torch.cat(\n [\n self.t_pos_idx[:, [0, 1]],\n self.t_pos_idx[:, [1, 2]],\n self.t_pos_idx[:, [2, 0]],\n ],\n dim=0,\n )\n edges = edges.sort()[0]\n edges = torch.unique(edges, dim=0)\n return edges\n\n def normal_consistency(self) -> Float[Tensor, \"\"]:\n edge_nrm: Float[Tensor, \"Ne 2 3\"] = self.v_nrm[self.edges]\n nc = (\n 1.0 - torch.cosine_similarity(edge_nrm[:, 0], edge_nrm[:, 1], dim=-1)\n ).mean()\n return nc\n\n def _laplacian_uniform(self):\n # from stable-dreamfusion\n # https://github.com/ashawkey/stable-dreamfusion/blob/8fb3613e9e4cd1ded1066b46e80ca801dfb9fd06/nerf/renderer.py#L224\n verts, faces = self.v_pos, self.t_pos_idx\n\n V = verts.shape[0]\n F = faces.shape[0]\n\n # Neighbor indices\n ii = faces[:, [1, 2, 0]].flatten()\n jj = faces[:, [2, 0, 1]].flatten()\n adj = torch.stack([torch.cat([ii, jj]), torch.cat([jj, ii])], dim=0).unique(\n dim=1\n )\n adj_values = torch.ones(adj.shape[1]).to(verts)\n\n # Diagonal indices\n diag_idx = adj[0]\n\n # Build the sparse matrix\n idx = torch.cat((adj, torch.stack((diag_idx, diag_idx), dim=0)), dim=1)\n values = torch.cat((-adj_values, adj_values))\n\n # The coalesce operation sums the duplicate indices, resulting in the\n # correct diagonal\n return torch.sparse_coo_tensor(idx, values, (V, V)).coalesce()\n\n def laplacian(self) -> Float[Tensor, \"\"]:\n with torch.no_grad():\n L = self._laplacian_uniform()\n loss = L.mm(self.v_pos)\n loss = loss.norm(dim=1)\n loss = loss.mean()\n return loss" }, { "identifier": "get_encoding", "path": "threestudio/models/networks.py", "snippet": "def get_encoding(n_input_dims: int, config) -> nn.Module:\n # input suppose to be range [0, 1]\n encoding: nn.Module\n if config.otype == \"ProgressiveBandFrequency\":\n encoding = ProgressiveBandFrequency(n_input_dims, config_to_primitive(config))\n elif config.otype == \"ProgressiveBandHashGrid\":\n encoding = ProgressiveBandHashGrid(n_input_dims, config_to_primitive(config))\n else:\n encoding = TCNNEncoding(n_input_dims, config_to_primitive(config))\n encoding = CompositeEncoding(\n encoding,\n include_xyz=config.get(\"include_xyz\", False),\n xyz_scale=2.0,\n xyz_offset=-1.0,\n ) # FIXME: hard coded\n return encoding" }, { "identifier": "get_mlp", "path": "threestudio/models/networks.py", "snippet": "def get_mlp(n_input_dims, n_output_dims, config) -> nn.Module:\n network: nn.Module\n if config.otype == \"VanillaMLP\":\n network = VanillaMLP(n_input_dims, n_output_dims, config_to_primitive(config))\n elif config.otype == \"SphereInitVanillaMLP\":\n network = SphereInitVanillaMLP(\n n_input_dims, n_output_dims, config_to_primitive(config)\n )\n else:\n assert (\n config.get(\"sphere_init\", False) is False\n ), \"sphere_init=True only supported by VanillaMLP\"\n network = TCNNNetwork(n_input_dims, n_output_dims, config_to_primitive(config))\n return network" }, { "identifier": "broadcast", "path": "threestudio/utils/misc.py", "snippet": "def broadcast(tensor, src=0):\n if not _distributed_available():\n return tensor\n else:\n torch.distributed.broadcast(tensor, src=src)\n return tensor" }, { "identifier": "scale_tensor", "path": "threestudio/utils/ops.py", "snippet": "def scale_tensor(\n dat: Num[Tensor, \"... D\"], inp_scale: ValidScale, tgt_scale: ValidScale\n):\n if inp_scale is None:\n inp_scale = (0, 1)\n if tgt_scale is None:\n tgt_scale = (0, 1)\n if isinstance(tgt_scale, Tensor):\n assert dat.shape[-1] == tgt_scale.shape[-1]\n dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0])\n dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0]\n return dat" } ]
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio import trimesh from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseExplicitGeometry, BaseGeometry, contract_to_unisphere, ) from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.models.geometry.implicit_volume import ImplicitVolume from threestudio.models.isosurface import MarchingTetrahedraHelper from threestudio.models.mesh import Mesh from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.misc import broadcast from threestudio.utils.ops import scale_tensor from threestudio.utils.typing import * from pysdf import SDF
15,049
).sqrt() - 1.0 # pseudo signed distance of an ellipsoid get_gt_sdf = func elif self.cfg.shape_init == "sphere": assert isinstance(self.cfg.shape_init_params, float) radius = self.cfg.shape_init_params def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius get_gt_sdf = func elif self.cfg.shape_init.startswith("mesh:"): assert isinstance(self.cfg.shape_init_params, float) mesh_path = self.cfg.shape_init[5:] if not os.path.exists(mesh_path): raise ValueError(f"Mesh file {mesh_path} does not exist.") mesh = trimesh.load(mesh_path) # move to center centroid = mesh.vertices.mean(0) mesh.vertices = mesh.vertices - centroid # align to up-z and front-x dirs = ["+x", "+y", "+z", "-x", "-y", "-z"] dir2vec = { "+x": np.array([1, 0, 0]), "+y": np.array([0, 1, 0]), "+z": np.array([0, 0, 1]), "-x": np.array([-1, 0, 0]), "-y": np.array([0, -1, 0]), "-z": np.array([0, 0, -1]), } if ( self.cfg.shape_init_mesh_up not in dirs or self.cfg.shape_init_mesh_front not in dirs ): raise ValueError( f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}." ) if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]: raise ValueError( "shape_init_mesh_up and shape_init_mesh_front must be orthogonal." ) z_, x_ = ( dir2vec[self.cfg.shape_init_mesh_up], dir2vec[self.cfg.shape_init_mesh_front], ) y_ = np.cross(z_, x_) std2mesh = np.stack([x_, y_, z_], axis=0).T mesh2std = np.linalg.inv(std2mesh) # scaling scale = np.abs(mesh.vertices).max() mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T sdf = SDF(mesh.vertices, mesh.faces) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: # add a negative signed here # as in pysdf the inside of the shape has positive signed distance return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to( points_rand )[..., None] get_gt_sdf = func else: raise ValueError( f"Unknown shape initialization type: {self.cfg.shape_init}" ) sdf_gt = get_gt_sdf( scale_tensor( self.isosurface_helper.grid_vertices, self.isosurface_helper.points_range, self.isosurface_bbox, ) ) self.sdf.data = sdf_gt # explicit broadcast to ensure param consistency across ranks for param in self.parameters(): broadcast(param, src=0) def isosurface(self) -> Mesh: # return cached mesh if fix_geometry is True to save computation if self.cfg.fix_geometry and self.mesh is not None: return self.mesh mesh = self.isosurface_helper(self.sdf, self.deformation) mesh.v_pos = scale_tensor( mesh.v_pos, self.isosurface_helper.points_range, self.isosurface_bbox ) if self.cfg.isosurface_remove_outliers: mesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold) self.mesh = mesh return mesh def forward( self, points: Float[Tensor, "*N Di"], output_normal: bool = False ) -> Dict[str, Float[Tensor, "..."]]: if self.cfg.geometry_only: return {} assert ( output_normal == False ), f"Normal output is not supported for {self.__class__.__name__}" points_unscaled = points # points in the original scale points = contract_to_unisphere(points, self.bbox) # points normalized to (0, 1) enc = self.encoding(points.view(-1, self.cfg.n_input_dims)) features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) return {"features": features} @staticmethod @torch.no_grad() def create_from(
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None shape_init_mesh_up: str = "+z" shape_init_mesh_front: str = "+x" force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self,*args, **kwargs) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone()) self.isosurface_helper = MarchingTetrahedraHelper( self.cfg.isosurface_resolution, f"load/tets/{self.cfg.isosurface_resolution}_tets.npz", ) self.sdf: Float[Tensor, "Nv 1"] self.deformation: Optional[Float[Tensor, "Nv 3"]] if not self.cfg.fix_geometry: self.register_parameter( "sdf", nn.Parameter( torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ) ), ) if self.cfg.isosurface_deformable_grid: self.register_parameter( "deformation", nn.Parameter( torch.zeros_like(self.isosurface_helper.grid_vertices) ), ) else: self.deformation = None else: self.register_buffer( "sdf", torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ), ) if self.cfg.isosurface_deformable_grid: self.register_buffer( "deformation", torch.zeros_like(self.isosurface_helper.grid_vertices), ) else: self.deformation = None if not self.cfg.geometry_only: self.encoding = get_encoding( self.cfg.n_input_dims, self.cfg.pos_encoding_config ) self.feature_network = get_mlp( self.encoding.n_output_dims, self.cfg.n_feature_dims, self.cfg.mlp_network_config, ) self.mesh: Optional[Mesh] = None def initialize_shape(self) -> None: if self.cfg.shape_init is None and not self.cfg.force_shape_init: return # do not initialize shape if weights are provided if self.cfg.weights is not None and not self.cfg.force_shape_init: return get_gt_sdf: Callable[[Float[Tensor, "N 3"]], Float[Tensor, "N 1"]] assert isinstance(self.cfg.shape_init, str) if self.cfg.shape_init == "ellipsoid": assert ( isinstance(self.cfg.shape_init_params, Sized) and len(self.cfg.shape_init_params) == 3 ) size = torch.as_tensor(self.cfg.shape_init_params).to(self.device) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return ((points_rand / size) ** 2).sum( dim=-1, keepdim=True ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid get_gt_sdf = func elif self.cfg.shape_init == "sphere": assert isinstance(self.cfg.shape_init_params, float) radius = self.cfg.shape_init_params def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius get_gt_sdf = func elif self.cfg.shape_init.startswith("mesh:"): assert isinstance(self.cfg.shape_init_params, float) mesh_path = self.cfg.shape_init[5:] if not os.path.exists(mesh_path): raise ValueError(f"Mesh file {mesh_path} does not exist.") mesh = trimesh.load(mesh_path) # move to center centroid = mesh.vertices.mean(0) mesh.vertices = mesh.vertices - centroid # align to up-z and front-x dirs = ["+x", "+y", "+z", "-x", "-y", "-z"] dir2vec = { "+x": np.array([1, 0, 0]), "+y": np.array([0, 1, 0]), "+z": np.array([0, 0, 1]), "-x": np.array([-1, 0, 0]), "-y": np.array([0, -1, 0]), "-z": np.array([0, 0, -1]), } if ( self.cfg.shape_init_mesh_up not in dirs or self.cfg.shape_init_mesh_front not in dirs ): raise ValueError( f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}." ) if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]: raise ValueError( "shape_init_mesh_up and shape_init_mesh_front must be orthogonal." ) z_, x_ = ( dir2vec[self.cfg.shape_init_mesh_up], dir2vec[self.cfg.shape_init_mesh_front], ) y_ = np.cross(z_, x_) std2mesh = np.stack([x_, y_, z_], axis=0).T mesh2std = np.linalg.inv(std2mesh) # scaling scale = np.abs(mesh.vertices).max() mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T sdf = SDF(mesh.vertices, mesh.faces) def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]: # add a negative signed here # as in pysdf the inside of the shape has positive signed distance return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to( points_rand )[..., None] get_gt_sdf = func else: raise ValueError( f"Unknown shape initialization type: {self.cfg.shape_init}" ) sdf_gt = get_gt_sdf( scale_tensor( self.isosurface_helper.grid_vertices, self.isosurface_helper.points_range, self.isosurface_bbox, ) ) self.sdf.data = sdf_gt # explicit broadcast to ensure param consistency across ranks for param in self.parameters(): broadcast(param, src=0) def isosurface(self) -> Mesh: # return cached mesh if fix_geometry is True to save computation if self.cfg.fix_geometry and self.mesh is not None: return self.mesh mesh = self.isosurface_helper(self.sdf, self.deformation) mesh.v_pos = scale_tensor( mesh.v_pos, self.isosurface_helper.points_range, self.isosurface_bbox ) if self.cfg.isosurface_remove_outliers: mesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold) self.mesh = mesh return mesh def forward( self, points: Float[Tensor, "*N Di"], output_normal: bool = False ) -> Dict[str, Float[Tensor, "..."]]: if self.cfg.geometry_only: return {} assert ( output_normal == False ), f"Normal output is not supported for {self.__class__.__name__}" points_unscaled = points # points in the original scale points = contract_to_unisphere(points, self.bbox) # points normalized to (0, 1) enc = self.encoding(points.view(-1, self.cfg.n_input_dims)) features = self.feature_network(enc).view( *points.shape[:-1], self.cfg.n_feature_dims ) return {"features": features} @staticmethod @torch.no_grad() def create_from(
other: BaseGeometry,
1
2023-11-27 23:39:49+00:00
24k
abdulhaim/LMRL-Gym
llm_rl_scripts/maze/ppo/train_ppo_online.py
[ { "identifier": "build_ppo_score_fn", "path": "LLM_RL/algorithms/ppo/score_fn.py", "snippet": "def build_ppo_score_fn(\n inference: PPOInference, \n tokenizer: PreTrainedTokenizer, \n max_length: int, \n bsize: int, \n):\n \n def score_fn(text_histories: List[TextHistory]) -> List[float]:\n assert all([text_history[-1].is_action for text_history in text_histories])\n\n prev_token_histories = []\n token_histories = []\n for text_history in text_histories:\n prev_token_histories.append(TokenHistory.from_text_history(text_history[:-1], tokenizer))\n token_histories.append(TokenHistory.from_text_history(text_history, tokenizer))\n \n # truncate to end and pad tokens\n tokens = np.stack([np.concatenate((token_history.tokens[-max_length:], np.full((max_length-min(token_history.tokens.shape[0], max_length),), tokenizer.pad_token_id)), axis=0) for token_history in token_histories], axis=0)\n tokens = jnp.asarray(tokens, dtype=jnp.int32)\n \n # str_lst = [[]]\n \n all_logprobs = []\n #TODO: need attention mask\n # or just do from string thing\n for i in range(0, len(text_histories), bsize):\n tokens_batch = jnp.asarray(tokens[i:i+bsize, :])\n \n attention_mask = (tokens_batch != tokenizer.pad_token_id).astype(np.float32)\n \n # new_key = None\n # # if prng_key is not None:\n # prng_key, new_key = jax.random.split(prng_key)\n \n forward_batch_output = inference.forward(\n tokens_batch,\n attention_mask=attention_mask,\n train=False,\n prng_key=None,\n )\n # embed()\n policy_logits = forward_batch_output.policy_raw_output.logits\n prefix_len = jnp.asarray([prev_token_histories[i+x].tokens.shape[0] for x in range(tokens_batch.shape[0])], dtype=jnp.int32)\n action_logprobs = jnp.empty(prefix_len.shape, dtype=jnp.float32)\n \n logprobs = jax.nn.log_softmax(policy_logits, axis=-1)\n action_logits = jnp.take_along_axis(logprobs[:, :-1], tokens_batch[:, 1:][..., None], axis=2).squeeze(2)\n # trying to batchify\n masked_action_logits = action_logits * attention_mask[:, 1:]\n for x in range(len(prefix_len)):\n action_logprobs = action_logprobs.at[x].set(masked_action_logits[x][(prefix_len[x]-1):].sum(axis=0))\n # for x in range(len(prefix_len)):\n # action_logprobs = action_logprobs.at[x].set((action_logits[x] * attention_mask[x, 1:])[(prefix_len[x]-1):].sum(axis=0))\n\n all_logprobs.extend(jax.device_get(action_logprobs).tolist())\n return all_logprobs\n\n return score_fn" }, { "identifier": "train_loop", "path": "LLM_RL/algorithms/ppo/train.py", "snippet": "def train_loop(\n trainer: PPOTrain, \n inference: PPOInference, \n policy: PPOPolicy, \n load_dataset: Callable[[PPOInference, PPOPolicy], Union[PPODataset, PPOIterableDataset]], \n evaluator: Optional[Callable[[PPOInference, PPOPolicy], Tuple[float, Dict[str, Any]]]], \n prng_key: KeyArray, \n save_dir: Optional[str], \n n_rounds: int, \n epochs: int, \n max_steps: Optional[int], \n bsize: int, \n log_every: int, \n eval_every_steps: Optional[int], \n eval_every_epochs: Optional[int], \n eval_every_rounds: Optional[int], \n eval_at_beginning: bool, \n eval_at_end: bool, \n save_every_steps: Optional[int], \n save_every_epochs: Optional[int], \n save_every_rounds: Optional[int], \n save_at_beginning: bool, \n save_at_end: bool, \n save_best: bool, \n max_checkpoints: Optional[int], \n save_train_state: bool, \n save_dtype: jnp.dtype, \n use_wandb: bool, \n wandb_project: Optional[str], \n wandb_run_name: Optional[str], \n wandb_config: Optional[Dict[str, Any]], \n is_main_process: Optional[bool]=None, \n bc_dataset: Optional[Union[MaskDataset, MaskIterableDataset]]=None, \n bc_bsize: Optional[int]=None, \n **loop_state: Dict[Hashable, Any], \n) -> Tuple[PPOTrain, PPOInference, PPOPolicy]:\n print(\"entering training loop ...\")\n assert (not use_wandb) or (use_wandb and wandb_project is not None)\n if is_main_process is None:\n is_main_process = jax.process_index() == 0\n if bc_bsize is None:\n bc_bsize = bsize\n \n # initalize wandb\n wandb_id = loop_state.get('wandb_id', None)\n if use_wandb and is_main_process:\n if wandb_id is None:\n wandb_id = wandb.util.generate_id()\n wandb.init(\n project=wandb_project, \n id=wandb_id, \n name=wandb_run_name, \n config=wandb_config, \n reinit=True, \n resume=\"allow\", \n )\n\n # initalize training loop state\n train_logs = []\n best_perf = loop_state.get('best_perf', float('inf'))\n saved_checkpoints = loop_state.get('saved_checkpoints', deque([]))\n step = 0\n epoch = -1\n round = -1\n def _save(\n name: str, \n add_to_queue: bool, \n **loop_state: Dict[Hashable, Any], \n ):\n nonlocal saved_checkpoints\n print(f'saving checkpoint {name} ...')\n print(f'saving in {save_dir}...')\n # conditionally delete old checkpoints\n if add_to_queue and is_main_process:\n if (max_checkpoints is not None) and (len(saved_checkpoints) >= max_checkpoints):\n delete(saved_checkpoints.popleft(), recursive=True)\n curr_save_dir = os.path.join(save_dir, name)\n if is_main_process:\n create_path(curr_save_dir)\n dump_state(\n policy_model=trainer.policy_model, \n policy_train_state=trainer.policy_train_state, \n value_head_model=trainer.value_head_model, \n value_head_train_state=trainer.value_head_train_state, \n save_dir=curr_save_dir, \n save_train_state=save_train_state, \n enable_save=is_main_process, \n save_dtype=save_dtype, \n **loop_state, \n )\n if add_to_queue and is_main_process:\n saved_checkpoints.append(curr_save_dir)\n print('saved.')\n \n def _eval(\n **loop_state: Dict[Hashable, Any], \n ):\n nonlocal best_perf\n nonlocal inference\n nonlocal policy\n # get eval logs\n print(\"beginning evaluation ...\")\n inference = inference.replace(\n policy_params=trainer.policy_train_state.params, \n value_head_params=trainer.value_head_train_state.params, \n )\n policy.set_params(trainer.policy_train_state.params)\n eval_perf, eval_logs = evaluator(inference, policy)\n\n # publish eval logs\n eval_logs = pull_logs(label_logs(eval_logs, 'eval', {'step': step+1, 'epoch': epoch, 'round': round}))\n log(eval_logs, use_wandb and is_main_process)\n\n # conditionally save best model and optimizer state\n if save_dir is not None and save_best and eval_perf < best_perf:\n print('new best model!')\n best_perf = eval_perf\n _save(\n name='best', \n add_to_queue=False, \n **{**loop_state, 'best_perf': best_perf}, \n )\n\n bc_d = None\n if bc_dataset is not None:\n prng_key, new_prng = jax.random.split(prng_key)\n bc_d = dataloader(new_prng, bc_dataset, bc_bsize, truncate=True)\n \n # begin training loop\n for round in tqdm(range(n_rounds)):\n \n print(f'beginning round {round} ...')\n print(f\"best performance: {best_perf}\")\n\n # load dataset\n dataset = load_dataset(inference, policy)\n\n steps_per_epoch = len(dataset) // bsize if isinstance(dataset, Dataset) else None\n if 'steps_per_epoch' in loop_state:\n assert steps_per_epoch == loop_state['steps_per_epoch'], 'loop_state steps_per_epoch does not match dataset steps_per_epoch'\n\n # begin evaluation\n if evaluator is not None and eval_at_beginning:\n _eval(\n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n # save initial checkpoint\n if save_dir is not None and save_at_beginning:\n _save(\n name='initial', \n add_to_queue=False, \n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n print(\"num epochs: \", epochs)\n for epoch in tqdm(range(epochs)):\n prng_key, new_prng = jax.random.split(prng_key)\n d = dataloader(new_prng, dataset, bsize, truncate=True)\n print(\"steps per epoch: \", steps_per_epoch)\n for batch in tqdm(d, total=steps_per_epoch):\n if bc_d is not None:\n try:\n bc_batch = next(bc_d)\n except StopIteration as e:\n prng_key, new_prng = jax.random.split(prng_key)\n bc_d = dataloader(new_prng, bc_dataset, bc_bsize, truncate=True)\n bc_batch = next(bc_d)\n batch = {**batch, **{'bc_data_'+k: v for k, v in bc_batch.items()}}\n \n # step model and get training logs\n if 'step' in loop_state and step < loop_state['step']:\n step += 1\n continue\n # print(\"trainer step: \", step)\n trainer, _, info = trainer.step(\n **batch, \n prng_key=new_prng, \n train=True, \n )\n train_logs.append(info)\n \n # publish training logs and clear logs\n if (step + 1) % log_every == 0:\n logs = combine_logs(train_logs)\n logs = pull_logs(label_logs(logs, 'train', {'step': step+1, 'epoch': epoch, 'round': round}))\n log(logs, use_wandb and is_main_process)\n train_logs = []\n \n # begin evaluation\n if evaluator is not None and eval_every_steps is not None and (step + 1) % eval_every_steps == 0:\n _eval(\n # loop state metadata\n best_perf=best_perf, \n step=step+1, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n # periodically save checkpoint\n if save_dir is not None and save_every_steps is not None and (step + 1) % save_every_steps == 0:\n _save(\n name='step_%d' % (step+1), \n add_to_queue=True, \n # loop state metadata\n best_perf=best_perf, \n step=step+1, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n step += 1\n \n # conditionally terminate\n if max_steps is not None and step >= max_steps:\n break\n \n # begin evaluation\n if evaluator is not None and eval_every_epochs is not None and (epoch + 1) % eval_every_epochs == 0:\n _eval(\n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n # periodically save checkpoint\n if save_dir is not None and save_every_epochs is not None and (epoch + 1) % save_every_epochs == 0:\n _save(\n name=f'epoch_{epoch}', \n add_to_queue=True, \n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n # conditionally terminate\n if max_steps is not None and step >= max_steps:\n break\n \n # begin evaluation\n if evaluator is not None and eval_every_rounds is not None and (round + 1) % eval_every_rounds == 0:\n _eval(\n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n # periodically save checkpoint\n if save_dir is not None and save_every_rounds is not None and (round + 1) % save_every_rounds == 0:\n _save(\n name='round_%d' % (round), \n add_to_queue=True, \n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n inference = inference.replace(\n policy_params=trainer.policy_train_state.params, \n value_head_params=trainer.value_head_train_state.params, \n )\n policy.set_params(trainer.policy_train_state.params)\n \n # begin evaluation\n if evaluator is not None and eval_at_end:\n _eval(\n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n \n # save final checkpoint\n if save_dir is not None and save_at_end:\n print(\"saving final checkpoint!\")\n _save(\n name='last', \n add_to_queue=False, \n # loop state metadata\n best_perf=best_perf, \n step=step, \n epoch=epoch, \n round=round, \n saved_checkpoints=saved_checkpoints, \n steps_per_epoch=steps_per_epoch, \n wandb_id=wandb_id, \n )\n\n # stop wandb\n if use_wandb and is_main_process:\n wandb.finish()\n \n inference = inference.replace(\n policy_params=trainer.policy_train_state.params, \n value_head_params=trainer.value_head_train_state.params, \n )\n policy.set_params(trainer.policy_train_state.params)\n return trainer, inference, policy" }, { "identifier": "ppo_loss_fn", "path": "LLM_RL/algorithms/ppo/base_interface.py", "snippet": "def ppo_loss_fn(\n attention_mask: jax.Array, # [batch, time-1] – output is masked; shift x[1:]\n logprobs: jax.Array, # [batch, time-1] – logprob of output produced; shift x[1:]\n values: jax.Array, # [batch, time-1] – value of current state; shift x[:-1]\n should_take_action: jax.Array, # [batch, time-1] – is output produced by action; shift x[1:]\n old_logprobs: jax.Array, # [batch, time-1] – logprob of output produced; shift x[1:]\n old_values: jax.Array, # [batch, time-1] – value of current state; shift x[:-1]\n old_advantages: jax.Array, # [batch, time-1] – advantage of output produced; shift x[1:]\n old_returns: jax.Array, # [batch, time-1] – return of current state; shift x[:-1]\n *, \n cliprange_value: Union[float, jax.Array], \n cliprange: Union[float, jax.Array], \n value_loss_coef: Union[float, jax.Array], \n) -> Tuple[jax.Array, Dict[str, Any]]:\n \"\"\"PPO objective function.\n References:\n - https://github.com/CarperAI/trlx/blob/main/trlx/models/modeling_ppo.py\n - https://stable-baselines.readthedocs.io/en/master/modules/ppo2.html\n \"\"\"\n mask = should_take_action.astype(jnp.float32) * attention_mask\n n = mask.sum()\n \n values_clipped = jnp.clip(\n values, \n old_values - cliprange_value, \n old_values + cliprange_value, \n )\n\n vf_loss1 = (values - old_returns) ** 2\n vf_loss2 = (values_clipped - old_returns) ** 2\n vf_loss = 0.5 * jnp.sum(jnp.maximum(vf_loss1, vf_loss2) * mask) / n\n vf_clipfrac = jnp.sum((vf_loss2 > vf_loss1).astype(jnp.float32) * mask) / n\n\n log_ratio = (logprobs - old_logprobs) * mask\n ratio = jnp.exp(log_ratio)\n # Unbiased KL-div estimates (`k3`). Ref: http://joschu.net/blog/kl-approx.html\n approx_kl = jnp.sum((ratio - 1) - log_ratio) / n\n\n pg_loss1 = -old_advantages * ratio\n pg_loss2 = -old_advantages * jnp.clip(\n ratio, \n 1.0 - cliprange, \n 1.0 + cliprange, \n )\n pg_loss = jnp.sum(jnp.maximum(pg_loss1, pg_loss2) * mask) / n\n pg_clipfrac = jnp.sum((pg_loss2 > pg_loss1).astype(jnp.float32) * mask) / n\n\n loss = pg_loss + value_loss_coef * vf_loss\n\n logs = dict(\n losses=dict(\n total_loss=loss, \n policy_loss=pg_loss, \n value_loss=vf_loss, \n ), \n values=dict(\n get_tensor_stats(values, mask, n), \n values_error=jnp.sum(((values - old_returns) * mask) ** 2) / n, \n clipfrac=vf_clipfrac, \n ), \n old_values=get_tensor_stats(old_values, mask, n), \n returns=get_tensor_stats(old_returns, mask, n), \n policy=dict(\n approx_kl=approx_kl, \n clipfrac=pg_clipfrac, \n ), \n ratio=(ratio * mask).sum() / n, \n padding_percentage=n / mask.size, \n )\n\n return loss, logs" }, { "identifier": "FixedKLController", "path": "LLM_RL/algorithms/ppo/base_interface.py", "snippet": "class FixedKLController:\n \"\"\"Fixed KL controller.\"\"\"\n\n def __init__(self, kl_coef):\n self.value = kl_coef\n\n def update(self, current: float, n_steps: int):\n \"\"\"Returns updated KL coefficient, βₜ₊₁.\n Arguments:\n current: The current KL value between the newest policy and the initial policy.\n \"\"\"\n pass" }, { "identifier": "AdaptiveKLController", "path": "LLM_RL/algorithms/ppo/base_interface.py", "snippet": "class AdaptiveKLController:\n \"\"\"Adaptive KL Controller as described in Ziegler et al. \"Fine-Tuning Language Models from Human Preferences\"\n Reference: Section 2.2 https://arxiv.org/pdf/1909.08593.pdf#page=2\n Source: https://github.com/openai/lm-human-preferences/blob/master/lm_human_preferences/train_policy.py\n \"\"\"\n\n def __init__(self, init_kl_coef: float, target: float, horizon: int):\n self.value = init_kl_coef\n self.target = target\n self.horizon = horizon\n\n def update(self, current: float, n_steps: int):\n \"\"\"Returns adaptively updated KL coefficient, βₜ₊₁.\n Arguments:\n current: The current KL value between the newest policy and the initial policy.\n \"\"\"\n proportional_error = np.clip(current / self.target - 1, -0.2, 0.2) # ϵₜ\n mult = 1 + proportional_error * n_steps / self.horizon\n self.value *= mult # βₜ₊₁" }, { "identifier": "Text", "path": "LLM_RL/environment.py", "snippet": "class Text:\n text: str\n is_action: bool" }, { "identifier": "TokenHistory", "path": "LLM_RL/environment.py", "snippet": "class TokenHistory:\n tokens: np.ndarray # 1d int32 array\n is_action: np.ndarray # 1d bool array\n\n def __post_init__(self):\n assert len(self.tokens.shape) == 1 and len(self.is_action.shape) == 1, '(tokens, is_action) must be 1 dimensional'\n assert self.tokens.shape == self.is_action.shape, '(tokens, is_action) must have the same shape'\n \n @classmethod\n def from_text_history(\n cls, \n text_history: TextHistory, \n tokenizer: PreTrainedTokenizer, \n token_process: Optional[Callable[[List[int]], List[int]]]=None, \n ) -> TokenHistory:\n if token_process is None:\n token_process = lambda x: x\n\n tokens = []\n is_action = []\n \n for item in text_history:\n \n # tokenize\n new_tokens = token_process(tokenizer.encode(item.text))\n \n tokens.extend(new_tokens)\n is_action.extend([item.is_action]*len(new_tokens))\n \n return cls(\n np.array(tokens, dtype=np.int32), \n np.array(is_action, dtype=np.bool_), \n )" }, { "identifier": "text_env_eval", "path": "LLM_RL/environment.py", "snippet": "def text_env_eval(\n env: Union[TextEnv, BatchedTextEnv], \n policy: Union[TextPolicy, BatchedTextPolicy], \n n_rollouts: int, \n initial_text_history: Optional[TextHistory]=None, # only allow one initial_text_history here\n seed_generator: Optional[Iterator[int]]=None, \n env_options: Optional[Dict]=None, # only allow one env_options here\n interaction_callback: Optional[Callable[[List[Tuple[TextHistory, TextHistory, TextHistory, float, bool]]], None]]=None, \n bsize: int=1, \n verbose: bool=True, \n) -> Tuple[List[List[InteractionTransition]], Dict[str, Any]]:\n interactions, rewards, dones, eps_lengths = [], [], [], []\n for _ in tqdm(range((n_rollouts+(bsize-1))//bsize), disable=not verbose):\n actual_bsize = min(n_rollouts-len(interactions), bsize)\n npad = bsize - actual_bsize\n interaction_batch = interact_environment(\n env, \n policy, \n initial_text_history=initial_text_history, \n env_seed=[None]*actual_bsize if seed_generator is None else [next(seed_generator) for _ in range(actual_bsize)], \n env_options=[env_options]*actual_bsize, \n bsize=actual_bsize,\n npad=npad,\n )\n \n for interaction in interaction_batch:\n interactions.append(interaction)\n rewards.append(sum(map(lambda x: x.reward, interaction)))\n dones.append(interaction[-1].done)\n eps_lengths.append(len(interaction))\n if interaction_callback is not None:\n interaction_callback(interaction)\n \n rewards = np.asarray(rewards, dtype=np.float32)\n dones = np.asarray(dones, dtype=np.float32)\n results_summary = dict(\n reward=dict(\n mean=np.mean(rewards), \n std=np.std(rewards), \n min=np.min(rewards), \n max=np.max(rewards), \n ), \n done=dict(\n mean=np.mean(dones), \n std=np.std(dones), \n min=np.min(dones), \n max=np.max(dones), \n ), \n length=dict(\n mean=np.mean(eps_lengths),\n std=np.std(eps_lengths),\n min=np.min(eps_lengths),\n max=np.max(eps_lengths),\n ),\n )\n \n return interactions, results_summary" }, { "identifier": "TextTrajectory", "path": "LLM_RL/environment.py", "snippet": "class TextTrajectory:\n text_history: TextHistory\n reward: Tuple[float, ...]\n done: bool\n\n def __post_init__(self):\n assert len(self.reward) == len(self.text_history), \"reward is needed for each text\"\n assert all([r == 0.0 for r, t in zip(self.reward, self.text_history) if not t.is_action]), \"reward for non-actions texts should be 0.0\"" }, { "identifier": "TextTrajectoryChain", "path": "LLM_RL/environment.py", "snippet": "class TextTrajectoryChain:\n text_trajectory: TextTrajectory\n next: Optional[TextTrajectoryChain]" }, { "identifier": "GPT2PPOPolicy", "path": "LLM_RL/algorithms/ppo/gpt2/interface.py", "snippet": "class GPT2PPOPolicy(PPOPolicy):\n def __init__(\n self, \n inference: GPT2Inference, \n prng_key: Optional[jax.random.KeyArray], \n generation_config: Optional[GenerationConfig]=None, \n blocking_strategy: BlockingStrategy=BlockingStrategy(padding=Padding.LEFT, truncation=Truncation.LEFT, max_length=None), \n in_str_process: Optional[Callable[[str], str]]=None, \n out_str_process: Optional[Callable[[str], str]]=None, \n input_token_process: Optional[Callable[[List[int]], List[int]]]=None, \n target_token_process: Optional[Callable[[List[int]], List[int]]]=None, \n trace: bool=True, \n ):\n self.inference = inference\n self.prng_key = prng_key\n self.generation_config = generation_config\n self.blocking_strategy = blocking_strategy\n self.in_str_process = in_str_process\n self.out_str_process = out_str_process\n self.input_token_process = input_token_process\n self.target_token_process = target_token_process\n if self.in_str_process is None:\n self.in_str_process = lambda x: x\n if self.out_str_process is None:\n self.out_str_process = lambda x: x\n self.trace = trace\n \n def act(self, text_history: List[Optional[TextHistory]], done: Optional[List[bool]]=None) -> List[Optional[TextHistory]]:\n if done is None:\n done = [False]*len(text_history)\n # force eos_token for done sequences\n eos_token = self.inference.tokenizer.eos_token\n if self.generation_config is not None and self.generation_config.eos_token_id is not None:\n eos_token = self.inference.tokenizer.decode(self.generation_config.eos_token_id)\n if eos_token is None:\n eos_token = self.inference.tokenizer.pad_token\n if eos_token is None:\n eos_token = ''\n \n raw_input_strs = [\n eos_token if d else self.in_str_process(text_history_to_str(item)) \\\n for item, d in zip(text_history, done)\n ]\n\n new_key = None\n if self.prng_key is not None:\n self.prng_key, new_key = jax.random.split(self.prng_key)\n model_outputs = self.inference.generate_from_str(\n input_strs=raw_input_strs, \n prng_key=new_key, \n blocking_strategy=self.blocking_strategy, \n generation_config=self.generation_config, \n input_token_process=self.input_token_process, \n target_token_process=self.target_token_process, \n trace=self.trace, \n )\n\n raw_output_strs = model_outputs.output_strs\n output_strs = [\n \"\" if d else self.out_str_process(strip_prompt_from_completion(raw_input_str, raw_output_str)) \\\n for raw_input_str, raw_output_str, d in zip(raw_input_strs, raw_output_strs, done)\n ]\n\n return [\n None if d else text_history_item+(Text(output_str, True),) \\\n for text_history_item, output_str, d in zip(text_history, output_strs, done)\n ]\n \n def set_params(self, policy_params: PyTree) -> None:\n self.inference = self.inference.replace(params=policy_params)" }, { "identifier": "GPT2PPOInference", "path": "LLM_RL/algorithms/ppo/gpt2/interface.py", "snippet": "class GPT2PPOInference(PPOInference):\n @classmethod\n def load_inference(\n cls, \n initial_policy_params: Optional[PyTree], \n policy_params: PyTree, \n value_head_params: PyTree, \n initial_policy_model: Optional[FlaxPreTrainedModel], \n policy_model: FlaxPreTrainedModel, \n value_head_model: nn.Module, \n tokenizer: PreTrainedTokenizerBase, \n loss_fn: Optional[Callable], \n dp_shard_logits: bool=True, \n bc_loss_fn: Optional[Callable]=None, \n bc_loss_weight: float=0.0, \n ) -> GPT2PPOInference:\n mesh = policy_model.config.mesh\n assert mesh is not None\n assert mesh == value_head_model.config.mesh\n assert (initial_policy_params is None and initial_policy_model) is None or (initial_policy_params is not None and initial_policy_model is not None)\n has_initial_policy = initial_policy_params is not None\n initial_policy_params_partition_spec = None\n if has_initial_policy:\n initial_policy_params_partition_spec = match_partition_rules(initial_policy_model.config.get_partition_rules(), initial_policy_params)\n policy_params_partition_spec = match_partition_rules(policy_model.config.get_partition_rules(), policy_params)\n value_head_params_partition_spec = match_partition_rules(value_head_model.config.get_partition_rules(), value_head_params)\n\n @partial(\n pjit, \n static_argnames=('initial_policy_output_attentions', 'initial_policy_output_hidden_states', 'policy_output_attentions', 'train'), \n in_shardings=(\n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), initial_policy_params_partition_spec) if has_initial_policy else NamedSharding(mesh, PS()), \n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), policy_params_partition_spec), \n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), value_head_params_partition_spec), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n ), \n out_shardings=PPOForwardOutputGPT2(\n initial_policy_raw_output=FlaxCausalLMOutputWithCrossAttentions(\n logits=NamedSharding(mesh, PS((\"dp\", \"fsdp\"), None, None)) if dp_shard_logits else NamedSharding(mesh, PS()), \n past_key_values=NamedSharding(mesh, PS()), # assume no sharding for past key values\n hidden_states=NamedSharding(mesh, PS()), # assume no sharding for hidden states\n attentions=NamedSharding(mesh, PS()), # assume no sharding for attentions\n cross_attentions=NamedSharding(mesh, PS()), # assume no sharding for cross attentions\n ) if has_initial_policy else NamedSharding(mesh, PS()), \n policy_raw_output=FlaxCausalLMOutputWithCrossAttentions(\n logits=NamedSharding(mesh, PS((\"dp\", \"fsdp\"), None, None)) if dp_shard_logits else NamedSharding(mesh, PS()), \n past_key_values=NamedSharding(mesh, PS()), # assume no sharding for past key values\n hidden_states=NamedSharding(mesh, PS()), # assume no sharding for hidden states\n attentions=NamedSharding(mesh, PS()), # assume no sharding for attentions\n cross_attentions=NamedSharding(mesh, PS()), # assume no sharding for cross attentions\n ), \n values=NamedSharding(mesh, PS()), \n ), \n )\n def _forward(\n initial_policy_params: Optional[PyTree], \n policy_params: PyTree, \n value_head_params: PyTree, \n input_ids: jax.Array, \n attention_mask: jax.Array, \n position_ids: jax.Array, \n prng_key: Optional[jax.random.PRNGKeyArray]=None, \n initial_policy_output_attentions: Optional[bool]=None, \n initial_policy_output_hidden_states: Optional[bool]=None, \n policy_output_attentions: Optional[bool]=None, # no policy_output_hidden_states option because this is required\n train: bool=False, \n ) -> PPOForwardOutputGPT2:\n # data parallel shard inputs\n input_ids = with_named_sharding_constraint(input_ids, mesh, PS((\"dp\", \"fsdp\"), None))\n attention_mask = with_named_sharding_constraint(attention_mask, mesh, PS((\"dp\", \"fsdp\"), None))\n position_ids = with_named_sharding_constraint(position_ids, mesh, PS((\"dp\", \"fsdp\"), None))\n \n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n initial_model_output = None\n if has_initial_policy:\n initial_model_output = initial_policy_model(\n input_ids=input_ids, \n attention_mask=attention_mask, \n position_ids=position_ids, \n params=initial_policy_params, \n dropout_rng=new_key, \n train=train, \n output_hidden_states=initial_policy_output_hidden_states, \n output_attentions=initial_policy_output_attentions, \n )\n # trunc padded logits\n initial_model_output = initial_model_output.replace(logits=initial_model_output.logits.at[:, :, initial_policy_model.config.unpadded_vocab_size:].set(-float('inf')))\n model_output = policy_model(\n input_ids=input_ids, \n attention_mask=attention_mask, \n position_ids=position_ids, \n params=policy_params, \n dropout_rng=new_key, \n train=train, \n output_hidden_states=True, \n output_attentions=policy_output_attentions, \n )\n # trunc padded logits\n model_output = model_output.replace(logits=model_output.logits.at[:, :, policy_model.config.unpadded_vocab_size:].set(-float('inf')))\n\n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n values = value_head_model.apply(\n {'params': value_head_params}, \n model_output.hidden_states[-1], \n train=train, \n rngs={'dropout': new_key} if new_key is not None else None, \n )\n values = jnp.squeeze(values, axis=-1)\n\n # assert sharding on outputs\n if dp_shard_logits:\n if has_initial_policy:\n initial_model_output = initial_model_output.replace(logits=with_named_sharding_constraint(initial_model_output.logits, mesh, PS((\"dp\", \"fsdp\"), None, None)))\n model_output = model_output.replace(logits=with_named_sharding_constraint(model_output.logits, mesh, PS((\"dp\", \"fsdp\"), None, None)))\n return PPOForwardOutputGPT2(\n initial_policy_raw_output=initial_model_output, \n policy_raw_output=model_output, \n values=values, \n )\n \n @partial(\n pjit, \n static_argnames=('train',), \n in_shardings=(\n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), policy_params_partition_spec), \n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), value_head_params_partition_spec), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n ), \n out_shardings=(\n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n ), \n )\n def _eval_loss(\n policy_params: PyTree, \n value_head_params: PyTree, \n input_ids: jax.Array, \n attention_mask: jax.Array, \n position_ids: jax.Array, \n should_take_action: jax.Array, \n old_logprobs: jax.Array, \n old_values: jax.Array, \n old_advantages: jax.Array, \n old_returns: jax.Array, \n prng_key: Optional[jax.random.PRNGKeyArray], \n bc_data_input_ids: Optional[jax.Array], \n bc_data_input_attention_mask: Optional[jax.Array], \n bc_data_input_position_ids: Optional[jax.Array], \n bc_data_input_training_mask: Optional[jax.Array], \n train: bool=False, \n ) -> Tuple[jax.Array, PyTree]:\n assert loss_fn is not None, \"loss_fn must be set to use eval_loss\"\n # data parallel shard inputs\n input_ids = with_named_sharding_constraint(input_ids, mesh, PS((\"dp\", \"fsdp\"), None))\n attention_mask = with_named_sharding_constraint(attention_mask, mesh, PS((\"dp\", \"fsdp\"), None))\n position_ids = with_named_sharding_constraint(position_ids, mesh, PS((\"dp\", \"fsdp\"), None))\n should_take_action = with_named_sharding_constraint(should_take_action, mesh, PS((\"dp\", \"fsdp\"), None))\n old_logprobs = with_named_sharding_constraint(old_logprobs, mesh, PS((\"dp\", \"fsdp\"), None))\n old_values = with_named_sharding_constraint(old_values, mesh, PS((\"dp\", \"fsdp\"), None))\n old_advantages = with_named_sharding_constraint(old_advantages, mesh, PS((\"dp\", \"fsdp\"), None))\n old_returns = with_named_sharding_constraint(old_returns, mesh, PS((\"dp\", \"fsdp\"), None))\n if bc_data_input_ids is not None:\n bc_data_input_ids = with_named_sharding_constraint(bc_data_input_ids, mesh, PS((\"dp\", \"fsdp\"), None))\n bc_data_input_attention_mask = with_named_sharding_constraint(bc_data_input_attention_mask, mesh, PS((\"dp\", \"fsdp\"), None))\n bc_data_input_position_ids = with_named_sharding_constraint(bc_data_input_position_ids, mesh, PS((\"dp\", \"fsdp\"), None))\n bc_data_input_training_mask = with_named_sharding_constraint(bc_data_input_training_mask, mesh, PS((\"dp\", \"fsdp\"), None))\n \n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n model_output = policy_model(\n input_ids=input_ids, \n attention_mask=attention_mask, \n position_ids=position_ids, \n params=policy_params, \n dropout_rng=new_key, \n train=train, \n output_hidden_states=True, \n )\n\n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n values = value_head_model.apply(\n {'params': value_head_params}, \n model_output.hidden_states[-1], \n train=train, \n rngs={'dropout': new_key} if new_key is not None else None, \n )[:, :-1]\n values = jnp.squeeze(values, axis=-1)\n\n logits = model_output.logits.astype(jnp.float32)\n logprobs = -softmax_cross_entropy_with_integer_labels(logits[:, :-1], input_ids[:, 1:])\n\n loss, info = loss_fn(\n attention_mask, \n logprobs, \n values, \n should_take_action, \n old_logprobs, \n old_values, \n old_advantages, \n old_returns, \n )\n\n if bc_loss_fn is not None:\n bc_loss, bc_info = bc_loss_fn(\n policy_model, \n policy_params, \n bc_data_input_ids, \n bc_data_input_attention_mask, \n bc_data_input_position_ids, \n bc_data_input_training_mask, \n prng_key, \n train, \n )\n\n info = {'ppo': info, 'bc': bc_info, 'total_loss': loss + bc_loss * bc_loss_weight}\n loss = loss + bc_loss * bc_loss_weight\n\n return loss, info\n \n return cls(\n initial_policy_params=initial_policy_params, \n policy_params=policy_params, \n value_head_params=value_head_params, \n initial_policy_model=initial_policy_model, \n policy_model=policy_model, \n value_head_model=value_head_model, \n tokenizer=tokenizer, \n _forward=_forward, \n _eval_loss=_eval_loss, \n )" }, { "identifier": "GPT2PPOTrain", "path": "LLM_RL/algorithms/ppo/gpt2/interface.py", "snippet": "class GPT2PPOTrain(PPOTrain):\n @classmethod\n def load_train(\n cls, \n policy_train_state: TrainState, \n value_head_train_state: TrainState, \n policy_model: FlaxPreTrainedModel, \n value_head_model: nn.Module, \n tokenizer: PreTrainedTokenizerBase, \n loss_fn: Callable, \n bc_loss_fn: Optional[Callable]=None, \n bc_loss_weight: float=0.0, \n ) -> GPT2PPOTrain:\n mesh = policy_model.config.mesh\n assert mesh is not None\n assert mesh == value_head_model.config.mesh\n policy_train_state_partition_spec = match_partition_rules(policy_model.config.get_partition_rules(), policy_train_state)\n value_head_train_state_partition_spec = match_partition_rules(value_head_model.config.get_partition_rules(), value_head_train_state)\n\n @partial(\n pjit, \n donate_argnums=(0, 1), \n static_argnames=('train',), \n in_shardings=(\n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), policy_train_state_partition_spec), \n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), value_head_train_state_partition_spec), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n ), \n out_shardings=(\n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), policy_train_state_partition_spec), \n jax.tree_util.tree_map(lambda ps: NamedSharding(mesh, ps), value_head_train_state_partition_spec), \n NamedSharding(mesh, PS()), \n NamedSharding(mesh, PS()), \n ), \n )\n def _step(\n policy_train_state: TrainState, \n value_head_train_state: TrainState, \n input_ids: jax.Array, \n attention_mask: jax.Array, \n position_ids: jax.Array, \n should_take_action: jax.Array, \n old_logprobs: jax.Array, \n old_values: jax.Array, \n old_advantages: jax.Array, \n old_returns: jax.Array, \n prng_key: Optional[jax.random.PRNGKeyArray], \n bc_data_input_ids: Optional[jax.Array], \n bc_data_input_attention_mask: Optional[jax.Array], \n bc_data_input_position_ids: Optional[jax.Array], \n bc_data_input_training_mask: Optional[jax.Array], \n train: bool=True, \n ) -> Tuple[TrainState, TrainState, jax.Array, PyTree]:\n # data parallel shard inputs\n input_ids = with_named_sharding_constraint(input_ids, mesh, PS(('dp', 'fsdp'), None))\n attention_mask = with_named_sharding_constraint(attention_mask, mesh, PS(('dp', 'fsdp'), None))\n position_ids = with_named_sharding_constraint(position_ids, mesh, PS(('dp', 'fsdp'), None))\n should_take_action = with_named_sharding_constraint(should_take_action, mesh, PS(('dp', 'fsdp'), None))\n old_logprobs = with_named_sharding_constraint(old_logprobs, mesh, PS(('dp', 'fsdp'), None))\n old_values = with_named_sharding_constraint(old_values, mesh, PS(('dp', 'fsdp'), None))\n old_advantages = with_named_sharding_constraint(old_advantages, mesh, PS(('dp', 'fsdp'), None))\n old_returns = with_named_sharding_constraint(old_returns, mesh, PS(('dp', 'fsdp'), None))\n if bc_loss_fn is not None:\n bc_data_input_ids = with_named_sharding_constraint(bc_data_input_ids, mesh, PS(('dp', 'fsdp'), None))\n bc_data_input_attention_mask = with_named_sharding_constraint(bc_data_input_attention_mask, mesh, PS(('dp', 'fsdp'), None))\n bc_data_input_position_ids = with_named_sharding_constraint(bc_data_input_position_ids, mesh, PS(('dp', 'fsdp'), None))\n bc_data_input_training_mask = with_named_sharding_constraint(bc_data_input_training_mask, mesh, PS(('dp', 'fsdp'), None))\n \n # define loss function\n def grad_loss(policy_params: PyTree, value_head_params: PyTree, prng_key: Optional[jax.random.PRNGKeyArray]):\n \n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n model_output = policy_model(\n input_ids=input_ids, \n attention_mask=attention_mask, \n position_ids=position_ids, \n params=policy_params, \n dropout_rng=new_key, \n train=train, \n output_hidden_states=True, \n )\n\n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n values = value_head_model.apply(\n {'params': value_head_params}, \n model_output.hidden_states[-1], \n train=train, \n rngs={'dropout': new_key} if new_key is not None else None, \n )[:, :-1]\n values = jnp.squeeze(values, axis=-1)\n\n logits = model_output.logits.astype(jnp.float32)\n logprobs = -softmax_cross_entropy_with_integer_labels(logits[:, :-1], input_ids[:, 1:])\n\n loss, info = loss_fn(\n attention_mask[:, 1:], \n logprobs, \n values, \n should_take_action, \n old_logprobs, \n old_values, \n old_advantages, \n old_returns, \n )\n return loss, info\n \n # define bc loss function\n def grad_bc_loss(policy_params: PyTree, prng_key: Optional[jax.random.PRNGKeyArray]):\n loss, info = bc_loss_fn(\n policy_model, \n policy_params, \n bc_data_input_ids, \n bc_data_input_attention_mask, \n bc_data_input_position_ids, \n bc_data_input_training_mask, \n prng_key, \n train, \n )\n return loss, info\n\n # take loss\n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n (loss, info), (policy_grads, value_head_grads) = jax.value_and_grad(grad_loss, has_aux=True, argnums=(0, 1))(\n policy_train_state.params, \n value_head_train_state.params, \n new_key, \n )\n\n # assert shard gradients\n policy_grads = jax.tree_util.tree_map(\n lambda x, ps: with_named_sharding_constraint(x, mesh, ps), \n policy_grads, \n policy_train_state_partition_spec.params, \n )\n value_head_grads = jax.tree_util.tree_map(\n lambda x, ps: with_named_sharding_constraint(x, mesh, ps), \n value_head_grads, \n value_head_train_state_partition_spec.params, \n )\n\n if bc_loss_fn is not None:\n new_key = None\n if prng_key is not None:\n prng_key, new_key = jax.random.split(prng_key)\n (bc_loss, bc_info), bc_grads = jax.value_and_grad(grad_bc_loss, has_aux=True, argnums=0)(\n policy_train_state.params, \n new_key, \n )\n\n info = {'ppo': info, 'bc': bc_info, 'total_loss': loss + bc_loss * bc_loss_weight}\n loss = loss + bc_loss * bc_loss_weight\n\n bc_grads = jax.tree_util.tree_map(\n lambda x, ps: with_named_sharding_constraint(x, mesh, ps), \n bc_grads, \n policy_train_state_partition_spec.params, \n )\n\n policy_grads = jax.tree_util.tree_map(\n lambda x, y: x + y * bc_loss_weight, \n policy_grads, \n bc_grads, \n )\n\n # update params and optim state\n policy_train_state = policy_train_state.apply_gradients(grads=policy_grads)\n value_head_train_state = value_head_train_state.apply_gradients(grads=value_head_grads)\n\n return policy_train_state, value_head_train_state, loss, info\n \n return cls(\n policy_train_state=policy_train_state, \n value_head_train_state=value_head_train_state, \n policy_model=policy_model, \n value_head_model=value_head_model, \n tokenizer=tokenizer, \n _step=_step, \n )" }, { "identifier": "load_train_state_from_config", "path": "LLM_RL/heads/linear_head.py", "snippet": "def load_train_state_from_config(\n model_config: LinearHeadConfig, \n model_dtype: Union[str, jnp.dtype], \n optim_getter: Callable[[PyTree], optax.GradientTransformation], \n mesh: Mesh, # should be shape (dp, mp)\n prng_key: jax.random.PRNGKeyArray, \n pad_to_output_dim: Optional[int]=None, \n params_dtype: Optional[Union[str, jnp.dtype]]=jnp.float32, \n) -> Tuple[TrainState, LinearHead]:\n \n model = LinearHead(model_config, dtype=model_dtype)\n model.config.mesh = mesh\n # shard params\n params = freeze(shard_params_from_config(model, prng_key, params_dtype=params_dtype))\n # pad outputs\n if pad_to_output_dim is not None:\n params = freeze(pad_outputs(unfreeze(params), model, pad_to_output_dim, dtype=params_dtype))\n # shard train_state\n train_state = shard_train_state_from_params(model, params, optim_getter(params))\n\n return train_state, model" }, { "identifier": "LinearHeadConfig", "path": "LLM_RL/heads/linear_head.py", "snippet": "class LinearHeadConfig(HeadConfig):\n def __init__(\n self, \n input_dim: int, \n output_dim: int, \n use_bias: bool=True, \n unpadded_output_dim: Optional[int]=None, \n initializer_range: Optional[int]=None, \n bias_init: Optional[float]=None, \n mesh: Optional[jax.sharding.Mesh]=None, \n ) -> None:\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.use_bias = use_bias\n self.initializer_range = initializer_range\n self.bias_init = bias_init\n self.mesh = mesh\n self.unpadded_output_dim = unpadded_output_dim\n if self.unpadded_output_dim is None:\n self.unpadded_output_dim = self.output_dim\n super().__init__()\n \n @staticmethod\n def get_partition_rules():\n return [\n (re.escape(\"['dense']['kernel']\"), PS()), \n (re.escape(\"['dense']['bias']\"), PS()), \n ]\n \n def to_dict(self) -> Dict[str, Any]:\n if self.mesh is None:\n return super().to_dict()\n else:\n new_conf = LinearHeadConfig(**self.__dict__)\n new_conf.mesh = None\n return new_conf.to_dict()" }, { "identifier": "PPODataset", "path": "LLM_RL/algorithms/ppo/data.py", "snippet": "class PPODataset(Dataset):\n def __init__(\n self, \n input_ids: np.ndarray, # [b, t]\n should_take_action: np.ndarray, # [b, t-1]\n old_logprobs: np.ndarray, # [b, t-1]\n old_values: np.ndarray, # [b, t-1]\n old_advantages: np.ndarray, # [b, t-1]\n old_returns: np.ndarray, # [b, t-1]\n ):\n assert input_ids.shape[1] == (should_take_action.shape[1]+1)\n assert input_ids.shape[1] == (old_logprobs.shape[1]+1)\n assert input_ids.shape[1] == (old_values.shape[1]+1)\n assert input_ids.shape[1] == (old_advantages.shape[1]+1)\n assert input_ids.shape[1] == (old_returns.shape[1]+1)\n\n assert input_ids.shape[0] == should_take_action.shape[0]\n assert input_ids.shape[0] == old_logprobs.shape[0]\n assert input_ids.shape[0] == old_values.shape[0]\n assert input_ids.shape[0] == old_advantages.shape[0]\n assert input_ids.shape[0] == old_returns.shape[0]\n\n self.input_ids = input_ids\n self.should_take_action = should_take_action\n self.old_logprobs = old_logprobs\n self.old_values = old_values\n self.old_advantages = old_advantages\n self.old_returns = old_returns\n \n def __getitem__(self, index):\n return {\n 'input_ids': jnp.asarray(self.input_ids[index], dtype=jnp.int32), \n 'should_take_action': jnp.asarray(self.should_take_action[index], dtype=jnp.bool_), \n 'old_logprobs': jnp.asarray(self.old_logprobs[index], dtype=jnp.float32), \n 'old_values': jnp.asarray(self.old_values[index], dtype=jnp.float32), \n 'old_advantages': jnp.asarray(self.old_advantages[index], dtype=jnp.float32), \n 'old_returns': jnp.asarray(self.old_returns[index], dtype=jnp.float32), \n }\n \n def __len__(self):\n return self.input_ids.shape[0]\n \n @classmethod\n def from_ppo_data_list(\n cls, \n ppo_data_list: List[PPOData], \n tokenizer: PreTrainedTokenizerBase, \n blocking_strategy: BlockingStrategy, \n ) -> PPODataset:\n \n data = PPOData.block(ppo_data_list, blocking_strategy, tokenizer)\n\n return cls(**data)" }, { "identifier": "get_tensor_stats_np", "path": "LLM_RL/utils.py", "snippet": "def get_tensor_stats_np(xs: np.ndarray, mask: np.ndarray, n: int):\n \"\"\"get stats about a tensor, used for logging\"\"\"\n mean = (xs * mask).sum() / n\n mask = mask.astype(np.bool_)\n return dict(\n mean=mean, \n min=np.min(xs, where=mask, initial=float('inf')), \n max=np.max(xs, where=mask, initial=float('-inf')), \n std=np.std(xs, where=mask), \n )" }, { "identifier": "double_t_maze_optimal_directions", "path": "llm_rl_scripts/maze/env/mazes.py", "snippet": "def double_t_maze_optimal_directions():\n dct = {\n (1, 1): \"move right\\n\",\n (1, 2): \"move right\\n\",\n (1, 3): \"move down\\n\",\n (1, 4): \"move left\\n\",\n (1, 5): \"move left\\n\",\n (1, 7): \"move right\\n\",\n (1, 8): \"move right\\n\",\n (1, 9): \"move down\\n\",\n (1, 10): \"move left\\n\",\n (1, 11): \"move left\\n\",\n (2, 3): \"move down\\n\",\n (3, 3): \"move down\\n\",\n (4, 3): \"move down\\n\",\n (5, 3): \"move right\\n\",\n (5, 4): \"move right\\n\",\n (5, 5): \"move right\\n\",\n (5, 6): \"move down\\n\",\n (6, 6): \"move down\\n\",\n (7, 6): \"move down\\n\",\n (5, 7): \"move left\\n\",\n (5, 8): \"move left\\n\",\n (5, 9): \"move left\\n\",\n (4, 9): \"move down\\n\",\n (3, 9): \"move down\\n\",\n (2, 9): \"move down\\n\",\n }\n return dct" }, { "identifier": "double_t_maze", "path": "llm_rl_scripts/maze/env/mazes.py", "snippet": "def double_t_maze():\n x = np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], \n [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1], \n [1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1], \n [1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1], \n [1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1], \n [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], \n [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], \n [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], \n [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], \n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=np.uint8)\n \n return x" }, { "identifier": "MazeEnv", "path": "llm_rl_scripts/maze/env/env.py", "snippet": "class MazeEnv(TextEnv):\n def __init__(self, maze: np.ndarray, \n valid_goals: np.ndarray, \n actions: Dict[str, Tuple[int, int]], \n max_steps: Optional[int]=None, \n display_initial_position: bool=False,\n describe_function: Callable[[np.ndarray, Tuple[int, int], Tuple[int, int], Optional[Tuple[int, int]], Optional[List[str]]], str]=describe_observation_give_position,\n reward_function: Callable[[str, Tuple[int, int], Tuple[int, int], Dict[str, Tuple[int, int]]], float]=standard_reward,\n last_k:int=40,\n ):\n assert len(maze.shape) == 2\n assert all([maze[goal[0], goal[1]] == 0 for goal in valid_goals])\n\n self.maze = maze\n self.valid_goals = valid_goals\n self.actions = actions\n self.max_steps = max_steps\n self.display_initial_position = display_initial_position\n self.num_steps = 0\n self.describe_function = describe_function\n self.move_history = []\n self.last_k = last_k\n \n self.reward_function = reward_function\n \n self.random_state = RandomState(None)\n self.reset()\n \n def step(self, text_history: TextHistory) -> Tuple[TextHistory, float, bool]:\n assert text_history[-1].is_action\n # embed()\n if self.max_steps is not None and self.num_steps >= self.max_steps:\n return (Text(\"Failure\\n\", False),), -1.0, True\n \n action = text_history[-1].text \n self.position = update_position(self.maze, self.position, action, self.actions)\n \n self.move_history.append(action.replace('\\n', ''))\n \n reward = self.reward_function(action, self.goal, self.position, self.actions)\n if self.position[0] == self.goal[0] and self.position[1] == self.goal[1]:\n return (Text(\"Success\\n\", False),), reward, True\n \n # move_history = [text_history[i].text for i in range(0, len(text_history), 2) if text_history[i].is_action]\n self.num_steps += 1\n obs_description = self.describe_function(self.maze, self.position, self.goal, self.initial_position, self.move_history)\n if action not in self.actions:\n return (Text(obs_description, False),), reward, False\n\n new_history = list(text_history) + [Text(obs_description, False)]\n new_history = new_history[max(0, len(new_history)-self.last_k):]\n return tuple(new_history), reward, False\n \n def reset(self, seed: Optional[int] = None, options: Optional[Dict] = None) -> TextHistory:\n self.random_state.reset(seed)\n self.num_steps = 0\n\n if options is not None and 'goal' in options:\n self.goal = options['goal']\n else:\n self.goal = random.choice(self.valid_goals).tolist()\n \n positions = np.argwhere(self.maze == 0).tolist()\n positions.remove(self.goal)\n \n if options is not None and 'init_position' in options:\n assert list(options['init_position']) in positions\n self.position = list(options['init_position'])\n else:\n self.position = random.choice(positions)\n \n if self.display_initial_position:\n self.initial_position = self.position.copy()\n else:\n self.initial_position = None\n \n # print('initial position:', self.position)\n obs_description = self.describe_function(self.maze, self.position, self.goal, self.initial_position)\n\n self.random_state.freeze()\n \n return (Text(obs_description, False),)" }, { "identifier": "describe_observation_give_position", "path": "llm_rl_scripts/maze/env/env.py", "snippet": "def describe_observation_give_position(maze:np.ndarray,\n position: Tuple[int, int],\n goal_position: Tuple[int, int],\n initial_position: Tuple[int, int]=None,\n move_history: List[str]=None,\n ) -> str:\n goal_description = f\"The goal is at position {' '.join(str(goal_position[0]))}, {' '.join(str(goal_position[1]))}.\"\n curr_position_description = f\"Your current position is at position {' '.join(str(position[0]))}, {' '.join(str(position[1]))}.\"\n delta_descriptions = {\"to your right\": (0, 1), \"to your left\": (0, -1), \"above you\": (-1, 0), \"below you\": (1, 0)} \n\n walls = []\n for k, (dy, dx) in delta_descriptions.items():\n if maze[position[0]+dy, position[1]+dx] == 1:\n walls.append(k)\n \n wall_description = describe_objects(\"wall\", walls)\n \n return f\"{goal_description} {curr_position_description} {wall_description}\\n\"" }, { "identifier": "maze_proposal_function", "path": "llm_rl_scripts/maze/env/env.py", "snippet": "def maze_proposal_function(text_history: TextHistory) -> List[TextHistory]:\n return [text_history+(Text(action, True),) for action in manhatten_actions.keys()]" }, { "identifier": "ReRankerPolicy", "path": "LLM_RL/algorithms/ppo/reranker_policy.py", "snippet": "class ReRankerPolicy(TextPolicy):\n \n def __init__(self, proposal_fn: Callable[[TextHistory], List[TextHistory]], score_fn: Callable[[List[TextHistory]], List[float]]):\n self.proposal_fn = proposal_fn\n self.score_fn = score_fn\n\n def act(self, text_history: TextHistory) -> TextHistory:\n proposals = self.proposal_fn(text_history)\n scores = self.score_fn(proposals)\n\n return proposals[np.argmax(np.asarray(scores, dtype=np.float32)).item()]" }, { "identifier": "setup_maze_env", "path": "llm_rl_scripts/maze/env/maze_utils.py", "snippet": "def setup_maze_env(maze_name, describe_function, reward_function=None, last_k=1, max_steps=100):\n # setup environment\n if maze_name == 'umaze':\n maze = maze2d_umaze()\n valid_goals = np.array([[3, 3]])\n start_position = (3, 1)\n elif maze_name == \"double_t_maze\":\n maze = double_t_maze()\n valid_goals = np.array([[8, 6]])\n start_position = (1, 1)\n else:\n raise ValueError(f'unknown maze name: {maze_name}')\n \n # valid_goals = np.where(maze == 0)\n # valid_goals = np.array(list(zip(valid_goals[0], valid_goals[1])), dtype=np.int32)\n if describe_function == \"describe_observation\":\n describe_function = describe_observation\n elif describe_function == \"describe_observation_give_position\":\n describe_function = describe_observation_give_position\n elif describe_function == \"describe_observation_only_walls\":\n describe_function = describe_observation_only_walls\n else:\n raise ValueError(f'unknown describe function: {describe_function}')\n \n if reward_function is None or reward_function == \"standard_reward\":\n reward_function = standard_reward\n elif reward_function == \"illegal_penalty_reward\":\n reward_function = illegal_penalty_reward\n elif reward_function == \"illegal_penalty_diff_scale\":\n reward_function = illegal_penalty_diff_scale\n else:\n raise ValueError(f'unknown reward function: {reward_function}')\n \n env = MazeEnv(\n maze=maze, \n valid_goals=valid_goals, \n actions=manhatten_actions, \n max_steps=max_steps, \n display_initial_position=True,\n describe_function=describe_function,\n reward_function=reward_function,\n last_k=last_k,\n )\n return env" }, { "identifier": "pick_start_position", "path": "llm_rl_scripts/maze/env/maze_utils.py", "snippet": "def pick_start_position(maze_name):\n if maze_name == 'umaze':\n return (3, 1)\n elif maze_name == \"double_t_maze\":\n return (1, 1)\n else:\n raise ValueError(f'unknown maze name: {maze_name}')" } ]
from typing import Optional, Dict, Any, Tuple from JaxSeq.bucket_manager import open_with_bucket as open from transformers import AutoTokenizer from JaxSeq.utils import convert_path, load_mesh, get_dtype, setup_experiment_save from JaxSeq.utils import BlockingStrategy, Padding, Truncation, get_weight_decay_mask, create_path, get_enabled_save_path from JaxSeq.models.gpt2.interface import GPT2Inference from JaxSeq.models.gpt2.load import load_train_state, ModelLoadMode from LLM_RL.algorithms.ppo.score_fn import build_ppo_score_fn from LLM_RL.algorithms.ppo.train import train_loop from LLM_RL.algorithms.ppo.base_interface import ppo_loss_fn, FixedKLController, AdaptiveKLController from transformers.generation import GenerationConfig from jaxtyping import PyTree from LLM_RL.environment import Text, TokenHistory, text_env_eval, TextTrajectory, TextTrajectoryChain from LLM_RL.algorithms.ppo.gpt2.interface import GPT2PPOPolicy, GPT2PPOInference, GPT2PPOTrain from LLM_RL.heads.linear_head import load_train_state_from_config as load_head_train_state_from_config from LLM_RL.heads.linear_head import LinearHeadConfig from JaxSeq.shard_model import shard_params_from_params from LLM_RL.algorithms.ppo.data import PPODataset from LLM_RL.utils import get_tensor_stats_np from functools import partial from JaxSeq.logs import label_logs, log, pull_logs from JaxSeq.utils import multihost_device_get from IPython import embed from llm_rl_scripts.maze.env.mazes import double_t_maze_optimal_directions, double_t_maze from JaxSeq.data import MaskDataset from JaxSeq.models.gpt2.interface import loss_fn_mask from llm_rl_scripts.maze.env.env import MazeEnv, describe_observation_give_position, maze_proposal_function from LLM_RL.algorithms.ppo.reranker_policy import ReRankerPolicy from JaxSeq.utils import block_sequences from llm_rl_scripts.maze.env.maze_utils import setup_maze_env, pick_start_position import tyro import jax import jax.numpy as jnp import os import optax import pickle as pkl import re import numpy as np import json
19,344
model_prng_key = jax.random.PRNGKey(2) policy_train_state, policy_model = load_train_state( model_load_mode=model_load_mode, model_load_path=convert_path(model_load_path) if model_load_mode != ModelLoadMode.HF else model_load_path, model_dtype=model_dtype, optim_getter=policy_optim_getter, tokenizer=tokenizer, mesh=mesh, prng_key=model_prng_key, force_pad_embeddings=force_pad_embeddings, params_dtype=params_dtype, ) policy_model.config.gradient_checkpointing = gradient_checkpointing policy_model.config.gradient_checkpointing_policy = gradient_checkpointing_policy with jax.default_device(jax.devices('cpu')[0]): initial_policy_params = jax.tree_util.tree_map( lambda x: multihost_device_get(x, mesh=mesh).copy(), policy_train_state.params, ) initial_policy_params = shard_params_from_params( model=policy_model, params=initial_policy_params, ) loop_state = dict() if should_restore_loop_state and (model_load_mode in {ModelLoadMode.TRAIN_STATE, ModelLoadMode.TRAIN_STATE_PARAMS, ModelLoadMode.PARAMS}): with open(os.path.join(convert_path(model_load_path), 'loop_state.pkl'), 'rb') as f: loop_state = pkl.load(f) policy_inference = GPT2Inference.load_inference( params=policy_train_state.params, model=policy_model, tokenizer=tokenizer, ) policy_prng = jax.random.PRNGKey(0) policy = GPT2PPOPolicy( inference=policy_inference, prng_key=policy_prng, generation_config=GenerationConfig( do_sample=policy_do_sample, num_beams=policy_num_beams, temperature=policy_temperature, top_p=policy_top_p, top_k=policy_top_k, eos_token_id=tokenizer.encode('\n')[0], pad_token_id=tokenizer.pad_token_id, max_new_tokens=max_output_length, ), blocking_strategy=BlockingStrategy( padding=Padding.LEFT, truncation=Truncation.LEFT, max_length=max_input_length, ), out_str_process=lambda x: x.removesuffix('\n')+'\n', ) def value_head_optim_getter(params: PyTree): mask = get_weight_decay_mask(("bias",))(params) return optax.MultiSteps( optax.adamw( learning_rate=lr, b1=0.9, b2=0.95, eps=1e-8, weight_decay=weight_decay, mask=mask, ), every_k_schedule=grad_accum_steps, ) head_prng_key = jax.random.PRNGKey(3) value_head_train_state, value_head = load_head_train_state_from_config( model_config=LinearHeadConfig( input_dim=policy_model.config.n_embd, output_dim=1, use_bias=True, initializer_range=0.0, bias_init=-1, ), model_dtype=jnp.float32, optim_getter=value_head_optim_getter, mesh=mesh, prng_key=head_prng_key, pad_to_output_dim=None, params_dtype=jnp.float32, ) loss_f = partial(ppo_loss_fn, cliprange_value=cliprange_value, cliprange=cliprange, value_loss_coef=value_loss_coef) ppo_inference = GPT2PPOInference.load_inference( initial_policy_params=initial_policy_params, policy_params=policy_train_state.params, value_head_params=value_head_train_state.params, initial_policy_model=policy_model, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, bc_loss_fn=loss_fn_mask if bc_data is not None else None, bc_loss_weight=bc_loss_weight if bc_data is not None else 0.0, ) ppo_trainer = GPT2PPOTrain.load_train( policy_train_state=policy_train_state, value_head_train_state=value_head_train_state, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, bc_loss_fn=loss_fn_mask if bc_data is not None else None, bc_loss_weight=bc_loss_weight if bc_data is not None else 0.0, ) if use_adaptive_kl: kl_controller = AdaptiveKLController(init_kl_coef=init_kl_coef, target=kl_target, horizon=kl_horizon) else:
# from LLM_RL.gpt2 import load_gpt2_from_pretrained def main( model_load_mode: ModelLoadMode, model_load_path: str, /, # Mark the end of positional arguments. bc_data_path: Optional[str]=None, train_bc_bsize: int=8, bc_loss_weight:int=0, model_str:str="gpt2", exp_name: Optional[str]=None, outputs_path: Optional[str]=None, maze_name: str="double_t_maze", data_mesh_shape: int=1, fsdp_mesh_shape: int=1, model_mesh_shape: int=-1, use_wandb: bool=False, wandb_project: Optional[str]=None, n_rounds: int=1, epochs: int=1, max_steps: Optional[int]=None, lr: float=1e-5, weight_decay: float=0.0, train_bsize: int=32, grad_accum_steps: int=1, rollout_bsize: int=32, n_rollouts: int=128, ppo_data_bsize: int=32, num_pos_per_setup: int=4, gradient_checkpointing: bool=False, gradient_checkpointing_policy: str='nothing_saveable', use_fp16_activations: bool=False, use_fp16_params: bool=False, max_input_length: int=64, max_output_length: int=32, log_every: int=256, eval_every_steps: Optional[int]=None, eval_every_epochs: Optional[int]=None, eval_every_rounds: Optional[int]=1, eval_at_beginning: bool=True, eval_at_end: bool=True, save_every_steps: Optional[int]=None, save_every_epochs: Optional[int]=None, save_every_rounds: Optional[int]=10, save_at_beginning: bool=False, save_at_end: bool=True, save_best: bool=True, max_checkpoints: Optional[int]=20, save_train_state: bool=True, save_ppo_dataset: bool=True, save_bf16: bool=True, policy_do_sample: bool=True, policy_num_beams: int=1, policy_temperature: Optional[float]=None, policy_top_p: Optional[float]=None, policy_top_k: Optional[int]=None, gamma: float=0.99, lam: float=0.95, use_advantage_whitening: bool=True, init_kl_coef: float=0.001, kl_target: Optional[float]=None, kl_horizon: Optional[int]=None, cliprange_value: float=0.2, cliprange: float=0.2, value_loss_coef: float=0.5, force_pad_embeddings: bool=False, should_restore_loop_state: bool=False, describe_function: str= "describe_observation", reranker_policy: bool=False, reward_function: str="standard_reward", ): input_args = locals().copy() print(input_args) use_adaptive_kl = (kl_target is not None and kl_horizon is not None) if not use_adaptive_kl: assert kl_target is None and kl_horizon is None tokenizer = AutoTokenizer.from_pretrained('gpt2') tokenizer.add_special_tokens({'pad_token': '<|pad|>'}) if bc_data_path is not None: with open(bc_data_path, 'rb') as f: text_histories = pkl.load(f) blocking_strategy = BlockingStrategy(Padding.RIGHT, Truncation.RIGHT, max_input_length+max_output_length) # in_tokens = list(map(lambda x: block_sequences([x.tokens], tokenizer.pad_token_id, dtype=np.int32, blocking_strategy=BlockingStrategy(Padding.RIGHT, Truncation.RIGHT, max_input_length))[0], text_histories)) # text_histories = list(map(lambda x: x.text_history, text_trajectories)) # no this doesn't work because we also need to pad the is_actions token_histories = list(map(lambda x: TokenHistory.from_text_history(x, tokenizer), text_histories)) in_tokens = list(map(lambda x: block_sequences([x.tokens], tokenizer.pad_token_id, dtype=np.int32, blocking_strategy=blocking_strategy)[0], token_histories)) is_actions = list(map(lambda x: block_sequences([x.is_action], 0.0, dtype=np.float32, blocking_strategy=blocking_strategy)[0], token_histories)) # tokens = list(map(lambda x: token_process(x.tokens), token_histories)) # is_actions = list(map(lambda x: x.is_action, token_histories)) bc_data = MaskDataset( in_tokens = jnp.array(in_tokens), in_training_mask = jnp.array(is_actions), ) else: bc_data = None mesh = load_mesh((data_mesh_shape, fsdp_mesh_shape, model_mesh_shape), ('dp', 'fsdp', 'mp')) is_main_process = jax.process_index() == 0 print(f"Mesh: {mesh}") print(f"Is main process: {is_main_process}") def policy_optim_getter(params: PyTree): mask = get_weight_decay_mask(( "".join([r"\['ln_[0-9]+'\]", re.escape("['bias']")]), "".join([r"\['ln_[0-9]+'\]", re.escape("['scale']")]), re.escape("['ln_f']['bias']"), re.escape("['ln_f']['scale']"), "bias", ))(params) return optax.MultiSteps( optax.adamw( learning_rate=lr, b1=0.9, b2=0.95, eps=1e-8, weight_decay=weight_decay, mask=mask, ), every_k_schedule=grad_accum_steps, ) model_dtype = get_dtype(use_fp16=use_fp16_activations) params_dtype = get_dtype(use_fp16=use_fp16_params) model_prng_key = jax.random.PRNGKey(2) policy_train_state, policy_model = load_train_state( model_load_mode=model_load_mode, model_load_path=convert_path(model_load_path) if model_load_mode != ModelLoadMode.HF else model_load_path, model_dtype=model_dtype, optim_getter=policy_optim_getter, tokenizer=tokenizer, mesh=mesh, prng_key=model_prng_key, force_pad_embeddings=force_pad_embeddings, params_dtype=params_dtype, ) policy_model.config.gradient_checkpointing = gradient_checkpointing policy_model.config.gradient_checkpointing_policy = gradient_checkpointing_policy with jax.default_device(jax.devices('cpu')[0]): initial_policy_params = jax.tree_util.tree_map( lambda x: multihost_device_get(x, mesh=mesh).copy(), policy_train_state.params, ) initial_policy_params = shard_params_from_params( model=policy_model, params=initial_policy_params, ) loop_state = dict() if should_restore_loop_state and (model_load_mode in {ModelLoadMode.TRAIN_STATE, ModelLoadMode.TRAIN_STATE_PARAMS, ModelLoadMode.PARAMS}): with open(os.path.join(convert_path(model_load_path), 'loop_state.pkl'), 'rb') as f: loop_state = pkl.load(f) policy_inference = GPT2Inference.load_inference( params=policy_train_state.params, model=policy_model, tokenizer=tokenizer, ) policy_prng = jax.random.PRNGKey(0) policy = GPT2PPOPolicy( inference=policy_inference, prng_key=policy_prng, generation_config=GenerationConfig( do_sample=policy_do_sample, num_beams=policy_num_beams, temperature=policy_temperature, top_p=policy_top_p, top_k=policy_top_k, eos_token_id=tokenizer.encode('\n')[0], pad_token_id=tokenizer.pad_token_id, max_new_tokens=max_output_length, ), blocking_strategy=BlockingStrategy( padding=Padding.LEFT, truncation=Truncation.LEFT, max_length=max_input_length, ), out_str_process=lambda x: x.removesuffix('\n')+'\n', ) def value_head_optim_getter(params: PyTree): mask = get_weight_decay_mask(("bias",))(params) return optax.MultiSteps( optax.adamw( learning_rate=lr, b1=0.9, b2=0.95, eps=1e-8, weight_decay=weight_decay, mask=mask, ), every_k_schedule=grad_accum_steps, ) head_prng_key = jax.random.PRNGKey(3) value_head_train_state, value_head = load_head_train_state_from_config( model_config=LinearHeadConfig( input_dim=policy_model.config.n_embd, output_dim=1, use_bias=True, initializer_range=0.0, bias_init=-1, ), model_dtype=jnp.float32, optim_getter=value_head_optim_getter, mesh=mesh, prng_key=head_prng_key, pad_to_output_dim=None, params_dtype=jnp.float32, ) loss_f = partial(ppo_loss_fn, cliprange_value=cliprange_value, cliprange=cliprange, value_loss_coef=value_loss_coef) ppo_inference = GPT2PPOInference.load_inference( initial_policy_params=initial_policy_params, policy_params=policy_train_state.params, value_head_params=value_head_train_state.params, initial_policy_model=policy_model, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, bc_loss_fn=loss_fn_mask if bc_data is not None else None, bc_loss_weight=bc_loss_weight if bc_data is not None else 0.0, ) ppo_trainer = GPT2PPOTrain.load_train( policy_train_state=policy_train_state, value_head_train_state=value_head_train_state, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, bc_loss_fn=loss_fn_mask if bc_data is not None else None, bc_loss_weight=bc_loss_weight if bc_data is not None else 0.0, ) if use_adaptive_kl: kl_controller = AdaptiveKLController(init_kl_coef=init_kl_coef, target=kl_target, horizon=kl_horizon) else:
kl_controller = FixedKLController(kl_coef=init_kl_coef)
3
2023-11-21 00:16:42+00:00
24k
jzmzhong/Automatic-Prosody-Annotator-with-SSWP-CLAP
src/clap_module/conformer/encoder.py
[ { "identifier": "ConvolutionModule", "path": "src/clap_module/conformer/convolution.py", "snippet": "class ConvolutionModule(nn.Module):\r\n \"\"\"ConvolutionModule in Conformer model.\r\n\r\n Args:\r\n channels (int): The number of channels of conv layers.\r\n kernel_size (int): Kernerl size of conv layers.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, channels, kernel_size, activation=nn.ReLU(), bias=True):\r\n \"\"\"Construct an ConvolutionModule object.\r\n \"\"\"\r\n super(ConvolutionModule, self).__init__()\r\n # kernerl_size should be a odd number for 'SAME' padding\r\n assert (kernel_size - 1) % 2 == 0\r\n\r\n self.pointwise_conv1 = nn.Conv1d(\r\n channels,\r\n 2 * channels,\r\n kernel_size=1,\r\n stride=1,\r\n padding=0,\r\n bias=bias,\r\n )\r\n self.depthwise_conv = nn.Conv1d(\r\n channels,\r\n channels,\r\n kernel_size,\r\n stride=1,\r\n padding=(kernel_size - 1) // 2,\r\n groups=channels,\r\n bias=bias,\r\n )\r\n self.norm = nn.BatchNorm1d(channels)\r\n self.pointwise_conv2 = nn.Conv1d(\r\n channels,\r\n channels,\r\n kernel_size=1,\r\n stride=1,\r\n padding=0,\r\n bias=bias,\r\n )\r\n self.activation = activation\r\n\r\n def forward(self, x):\r\n \"\"\"Compute convolution module.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (#batch, time, channels).\r\n\r\n Returns:\r\n torch.Tensor: Output tensor (#batch, time, channels).\r\n\r\n \"\"\"\r\n # exchange the temporal dimension and the feature dimension\r\n x = x.transpose(1, 2)\r\n\r\n # GLU mechanism\r\n x = self.pointwise_conv1(x) # (batch, 2*channel, dim)\r\n x = nn.functional.glu(x, dim=1) # (batch, channel, dim)\r\n\r\n # 1D Depthwise Conv\r\n x = self.depthwise_conv(x)\r\n x = self.activation(self.norm(x))\r\n\r\n x = self.pointwise_conv2(x)\r\n\r\n return x.transpose(1, 2)\r" }, { "identifier": "EncoderLayer", "path": "src/clap_module/conformer/encoder_layer.py", "snippet": "class EncoderLayer(nn.Module):\r\n \"\"\"Encoder layer module.\r\n\r\n Args:\r\n size (int): Input dimension.\r\n self_attn (torch.nn.Module): Self-attention module instance.\r\n `MultiHeadedAttention` or `RelPositionMultiHeadedAttention` instance\r\n can be used as the argument.\r\n feed_forward (torch.nn.Module): Feed-forward module instance.\r\n `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear` instance\r\n can be used as the argument.\r\n feed_forward_macaron (torch.nn.Module): Additional feed-forward module instance.\r\n `PositionwiseFeedForward`, `MultiLayeredConv1d`, or `Conv1dLinear` instance\r\n can be used as the argument.\r\n conv_module (torch.nn.Module): Convolution module instance.\r\n `ConvlutionModule` instance can be used as the argument.\r\n dropout_rate (float): Dropout rate.\r\n normalize_before (bool): Whether to use layer_norm before the first block.\r\n concat_after (bool): Whether to concat attention layer's input and output.\r\n if True, additional linear will be applied.\r\n i.e. x -> x + linear(concat(x, att(x)))\r\n if False, no additional linear will be applied. i.e. x -> x + att(x)\r\n stochastic_depth_rate (float): Proability to skip this layer.\r\n During training, the layer may skip residual computation and return input\r\n as-is with given probability.\r\n\r\n \"\"\"\r\n\r\n def __init__(\r\n self,\r\n size,\r\n self_attn,\r\n feed_forward,\r\n feed_forward_macaron,\r\n conv_module,\r\n dropout_rate,\r\n normalize_before=True,\r\n concat_after=False,\r\n stochastic_depth_rate=0.0,\r\n ):\r\n \"\"\"Construct an EncoderLayer object.\"\"\"\r\n super(EncoderLayer, self).__init__()\r\n self.self_attn = self_attn\r\n self.feed_forward = feed_forward\r\n self.feed_forward_macaron = feed_forward_macaron\r\n self.conv_module = conv_module\r\n self.norm_ff = LayerNorm(size) # for the FNN module\r\n self.norm_mha = LayerNorm(size) # for the MHA module\r\n if feed_forward_macaron is not None:\r\n self.norm_ff_macaron = LayerNorm(size)\r\n self.ff_scale = 0.5\r\n else:\r\n self.ff_scale = 1.0\r\n if self.conv_module is not None:\r\n self.norm_conv = LayerNorm(size) # for the CNN module\r\n self.norm_final = LayerNorm(size) # for the final output of the block\r\n self.dropout = nn.Dropout(dropout_rate)\r\n self.size = size\r\n self.normalize_before = normalize_before\r\n self.concat_after = concat_after\r\n if self.concat_after:\r\n self.concat_linear = nn.Linear(size + size, size)\r\n self.stochastic_depth_rate = stochastic_depth_rate\r\n\r\n def forward(self, x_input, mask, cache=None):\r\n \"\"\"Compute encoded features.\r\n\r\n Args:\r\n x_input (Union[Tuple, torch.Tensor]): Input tensor w/ or w/o pos emb.\r\n - w/ pos emb: Tuple of tensors [(#batch, time, size), (1, time, size)].\r\n - w/o pos emb: Tensor (#batch, time, size).\r\n mask (torch.Tensor): Mask tensor for the input (#batch, 1, time).\r\n cache (torch.Tensor): Cache tensor of the input (#batch, time - 1, size).\r\n\r\n Returns:\r\n torch.Tensor: Output tensor (#batch, time, size).\r\n torch.Tensor: Mask tensor (#batch, 1, time).\r\n\r\n \"\"\"\r\n if isinstance(x_input, tuple):\r\n x, pos_emb = x_input[0], x_input[1]\r\n else:\r\n x, pos_emb = x_input, None\r\n\r\n skip_layer = False\r\n # with stochastic depth, residual connection `x + f(x)` becomes\r\n # `x <- x + 1 / (1 - p) * f(x)` at training time.\r\n stoch_layer_coeff = 1.0\r\n if self.training and self.stochastic_depth_rate > 0:\r\n skip_layer = torch.rand(1).item() < self.stochastic_depth_rate\r\n stoch_layer_coeff = 1.0 / (1 - self.stochastic_depth_rate)\r\n\r\n if skip_layer:\r\n if cache is not None:\r\n x = torch.cat([cache, x], dim=1)\r\n if pos_emb is not None:\r\n return (x, pos_emb), mask\r\n return x, mask\r\n\r\n # whether to use macaron style\r\n if self.feed_forward_macaron is not None:\r\n residual = x\r\n if self.normalize_before:\r\n x = self.norm_ff_macaron(x)\r\n x = residual + stoch_layer_coeff * self.ff_scale * self.dropout(\r\n self.feed_forward_macaron(x)\r\n )\r\n if not self.normalize_before:\r\n x = self.norm_ff_macaron(x)\r\n\r\n # convolution module\r\n \"\"\"\r\n if self.conv_module is not None:\r\n residual = x\r\n if self.normalize_before:\r\n x = self.norm_conv(x)\r\n x = residual + stoch_layer_coeff * self.dropout(self.conv_module(x))\r\n if not self.normalize_before:\r\n x = self.norm_conv(x)\r\n \"\"\"\r\n\r\n # multi-headed self-attention module\r\n residual = x\r\n if self.normalize_before:\r\n x = self.norm_mha(x)\r\n\r\n if cache is None:\r\n x_q = x\r\n else:\r\n assert cache.shape == (x.shape[0], x.shape[1] - 1, self.size)\r\n x_q = x[:, -1:, :]\r\n residual = residual[:, -1:, :]\r\n mask = None if mask is None else mask[:, -1:, :]\r\n\r\n if pos_emb is not None:\r\n x_att = self.self_attn(x_q, x, x, pos_emb, mask)\r\n else:\r\n x_att = self.self_attn(x_q, x, x, mask)\r\n\r\n if self.concat_after:\r\n x_concat = torch.cat((x, x_att), dim=-1)\r\n x = residual + stoch_layer_coeff * self.concat_linear(x_concat)\r\n else:\r\n x = residual + stoch_layer_coeff * self.dropout(x_att)\r\n if not self.normalize_before:\r\n x = self.norm_mha(x)\r\n\r\n # convolution module\r\n if self.conv_module is not None:\r\n residual = x\r\n if self.normalize_before:\r\n x = self.norm_conv(x)\r\n x = residual + stoch_layer_coeff * self.dropout(self.conv_module(x))\r\n if not self.normalize_before:\r\n x = self.norm_conv(x)\r\n\r\n # feed forward module\r\n if self.feed_forward:\r\n residual = x\r\n if self.normalize_before:\r\n x = self.norm_ff(x)\r\n x = residual + stoch_layer_coeff * self.ff_scale * self.dropout(\r\n self.feed_forward(x)\r\n )\r\n if not self.normalize_before:\r\n x = self.norm_ff(x)\r\n else:\r\n raise ValueError(\"not exit\")\r\n\r\n if self.conv_module is not None:\r\n x = self.norm_final(x)\r\n\r\n if cache is not None:\r\n x = torch.cat([cache, x], dim=1)\r\n\r\n if pos_emb is not None:\r\n return (x, pos_emb), mask\r\n\r\n return x, mask\r" }, { "identifier": "get_activation", "path": "src/clap_module/conformer/modules.py", "snippet": "def get_activation(act):\r\n \"\"\"Return activation function.\r\n \"\"\"\r\n # Lazy load to avoid unused import\r\n\r\n activation_funcs = {\r\n \"hardtanh\": torch.nn.Hardtanh,\r\n \"tanh\": torch.nn.Tanh,\r\n \"relu\": torch.nn.ReLU,\r\n \"selu\": torch.nn.SELU,\r\n \"swish\": Swish,\r\n }\r\n\r\n return activation_funcs[act]()\r" }, { "identifier": "VGG2L", "path": "src/clap_module/conformer/modules.py", "snippet": "class VGG2L(torch.nn.Module):\r\n \"\"\"VGG2L module for custom encoder.\r\n\r\n Args:\r\n idim: Input dimension.\r\n odim: Output dimension.\r\n pos_enc: Positional encoding class.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, idim: int, odim: int, pos_enc: torch.nn.Module = None):\r\n \"\"\"Construct a VGG2L object.\"\"\"\r\n super().__init__()\r\n\r\n self.vgg2l = torch.nn.Sequential(\r\n torch.nn.Conv2d(1, 64, 3, stride=1, padding=1),\r\n torch.nn.ReLU(),\r\n torch.nn.Conv2d(64, 64, 3, stride=1, padding=1),\r\n torch.nn.ReLU(),\r\n torch.nn.MaxPool2d((3, 2)),\r\n torch.nn.Conv2d(64, 128, 3, stride=1, padding=1),\r\n torch.nn.ReLU(),\r\n torch.nn.Conv2d(128, 128, 3, stride=1, padding=1),\r\n torch.nn.ReLU(),\r\n torch.nn.MaxPool2d((2, 2)),\r\n )\r\n\r\n if pos_enc is not None:\r\n self.output = torch.nn.Sequential(\r\n torch.nn.Linear(128 * ((idim // 2) // 2), odim), pos_enc\r\n )\r\n else:\r\n self.output = torch.nn.Linear(128 * ((idim // 2) // 2), odim)\r\n\r\n def forward(\r\n self, feats: torch.Tensor, feats_mask: torch.Tensor\r\n ) -> Union[\r\n Tuple[torch.Tensor, torch.Tensor],\r\n Tuple[Tuple[torch.Tensor, torch.Tensor], torch.Tensor],\r\n ]:\r\n \"\"\"Forward VGG2L bottleneck.\r\n\r\n Args:\r\n feats: Feature sequences. (B, F, D_feats)\r\n feats_mask: Mask of feature sequences. (B, 1, F)\r\n\r\n Returns:\r\n vgg_output: VGG output sequences.\r\n (B, sub(F), D_out) or ((B, sub(F), D_out), (B, sub(F), D_att))\r\n vgg_mask: Mask of VGG output sequences. (B, 1, sub(F))\r\n\r\n \"\"\"\r\n feats = feats.unsqueeze(1)\r\n vgg_output = self.vgg2l(feats)\r\n\r\n b, c, t, f = vgg_output.size()\r\n\r\n vgg_output = self.output(\r\n vgg_output.transpose(1, 2).contiguous().view(b, t, c * f)\r\n )\r\n\r\n if feats_mask is not None:\r\n vgg_mask = self.create_new_mask(feats_mask)\r\n else:\r\n vgg_mask = feats_mask\r\n\r\n return vgg_output, vgg_mask\r\n\r\n def create_new_mask(self, feats_mask: torch.Tensor) -> torch.Tensor:\r\n \"\"\"Create a subsampled mask of feature sequences.\r\n\r\n Args:\r\n feats_mask: Mask of feature sequences. (B, 1, F)\r\n\r\n Returns:\r\n vgg_mask: Mask of VGG2L output sequences. (B, 1, sub(F))\r\n\r\n \"\"\"\r\n vgg1_t_len = feats_mask.size(2) - (feats_mask.size(2) % 3)\r\n vgg_mask = feats_mask[:, :, :vgg1_t_len][:, :, ::3]\r\n\r\n vgg2_t_len = vgg_mask.size(2) - (vgg_mask.size(2) % 2)\r\n vgg_mask = vgg_mask[:, :, :vgg2_t_len][:, :, ::2]\r\n\r\n return vgg_mask\r" }, { "identifier": "LegacyRelPositionMultiHeadedAttention", "path": "src/clap_module/conformer/modules.py", "snippet": "class LegacyRelPositionMultiHeadedAttention(MultiHeadedAttention):\r\n \"\"\"Multi-Head Attention layer with relative position encoding (old version).\r\n\r\n Details can be found in https://github.com/espnet/espnet/pull/2816.\r\n\r\n Paper: https://arxiv.org/abs/1901.02860\r\n\r\n Args:\r\n n_head (int): The number of heads.\r\n n_feat (int): The number of features.\r\n dropout_rate (float): Dropout rate.\r\n zero_triu (bool): Whether to zero the upper triangular part of attention matrix.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False):\r\n \"\"\"Construct an RelPositionMultiHeadedAttention object.\"\"\"\r\n super().__init__(n_head, n_feat, dropout_rate)\r\n self.zero_triu = zero_triu\r\n # linear transformation for positional encoding\r\n self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\r\n # these two learnable bias are used in matrix c and matrix d\r\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\r\n self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\r\n self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\r\n torch.nn.init.xavier_uniform_(self.pos_bias_u)\r\n torch.nn.init.xavier_uniform_(self.pos_bias_v)\r\n\r\n def rel_shift(self, x):\r\n \"\"\"Compute relative positional encoding.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (batch, head, time1, time2).\r\n\r\n Returns:\r\n torch.Tensor: Output tensor.\r\n\r\n \"\"\"\r\n zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype)\r\n x_padded = torch.cat([zero_pad, x], dim=-1)\r\n\r\n x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2))\r\n x = x_padded[:, :, 1:].view_as(x)\r\n\r\n if self.zero_triu:\r\n ones = torch.ones((x.size(2), x.size(3)))\r\n x = x * torch.tril(ones, x.size(3) - x.size(2))[None, None, :, :]\r\n\r\n return x\r\n\r\n def forward(self, query, key, value, pos_emb, mask):\r\n \"\"\"Compute 'Scaled Dot Product Attention' with rel. positional encoding.\r\n\r\n Args:\r\n query (torch.Tensor): Query tensor (#batch, time1, size).\r\n key (torch.Tensor): Key tensor (#batch, time2, size).\r\n value (torch.Tensor): Value tensor (#batch, time2, size).\r\n pos_emb (torch.Tensor): Positional embedding tensor (#batch, time1, size).\r\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\r\n (#batch, time1, time2).\r\n\r\n Returns:\r\n torch.Tensor: Output tensor (#batch, time1, d_model).\r\n\r\n \"\"\"\r\n q, k, v = self.forward_qkv(query, key, value)\r\n q = q.transpose(1, 2) # (batch, time1, head, d_k)\r\n\r\n n_batch_pos = pos_emb.size(0)\r\n p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)\r\n p = p.transpose(1, 2) # (batch, head, time1, d_k)\r\n\r\n # (batch, head, time1, d_k)\r\n q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)\r\n # (batch, head, time1, d_k)\r\n q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)\r\n\r\n # compute attention score\r\n # first compute matrix a and matrix c\r\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\r\n # (batch, head, time1, time2)\r\n matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))\r\n\r\n # compute matrix b and matrix d\r\n # (batch, head, time1, time1)\r\n matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))\r\n matrix_bd = self.rel_shift(matrix_bd)\r\n\r\n scores = (matrix_ac + matrix_bd) / math.sqrt(\r\n self.d_k\r\n ) # (batch, head, time1, time2)\r\n\r\n return self.forward_attention(v, scores, mask)\r" }, { "identifier": "MultiHeadedAttention", "path": "src/clap_module/conformer/modules.py", "snippet": "class MultiHeadedAttention(nn.Module):\r\n \"\"\"Multi-Head Attention layer.\r\n\r\n Args:\r\n n_head (int): The number of heads.\r\n n_feat (int): The number of features.\r\n dropout_rate (float): Dropout rate.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, n_head, n_feat, dropout_rate):\r\n \"\"\"Construct an MultiHeadedAttention object.\"\"\"\r\n super(MultiHeadedAttention, self).__init__()\r\n assert n_feat % n_head == 0\r\n # We assume d_v always equals d_k\r\n self.d_k = n_feat // n_head\r\n self.h = n_head\r\n self.linear_q = nn.Linear(n_feat, n_feat)\r\n self.linear_k = nn.Linear(n_feat, n_feat)\r\n self.linear_v = nn.Linear(n_feat, n_feat)\r\n self.linear_out = nn.Linear(n_feat, n_feat)\r\n self.attn = None\r\n self.dropout = nn.Dropout(p=dropout_rate)\r\n\r\n def forward_qkv(self, query, key, value):\r\n \"\"\"Transform query, key and value.\r\n\r\n Args:\r\n query (torch.Tensor): Query tensor (#batch, time1, size).\r\n key (torch.Tensor): Key tensor (#batch, time2, size).\r\n value (torch.Tensor): Value tensor (#batch, time2, size).\r\n\r\n Returns:\r\n torch.Tensor: Transformed query tensor (#batch, n_head, time1, d_k).\r\n torch.Tensor: Transformed key tensor (#batch, n_head, time2, d_k).\r\n torch.Tensor: Transformed value tensor (#batch, n_head, time2, d_k).\r\n\r\n \"\"\"\r\n n_batch = query.size(0)\r\n q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)\r\n k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)\r\n v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)\r\n q = q.transpose(1, 2) # (batch, head, time1, d_k)\r\n k = k.transpose(1, 2) # (batch, head, time2, d_k)\r\n v = v.transpose(1, 2) # (batch, head, time2, d_k)\r\n\r\n return q, k, v\r\n\r\n def forward_attention(self, value, scores, mask):\r\n \"\"\"Compute attention context vector.\r\n\r\n Args:\r\n value (torch.Tensor): Transformed value (#batch, n_head, time2, d_k).\r\n scores (torch.Tensor): Attention score (#batch, n_head, time1, time2).\r\n mask (torch.Tensor): Mask (#batch, 1, time2) or (#batch, time1, time2).\r\n\r\n Returns:\r\n torch.Tensor: Transformed value (#batch, time1, d_model)\r\n weighted by the attention score (#batch, time1, time2).\r\n\r\n \"\"\"\r\n n_batch = value.size(0)\r\n if mask is not None:\r\n mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2)\r\n min_value = torch.finfo(scores.dtype).min\r\n scores = scores.masked_fill(mask, min_value)\r\n self.attn = torch.softmax(scores, dim=-1).masked_fill(\r\n mask, 0.0\r\n ) # (batch, head, time1, time2)\r\n else:\r\n self.attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)\r\n\r\n p_attn = self.dropout(self.attn)\r\n x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)\r\n x = (\r\n x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k)\r\n ) # (batch, time1, d_model)\r\n\r\n return self.linear_out(x) # (batch, time1, d_model)\r\n\r\n def forward(self, query, key, value, mask):\r\n \"\"\"Compute scaled dot product attention.\r\n\r\n Args:\r\n query (torch.Tensor): Query tensor (#batch, time1, size).\r\n key (torch.Tensor): Key tensor (#batch, time2, size).\r\n value (torch.Tensor): Value tensor (#batch, time2, size).\r\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\r\n (#batch, time1, time2).\r\n\r\n Returns:\r\n torch.Tensor: Output tensor (#batch, time1, d_model).\r\n\r\n \"\"\"\r\n q, k, v = self.forward_qkv(query, key, value)\r\n scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)\r\n return self.forward_attention(v, scores, mask)\r" }, { "identifier": "RelPositionMultiHeadedAttention", "path": "src/clap_module/conformer/modules.py", "snippet": "class RelPositionMultiHeadedAttention(MultiHeadedAttention):\r\n \"\"\"Multi-Head Attention layer with relative position encoding (new implementation).\r\n\r\n Details can be found in https://github.com/espnet/espnet/pull/2816.\r\n\r\n Paper: https://arxiv.org/abs/1901.02860\r\n\r\n Args:\r\n n_head (int): The number of heads.\r\n n_feat (int): The number of features.\r\n dropout_rate (float): Dropout rate.\r\n zero_triu (bool): Whether to zero the upper triangular part of attention matrix.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False):\r\n \"\"\"Construct an RelPositionMultiHeadedAttention object.\"\"\"\r\n super().__init__(n_head, n_feat, dropout_rate)\r\n self.zero_triu = zero_triu\r\n # linear transformation for positional encoding\r\n self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\r\n # these two learnable bias are used in matrix c and matrix d\r\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\r\n self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\r\n self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\r\n torch.nn.init.xavier_uniform_(self.pos_bias_u)\r\n torch.nn.init.xavier_uniform_(self.pos_bias_v)\r\n\r\n def rel_shift(self, x):\r\n \"\"\"Compute relative positional encoding.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1).\r\n time1 means the length of query vector.\r\n\r\n Returns:\r\n torch.Tensor: Output tensor.\r\n\r\n \"\"\"\r\n zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype)\r\n x_padded = torch.cat([zero_pad, x], dim=-1)\r\n\r\n x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2))\r\n x = x_padded[:, :, 1:].view_as(x)[\r\n :, :, :, : x.size(-1) // 2 + 1\r\n ] # only keep the positions from 0 to time2\r\n\r\n if self.zero_triu:\r\n ones = torch.ones((x.size(2), x.size(3)), device=x.device)\r\n x = x * torch.tril(ones, x.size(3) - x.size(2))[None, None, :, :]\r\n\r\n return x\r\n\r\n def forward(self, query, key, value, pos_emb, mask):\r\n \"\"\"Compute 'Scaled Dot Product Attention' with rel. positional encoding.\r\n\r\n Args:\r\n query (torch.Tensor): Query tensor (#batch, time1, size).\r\n key (torch.Tensor): Key tensor (#batch, time2, size).\r\n value (torch.Tensor): Value tensor (#batch, time2, size).\r\n pos_emb (torch.Tensor): Positional embedding tensor\r\n (#batch, 2*time1-1, size).\r\n mask (torch.Tensor): Mask tensor (#batch, 1, time2) or\r\n (#batch, time1, time2).\r\n\r\n Returns:\r\n torch.Tensor: Output tensor (#batch, time1, d_model).\r\n\r\n \"\"\"\r\n q, k, v = self.forward_qkv(query, key, value)\r\n q = q.transpose(1, 2) # (batch, time1, head, d_k)\r\n\r\n n_batch_pos = pos_emb.size(0)\r\n p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)\r\n p = p.transpose(1, 2) # (batch, head, 2*time1-1, d_k)\r\n\r\n # (batch, head, time1, d_k)\r\n q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)\r\n # (batch, head, time1, d_k)\r\n q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)\r\n\r\n # compute attention score\r\n # first compute matrix a and matrix c\r\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\r\n # (batch, head, time1, time2)\r\n matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))\r\n\r\n # compute matrix b and matrix d\r\n # (batch, head, time1, 2*time1-1)\r\n matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))\r\n matrix_bd = self.rel_shift(matrix_bd)\r\n\r\n scores = (matrix_ac + matrix_bd) / math.sqrt(\r\n self.d_k\r\n ) # (batch, head, time1, time2)\r\n\r\n return self.forward_attention(v, scores, mask)\r" }, { "identifier": "LegacyRelPositionalEncoding", "path": "src/clap_module/conformer/embedding.py", "snippet": "class LegacyRelPositionalEncoding(PositionalEncoding):\r\n \"\"\"Relative positional encoding module (old version).\r\n\r\n Details can be found in https://github.com/espnet/espnet/pull/2816.\r\n\r\n See : Appendix B in https://arxiv.org/abs/1901.02860\r\n\r\n Args:\r\n d_model (int): Embedding dimension.\r\n dropout_rate (float): Dropout rate.\r\n max_len (int): Maximum input length.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, d_model, dropout_rate, max_len=5000):\r\n \"\"\"Initialize class.\"\"\"\r\n super().__init__(\r\n d_model=d_model,\r\n dropout_rate=dropout_rate,\r\n max_len=max_len,\r\n reverse=True,\r\n )\r\n\r\n def forward(self, x):\r\n \"\"\"Compute positional encoding.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (batch, time, `*`).\r\n\r\n Returns:\r\n torch.Tensor: Encoded tensor (batch, time, `*`).\r\n torch.Tensor: Positional embedding tensor (1, time, `*`).\r\n\r\n \"\"\"\r\n self.extend_pe(x)\r\n x = x * self.xscale\r\n pos_emb = self.pe[:, : x.size(1)]\r\n return self.dropout(x), self.dropout(pos_emb)\r" }, { "identifier": "PositionalEncoding", "path": "src/clap_module/conformer/embedding.py", "snippet": "class PositionalEncoding(torch.nn.Module):\r\n \"\"\"Positional encoding.\r\n\r\n Args:\r\n d_model (int): Embedding dimension.\r\n dropout_rate (float): Dropout rate.\r\n max_len (int): Maximum input length.\r\n reverse (bool): Whether to reverse the input position. Only for\r\n the class LegacyRelPositionalEncoding. We remove it in the current\r\n class RelPositionalEncoding.\r\n \"\"\"\r\n\r\n def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):\r\n \"\"\"Construct an PositionalEncoding object.\r\n \"\"\"\r\n super(PositionalEncoding, self).__init__()\r\n self.d_model = d_model\r\n self.reverse = reverse\r\n self.xscale = math.sqrt(self.d_model)\r\n self.dropout = torch.nn.Dropout(p=dropout_rate)\r\n self.pe = None\r\n self.extend_pe(torch.tensor(0.0).expand(1, max_len))\r\n self._register_load_state_dict_pre_hook(_pre_hook)\r\n\r\n def extend_pe(self, x):\r\n \"\"\"Reset the positional encodings.\r\n \"\"\"\r\n if self.pe is not None:\r\n if self.pe.size(1) >= x.size(1):\r\n if self.pe.dtype != x.dtype or self.pe.device != x.device:\r\n self.pe = self.pe.to(dtype=x.dtype, device=x.device)\r\n return\r\n pe = torch.zeros(x.size(1), self.d_model)\r\n if self.reverse:\r\n position = torch.arange(\r\n x.size(1) - 1, -1, -1.0, dtype=torch.float32\r\n ).unsqueeze(1)\r\n else:\r\n position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)\r\n div_term = torch.exp(\r\n torch.arange(0, self.d_model, 2, dtype=torch.float32)\r\n * -(math.log(10000.0) / self.d_model)\r\n )\r\n pe[:, 0::2] = torch.sin(position * div_term)\r\n pe[:, 1::2] = torch.cos(position * div_term)\r\n pe = pe.unsqueeze(0)\r\n self.pe = pe.to(device=x.device, dtype=x.dtype)\r\n\r\n def forward(self, x: torch.Tensor):\r\n \"\"\"Add positional encoding.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (batch, time, `*`).\r\n\r\n Returns:\r\n torch.Tensor: Encoded tensor (batch, time, `*`).\r\n \"\"\"\r\n self.extend_pe(x)\r\n x = x * self.xscale + self.pe[:, : x.size(1)]\r\n return self.dropout(x)\r" }, { "identifier": "RelPositionalEncoding", "path": "src/clap_module/conformer/embedding.py", "snippet": "class RelPositionalEncoding(torch.nn.Module):\r\n \"\"\"Relative positional encoding module (new implementation).\r\n\r\n Details can be found in https://github.com/espnet/espnet/pull/2816.\r\n\r\n See : Appendix B in https://arxiv.org/abs/1901.02860\r\n\r\n Args:\r\n d_model (int): Embedding dimension.\r\n dropout_rate (float): Dropout rate.\r\n max_len (int): Maximum input length.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, d_model, dropout_rate, max_len=5000):\r\n \"\"\"Construct an PositionalEncoding object.\r\n \"\"\"\r\n super(RelPositionalEncoding, self).__init__()\r\n self.d_model = d_model\r\n self.xscale = math.sqrt(self.d_model)\r\n self.dropout = torch.nn.Dropout(p=dropout_rate)\r\n self.pe = None\r\n self.extend_pe(torch.tensor(0.0).expand(1, max_len))\r\n\r\n def extend_pe(self, x):\r\n \"\"\"Reset the positional encodings.\r\n \"\"\"\r\n if self.pe is not None:\r\n # self.pe contains both positive and negative parts\r\n # the length of self.pe is 2 * input_len - 1\r\n if self.pe.size(1) >= x.size(1) * 2 - 1:\r\n if self.pe.dtype != x.dtype or self.pe.device != x.device:\r\n self.pe = self.pe.to(dtype=x.dtype, device=x.device)\r\n return\r\n # Suppose `i` means to the position of query vecotr and `j` means the\r\n # position of key vector. We use position relative positions when keys\r\n # are to the left (i>j) and negative relative positions otherwise (i<j).\r\n pe_positive = torch.zeros(x.size(1), self.d_model)\r\n pe_negative = torch.zeros(x.size(1), self.d_model)\r\n position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)\r\n div_term = torch.exp(\r\n torch.arange(0, self.d_model, 2, dtype=torch.float32)\r\n * -(math.log(10000.0) / self.d_model)\r\n )\r\n pe_positive[:, 0::2] = torch.sin(position * div_term)\r\n pe_positive[:, 1::2] = torch.cos(position * div_term)\r\n pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)\r\n pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)\r\n\r\n # Reserve the order of positive indices and concat both positive and\r\n # negative indices. This is used to support the shifting trick\r\n # as in https://arxiv.org/abs/1901.02860\r\n pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)\r\n pe_negative = pe_negative[1:].unsqueeze(0)\r\n pe = torch.cat([pe_positive, pe_negative], dim=1)\r\n self.pe = pe.to(device=x.device, dtype=x.dtype)\r\n\r\n def forward(self, x: torch.Tensor):\r\n \"\"\"Add positional encoding.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (batch, time, `*`).\r\n\r\n Returns:\r\n torch.Tensor: Encoded tensor (batch, time, `*`).\r\n\r\n \"\"\"\r\n self.extend_pe(x)\r\n x = x * self.xscale\r\n pos_emb = self.pe[\r\n :,\r\n self.pe.size(1) // 2 - x.size(1) + 1 : self.pe.size(1) // 2 + x.size(1),\r\n ]\r\n return self.dropout(x), self.dropout(pos_emb)\r" }, { "identifier": "ScaledPositionalEncoding", "path": "src/clap_module/conformer/embedding.py", "snippet": "class ScaledPositionalEncoding(PositionalEncoding):\r\n \"\"\"Scaled positional encoding module.\r\n\r\n See Sec. 3.2 https://arxiv.org/abs/1809.08895\r\n\r\n Args:\r\n d_model (int): Embedding dimension.\r\n dropout_rate (float): Dropout rate.\r\n max_len (int): Maximum input length.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, d_model, dropout_rate, max_len=5000):\r\n \"\"\"Initialize class.\"\"\"\r\n super().__init__(d_model=d_model, dropout_rate=dropout_rate, max_len=max_len)\r\n self.alpha = torch.nn.Parameter(torch.tensor(1.0))\r\n\r\n def reset_parameters(self):\r\n \"\"\"Reset parameters.\"\"\"\r\n self.alpha.data = torch.tensor(1.0)\r\n\r\n def forward(self, x):\r\n \"\"\"Add positional encoding.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (batch, time, `*`).\r\n\r\n Returns:\r\n torch.Tensor: Encoded tensor (batch, time, `*`).\r\n\r\n \"\"\"\r\n self.extend_pe(x)\r\n x = x + self.alpha * self.pe[:, : x.size(1)]\r\n return self.dropout(x)\r" }, { "identifier": "LayerNorm", "path": "src/clap_module/conformer/modules.py", "snippet": "class LayerNorm(torch.nn.LayerNorm):\r\n \"\"\"Layer normalization module.\r\n\r\n Args:\r\n nout (int): Output dim size.\r\n dim (int): Dimension to be normalized.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, nout, dim=-1):\r\n \"\"\"Construct an LayerNorm object.\"\"\"\r\n super(LayerNorm, self).__init__(nout, eps=1e-12)\r\n self.dim = dim\r\n\r\n def forward(self, x):\r\n \"\"\"Apply layer normalization.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor.\r\n\r\n Returns:\r\n torch.Tensor: Normalized tensor.\r\n\r\n \"\"\"\r\n if self.dim == -1:\r\n return super(LayerNorm, self).forward(x)\r\n return (\r\n super(LayerNorm, self)\r\n .forward(x.transpose(self.dim, -1))\r\n .transpose(self.dim, -1)\r\n )\r" }, { "identifier": "Conv1dLinear", "path": "src/clap_module/conformer/multi_layer_conv.py", "snippet": "class Conv1dLinear(torch.nn.Module):\r\n \"\"\"Conv1D + Linear for Transformer block.\r\n\r\n A variant of MultiLayeredConv1d, which replaces second conv-layer to linear.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):\r\n \"\"\"Initialize Conv1dLinear module.\r\n\r\n Args:\r\n in_chans (int): Number of input channels.\r\n hidden_chans (int): Number of hidden channels.\r\n kernel_size (int): Kernel size of conv1d.\r\n dropout_rate (float): Dropout rate.\r\n\r\n \"\"\"\r\n super(Conv1dLinear, self).__init__()\r\n self.w_1 = torch.nn.Conv1d(\r\n in_chans,\r\n hidden_chans,\r\n kernel_size,\r\n stride=1,\r\n padding=(kernel_size - 1) // 2,\r\n )\r\n self.w_2 = torch.nn.Linear(hidden_chans, in_chans)\r\n self.dropout = torch.nn.Dropout(dropout_rate)\r\n\r\n def forward(self, x):\r\n \"\"\"Calculate forward propagation.\r\n\r\n Args:\r\n x (torch.Tensor): Batch of input tensors (B, T, in_chans).\r\n\r\n Returns:\r\n torch.Tensor: Batch of output tensors (B, T, hidden_chans).\r\n\r\n \"\"\"\r\n x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)\r\n return self.w_2(self.dropout(x))\r" }, { "identifier": "MultiLayeredConv1d", "path": "src/clap_module/conformer/multi_layer_conv.py", "snippet": "class MultiLayeredConv1d(torch.nn.Module):\r\n \"\"\"Multi-layered conv1d for Transformer block.\r\n\r\n This is a module of multi-leyered conv1d designed\r\n to replace positionwise feed-forward network\r\n in Transforner block, which is introduced in\r\n `FastSpeech: Fast, Robust and Controllable Text to Speech`_.\r\n\r\n .. _`FastSpeech: Fast, Robust and Controllable Text to Speech`:\r\n https://arxiv.org/pdf/1905.09263.pdf\r\n\r\n \"\"\"\r\n\r\n def __init__(self, in_chans, hidden_chans, kernel_size, dropout_rate):\r\n \"\"\"Initialize MultiLayeredConv1d module.\r\n\r\n Args:\r\n in_chans (int): Number of input channels.\r\n hidden_chans (int): Number of hidden channels.\r\n kernel_size (int): Kernel size of conv1d.\r\n dropout_rate (float): Dropout rate.\r\n\r\n \"\"\"\r\n super(MultiLayeredConv1d, self).__init__()\r\n self.w_1 = torch.nn.Conv1d(\r\n in_chans,\r\n hidden_chans,\r\n kernel_size,\r\n stride=1,\r\n padding=(kernel_size - 1) // 2,\r\n )\r\n self.w_2 = torch.nn.Conv1d(\r\n hidden_chans,\r\n in_chans,\r\n kernel_size,\r\n stride=1,\r\n padding=(kernel_size - 1) // 2,\r\n )\r\n self.dropout = torch.nn.Dropout(dropout_rate)\r\n\r\n def forward(self, x):\r\n \"\"\"Calculate forward propagation.\r\n\r\n Args:\r\n x (torch.Tensor): Batch of input tensors (B, T, in_chans).\r\n\r\n Returns:\r\n torch.Tensor: Batch of output tensors (B, T, hidden_chans).\r\n\r\n \"\"\"\r\n x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)\r\n return self.w_2(self.dropout(x).transpose(-1, 1)).transpose(-1, 1)\r" }, { "identifier": "PositionwiseFeedForward", "path": "src/clap_module/conformer/modules.py", "snippet": "class PositionwiseFeedForward(torch.nn.Module):\r\n \"\"\"Positionwise feed forward layer.\r\n\r\n Args:\r\n idim (int): Input dimenstion.\r\n hidden_units (int): The number of hidden units.\r\n dropout_rate (float): Dropout rate.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, idim, hidden_units, dropout_rate, activation=torch.nn.ReLU()):\r\n \"\"\"Construct an PositionwiseFeedForward object.\"\"\"\r\n super(PositionwiseFeedForward, self).__init__()\r\n self.w_1 = torch.nn.Linear(idim, hidden_units)\r\n self.w_2 = torch.nn.Linear(hidden_units, idim)\r\n self.dropout = torch.nn.Dropout(dropout_rate)\r\n self.activation = activation\r\n\r\n def forward(self, x):\r\n \"\"\"Forward function.\"\"\"\r\n return self.w_2(self.dropout(self.activation(self.w_1(x))))\r" }, { "identifier": "repeat", "path": "src/clap_module/conformer/modules.py", "snippet": "def repeat(N, fn, layer_drop_rate=0.0):\r\n \"\"\"Repeat module N times.\r\n\r\n Args:\r\n N (int): Number of repeat time.\r\n fn (Callable): Function to generate module.\r\n layer_drop_rate (float): Probability of dropping out each fn (layer).\r\n\r\n Returns:\r\n MultiSequential: Repeated model instance.\r\n\r\n \"\"\"\r\n return MultiSequential(*[fn(n) for n in range(N)], layer_drop_rate=layer_drop_rate)\r" }, { "identifier": "Conv2dSubsampling", "path": "src/clap_module/conformer/sub_sampling.py", "snippet": "class Conv2dSubsampling(torch.nn.Module):\r\n \"\"\"Convolutional 2D subsampling (to 1/4 length).\r\n\r\n Args:\r\n idim (int): Input dimension.\r\n odim (int): Output dimension.\r\n dropout_rate (float): Dropout rate.\r\n pos_enc (torch.nn.Module): Custom position encoding layer.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, idim, odim, dropout_rate, pos_enc=None):\r\n \"\"\"Construct an Conv2dSubsampling object.\"\"\"\r\n super(Conv2dSubsampling, self).__init__()\r\n self.conv = torch.nn.Sequential(\r\n torch.nn.Conv2d(1, odim, 3, 2),\r\n torch.nn.ReLU(),\r\n torch.nn.Conv2d(odim, odim, 3, 2),\r\n torch.nn.ReLU(),\r\n )\r\n self.out = torch.nn.Sequential(\r\n torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim),\r\n pos_enc if pos_enc is not None else PositionalEncoding(odim, dropout_rate),\r\n )\r\n\r\n def forward(self, x, x_mask):\r\n \"\"\"Subsample x.\r\n\r\n Args:\r\n x (torch.Tensor): Input tensor (#batch, time, idim).\r\n x_mask (torch.Tensor): Input mask (#batch, 1, time).\r\n\r\n Returns:\r\n torch.Tensor: Subsampled tensor (#batch, time', odim),\r\n where time' = time // 4.\r\n torch.Tensor: Subsampled mask (#batch, 1, time'),\r\n where time' = time // 4.\r\n\r\n \"\"\"\r\n x = x.unsqueeze(1) # (b, c, t, f)\r\n x = self.conv(x)\r\n b, c, t, f = x.size()\r\n x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))\r\n if x_mask is None:\r\n return x, None\r\n return x, x_mask[:, :, :-2:2][:, :, :-2:2]\r\n\r\n def __getitem__(self, key):\r\n \"\"\"Get item.\r\n\r\n When reset_parameters() is called, if use_scaled_pos_enc is used,\r\n return the positioning encoding.\r\n\r\n \"\"\"\r\n if key != -1:\r\n raise NotImplementedError(\"Support only `-1` (for `reset_parameters`).\")\r\n return self.out[key]\r" }, { "identifier": "AttentionPool1d", "path": "src/clap_module/feature_fusion.py", "snippet": "class AttentionPool1d(nn.Module):\r\n def __init__(\r\n self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None\r\n ):\r\n super().__init__()\r\n self.positional_embedding = nn.Parameter(\r\n torch.randn(spacial_dim + 1, embed_dim) / embed_dim\r\n # torch.randn(spacial_dim, embed_dim) / embed_dim\r\n )\r\n self.k_proj = nn.Linear(embed_dim, embed_dim)\r\n self.q_proj = nn.Linear(embed_dim, embed_dim)\r\n self.v_proj = nn.Linear(embed_dim, embed_dim)\r\n self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)\r\n self.num_heads = num_heads\r\n\r\n def forward(self, x):\r\n # import pdb; pdb.set_trace()\r\n x = x.permute(1, 0, 2) # B*L*D -> L*B*D; NCHW -> (HW)NC\r\n x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC\r\n x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC\r\n x, _ = F.multi_head_attention_forward(\r\n query=x,\r\n key=x,\r\n value=x,\r\n embed_dim_to_check=x.shape[-1],\r\n num_heads=self.num_heads,\r\n q_proj_weight=self.q_proj.weight,\r\n k_proj_weight=self.k_proj.weight,\r\n v_proj_weight=self.v_proj.weight,\r\n in_proj_weight=None,\r\n in_proj_bias=torch.cat(\r\n [self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]\r\n ),\r\n bias_k=None,\r\n bias_v=None,\r\n add_zero_attn=False,\r\n dropout_p=0,\r\n out_proj_weight=self.c_proj.weight,\r\n out_proj_bias=self.c_proj.bias,\r\n use_separate_proj_weight=True,\r\n training=self.training,\r\n need_weights=False,\r\n )\r\n\r\n return x[0] # B*D\r" }, { "identifier": "DAF", "path": "src/clap_module/feature_fusion.py", "snippet": "class DAF(nn.Module):\r\n \"\"\"直接相加 DirectAddFuse\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super(DAF, self).__init__()\r\n\r\n def forward(self, x, residual):\r\n return x + residual\r" }, { "identifier": "AFF", "path": "src/clap_module/feature_fusion.py", "snippet": "class AFF(nn.Module):\r\n \"\"\"多特征融合 AFF\r\n \"\"\"\r\n\r\n def __init__(self, channels=64, r=4, type='2D'):\r\n super(AFF, self).__init__()\r\n inter_channels = int(channels // r)\r\n\r\n if type == '1D':\r\n self.local_att = nn.Sequential(\r\n nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(channels),\r\n )\r\n self.global_att = nn.Sequential(\r\n nn.AdaptiveAvgPool1d(1),\r\n nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(channels),\r\n )\r\n elif type == '2D':\r\n self.local_att = nn.Sequential(\r\n nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(channels),\r\n )\r\n self.global_att = nn.Sequential(\r\n nn.AdaptiveAvgPool2d(1),\r\n nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(channels),\r\n )\r\n else:\r\n raise f'the type is not supported.'\r\n\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, x, residual):\r\n flag = False\r\n xa = x + residual\r\n if xa.size(0) == 1:\r\n xa = torch.cat([xa, xa], dim=0)\r\n flag = True\r\n xl = self.local_att(xa)\r\n xg = self.global_att(xa)\r\n xlg = xl + xg\r\n wei = self.sigmoid(xlg)\r\n xo = 2 * x * wei + 2 * residual * (1 - wei)\r\n if flag:\r\n xo = xo[0].unsqueeze(0)\r\n return xo\r" }, { "identifier": "iAFF", "path": "src/clap_module/feature_fusion.py", "snippet": "class iAFF(nn.Module):\r\n \"\"\"多特征融合 iAFF\r\n \"\"\"\r\n\r\n def __init__(self, channels=64, r=4, type='2D'):\r\n super(iAFF, self).__init__()\r\n inter_channels = int(channels // r)\r\n\r\n if type == '1D':\r\n # 本地注意力\r\n self.local_att = nn.Sequential(\r\n nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(channels),\r\n )\r\n\r\n # 全局注意力\r\n self.global_att = nn.Sequential(\r\n nn.AdaptiveAvgPool1d(1),\r\n nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(channels),\r\n )\r\n\r\n # 第二次本地注意力\r\n self.local_att2 = nn.Sequential(\r\n nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(channels),\r\n )\r\n # 第二次全局注意力\r\n self.global_att2 = nn.Sequential(\r\n nn.AdaptiveAvgPool1d(1),\r\n nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm1d(channels),\r\n )\r\n elif type == '2D':\r\n # 本地注意力\r\n self.local_att = nn.Sequential(\r\n nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(channels),\r\n )\r\n\r\n # 全局注意力\r\n self.global_att = nn.Sequential(\r\n nn.AdaptiveAvgPool2d(1),\r\n nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(channels),\r\n )\r\n\r\n # 第二次本地注意力\r\n self.local_att2 = nn.Sequential(\r\n nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(channels),\r\n )\r\n # 第二次全局注意力\r\n self.global_att2 = nn.Sequential(\r\n nn.AdaptiveAvgPool2d(1),\r\n nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(inter_channels),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),\r\n nn.BatchNorm2d(channels),\r\n )\r\n else:\r\n raise f'the type is not supported'\r\n\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, x, residual):\r\n flag = False\r\n xa = x + residual\r\n if xa.size(0) == 1:\r\n xa = torch.cat([xa, xa], dim=0)\r\n flag = True\r\n xl = self.local_att(xa)\r\n xg = self.global_att(xa)\r\n xlg = xl + xg\r\n wei = self.sigmoid(xlg)\r\n xi = x * wei + residual * (1 - wei)\r\n\r\n xl2 = self.local_att2(xi)\r\n xg2 = self.global_att(xi)\r\n xlg2 = xl2 + xg2\r\n wei2 = self.sigmoid(xlg2)\r\n xo = x * wei2 + residual * (1 - wei2)\r\n if flag:\r\n xo = xo[0].unsqueeze(0)\r\n return xo\r" } ]
import logging import torch import math from .convolution import ConvolutionModule from .encoder_layer import EncoderLayer from .modules import get_activation from .modules import VGG2L from .modules import ( LegacyRelPositionMultiHeadedAttention, MultiHeadedAttention, RelPositionMultiHeadedAttention, ) from .embedding import ( LegacyRelPositionalEncoding, PositionalEncoding, RelPositionalEncoding, ScaledPositionalEncoding, ) from .modules import LayerNorm from .multi_layer_conv import ( Conv1dLinear, MultiLayeredConv1d, ) from .modules import ( PositionwiseFeedForward, ) from .modules import repeat from .sub_sampling import Conv2dSubsampling from ..feature_fusion import AttentionPool1d, DAF, AFF, iAFF
15,252
attention_dim, dropout_rate, pos_enc_class(attention_dim, positional_dropout_rate), ) self.conv_subsampling_factor = 4 elif input_layer == "vgg2l": self.embed = VGG2L(idim, attention_dim) self.conv_subsampling_factor = 4 elif input_layer == "embed": self.embed = torch.nn.Sequential( torch.nn.Embedding(idim, attention_dim, padding_idx=padding_idx), pos_enc_class(attention_dim, positional_dropout_rate), ) elif isinstance(input_layer, torch.nn.Module): self.embed = torch.nn.Sequential( input_layer, pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer is None: self.embed = torch.nn.Sequential( pos_enc_class(attention_dim, positional_dropout_rate) ) else: raise ValueError("unknown input_layer: " + input_layer) self.normalize_before = normalize_before # self-attention module definition if selfattention_layer_type == "selfattn": logging.info("encoder self-attention layer type = self-attention") encoder_selfattn_layer = MultiHeadedAttention encoder_selfattn_layer_args = ( attention_heads, attention_dim, attention_dropout_rate, ) elif selfattention_layer_type == "legacy_rel_selfattn": assert pos_enc_layer_type == "legacy_rel_pos" encoder_selfattn_layer = LegacyRelPositionMultiHeadedAttention encoder_selfattn_layer_args = ( attention_heads, attention_dim, attention_dropout_rate, ) elif selfattention_layer_type == "rel_selfattn": logging.info("encoder self-attention layer type = relative self-attention") assert pos_enc_layer_type == "rel_pos" encoder_selfattn_layer = RelPositionMultiHeadedAttention encoder_selfattn_layer_args = ( attention_heads, attention_dim, attention_dropout_rate, zero_triu, ) else: raise ValueError("unknown encoder_attn_layer: " + selfattention_layer_type) # feed-forward module definition if ffn_layer_type == "linear": ffn_layer = PositionwiseFeedForward ffn_layer_args = ( attention_dim, linear_units, dropout_rate, activation, ) elif ffn_layer_type == "conv1d": ffn_layer = MultiLayeredConv1d ffn_layer_args = ( attention_dim, linear_units, ffn_conv_kernel_size, dropout_rate, ) elif ffn_layer_type == "conv1d-linear": ffn_layer = Conv1dLinear ffn_layer_args = ( attention_dim, linear_units, ffn_conv_kernel_size, dropout_rate, ) else: raise NotImplementedError("Support only linear or conv1d.") # convolution module definition convolution_layer = ConvolutionModule convolution_layer_args = (attention_dim, cnn_module_kernel, activation) self.encoders = repeat( num_blocks, lambda lnum: EncoderLayer( attention_dim, encoder_selfattn_layer(*encoder_selfattn_layer_args), ffn_layer(*ffn_layer_args), ffn_layer(*ffn_layer_args) if macaron_style else None, convolution_layer(*convolution_layer_args) if use_cnn_module else None, dropout_rate, normalize_before, concat_after, stochastic_depth_rate * float(1 + lnum) / num_blocks, ), ) if self.normalize_before: self.after_norm = LayerNorm(attention_dim) self.intermediate_layers = intermediate_layers self.use_conditioning = True if ctc_softmax is not None else False if self.use_conditioning: self.ctc_softmax = ctc_softmax self.conditioning_layer = torch.nn.Linear( conditioning_layer_dim, attention_dim ) self.enable_fusion = enable_fusion self.fusion_type = fusion_type if (self.enable_fusion) and (self.fusion_type in ['daf_1d','aff_1d','iaff_1d']): raise NotImplementedError if self.fusion_type == 'daf_1d': self.fusion_model = DAF() elif self.fusion_type == 'aff_1d':
# Copyright 2020 Johns Hopkins University (Shinji Watanabe) # Northwestern Polytechnical University (Pengcheng Guo) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Encoder definition.""" class Encoder(torch.nn.Module): """Conformer encoder module. Args: idim (int): Input dimension. attention_dim (int): Dimension of attention. attention_heads (int): The number of heads of multi head attention. linear_units (int): The number of units of position-wise feed forward. num_blocks (int): The number of decoder blocks. dropout_rate (float): Dropout rate. positional_dropout_rate (float): Dropout rate after adding positional encoding. attention_dropout_rate (float): Dropout rate in attention. input_layer (Union[str, torch.nn.Module]): Input layer type. normalize_before (bool): Whether to use layer_norm before the first block. concat_after (bool): Whether to concat attention layer's input and output. if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type (str): "linear", "conv1d", or "conv1d-linear". positionwise_conv_kernel_size (int): Kernel size of positionwise conv1d layer. macaron_style (bool): Whether to use macaron style for positionwise layer. pos_enc_layer_type (str): Encoder positional encoding layer type. selfattention_layer_type (str): Encoder attention layer type. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. zero_triu (bool): Whether to zero the upper triangular part of attention matrix. cnn_module_kernel (int): Kernerl size of convolution module. padding_idx (int): Padding idx for input_layer=embed. stochastic_depth_rate (float): Maximum probability to skip the encoder layer. intermediate_layers (Union[List[int], None]): indices of intermediate CTC layer. indices start from 1. if not None, intermediate outputs are returned (which changes return type signature.) """ def __init__( self, idim, attention_dim=256, attention_heads=4, linear_units=2048, num_blocks=6, dropout_rate=0.1, positional_dropout_rate=0.1, attention_dropout_rate=0.0, input_layer="conv2d", normalize_before=True, concat_after=False, ffn_layer_type="linear", ffn_conv_kernel_size=1, macaron_style=False, pos_enc_layer_type="abs_pos", selfattention_layer_type="selfattn", activation_type="relu", use_cnn_module=True, zero_triu=False, cnn_module_kernel=31, padding_idx=-1, stochastic_depth_rate=0.0, intermediate_layers=None, ctc_softmax=None, conditioning_layer_dim=None, max_seq_len=100, enable_fusion=False, fusion_type="", ): """Construct an Encoder object.""" super(Encoder, self).__init__() self.max_seq_len = max_seq_len activation = get_activation(activation_type) if pos_enc_layer_type == "abs_pos": pos_enc_class = PositionalEncoding elif pos_enc_layer_type == "scaled_abs_pos": pos_enc_class = ScaledPositionalEncoding elif pos_enc_layer_type == "rel_pos": assert selfattention_layer_type == "rel_selfattn" pos_enc_class = RelPositionalEncoding elif pos_enc_layer_type == "legacy_rel_pos": assert selfattention_layer_type == "legacy_rel_selfattn" pos_enc_class = LegacyRelPositionalEncoding else: raise ValueError("unknown pos_enc_layer: " + pos_enc_layer_type) self.conv_subsampling_factor = 1 if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(idim, attention_dim), torch.nn.LayerNorm(attention_dim), torch.nn.Dropout(dropout_rate), pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling( idim, attention_dim, dropout_rate, pos_enc_class(attention_dim, positional_dropout_rate), ) self.conv_subsampling_factor = 4 elif input_layer == "vgg2l": self.embed = VGG2L(idim, attention_dim) self.conv_subsampling_factor = 4 elif input_layer == "embed": self.embed = torch.nn.Sequential( torch.nn.Embedding(idim, attention_dim, padding_idx=padding_idx), pos_enc_class(attention_dim, positional_dropout_rate), ) elif isinstance(input_layer, torch.nn.Module): self.embed = torch.nn.Sequential( input_layer, pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer is None: self.embed = torch.nn.Sequential( pos_enc_class(attention_dim, positional_dropout_rate) ) else: raise ValueError("unknown input_layer: " + input_layer) self.normalize_before = normalize_before # self-attention module definition if selfattention_layer_type == "selfattn": logging.info("encoder self-attention layer type = self-attention") encoder_selfattn_layer = MultiHeadedAttention encoder_selfattn_layer_args = ( attention_heads, attention_dim, attention_dropout_rate, ) elif selfattention_layer_type == "legacy_rel_selfattn": assert pos_enc_layer_type == "legacy_rel_pos" encoder_selfattn_layer = LegacyRelPositionMultiHeadedAttention encoder_selfattn_layer_args = ( attention_heads, attention_dim, attention_dropout_rate, ) elif selfattention_layer_type == "rel_selfattn": logging.info("encoder self-attention layer type = relative self-attention") assert pos_enc_layer_type == "rel_pos" encoder_selfattn_layer = RelPositionMultiHeadedAttention encoder_selfattn_layer_args = ( attention_heads, attention_dim, attention_dropout_rate, zero_triu, ) else: raise ValueError("unknown encoder_attn_layer: " + selfattention_layer_type) # feed-forward module definition if ffn_layer_type == "linear": ffn_layer = PositionwiseFeedForward ffn_layer_args = ( attention_dim, linear_units, dropout_rate, activation, ) elif ffn_layer_type == "conv1d": ffn_layer = MultiLayeredConv1d ffn_layer_args = ( attention_dim, linear_units, ffn_conv_kernel_size, dropout_rate, ) elif ffn_layer_type == "conv1d-linear": ffn_layer = Conv1dLinear ffn_layer_args = ( attention_dim, linear_units, ffn_conv_kernel_size, dropout_rate, ) else: raise NotImplementedError("Support only linear or conv1d.") # convolution module definition convolution_layer = ConvolutionModule convolution_layer_args = (attention_dim, cnn_module_kernel, activation) self.encoders = repeat( num_blocks, lambda lnum: EncoderLayer( attention_dim, encoder_selfattn_layer(*encoder_selfattn_layer_args), ffn_layer(*ffn_layer_args), ffn_layer(*ffn_layer_args) if macaron_style else None, convolution_layer(*convolution_layer_args) if use_cnn_module else None, dropout_rate, normalize_before, concat_after, stochastic_depth_rate * float(1 + lnum) / num_blocks, ), ) if self.normalize_before: self.after_norm = LayerNorm(attention_dim) self.intermediate_layers = intermediate_layers self.use_conditioning = True if ctc_softmax is not None else False if self.use_conditioning: self.ctc_softmax = ctc_softmax self.conditioning_layer = torch.nn.Linear( conditioning_layer_dim, attention_dim ) self.enable_fusion = enable_fusion self.fusion_type = fusion_type if (self.enable_fusion) and (self.fusion_type in ['daf_1d','aff_1d','iaff_1d']): raise NotImplementedError if self.fusion_type == 'daf_1d': self.fusion_model = DAF() elif self.fusion_type == 'aff_1d':
self.fusion_model = AFF(channels=attention_dim, type='1D')
19
2023-11-25 02:38:32+00:00
24k
Luo-Z13/pointobb
PointOBB/mmdet/models/roi_heads/PointOBB_head.py
[ { "identifier": "HEADS", "path": "PointOBB/mmdet/models/builder.py", "snippet": "HEADS = MODELS" }, { "identifier": "MODELS", "path": "PointOBB/mmdet/models/builder.py", "snippet": "MODELS = Registry('models', parent=MMCV_MODELS)" }, { "identifier": "build_head", "path": "PointOBB/mmdet/models/builder.py", "snippet": "def build_head(cfg):\n \"\"\"Build head.\"\"\"\n return HEADS.build(cfg)" }, { "identifier": "build_roi_extractor", "path": "PointOBB/mmdet/models/builder.py", "snippet": "def build_roi_extractor(cfg):\n \"\"\"Build roi extractor.\"\"\"\n return ROI_EXTRACTORS.build(cfg)" }, { "identifier": "build_loss", "path": "PointOBB/mmdet/models/builder.py", "snippet": "def build_loss(cfg):\n \"\"\"Build loss.\"\"\"\n return LOSSES.build(cfg)" }, { "identifier": "StandardRoIHead", "path": "PointOBB/mmdet/models/roi_heads/standard_roi_head.py", "snippet": "class StandardRoIHead(BaseRoIHead, BBoxTestMixin, MaskTestMixin):\n \"\"\"Simplest base roi head including one bbox head and one mask head.\"\"\"\n\n def init_assigner_sampler(self):\n \"\"\"Initialize assigner and sampler.\"\"\"\n self.bbox_assigner = None\n self.bbox_sampler = None\n if self.train_cfg:\n self.bbox_assigner = build_assigner(self.train_cfg.assigner)\n self.bbox_sampler = build_sampler(\n self.train_cfg.sampler, context=self)\n\n def init_bbox_head(self, bbox_roi_extractor, bbox_head):\n \"\"\"Initialize ``bbox_head``\"\"\"\n self.bbox_roi_extractor = build_roi_extractor(bbox_roi_extractor)\n self.bbox_head = build_head(bbox_head)\n\n def init_mask_head(self, mask_roi_extractor, mask_head):\n \"\"\"Initialize ``mask_head``\"\"\"\n if mask_roi_extractor is not None:\n self.mask_roi_extractor = build_roi_extractor(mask_roi_extractor)\n self.share_roi_extractor = False\n else:\n self.share_roi_extractor = True\n self.mask_roi_extractor = self.bbox_roi_extractor\n self.mask_head = build_head(mask_head)\n\n def forward_dummy(self, x, proposals):\n \"\"\"Dummy forward function.\"\"\"\n # bbox head\n outs = ()\n rois = bbox2roi([proposals])\n if self.with_bbox:\n bbox_results = self._bbox_forward(x, rois)\n outs = outs + (bbox_results['cls_score'],\n bbox_results['bbox_pred'])\n # mask head\n if self.with_mask:\n mask_rois = rois[:100]\n mask_results = self._mask_forward(x, mask_rois)\n outs = outs + (mask_results['mask_pred'], )\n return outs\n\n def forward_train(self,\n x,\n img_metas,\n proposal_list,\n gt_bboxes,\n gt_labels,\n ann_weight,\n gt_bboxes_ignore=None,\n gt_masks=None):\n \"\"\"\n Args:\n x (list[Tensor]): list of multi-level img features.\n img_metas (list[dict]): list of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmdet/datasets/pipelines/formatting.py:Collect`.\n proposals (list[Tensors]): list of region proposals.\n gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (list[Tensor]): class indices corresponding to each box\n gt_bboxes_ignore (None | list[Tensor]): specify which bounding\n boxes can be ignored when computing the loss.\n gt_masks (None | Tensor) : true segmentation masks for each box\n used if the architecture supports a segmentation task.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n # assign gts and sample proposals\n if self.with_bbox or self.with_mask:\n num_imgs = len(img_metas)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n sampling_results = []\n for i in range(num_imgs):\n assign_result = self.bbox_assigner.assign(\n proposal_list[i], gt_bboxes[i], gt_bboxes_ignore[i],\n gt_labels[i])\n sampling_result = self.bbox_sampler.sample(\n assign_result,\n proposal_list[i],\n gt_bboxes[i],\n gt_labels[i],\n feats=[lvl_feat[i][None] for lvl_feat in x])\n sampling_results.append(sampling_result)\n\n losses = dict()\n # bbox head forward and loss\n if self.with_bbox:\n bbox_results = self._bbox_forward_train(x, sampling_results,\n gt_bboxes, gt_labels,ann_weight, #add by fei\n img_metas)\n losses.update(bbox_results['loss_bbox'])\n\n # mask head forward and loss\n if self.with_mask:\n mask_results = self._mask_forward_train(x, sampling_results,\n bbox_results['bbox_feats'],\n gt_masks, img_metas)\n losses.update(mask_results['loss_mask'])\n\n return losses\n\n def _bbox_forward(self, x, rois):\n \"\"\"Box head forward function used in both training and testing.\"\"\"\n # TODO: a more flexible way to decide which feature maps to use\n bbox_feats = self.bbox_roi_extractor(\n x[:self.bbox_roi_extractor.num_inputs], rois)\n if self.with_shared_head:\n bbox_feats = self.shared_head(bbox_feats)\n cls_score, bbox_pred = self.bbox_head(bbox_feats)\n\n bbox_results = dict(\n cls_score=cls_score, bbox_pred=bbox_pred, bbox_feats=bbox_feats)\n return bbox_results\n\n def _bbox_forward_train(self, x, sampling_results, gt_bboxes, gt_labels, ann_weight,\n img_metas):\n \"\"\"Run forward function and calculate loss for box head in training.\"\"\"\n rois = bbox2roi([res.bboxes for res in sampling_results])\n bbox_results = self._bbox_forward(x, rois)\n\n bbox_targets = self.bbox_head.get_targets(sampling_results, gt_bboxes,\n gt_labels,ann_weight, self.train_cfg) ## add by fei\n loss_bbox = self.bbox_head.loss(bbox_results['cls_score'],\n bbox_results['bbox_pred'], rois,\n *bbox_targets)\n\n bbox_results.update(loss_bbox=loss_bbox)\n return bbox_results\n\n def _mask_forward_train(self, x, sampling_results, bbox_feats, gt_masks,\n img_metas):\n \"\"\"Run forward function and calculate loss for mask head in\n training.\"\"\"\n if not self.share_roi_extractor:\n pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])\n mask_results = self._mask_forward(x, pos_rois)\n else:\n pos_inds = []\n device = bbox_feats.device\n for res in sampling_results:\n pos_inds.append(\n torch.ones(\n res.pos_bboxes.shape[0],\n device=device,\n dtype=torch.uint8))\n pos_inds.append(\n torch.zeros(\n res.neg_bboxes.shape[0],\n device=device,\n dtype=torch.uint8))\n pos_inds = torch.cat(pos_inds)\n\n mask_results = self._mask_forward(\n x, pos_inds=pos_inds, bbox_feats=bbox_feats)\n\n mask_targets = self.mask_head.get_targets(sampling_results, gt_masks,\n self.train_cfg)\n pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])\n loss_mask = self.mask_head.loss(mask_results['mask_pred'],\n mask_targets, pos_labels)\n\n mask_results.update(loss_mask=loss_mask, mask_targets=mask_targets)\n return mask_results\n\n def _mask_forward(self, x, rois=None, pos_inds=None, bbox_feats=None):\n \"\"\"Mask head forward function used in both training and testing.\"\"\"\n assert ((rois is not None) ^\n (pos_inds is not None and bbox_feats is not None))\n if rois is not None:\n mask_feats = self.mask_roi_extractor(\n x[:self.mask_roi_extractor.num_inputs], rois)\n if self.with_shared_head:\n mask_feats = self.shared_head(mask_feats)\n else:\n assert bbox_feats is not None\n mask_feats = bbox_feats[pos_inds]\n\n mask_pred = self.mask_head(mask_feats)\n mask_results = dict(mask_pred=mask_pred, mask_feats=mask_feats)\n return mask_results\n\n async def async_simple_test(self,\n x,\n proposal_list,\n img_metas,\n proposals=None,\n rescale=False):\n \"\"\"Async test without augmentation.\"\"\"\n assert self.with_bbox, 'Bbox head must be implemented.'\n\n det_bboxes, det_labels = await self.async_test_bboxes(\n x, img_metas, proposal_list, self.test_cfg, rescale=rescale)\n bbox_results = bbox2result(det_bboxes, det_labels,\n self.bbox_head.num_classes)\n if not self.with_mask:\n return bbox_results\n else:\n segm_results = await self.async_test_mask(\n x,\n img_metas,\n det_bboxes,\n det_labels,\n rescale=rescale,\n mask_test_cfg=self.test_cfg.get('mask'))\n return bbox_results, segm_results\n\n def simple_test(self,\n x,\n proposal_list,\n img_metas,\n proposals=None,\n rescale=False):\n \"\"\"Test without augmentation.\"\"\"\n assert self.with_bbox, 'Bbox head must be implemented.'\n\n det_bboxes, det_labels = self.simple_test_bboxes(\n x, img_metas, proposal_list, self.test_cfg, rescale=rescale)\n\n bbox_results = [\n bbox2result(det_bboxes[i], det_labels[i],\n self.bbox_head.num_classes)\n for i in range(len(det_bboxes))\n ]\n\n if not self.with_mask:\n return bbox_results\n else:\n segm_results = self.simple_test_mask(\n x, img_metas, det_bboxes, det_labels, rescale=rescale)\n return list(zip(bbox_results, segm_results))\n\n def aug_test(self, x, proposal_list, img_metas, rescale=False):\n \"\"\"Test with augmentations.\n\n If rescale is False, then returned bboxes and masks will fit the scale\n of imgs[0].\n \"\"\"\n det_bboxes, det_labels = self.aug_test_bboxes(x, img_metas,\n proposal_list,\n self.test_cfg)\n if rescale:\n _det_bboxes = det_bboxes\n else:\n _det_bboxes = det_bboxes.clone()\n _det_bboxes[:, :4] *= det_bboxes.new_tensor(\n img_metas[0][0]['scale_factor'])\n bbox_results = bbox2result(_det_bboxes, det_labels,\n self.bbox_head.num_classes)\n\n # det_bboxes always keep the original scale\n if self.with_mask:\n segm_results = self.aug_test_mask(x, img_metas, det_bboxes,\n det_labels)\n return [(bbox_results, segm_results)]\n else:\n return [bbox_results]\n\n def onnx_export(self, x, proposals, img_metas, rescale=False):\n \"\"\"Test without augmentation.\"\"\"\n assert self.with_bbox, 'Bbox head must be implemented.'\n det_bboxes, det_labels = self.bbox_onnx_export(\n x, img_metas, proposals, self.test_cfg, rescale=rescale)\n\n if not self.with_mask:\n return det_bboxes, det_labels\n else:\n segm_results = self.mask_onnx_export(\n x, img_metas, det_bboxes, det_labels, rescale=rescale)\n return det_bboxes, det_labels, segm_results\n\n def mask_onnx_export(self, x, img_metas, det_bboxes, det_labels, **kwargs):\n \"\"\"Export mask branch to onnx which supports batch inference.\n\n Args:\n x (tuple[Tensor]): Feature maps of all scale level.\n img_metas (list[dict]): Image meta info.\n det_bboxes (Tensor): Bboxes and corresponding scores.\n has shape [N, num_bboxes, 5].\n det_labels (Tensor): class labels of\n shape [N, num_bboxes].\n\n Returns:\n tuple[Tensor, Tensor]: bboxes of shape [N, num_bboxes, 5]\n and class labels of shape [N, num_bboxes].\n \"\"\"\n # image shapes of images in the batch\n\n if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):\n raise RuntimeError('[ONNX Error] Can not record MaskHead '\n 'as it has not been executed this time')\n batch_size = det_bboxes.size(0)\n # if det_bboxes is rescaled to the original image size, we need to\n # rescale it back to the testing scale to obtain RoIs.\n det_bboxes = det_bboxes[..., :4]\n batch_index = torch.arange(\n det_bboxes.size(0), device=det_bboxes.device).float().view(\n -1, 1, 1).expand(det_bboxes.size(0), det_bboxes.size(1), 1)\n mask_rois = torch.cat([batch_index, det_bboxes], dim=-1)\n mask_rois = mask_rois.view(-1, 5)\n mask_results = self._mask_forward(x, mask_rois)\n mask_pred = mask_results['mask_pred']\n max_shape = img_metas[0]['img_shape_for_onnx']\n num_det = det_bboxes.shape[1]\n det_bboxes = det_bboxes.reshape(-1, 4)\n det_labels = det_labels.reshape(-1)\n segm_results = self.mask_head.onnx_export(mask_pred, det_bboxes,\n det_labels, self.test_cfg,\n max_shape)\n segm_results = segm_results.reshape(batch_size, num_det, max_shape[0],\n max_shape[1])\n return segm_results\n\n def bbox_onnx_export(self, x, img_metas, proposals, rcnn_test_cfg,\n **kwargs):\n \"\"\"Export bbox branch to onnx which supports batch inference.\n\n Args:\n x (tuple[Tensor]): Feature maps of all scale level.\n img_metas (list[dict]): Image meta info.\n proposals (Tensor): Region proposals with\n batch dimension, has shape [N, num_bboxes, 5].\n rcnn_test_cfg (obj:`ConfigDict`): `test_cfg` of R-CNN.\n\n Returns:\n tuple[Tensor, Tensor]: bboxes of shape [N, num_bboxes, 5]\n and class labels of shape [N, num_bboxes].\n \"\"\"\n # get origin input shape to support onnx dynamic input shape\n assert len(\n img_metas\n ) == 1, 'Only support one input image while in exporting to ONNX'\n img_shapes = img_metas[0]['img_shape_for_onnx']\n\n rois = proposals\n batch_index = torch.arange(\n rois.size(0), device=rois.device).float().view(-1, 1, 1).expand(\n rois.size(0), rois.size(1), 1)\n rois = torch.cat([batch_index, rois[..., :4]], dim=-1)\n batch_size = rois.shape[0]\n num_proposals_per_img = rois.shape[1]\n\n # Eliminate the batch dimension\n rois = rois.view(-1, 5)\n bbox_results = self._bbox_forward(x, rois)\n cls_score = bbox_results['cls_score']\n bbox_pred = bbox_results['bbox_pred']\n\n # Recover the batch dimension\n rois = rois.reshape(batch_size, num_proposals_per_img, rois.size(-1))\n cls_score = cls_score.reshape(batch_size, num_proposals_per_img,\n cls_score.size(-1))\n\n bbox_pred = bbox_pred.reshape(batch_size, num_proposals_per_img,\n bbox_pred.size(-1))\n det_bboxes, det_labels = self.bbox_head.onnx_export(\n rois, cls_score, bbox_pred, img_shapes, cfg=rcnn_test_cfg)\n\n return det_bboxes, det_labels" }, { "identifier": "CascadeRoIHead", "path": "PointOBB/mmdet/models/roi_heads/cascade_roi_head.py", "snippet": "class CascadeRoIHead(BaseRoIHead, BBoxTestMixin, MaskTestMixin):\n \"\"\"Cascade roi head including one bbox head and one mask head.\n\n https://arxiv.org/abs/1712.00726\n \"\"\"\n\n def __init__(self,\n num_stages,\n stage_loss_weights,\n bbox_roi_extractor=None,\n bbox_head=None,\n mask_roi_extractor=None,\n mask_head=None,\n shared_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None,\n init_cfg=None):\n assert bbox_roi_extractor is not None\n assert bbox_head is not None\n assert shared_head is None, \\\n 'Shared head is not supported in Cascade RCNN anymore'\n\n self.num_stages = num_stages\n self.stage_loss_weights = stage_loss_weights\n super(CascadeRoIHead, self).__init__(\n bbox_roi_extractor=bbox_roi_extractor,\n bbox_head=bbox_head,\n mask_roi_extractor=mask_roi_extractor,\n mask_head=mask_head,\n shared_head=shared_head,\n train_cfg=train_cfg,\n test_cfg=test_cfg,\n pretrained=pretrained,\n init_cfg=init_cfg)\n\n def init_bbox_head(self, bbox_roi_extractor, bbox_head):\n \"\"\"Initialize box head and box roi extractor.\n\n Args:\n bbox_roi_extractor (dict): Config of box roi extractor.\n bbox_head (dict): Config of box in box head.\n \"\"\"\n self.bbox_roi_extractor = ModuleList()\n self.bbox_head = ModuleList()\n if not isinstance(bbox_roi_extractor, list):\n bbox_roi_extractor = [\n bbox_roi_extractor for _ in range(self.num_stages)\n ]\n if not isinstance(bbox_head, list):\n bbox_head = [bbox_head for _ in range(self.num_stages)]\n assert len(bbox_roi_extractor) == len(bbox_head) == self.num_stages\n for roi_extractor, head in zip(bbox_roi_extractor, bbox_head):\n self.bbox_roi_extractor.append(build_roi_extractor(roi_extractor))\n self.bbox_head.append(build_head(head))\n\n def init_mask_head(self, mask_roi_extractor, mask_head):\n \"\"\"Initialize mask head and mask roi extractor.\n\n Args:\n mask_roi_extractor (dict): Config of mask roi extractor.\n mask_head (dict): Config of mask in mask head.\n \"\"\"\n self.mask_head = nn.ModuleList()\n if not isinstance(mask_head, list):\n mask_head = [mask_head for _ in range(self.num_stages)]\n assert len(mask_head) == self.num_stages\n for head in mask_head:\n self.mask_head.append(build_head(head))\n if mask_roi_extractor is not None:\n self.share_roi_extractor = False\n self.mask_roi_extractor = ModuleList()\n if not isinstance(mask_roi_extractor, list):\n mask_roi_extractor = [\n mask_roi_extractor for _ in range(self.num_stages)\n ]\n assert len(mask_roi_extractor) == self.num_stages\n for roi_extractor in mask_roi_extractor:\n self.mask_roi_extractor.append(\n build_roi_extractor(roi_extractor))\n else:\n self.share_roi_extractor = True\n self.mask_roi_extractor = self.bbox_roi_extractor\n\n def init_assigner_sampler(self):\n \"\"\"Initialize assigner and sampler for each stage.\"\"\"\n self.bbox_assigner = []\n self.bbox_sampler = []\n if self.train_cfg is not None:\n for idx, rcnn_train_cfg in enumerate(self.train_cfg):\n self.bbox_assigner.append(\n build_assigner(rcnn_train_cfg.assigner))\n self.current_stage = idx\n self.bbox_sampler.append(\n build_sampler(rcnn_train_cfg.sampler, context=self))\n\n def forward_dummy(self, x, proposals):\n \"\"\"Dummy forward function.\"\"\"\n # bbox head\n outs = ()\n rois = bbox2roi([proposals])\n if self.with_bbox:\n for i in range(self.num_stages):\n bbox_results = self._bbox_forward(i, x, rois)\n outs = outs + (bbox_results['cls_score'],\n bbox_results['bbox_pred'])\n # mask heads\n if self.with_mask:\n mask_rois = rois[:100]\n for i in range(self.num_stages):\n mask_results = self._mask_forward(i, x, mask_rois)\n outs = outs + (mask_results['mask_pred'], )\n return outs\n\n def _bbox_forward(self, stage, x, rois):\n \"\"\"Box head forward function used in both training and testing.\"\"\"\n bbox_roi_extractor = self.bbox_roi_extractor[stage]\n bbox_head = self.bbox_head[stage]\n bbox_feats = bbox_roi_extractor(x[:bbox_roi_extractor.num_inputs],\n rois)\n # do not support caffe_c4 model anymore\n cls_score, bbox_pred = bbox_head(bbox_feats)\n\n bbox_results = dict(\n cls_score=cls_score, bbox_pred=bbox_pred, bbox_feats=bbox_feats)\n return bbox_results\n\n def _bbox_forward_train(self, stage, x, sampling_results, gt_bboxes,\n gt_labels, rcnn_train_cfg):\n \"\"\"Run forward function and calculate loss for box head in training.\"\"\"\n rois = bbox2roi([res.bboxes for res in sampling_results])\n bbox_results = self._bbox_forward(stage, x, rois)\n bbox_targets = self.bbox_head[stage].get_targets(\n sampling_results, gt_bboxes, gt_labels, rcnn_train_cfg)\n loss_bbox = self.bbox_head[stage].loss(bbox_results['cls_score'],\n bbox_results['bbox_pred'], rois,\n *bbox_targets)\n\n bbox_results.update(\n loss_bbox=loss_bbox, rois=rois, bbox_targets=bbox_targets)\n return bbox_results\n\n def _mask_forward(self, stage, x, rois):\n \"\"\"Mask head forward function used in both training and testing.\"\"\"\n mask_roi_extractor = self.mask_roi_extractor[stage]\n mask_head = self.mask_head[stage]\n mask_feats = mask_roi_extractor(x[:mask_roi_extractor.num_inputs],\n rois)\n # do not support caffe_c4 model anymore\n mask_pred = mask_head(mask_feats)\n\n mask_results = dict(mask_pred=mask_pred)\n return mask_results\n\n def _mask_forward_train(self,\n stage,\n x,\n sampling_results,\n gt_masks,\n rcnn_train_cfg,\n bbox_feats=None):\n \"\"\"Run forward function and calculate loss for mask head in\n training.\"\"\"\n pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])\n mask_results = self._mask_forward(stage, x, pos_rois)\n\n mask_targets = self.mask_head[stage].get_targets(\n sampling_results, gt_masks, rcnn_train_cfg)\n pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])\n loss_mask = self.mask_head[stage].loss(mask_results['mask_pred'],\n mask_targets, pos_labels)\n\n mask_results.update(loss_mask=loss_mask)\n return mask_results\n\n def forward_train(self,\n x,\n img_metas,\n proposal_list,\n gt_bboxes,\n gt_labels,\n gt_bboxes_ignore=None,\n gt_masks=None):\n \"\"\"\n Args:\n x (list[Tensor]): list of multi-level img features.\n img_metas (list[dict]): list of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmdet/datasets/pipelines/formatting.py:Collect`.\n proposals (list[Tensors]): list of region proposals.\n gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (list[Tensor]): class indices corresponding to each box\n gt_bboxes_ignore (None | list[Tensor]): specify which bounding\n boxes can be ignored when computing the loss.\n gt_masks (None | Tensor) : true segmentation masks for each box\n used if the architecture supports a segmentation task.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n losses = dict()\n for i in range(self.num_stages):\n self.current_stage = i\n rcnn_train_cfg = self.train_cfg[i]\n lw = self.stage_loss_weights[i]\n\n # assign gts and sample proposals\n sampling_results = []\n if self.with_bbox or self.with_mask:\n bbox_assigner = self.bbox_assigner[i]\n bbox_sampler = self.bbox_sampler[i]\n num_imgs = len(img_metas)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n\n for j in range(num_imgs):\n assign_result = bbox_assigner.assign(\n proposal_list[j], gt_bboxes[j], gt_bboxes_ignore[j],\n gt_labels[j])\n sampling_result = bbox_sampler.sample(\n assign_result,\n proposal_list[j],\n gt_bboxes[j],\n gt_labels[j],\n feats=[lvl_feat[j][None] for lvl_feat in x])\n sampling_results.append(sampling_result)\n\n # bbox head forward and loss\n bbox_results = self._bbox_forward_train(i, x, sampling_results,\n gt_bboxes, gt_labels,\n rcnn_train_cfg)\n\n for name, value in bbox_results['loss_bbox'].items():\n losses[f's{i}.{name}'] = (\n value * lw if 'loss' in name else value)\n\n # mask head forward and loss\n if self.with_mask:\n mask_results = self._mask_forward_train(\n i, x, sampling_results, gt_masks, rcnn_train_cfg,\n bbox_results['bbox_feats'])\n for name, value in mask_results['loss_mask'].items():\n losses[f's{i}.{name}'] = (\n value * lw if 'loss' in name else value)\n\n # refine bboxes\n if i < self.num_stages - 1:\n pos_is_gts = [res.pos_is_gt for res in sampling_results]\n # bbox_targets is a tuple\n roi_labels = bbox_results['bbox_targets'][0]\n with torch.no_grad():\n roi_labels = torch.where(\n roi_labels == self.bbox_head[i].num_classes,\n bbox_results['cls_score'][:, :-1].argmax(1),\n roi_labels)\n proposal_list = self.bbox_head[i].refine_bboxes(\n bbox_results['rois'], roi_labels,\n bbox_results['bbox_pred'], pos_is_gts, img_metas)\n\n return losses\n\n def simple_test(self, x, proposal_list, img_metas, rescale=False):\n \"\"\"Test without augmentation.\"\"\"\n assert self.with_bbox, 'Bbox head must be implemented.'\n num_imgs = len(proposal_list)\n img_shapes = tuple(meta['img_shape'] for meta in img_metas)\n ori_shapes = tuple(meta['ori_shape'] for meta in img_metas)\n scale_factors = tuple(meta['scale_factor'] for meta in img_metas)\n\n # \"ms\" in variable names means multi-stage\n ms_bbox_result = {}\n ms_segm_result = {}\n ms_scores = []\n rcnn_test_cfg = self.test_cfg\n\n rois = bbox2roi(proposal_list)\n for i in range(self.num_stages):\n bbox_results = self._bbox_forward(i, x, rois)\n\n # split batch bbox prediction back to each image\n cls_score = bbox_results['cls_score']\n bbox_pred = bbox_results['bbox_pred']\n num_proposals_per_img = tuple(\n len(proposals) for proposals in proposal_list)\n rois = rois.split(num_proposals_per_img, 0)\n cls_score = cls_score.split(num_proposals_per_img, 0)\n if isinstance(bbox_pred, torch.Tensor):\n bbox_pred = bbox_pred.split(num_proposals_per_img, 0)\n else:\n bbox_pred = self.bbox_head[i].bbox_pred_split(\n bbox_pred, num_proposals_per_img)\n ms_scores.append(cls_score)\n\n if i < self.num_stages - 1:\n bbox_label = [s[:, :-1].argmax(dim=1) for s in cls_score]\n rois = torch.cat([\n self.bbox_head[i].regress_by_class(rois[j], bbox_label[j],\n bbox_pred[j],\n img_metas[j])\n for j in range(num_imgs)\n ])\n\n # average scores of each image by stages\n cls_score = [\n sum([score[i] for score in ms_scores]) / float(len(ms_scores))\n for i in range(num_imgs)\n ]\n\n # apply bbox post-processing to each image individually\n det_bboxes = []\n det_labels = []\n for i in range(num_imgs):\n det_bbox, det_label = self.bbox_head[-1].get_bboxes(\n rois[i],\n cls_score[i],\n bbox_pred[i],\n img_shapes[i],\n scale_factors[i],\n rescale=rescale,\n cfg=rcnn_test_cfg)\n det_bboxes.append(det_bbox)\n det_labels.append(det_label)\n\n if torch.onnx.is_in_onnx_export():\n return det_bboxes, det_labels\n bbox_results = [\n bbox2result(det_bboxes[i], det_labels[i],\n self.bbox_head[-1].num_classes)\n for i in range(num_imgs)\n ]\n ms_bbox_result['ensemble'] = bbox_results\n\n if self.with_mask:\n if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):\n mask_classes = self.mask_head[-1].num_classes\n segm_results = [[[] for _ in range(mask_classes)]\n for _ in range(num_imgs)]\n else:\n if rescale and not isinstance(scale_factors[0], float):\n scale_factors = [\n torch.from_numpy(scale_factor).to(det_bboxes[0].device)\n for scale_factor in scale_factors\n ]\n _bboxes = [\n det_bboxes[i][:, :4] *\n scale_factors[i] if rescale else det_bboxes[i][:, :4]\n for i in range(len(det_bboxes))\n ]\n mask_rois = bbox2roi(_bboxes)\n num_mask_rois_per_img = tuple(\n _bbox.size(0) for _bbox in _bboxes)\n aug_masks = []\n for i in range(self.num_stages):\n mask_results = self._mask_forward(i, x, mask_rois)\n mask_pred = mask_results['mask_pred']\n # split batch mask prediction back to each image\n mask_pred = mask_pred.split(num_mask_rois_per_img, 0)\n aug_masks.append(\n [m.sigmoid().cpu().numpy() for m in mask_pred])\n\n # apply mask post-processing to each image individually\n segm_results = []\n for i in range(num_imgs):\n if det_bboxes[i].shape[0] == 0:\n segm_results.append(\n [[]\n for _ in range(self.mask_head[-1].num_classes)])\n else:\n aug_mask = [mask[i] for mask in aug_masks]\n merged_masks = merge_aug_masks(\n aug_mask, [[img_metas[i]]] * self.num_stages,\n rcnn_test_cfg)\n segm_result = self.mask_head[-1].get_seg_masks(\n merged_masks, _bboxes[i], det_labels[i],\n rcnn_test_cfg, ori_shapes[i], scale_factors[i],\n rescale)\n segm_results.append(segm_result)\n ms_segm_result['ensemble'] = segm_results\n\n if self.with_mask:\n results = list(\n zip(ms_bbox_result['ensemble'], ms_segm_result['ensemble']))\n else:\n results = ms_bbox_result['ensemble']\n\n return results\n\n def aug_test(self, features, proposal_list, img_metas, rescale=False):\n \"\"\"Test with augmentations.\n\n If rescale is False, then returned bboxes and masks will fit the scale\n of imgs[0].\n \"\"\"\n rcnn_test_cfg = self.test_cfg\n aug_bboxes = []\n aug_scores = []\n for x, img_meta in zip(features, img_metas):\n # only one image in the batch\n img_shape = img_meta[0]['img_shape']\n scale_factor = img_meta[0]['scale_factor']\n flip = img_meta[0]['flip']\n flip_direction = img_meta[0]['flip_direction']\n\n proposals = bbox_mapping(proposal_list[0][:, :4], img_shape,\n scale_factor, flip, flip_direction)\n # \"ms\" in variable names means multi-stage\n ms_scores = []\n\n rois = bbox2roi([proposals])\n for i in range(self.num_stages):\n bbox_results = self._bbox_forward(i, x, rois)\n ms_scores.append(bbox_results['cls_score'])\n\n if i < self.num_stages - 1:\n bbox_label = bbox_results['cls_score'][:, :-1].argmax(\n dim=1)\n rois = self.bbox_head[i].regress_by_class(\n rois, bbox_label, bbox_results['bbox_pred'],\n img_meta[0])\n\n cls_score = sum(ms_scores) / float(len(ms_scores))\n bboxes, scores = self.bbox_head[-1].get_bboxes(\n rois,\n cls_score,\n bbox_results['bbox_pred'],\n img_shape,\n scale_factor,\n rescale=False,\n cfg=None)\n aug_bboxes.append(bboxes)\n aug_scores.append(scores)\n\n # after merging, bboxes will be rescaled to the original image size\n merged_bboxes, merged_scores = merge_aug_bboxes(\n aug_bboxes, aug_scores, img_metas, rcnn_test_cfg)\n det_bboxes, det_labels = multiclass_nms(merged_bboxes, merged_scores,\n rcnn_test_cfg.score_thr,\n rcnn_test_cfg.nms,\n rcnn_test_cfg.max_per_img)\n\n bbox_result = bbox2result(det_bboxes, det_labels,\n self.bbox_head[-1].num_classes)\n\n if self.with_mask:\n if det_bboxes.shape[0] == 0:\n segm_result = [[]\n for _ in range(self.mask_head[-1].num_classes)]\n else:\n aug_masks = []\n aug_img_metas = []\n for x, img_meta in zip(features, img_metas):\n img_shape = img_meta[0]['img_shape']\n scale_factor = img_meta[0]['scale_factor']\n flip = img_meta[0]['flip']\n flip_direction = img_meta[0]['flip_direction']\n _bboxes = bbox_mapping(det_bboxes[:, :4], img_shape,\n scale_factor, flip, flip_direction)\n mask_rois = bbox2roi([_bboxes])\n for i in range(self.num_stages):\n mask_results = self._mask_forward(i, x, mask_rois)\n aug_masks.append(\n mask_results['mask_pred'].sigmoid().cpu().numpy())\n aug_img_metas.append(img_meta)\n merged_masks = merge_aug_masks(aug_masks, aug_img_metas,\n self.test_cfg)\n\n ori_shape = img_metas[0][0]['ori_shape']\n segm_result = self.mask_head[-1].get_seg_masks(\n merged_masks,\n det_bboxes,\n det_labels,\n rcnn_test_cfg,\n ori_shape,\n scale_factor=1.0,\n rescale=False)\n return [(bbox_result, segm_result)]\n else:\n return [bbox_result]" }, { "identifier": "BBoxTestMixin", "path": "PointOBB/mmdet/models/roi_heads/test_mixins.py", "snippet": "class BBoxTestMixin:\n\n if sys.version_info >= (3, 7):\n\n async def async_test_bboxes(self,\n x,\n img_metas,\n proposals,\n rcnn_test_cfg,\n rescale=False,\n **kwargs):\n \"\"\"Asynchronized test for box head without augmentation.\"\"\"\n rois = bbox2roi(proposals)\n roi_feats = self.bbox_roi_extractor(\n x[:len(self.bbox_roi_extractor.featmap_strides)], rois)\n if self.with_shared_head:\n roi_feats = self.shared_head(roi_feats)\n sleep_interval = rcnn_test_cfg.get('async_sleep_interval', 0.017)\n\n async with completed(\n __name__, 'bbox_head_forward',\n sleep_interval=sleep_interval):\n cls_score, bbox_pred = self.bbox_head(roi_feats)\n\n img_shape = img_metas[0]['img_shape']\n scale_factor = img_metas[0]['scale_factor']\n det_bboxes, det_labels = self.bbox_head.get_bboxes(\n rois,\n cls_score,\n bbox_pred,\n img_shape,\n scale_factor,\n rescale=rescale,\n cfg=rcnn_test_cfg)\n return det_bboxes, det_labels\n\n def simple_test_bboxes(self,\n x,\n img_metas,\n proposals,\n rcnn_test_cfg,\n rescale=False):\n \"\"\"Test only det bboxes without augmentation.\n\n Args:\n x (tuple[Tensor]): Feature maps of all scale level.\n img_metas (list[dict]): Image meta info.\n proposals (List[Tensor]): Region proposals.\n rcnn_test_cfg (obj:`ConfigDict`): `test_cfg` of R-CNN.\n rescale (bool): If True, return boxes in original image space.\n Default: False.\n\n Returns:\n tuple[list[Tensor], list[Tensor]]: The first list contains\n the boxes of the corresponding image in a batch, each\n tensor has the shape (num_boxes, 5) and last dimension\n 5 represent (tl_x, tl_y, br_x, br_y, score). Each Tensor\n in the second list is the labels with shape (num_boxes, ).\n The length of both lists should be equal to batch_size.\n \"\"\"\n # get origin input shape to support onnx dynamic input shape\n\n img_shapes = tuple(meta['img_shape'] for meta in img_metas)\n scale_factors = tuple(meta['scale_factor'] for meta in img_metas)\n\n # The length of proposals of different batches may be different.\n # In order to form a batch, a padding operation is required.\n max_size = max([proposal.size(0) for proposal in proposals])\n # padding to form a batch\n for i, proposal in enumerate(proposals):\n supplement = proposal.new_full(\n (max_size - proposal.size(0), proposal.size(1)), 0)\n proposals[i] = torch.cat((supplement, proposal), dim=0)\n rois = torch.stack(proposals, dim=0)\n\n batch_index = torch.arange(\n rois.size(0), device=rois.device).float().view(-1, 1, 1).expand(\n rois.size(0), rois.size(1), 1)\n rois = torch.cat([batch_index, rois[..., :4]], dim=-1)\n batch_size = rois.shape[0]\n num_proposals_per_img = rois.shape[1]\n\n # Eliminate the batch dimension\n rois = rois.view(-1, 5)\n bbox_results = self._bbox_forward(x, rois)\n cls_score = bbox_results['cls_score']\n bbox_pred = bbox_results['bbox_pred']\n\n # Recover the batch dimension\n rois = rois.reshape(batch_size, num_proposals_per_img, rois.size(-1))\n cls_score = cls_score.reshape(batch_size, num_proposals_per_img,\n cls_score.size(-1))\n\n # remove padding, ignore batch_index when calculating mask\n supplement_mask = rois.abs()[..., 1:].sum(dim=-1) == 0\n cls_score[supplement_mask, :] = 0\n\n # bbox_pred would be None in some detector when with_reg is False,\n # e.g. Grid R-CNN.\n if bbox_pred is not None:\n # the bbox prediction of some detectors like SABL is not Tensor\n if isinstance(bbox_pred, torch.Tensor):\n bbox_pred = bbox_pred.reshape(batch_size,\n num_proposals_per_img,\n bbox_pred.size(-1))\n bbox_pred[supplement_mask, :] = 0\n else:\n # TODO: Looking forward to a better way\n # TODO move these special process to a corresponding head\n # For SABL\n bbox_preds = self.bbox_head.bbox_pred_split(\n bbox_pred, num_proposals_per_img)\n # apply bbox post-processing to each image individually\n det_bboxes = []\n det_labels = []\n for i in range(len(proposals)):\n # remove padding\n supplement_mask = proposals[i].abs().sum(dim=-1) == 0\n for bbox in bbox_preds[i]:\n bbox[supplement_mask] = 0\n det_bbox, det_label = self.bbox_head.get_bboxes(\n rois[i],\n cls_score[i],\n bbox_preds[i],\n img_shapes[i],\n scale_factors[i],\n rescale=rescale,\n cfg=rcnn_test_cfg)\n det_bboxes.append(det_bbox)\n det_labels.append(det_label)\n return det_bboxes, det_labels\n else:\n bbox_pred = None\n\n return self.bbox_head.get_bboxes(\n rois,\n cls_score,\n bbox_pred,\n img_shapes,\n scale_factors,\n rescale=rescale,\n cfg=rcnn_test_cfg)\n\n def aug_test_bboxes(self, feats, img_metas, proposal_list, rcnn_test_cfg):\n \"\"\"Test det bboxes with test time augmentation.\"\"\"\n aug_bboxes = []\n aug_scores = []\n for x, img_meta in zip(feats, img_metas):\n # only one image in the batch\n img_shape = img_meta[0]['img_shape']\n scale_factor = img_meta[0]['scale_factor']\n flip = img_meta[0]['flip']\n flip_direction = img_meta[0]['flip_direction']\n # TODO more flexible\n proposals = bbox_mapping(proposal_list[0][:, :4], img_shape,\n scale_factor, flip, flip_direction, img_meta[0].get('tile_offset', None)) # add by hui\n rois = bbox2roi([proposals])\n bbox_results = self._bbox_forward(x, rois)\n bboxes, scores = self.bbox_head.get_bboxes(\n rois,\n bbox_results['cls_score'],\n bbox_results['bbox_pred'],\n img_shape,\n scale_factor,\n rescale=False,\n cfg=None)\n aug_bboxes.append(bboxes)\n aug_scores.append(scores)\n # after merging, bboxes will be rescaled to the original image size\n merged_bboxes, merged_scores = merge_aug_bboxes(\n aug_bboxes, aug_scores, img_metas, rcnn_test_cfg)\n det_bboxes, det_labels = multiclass_nms(merged_bboxes, merged_scores,\n rcnn_test_cfg.score_thr,\n rcnn_test_cfg.nms,\n rcnn_test_cfg.max_per_img)\n return det_bboxes, det_labels" }, { "identifier": "MaskTestMixin", "path": "PointOBB/mmdet/models/roi_heads/test_mixins.py", "snippet": "class MaskTestMixin:\n\n if sys.version_info >= (3, 7):\n\n async def async_test_mask(self,\n x,\n img_metas,\n det_bboxes,\n det_labels,\n rescale=False,\n mask_test_cfg=None):\n \"\"\"Asynchronized test for mask head without augmentation.\"\"\"\n # image shape of the first image in the batch (only one)\n ori_shape = img_metas[0]['ori_shape']\n scale_factor = img_metas[0]['scale_factor']\n if det_bboxes.shape[0] == 0:\n segm_result = [[] for _ in range(self.mask_head.num_classes)]\n else:\n if rescale:\n scale_factor = det_bboxes.new_tensor(scale_factor)\n _bboxes = (\n det_bboxes[:, :4] *\n scale_factor if rescale else det_bboxes)\n mask_rois = bbox2roi([_bboxes])\n mask_feats = self.mask_roi_extractor(\n x[:len(self.mask_roi_extractor.featmap_strides)],\n mask_rois)\n\n if self.with_shared_head:\n mask_feats = self.shared_head(mask_feats)\n if mask_test_cfg and mask_test_cfg.get('async_sleep_interval'):\n sleep_interval = mask_test_cfg['async_sleep_interval']\n else:\n sleep_interval = 0.035\n async with completed(\n __name__,\n 'mask_head_forward',\n sleep_interval=sleep_interval):\n mask_pred = self.mask_head(mask_feats)\n segm_result = self.mask_head.get_seg_masks(\n mask_pred, _bboxes, det_labels, self.test_cfg, ori_shape,\n scale_factor, rescale)\n return segm_result\n\n def simple_test_mask(self,\n x,\n img_metas,\n det_bboxes,\n det_labels,\n rescale=False):\n \"\"\"Simple test for mask head without augmentation.\"\"\"\n # image shapes of images in the batch\n ori_shapes = tuple(meta['ori_shape'] for meta in img_metas)\n scale_factors = tuple(meta['scale_factor'] for meta in img_metas)\n\n if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):\n segm_results = [[[] for _ in range(self.mask_head.num_classes)]\n for _ in range(len(det_bboxes))]\n return segm_results\n\n # The length of proposals of different batches may be different.\n # In order to form a batch, a padding operation is required.\n\n # padding to form a batch\n max_size = max([bboxes.size(0) for bboxes in det_bboxes])\n for i, (bbox, label) in enumerate(zip(det_bboxes, det_labels)):\n supplement_bbox = bbox.new_full(\n (max_size - bbox.size(0), bbox.size(1)), 0)\n supplement_label = label.new_full((max_size - label.size(0), ), 0)\n det_bboxes[i] = torch.cat((supplement_bbox, bbox), dim=0)\n det_labels[i] = torch.cat((supplement_label, label), dim=0)\n det_bboxes = torch.stack(det_bboxes, dim=0)\n det_labels = torch.stack(det_labels, dim=0)\n\n batch_size = det_bboxes.size(0)\n num_proposals_per_img = det_bboxes.shape[1]\n\n # if det_bboxes is rescaled to the original image size, we need to\n # rescale it back to the testing scale to obtain RoIs.\n det_bboxes = det_bboxes[..., :4]\n if rescale:\n scale_factors = det_bboxes.new_tensor(scale_factors)\n det_bboxes = det_bboxes * scale_factors.unsqueeze(1)\n\n batch_index = torch.arange(\n det_bboxes.size(0), device=det_bboxes.device).float().view(\n -1, 1, 1).expand(det_bboxes.size(0), det_bboxes.size(1), 1)\n mask_rois = torch.cat([batch_index, det_bboxes], dim=-1)\n mask_rois = mask_rois.view(-1, 5)\n mask_results = self._mask_forward(x, mask_rois)\n mask_pred = mask_results['mask_pred']\n\n # Recover the batch dimension\n mask_preds = mask_pred.reshape(batch_size, num_proposals_per_img,\n *mask_pred.shape[1:])\n\n # apply mask post-processing to each image individually\n segm_results = []\n for i in range(batch_size):\n mask_pred = mask_preds[i]\n det_bbox = det_bboxes[i]\n det_label = det_labels[i]\n\n # remove padding\n supplement_mask = det_bbox.abs().sum(dim=-1) != 0\n mask_pred = mask_pred[supplement_mask]\n det_bbox = det_bbox[supplement_mask]\n det_label = det_label[supplement_mask]\n\n if det_label.shape[0] == 0:\n segm_results.append([[]\n for _ in range(self.mask_head.num_classes)\n ])\n else:\n segm_result = self.mask_head.get_seg_masks(\n mask_pred, det_bbox, det_label, self.test_cfg,\n ori_shapes[i], scale_factors[i], rescale)\n segm_results.append(segm_result)\n return segm_results\n\n def aug_test_mask(self, feats, img_metas, det_bboxes, det_labels):\n \"\"\"Test for mask head with test time augmentation.\"\"\"\n if det_bboxes.shape[0] == 0:\n segm_result = [[] for _ in range(self.mask_head.num_classes)]\n else:\n aug_masks = []\n for x, img_meta in zip(feats, img_metas):\n img_shape = img_meta[0]['img_shape']\n scale_factor = img_meta[0]['scale_factor']\n flip = img_meta[0]['flip']\n flip_direction = img_meta[0]['flip_direction']\n _bboxes = bbox_mapping(det_bboxes[:, :4], img_shape,\n scale_factor, flip, flip_direction, img_meta[0].get('tile_offset', None)) # add by hui\n mask_rois = bbox2roi([_bboxes])\n mask_results = self._mask_forward(x, mask_rois)\n # convert to numpy array to save memory\n aug_masks.append(\n mask_results['mask_pred'].sigmoid().cpu().numpy())\n merged_masks = merge_aug_masks(aug_masks, img_metas, self.test_cfg)\n\n ori_shape = img_metas[0][0]['ori_shape']\n scale_factor = det_bboxes.new_ones(4)\n segm_result = self.mask_head.get_seg_masks(\n merged_masks,\n det_bboxes,\n det_labels,\n self.test_cfg,\n ori_shape,\n scale_factor=scale_factor,\n rescale=False)\n return segm_result" }, { "identifier": "obb2xyxy", "path": "PointOBB/mmdet/models/detectors/utils.py", "snippet": "def obb2xyxy(rbboxes, version='oc'):\n \"\"\"Convert oriented bounding boxes to horizontal bounding boxes.\n\n Args:\n obbs (torch.Tensor): [x_ctr,y_ctr,w,h,angle]\n version (Str): angle representations.\n\n Returns:\n hbbs (torch.Tensor): [x_lt,y_lt,x_rb,y_rb]\n \"\"\"\n if version == 'oc':\n results = obb2xyxy_oc(rbboxes)\n elif version == 'le135':\n results = obb2xyxy_le135(rbboxes)\n elif version == 'le90':\n results = obb2xyxy_le90(rbboxes)\n else:\n raise NotImplementedError\n return results" }, { "identifier": "regularize_boxes", "path": "PointOBB/mmdet/models/detectors/utils.py", "snippet": "def regularize_boxes(boxes,\n pattern: str = None,\n width_longer: bool = True,\n start_angle: float = -90) -> Tensor:\n \"\"\"Regularize rotated boxes.\n\n Due to the angle periodicity, one rotated box can be represented in\n many different (x, y, w, h, t). To make each rotated box unique,\n ``regularize_boxes`` will take the remainder of the angle divided by\n 180 degrees.\n\n However, after taking the remainder of the angle, there are still two\n representations for one rotate box. For example, (0, 0, 4, 5, 0.5) and\n (0, 0, 5, 4, 0.5 + pi/2) are the same areas in the image. To solve the\n problem, the code will swap edges w.r.t ``width_longer``:\n\n - width_longer=True: Make sure the width is longer than the height. If\n not, swap the width and height. The angle ranges in [start_angle,\n start_angle + 180). For the above example, the rotated box will be\n represented as (0, 0, 5, 4, 0.5 + pi/2).\n - width_longer=False: Make sure the angle is lower than\n start_angle+pi/2. If not, swap the width and height. The angle\n ranges in [start_angle, start_angle + 90). For the above example,\n the rotated box will be represented as (0, 0, 4, 5, 0.5).\n\n For convenience, three commonly used patterns are preset in\n ``regualrize_boxes``:\n\n - 'oc': OpenCV Definition. Has the same box representation as\n ``cv2.minAreaRect`` the angle ranges in [-90, 0). Equal to set\n width_longer=False and start_angle=-90.\n - 'le90': Long Edge Definition (90). the angle ranges in [-90, 90).\n The width is always longer than the height. Equal to set\n width_longer=True and start_angle=-90.\n - 'le135': Long Edge Definition (135). the angle ranges in [-45, 135).\n The width is always longer than the height. Equal to set\n width_longer=True and start_angle=-45.\n\n Args:\n pattern (str, Optional): Regularization pattern. Can only be 'oc',\n 'le90', or 'le135'. Defaults to None.\n width_longer (bool): Whether to make sure width is larger than\n height. Defaults to True.\n start_angle (float): The starting angle of the box angle\n represented in degrees. Defaults to -90.\n\n Returns:\n Tensor: Regularized box tensor.\n \"\"\"\n\n if pattern is not None:\n if pattern == 'oc':\n width_longer, start_angle = False, -90\n elif pattern == 'le90':\n width_longer, start_angle = True, -90\n elif pattern == 'le135':\n width_longer, start_angle = True, -45\n else:\n raise ValueError(\"pattern only can be 'oc', 'le90', and\"\n f\"'le135', but get {pattern}.\")\n start_angle = start_angle / 180 * np.pi\n\n x, y, w, h, t = boxes.unbind(dim=-1)\n if width_longer:\n # swap edge and angle if h >= w\n w_ = torch.where(w > h, w, h)\n h_ = torch.where(w > h, h, w)\n t = torch.where(w > h, t, t + np.pi / 2)\n t = ((t - start_angle) % np.pi) + start_angle\n else:\n # swap edge and angle if angle > pi/2\n t = ((t - start_angle) % np.pi)\n w_ = torch.where(t < np.pi / 2, w, h)\n h_ = torch.where(t < np.pi / 2, h, w)\n t = torch.where(t < np.pi / 2, t, t - np.pi / 2) + start_angle\n obb = torch.stack([x, y, w_, h_, t], dim=-1)\n return obb" }, { "identifier": "reduce_mean", "path": "PointOBB/mmdet/models/detectors/utils.py", "snippet": "def reduce_mean(tensor):\n \"\"\"\"Obtain the mean of tensor on different GPUs.\"\"\"\n if not (dist.is_available() and dist.is_initialized()):\n return tensor\n tensor = tensor.clone()\n dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM)\n return tensor" }, { "identifier": "obb2poly_np", "path": "PointOBB/mmdet/models/detectors/utils.py", "snippet": "def obb2poly_np(rbboxes, version='oc'):\n \"\"\"Convert oriented bounding boxes to polygons.\n\n Args:\n obbs (ndarray): [x_ctr,y_ctr,w,h,angle]\n version (Str): angle representations.\n\n Returns:\n polys (ndarray): [x0,y0,x1,y1,x2,y2,x3,y3]\n \"\"\"\n if version == 'oc':\n results = obb2poly_np_oc(rbboxes)\n elif version == 'le135':\n results = obb2poly_np_le135(rbboxes)\n elif version == 'le90':\n results = obb2poly_np_le90(rbboxes)\n else:\n raise NotImplementedError\n return results" } ]
import math import torch import torch.nn.functional as F import torch.nn as nn import copy import numpy as np import cv2 from mmdet.core import bbox2result, bbox2roi, rbbox2roi, build_assigner, build_sampler, multi_apply from ..builder import HEADS, MODELS, build_head, build_roi_extractor, build_loss from .standard_roi_head import StandardRoIHead from .cascade_roi_head import CascadeRoIHead from mmdet.core.bbox.iou_calculators import bbox_overlaps from .test_mixins import BBoxTestMixin, MaskTestMixin from mmdet.core.bbox import bbox_xyxy_to_cxcywh from mmdet.core.bbox.transforms import rbbox2result from mmcv.cnn import Scale, ConvModule from mmcv.ops import box_iou_rotated from typing import Any, List, Sequence, Tuple, Union from torch import Tensor from mmdet.models.utils.base_bbox_coder import BaseBBoxCoder from ..detectors.utils import obb2xyxy, regularize_boxes, reduce_mean, obb2poly_np
16,264
def __init__(self, bbox_roi_extractor, num_stages, bbox_head, top_k=7, with_atten=None, conv_cfg=None, norm_cfg=None, scale_angle: bool = True, stacked_convs = 4, loss_symmetry_ss=dict( type='SmoothL1Loss', loss_weight=1.0, beta=0.1), angle_coder=dict( type='PSCCoder', angle_version='le90', dual_freq=False, num_step=3, thr_mod=0), angle_version = 'le90', use_angle_loss = True, add_angle_pred_begin = False, not_use_rot_mil = False, detach_angle_head = False, rotation_agnostic_classes = None, agnostic_resize_classes = None, cls_scores_weight = 1.0, ins_scores_weight = 1.0, **kwargs): super(PointOBBHead, self).__init__(bbox_roi_extractor=bbox_roi_extractor, bbox_head=bbox_head, **kwargs) self.threshold = 0.3 self.merge_mode = 'weighted_clsins' self.test_mean_iou = False # self.test_mean_iou = True self.sum_iou = 0 self.sum_num = 0 self.num_stages = num_stages self.topk1 = top_k # 7 self.topk2 = top_k # 7 self.featmap_strides = bbox_roi_extractor.featmap_strides self.with_atten = with_atten self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.in_channels=256 self.feat_channels=256 self.stacked_convs=stacked_convs self.is_scale_angle = scale_angle self.angle_coder = HEADS.build(angle_coder) self.loss_symmetry_ss = build_loss(loss_symmetry_ss) self.angle_version = angle_version self.rotation_agnostic_classes = rotation_agnostic_classes self.agnostic_resize_classes = agnostic_resize_classes self.add_angle_pred_begin = add_angle_pred_begin self.use_angle_loss = use_angle_loss self.not_use_rot_mil = not_use_rot_mil self.detach_angle_head = detach_angle_head self.cls_scores_weight = cls_scores_weight self.ins_scores_weight = ins_scores_weight self.num_classes = self.bbox_head.num_classes self._init_layers() def _init_layers(self): """Initialize layers of the head.""" self.relu = nn.ReLU(inplace=True) self.cls_convs = nn.ModuleList() for i in range(self.stacked_convs): chn = self.in_channels if i == 0 else self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg)) self.conv_angle = nn.Conv2d( self.feat_channels, self.angle_coder.encode_size, 3, padding=1) if self.is_scale_angle: self.scale_angle = Scale(1.0) def angle_forward(self, feats: Tuple[Tensor]) -> Tuple[List[Tensor], List[Tensor]]: angle_results = [] for feat in feats: if self.detach_angle_head: feat_detach = feat.clone().detach() single_angle_pred = self.angle_forward_single(feat_detach) else: single_angle_pred = self.angle_forward_single(feat) angle_results.append(single_angle_pred) return tuple(angle_results) def angle_forward_single(self, x: Tensor): cls_feat = x for cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat) # cls_score = self.conv_cls(cls_feat) angle_pred = self.conv_angle(cls_feat) if self.is_scale_angle: angle_pred = self.scale_angle(angle_pred).float() return angle_pred def init_assigner_sampler(self): """Initialize assigner and sampler.""" self.bbox_assigner = None self.bbox_sampler = None if self.train_cfg: self.bbox_assigner = build_assigner(self.train_cfg.assigner) self.bbox_sampler = build_sampler( self.train_cfg.sampler, context=self) def init_bbox_head(self, bbox_roi_extractor, bbox_head): """Initialize ``bbox_head``""" self.bbox_roi_extractor = build_roi_extractor(bbox_roi_extractor) # self.cdb = build_head(dict(type='ConvConcreteDB', cfg=None, planes=256))
RangeType = Sequence[Tuple[int, int]] INF = 1e8 def meshgrid(x: Tensor, y: Tensor, row_major: bool = True) -> Tuple[Tensor, Tensor]: yy, xx = torch.meshgrid(y, x) if row_major: # warning .flatten() would cause error in ONNX exportingF # have to use reshape here return xx.reshape(-1), yy.reshape(-1) else: return yy.reshape(-1), xx.reshape(-1) def obb2cxcywh_le90(obboxes): """Convert oriented bounding boxes to horizontal bounding boxes. Args: obbs (torch.Tensor): [x_ctr,y_ctr,w,h,angle] Returns: hbbs (torch.Tensor): [x_lt,y_lt,x_rb,y_rb] """ center, w, h, theta = torch.split(obboxes, [2, 1, 1, 1], dim=-1) Cos, Sin = torch.cos(theta), torch.sin(theta) x_bias = torch.abs(w / 2 * Cos) + torch.abs(h / 2 * Sin) y_bias = torch.abs(w / 2 * Sin) + torch.abs(h / 2 * Cos) bias = torch.cat([x_bias, y_bias], dim=-1) wh = bias * 2 return torch.cat([center, wh, torch.zeros_like(theta)], dim=-1) @HEADS.register_module() class PSCCoder(BaseBBoxCoder): """Phase-Shifting Coder. `Phase-Shifting Coder (PSC) <https://arxiv.org/abs/2211.06368>`. Args: angle_version (str): Angle definition. Only 'le90' is supported at present. dual_freq (bool, optional): Use dual frequency. Default: True. num_step (int, optional): Number of phase steps. Default: 3. thr_mod (float): Threshold of modulation. Default: 0.47. """ def __init__(self, angle_version: str, dual_freq: bool = True, num_step: int = 3, thr_mod: float = 0.47): super().__init__() self.angle_version = angle_version assert angle_version in ['le90'] self.dual_freq = dual_freq self.num_step = num_step self.thr_mod = thr_mod if self.dual_freq: self.encode_size = 2 * self.num_step else: self.encode_size = self.num_step self.coef_sin = torch.tensor( tuple( torch.sin(torch.tensor(2 * k * math.pi / self.num_step)) for k in range(self.num_step))) self.coef_cos = torch.tensor( tuple( torch.cos(torch.tensor(2 * k * math.pi / self.num_step)) for k in range(self.num_step))) def encode(self, angle_targets: Tensor) -> Tensor: """Phase-Shifting Encoder. Args: angle_targets (Tensor): Angle offset for each scale level. Has shape (num_anchors * H * W, 1) Returns: list[Tensor]: The psc coded data (phase-shifting patterns) for each scale level. Has shape (num_anchors * H * W, encode_size) """ phase_targets = angle_targets * 2 phase_shift_targets = tuple( torch.cos(phase_targets + 2 * math.pi * x / self.num_step) for x in range(self.num_step)) # Dual-freq PSC for square-like problem if self.dual_freq: phase_targets = angle_targets * 4 phase_shift_targets += tuple( torch.cos(phase_targets + 2 * math.pi * x / self.num_step) for x in range(self.num_step)) return torch.cat(phase_shift_targets, axis=-1) def decode(self, angle_preds: Tensor, keepdim: bool = False) -> Tensor: """Phase-Shifting Decoder. Args: angle_preds (Tensor): The psc coded data (phase-shifting patterns) for each scale level. Has shape (num_anchors * H * W, encode_size) keepdim (bool): Whether the output tensor has dim retained or not. Returns: list[Tensor]: Angle offset for each scale level. Has shape (num_anchors * H * W, 1) when keepdim is true, (num_anchors * H * W) otherwise """ self.coef_sin = self.coef_sin.to(angle_preds) self.coef_cos = self.coef_cos.to(angle_preds) phase_sin = torch.sum( angle_preds[:, 0:self.num_step] * self.coef_sin, dim=-1, keepdim=keepdim) phase_cos = torch.sum( angle_preds[:, 0:self.num_step] * self.coef_cos, dim=-1, keepdim=keepdim) phase_mod = phase_cos**2 + phase_sin**2 phase = -torch.atan2(phase_sin, phase_cos) # In range [-pi,pi) if self.dual_freq: phase_sin = torch.sum( angle_preds[:, self.num_step:(2 * self.num_step)] * self.coef_sin, dim=-1, keepdim=keepdim) phase_cos = torch.sum( angle_preds[:, self.num_step:(2 * self.num_step)] * self.coef_cos, dim=-1, keepdim=keepdim) phase_mod = phase_cos**2 + phase_sin**2 phase2 = -torch.atan2(phase_sin, phase_cos) / 2 # Phase unwarpping, dual freq mixing # Angle between phase and phase2 is obtuse angle idx = torch.cos(phase) * torch.cos(phase2) + torch.sin( phase) * torch.sin(phase2) < 0 # Add pi to phase2 and keep it in range [-pi,pi) phase2[idx] = phase2[idx] % (2 * math.pi) - math.pi phase = phase2 # Set the angle of isotropic objects to zero phase[phase_mod < self.thr_mod] *= 0 angle_pred = phase / 2 return angle_pred @HEADS.register_module() class PointOBBHead(StandardRoIHead): """Simplest base roi head including one bbox head and one mask head.""" def __init__(self, bbox_roi_extractor, num_stages, bbox_head, top_k=7, with_atten=None, conv_cfg=None, norm_cfg=None, scale_angle: bool = True, stacked_convs = 4, loss_symmetry_ss=dict( type='SmoothL1Loss', loss_weight=1.0, beta=0.1), angle_coder=dict( type='PSCCoder', angle_version='le90', dual_freq=False, num_step=3, thr_mod=0), angle_version = 'le90', use_angle_loss = True, add_angle_pred_begin = False, not_use_rot_mil = False, detach_angle_head = False, rotation_agnostic_classes = None, agnostic_resize_classes = None, cls_scores_weight = 1.0, ins_scores_weight = 1.0, **kwargs): super(PointOBBHead, self).__init__(bbox_roi_extractor=bbox_roi_extractor, bbox_head=bbox_head, **kwargs) self.threshold = 0.3 self.merge_mode = 'weighted_clsins' self.test_mean_iou = False # self.test_mean_iou = True self.sum_iou = 0 self.sum_num = 0 self.num_stages = num_stages self.topk1 = top_k # 7 self.topk2 = top_k # 7 self.featmap_strides = bbox_roi_extractor.featmap_strides self.with_atten = with_atten self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.in_channels=256 self.feat_channels=256 self.stacked_convs=stacked_convs self.is_scale_angle = scale_angle self.angle_coder = HEADS.build(angle_coder) self.loss_symmetry_ss = build_loss(loss_symmetry_ss) self.angle_version = angle_version self.rotation_agnostic_classes = rotation_agnostic_classes self.agnostic_resize_classes = agnostic_resize_classes self.add_angle_pred_begin = add_angle_pred_begin self.use_angle_loss = use_angle_loss self.not_use_rot_mil = not_use_rot_mil self.detach_angle_head = detach_angle_head self.cls_scores_weight = cls_scores_weight self.ins_scores_weight = ins_scores_weight self.num_classes = self.bbox_head.num_classes self._init_layers() def _init_layers(self): """Initialize layers of the head.""" self.relu = nn.ReLU(inplace=True) self.cls_convs = nn.ModuleList() for i in range(self.stacked_convs): chn = self.in_channels if i == 0 else self.feat_channels self.cls_convs.append( ConvModule( chn, self.feat_channels, 3, stride=1, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg)) self.conv_angle = nn.Conv2d( self.feat_channels, self.angle_coder.encode_size, 3, padding=1) if self.is_scale_angle: self.scale_angle = Scale(1.0) def angle_forward(self, feats: Tuple[Tensor]) -> Tuple[List[Tensor], List[Tensor]]: angle_results = [] for feat in feats: if self.detach_angle_head: feat_detach = feat.clone().detach() single_angle_pred = self.angle_forward_single(feat_detach) else: single_angle_pred = self.angle_forward_single(feat) angle_results.append(single_angle_pred) return tuple(angle_results) def angle_forward_single(self, x: Tensor): cls_feat = x for cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat) # cls_score = self.conv_cls(cls_feat) angle_pred = self.conv_angle(cls_feat) if self.is_scale_angle: angle_pred = self.scale_angle(angle_pred).float() return angle_pred def init_assigner_sampler(self): """Initialize assigner and sampler.""" self.bbox_assigner = None self.bbox_sampler = None if self.train_cfg: self.bbox_assigner = build_assigner(self.train_cfg.assigner) self.bbox_sampler = build_sampler( self.train_cfg.sampler, context=self) def init_bbox_head(self, bbox_roi_extractor, bbox_head): """Initialize ``bbox_head``""" self.bbox_roi_extractor = build_roi_extractor(bbox_roi_extractor) # self.cdb = build_head(dict(type='ConvConcreteDB', cfg=None, planes=256))
self.bbox_head = build_head(bbox_head)
2
2023-11-20 07:50:12+00:00
24k
ModelTC/EasyLLM
llm/models/hf_models/qwen_vl/modeling_qwen.py
[ { "identifier": "QWenConfig", "path": "llm/models/hf_models/qwen_vl/configuration_qwen.py", "snippet": "class QWenConfig(PretrainedConfig):\n model_type = \"qwen\"\n keys_to_ignore_at_inference = [\"past_key_values\"]\n\n def __init__(\n self,\n vocab_size=151936,\n hidden_size=4096,\n num_hidden_layers=32,\n num_attention_heads=32,\n emb_dropout_prob=0.0,\n attn_dropout_prob=0.0,\n layer_norm_epsilon=1e-6,\n initializer_range=0.02,\n max_position_embeddings=8192,\n scale_attn_weights=True,\n use_cache=True,\n bf16=False,\n fp16=False,\n fp32=False,\n kv_channels=128,\n rotary_pct=1.0,\n rotary_emb_base=10000,\n use_dynamic_ntk=True,\n use_logn_attn=True,\n use_flash_attn=\"auto\",\n intermediate_size=22016,\n no_bias=True,\n tie_word_embeddings=False,\n **kwargs,\n ):\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.intermediate_size = intermediate_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.emb_dropout_prob = emb_dropout_prob\n self.attn_dropout_prob = attn_dropout_prob\n self.layer_norm_epsilon = layer_norm_epsilon\n self.initializer_range = initializer_range\n self.scale_attn_weights = scale_attn_weights\n self.use_cache = use_cache\n self.max_position_embeddings = max_position_embeddings\n self.bf16 = bf16\n self.fp16 = fp16\n self.fp32 = fp32\n self.kv_channels = kv_channels\n self.rotary_pct = rotary_pct\n self.rotary_emb_base = rotary_emb_base\n self.use_dynamic_ntk = use_dynamic_ntk\n self.use_logn_attn = use_logn_attn\n self.use_flash_attn = use_flash_attn\n self.no_bias = no_bias\n super().__init__(\n tie_word_embeddings=tie_word_embeddings,\n **kwargs\n )" }, { "identifier": "make_context", "path": "llm/models/hf_models/qwen_vl/qwen_generation_utils.py", "snippet": "def make_context(\n tokenizer: PreTrainedTokenizer,\n query: str,\n history: List[Tuple[str, str]] = None,\n system: str = \"\",\n max_window_size: int = 6144,\n chat_format: str = \"chatml\",\n):\n if history is None:\n history = []\n\n if chat_format == \"chatml\":\n im_start, im_end = \"<|im_start|>\", \"<|im_end|>\"\n im_start_tokens = [tokenizer.im_start_id]\n im_end_tokens = [tokenizer.im_end_id]\n nl_tokens = tokenizer.encode(\"\\n\")\n\n def _tokenize_str(role, content):\n return f\"{role}\\n{content}\", tokenizer.encode(\n role, allowed_special=set(tokenizer.IMAGE_ST)\n ) + nl_tokens + tokenizer.encode(content, allowed_special=set(tokenizer.IMAGE_ST))\n\n system_text, system_tokens_part = _tokenize_str(\"system\", system)\n system_tokens = im_start_tokens + system_tokens_part + im_end_tokens\n\n raw_text = \"\"\n context_tokens = []\n\n for turn_query, turn_response in reversed(history):\n query_text, query_tokens_part = _tokenize_str(\"user\", turn_query)\n query_tokens = im_start_tokens + query_tokens_part + im_end_tokens\n if turn_response is not None:\n response_text, response_tokens_part = _tokenize_str(\n \"assistant\", turn_response\n )\n response_tokens = im_start_tokens + response_tokens_part + im_end_tokens\n\n next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens\n prev_chat = (\n f\"\\n{im_start}{query_text}{im_end}\\n{im_start}{response_text}{im_end}\"\n )\n else:\n next_context_tokens = nl_tokens + query_tokens + nl_tokens\n prev_chat = f\"\\n{im_start}{query_text}{im_end}\\n\"\n\n current_context_size = (\n len(system_tokens) + len(next_context_tokens) + len(context_tokens)\n )\n if current_context_size < max_window_size:\n context_tokens = next_context_tokens + context_tokens\n raw_text = prev_chat + raw_text\n else:\n break\n\n context_tokens = system_tokens + context_tokens\n raw_text = f\"{im_start}{system_text}{im_end}\" + raw_text\n context_tokens += (\n nl_tokens\n + im_start_tokens\n + _tokenize_str(\"user\", query)[1]\n + im_end_tokens\n + nl_tokens\n + im_start_tokens\n + tokenizer.encode(\"assistant\")\n + nl_tokens\n )\n raw_text += f\"\\n{im_start}user\\n{query}{im_end}\\n{im_start}assistant\\n\"\n\n elif chat_format == \"raw\":\n raw_text = query\n context_tokens = tokenizer.encode(raw_text)\n else:\n raise NotImplementedError(f\"Unknown chat format {chat_format!r}\")\n\n return raw_text, context_tokens" }, { "identifier": "HistoryType", "path": "llm/models/hf_models/qwen/qwen_generation_utils.py", "snippet": "def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:\ndef get_ltor_masks_and_position_ids(\n data,\n eod_token,\n reset_position_ids,\n reset_attention_mask,\n eod_mask_loss,\n):\ndef get_batch(context_tokens: torch.LongTensor, eod_id: int):\ndef get_stop_words_ids(chat_format, tokenizer):\ndef make_context(\n tokenizer: PreTrainedTokenizer,\n query: str,\n history: List[Tuple[str, str]] = None,\n system: str = \"\",\n max_window_size: int = 6144,\n chat_format: str = \"chatml\",\n):\n def _tokenize_str(role, content):\ndef _decode_default(\n tokens: List[int],\n *,\n stop_words: List[str],\n eod_words: List[str],\n tokenizer: PreTrainedTokenizer,\n raw_text_len: int,\n verbose: bool = False,\n return_end_reason: bool = False,\n errors: str = 'replace',\n):\ndef _decode_chatml(\n tokens: List[int],\n *,\n stop_words: List[str],\n eod_token_ids: List[int],\n tokenizer: PreTrainedTokenizer,\n raw_text_len: int,\n context_length: int,\n verbose: bool = False,\n return_end_reason: bool = False,\n errors: str = 'replace'\n):\ndef decode_tokens(\n tokens: Union[torch.LongTensor, TokensType],\n tokenizer: PreTrainedTokenizer,\n raw_text_len: int,\n context_length: int,\n chat_format: str,\n verbose: bool = False,\n return_end_reason: bool = False,\n errors: str = \"replace\",\n) -> str:\n def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):\n def __call__(\n self, input_ids: torch.LongTensor, scores: torch.FloatTensor\n ) -> torch.FloatTensor:\n def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:\n def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:\ndef top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float(\"Inf\")):\ndef switch(val1, val2, boolean):\nclass StopWordsLogitsProcessor(LogitsProcessor):" }, { "identifier": "VisionTransformer", "path": "llm/models/hf_models/qwen_vl/visual.py", "snippet": "class VisionTransformer(nn.Module):\n\n def __init__(\n self,\n image_size: int,\n patch_size: int,\n width: int,\n layers: int,\n heads: int,\n mlp_ratio: float,\n n_queries: int = 256,\n output_dim: int = 512,\n **kwargs\n ):\n super().__init__()\n image_height, image_width = self.image_size = (image_size, image_size)\n patch_height, patch_width = self.patch_size = (patch_size, patch_size)\n self.grid_size = (image_height // patch_height, image_width // patch_width)\n self.output_dim = output_dim\n\n mean = (0.48145466, 0.4578275, 0.40821073)\n std = (0.26862954, 0.26130258, 0.27577711)\n self.image_transform = transforms.Compose([\n transforms.Resize(\n (image_size, image_size),\n interpolation=InterpolationMode.BICUBIC\n ),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std),\n ])\n\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)\n\n # class embeddings and positional embeddings\n scale = width ** -0.5\n self.positional_embedding = nn.Parameter(scale * torch.randn(256, width))\n\n norm_layer = partial(nn.LayerNorm, eps=1e-6)\n act_layer = nn.GELU\n\n self.ln_pre = norm_layer(width)\n self.transformer = TransformerBlock(\n width,\n layers,\n heads,\n mlp_ratio,\n act_layer=act_layer,\n norm_layer=norm_layer,\n )\n\n self.attn_pool = Resampler(\n grid_size=int(math.sqrt(n_queries)),\n embed_dim=output_dim,\n num_heads=output_dim // 128,\n kv_dim=width,\n norm_layer=norm_layer,\n )\n self.ln_post = norm_layer(output_dim)\n self.proj = nn.Parameter((output_dim ** -0.5) * torch.randn(output_dim, output_dim))\n\n def forward(self, x: torch.Tensor):\n x = x.to(\n dtype=self.transformer.get_cast_dtype(),\n device=self.transformer.get_cast_device(),\n )\n # to patches\n x = self.conv1(x) # shape = [*, width, grid, grid]\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n\n x = x + get_abs_pos(self.positional_embedding, x.size(1))\n\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer(x)\n x = x.permute(1, 0, 2) # LND -> NLD\n\n x = self.attn_pool(x)\n x = self.ln_post(x)\n x = x @ self.proj\n\n return x\n\n def encode(self, image_paths: List[str]):\n images = []\n for image_path in image_paths:\n if image_path.startswith(\"http://\") or image_path.startswith(\"https://\"):\n image = Image.open(requests.get(image_path, stream=True).raw)\n else:\n image = Image.open(image_path)\n image = image.convert(\"RGB\")\n images.append(self.image_transform(image))\n images = torch.stack(images, dim=0)\n return self(images)" }, { "identifier": "RMSNorm", "path": "llm/models/hf_models/qwen/modeling_qwen.py", "snippet": "class RMSNorm(torch.nn.Module):\n def __init__(self, dim: int, eps: float = 1e-6):\n super().__init__()\n self.eps = eps\n self.weight = nn.Parameter(torch.ones(dim))\n\n def _norm(self, x):\n return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n\n def forward(self, x):\n if rms_norm is not None and x.is_cuda:\n return rms_norm(x, self.weight, self.eps)\n else:\n output = self._norm(x.float()).type_as(x)\n return output * self.weight" }, { "identifier": "apply_rotary_pos_emb", "path": "llm/models/hf_models/qwen/modeling_qwen.py", "snippet": "def apply_rotary_pos_emb(t, freqs):\n cos, sin = freqs\n if apply_rotary_emb_func is not None and t.is_cuda:\n t_ = t.float()\n cos = cos.squeeze(0).squeeze(1)[:, : cos.shape[-1] // 2]\n sin = sin.squeeze(0).squeeze(1)[:, : sin.shape[-1] // 2]\n output = apply_rotary_emb_func(t_, cos, sin).type_as(t)\n return output\n else:\n rot_dim = freqs[0].shape[-1]\n cos, sin = freqs\n t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]\n t_ = t_.float()\n t_pass_ = t_pass_.float()\n t_ = (t_ * cos) + (_rotate_half(t_) * sin)\n return torch.cat((t_, t_pass_), dim=-1).type_as(t)" }, { "identifier": "QWenMLP", "path": "llm/models/hf_models/qwen/modeling_qwen.py", "snippet": "class QWenMLP(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.w1 = nn.Linear(\n config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias\n )\n self.w2 = nn.Linear(\n config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias\n )\n ff_dim_in = config.intermediate_size // 2\n self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)\n\n def forward(self, hidden_states):\n a1 = self.w1(hidden_states)\n a2 = self.w2(hidden_states)\n intermediate_parallel = a1 * F.silu(a2)\n output = self.c_proj(intermediate_parallel)\n return output" }, { "identifier": "QWenAttention", "path": "llm/models/hf_models/qwen/modeling_qwen.py", "snippet": "class QWenAttention(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n self.register_buffer(\"masked_bias\", torch.tensor(-1e4), persistent=False)\n self.seq_length = config.seq_length\n\n self.hidden_size = config.hidden_size\n self.split_size = config.hidden_size\n self.num_heads = config.num_attention_heads\n self.head_dim = self.hidden_size // self.num_heads\n\n self.use_flash_attn = config.use_flash_attn\n self.scale_attn_weights = True\n\n self.projection_size = config.kv_channels * config.num_attention_heads\n\n assert self.projection_size % config.num_attention_heads == 0\n self.hidden_size_per_attention_head = (\n self.projection_size // config.num_attention_heads\n )\n\n self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)\n\n self.c_proj = nn.Linear(\n config.hidden_size, self.projection_size, bias=not config.no_bias\n )\n\n self.is_fp32 = not (config.bf16 or config.fp16)\n if (\n self.use_flash_attn\n and flash_attn_unpadded_func is not None\n and not self.is_fp32\n ):\n self.core_attention_flash = FlashSelfAttention(\n causal=True, attention_dropout=config.attn_dropout_prob\n )\n self.bf16 = config.bf16\n\n self.use_dynamic_ntk = config.use_dynamic_ntk\n self.use_logn_attn = config.use_logn_attn\n\n logn_list = [\n math.log(i, self.seq_length) if i > self.seq_length else 1\n for i in range(1, 32768)\n ]\n logn_tensor = torch.tensor(logn_list)[None, :, None, None]\n self.register_buffer(\"logn_tensor\", logn_tensor, persistent=False)\n\n self.attn_dropout = nn.Dropout(config.attn_dropout_prob)\n self.softmax_in_fp32 = config.softmax_in_fp32 if hasattr(config, 'softmax_in_fp32') else False\n self.use_cache_quantization = config.use_cache_quantization if hasattr(\n config, 'use_cache_quantization') else False\n self.use_cache_kernel = config.use_cache_kernel if hasattr(config, 'use_cache_kernel') else False\n cache_dtype = torch.float\n if self.bf16:\n cache_dtype = torch.bfloat16\n elif config.fp16:\n cache_dtype = torch.float16\n self.cache_qmax = torch.tensor(torch.iinfo(torch.uint8).max, dtype=cache_dtype)\n self.cache_qmin = torch.tensor(torch.iinfo(torch.uint8).min, dtype=cache_dtype)\n\n if config.use_cache_quantization and config.use_cache_kernel:\n try:\n from .cpp_kernels import cache_autogptq_cuda_256\n self.cache_kernels = cache_autogptq_cuda_256\n except ImportError:\n self.cache_kernels = None\n\n def _attn(self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None):\n device = query.device\n if self.use_cache_quantization:\n qk, qk_scale, qk_zero = key\n if self.use_cache_kernel and self.cache_kernels is not None:\n shape = query.shape[:-1] + (qk.shape[-2],)\n attn_weights = torch.zeros(shape, dtype=torch.float16, device=device)\n self.cache_kernels.vecquant8matmul_batched_faster_old(\n query.contiguous() if query.dtype == torch.float16 else query.to(torch.float16).contiguous(),\n qk.transpose(-1, -2).contiguous(),\n attn_weights,\n qk_scale.contiguous() if qk_scale.dtype == torch.float16 else qk_scale.to(torch.float16).contiguous(),\n qk_zero.contiguous()if qk_zero.dtype == torch.float16 else qk_zero.to(torch.float16).contiguous())\n # attn_weights = attn_weights.to(query.dtype).contiguous()\n else:\n key = dequantize_cache_torch(qk, qk_scale, qk_zero)\n attn_weights = torch.matmul(query, key.transpose(-1, -2))\n else:\n attn_weights = torch.matmul(query, key.transpose(-1, -2))\n\n if self.scale_attn_weights:\n if self.use_cache_quantization:\n size_temp = value[0].size(-1)\n else:\n size_temp = value.size(-1)\n attn_weights = attn_weights / torch.full(\n [],\n size_temp ** 0.5,\n dtype=attn_weights.dtype,\n device=attn_weights.device,\n )\n if self.use_cache_quantization:\n query_length, key_length = query.size(-2), key[0].size(-2)\n else:\n query_length, key_length = query.size(-2), key.size(-2)\n causal_mask = registered_causal_mask[\n :, :, key_length - query_length: key_length, :key_length\n ]\n mask_value = torch.finfo(attn_weights.dtype).min\n mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(\n attn_weights.device\n )\n attn_weights = torch.where(\n causal_mask, attn_weights.to(attn_weights.dtype), mask_value\n )\n\n if attention_mask is not None:\n attn_weights = attn_weights + attention_mask\n\n if self.softmax_in_fp32:\n attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1)\n else:\n attn_weights = nn.functional.softmax(attn_weights, dim=-1)\n\n attn_weights = attn_weights.type(query.dtype)\n attn_weights = self.attn_dropout(attn_weights)\n\n if head_mask is not None:\n attn_weights = attn_weights * head_mask\n\n if self.use_cache_quantization:\n qv, qv_scale, qv_zero = value\n if self.use_cache_kernel and self.cache_kernels is not None:\n shape = attn_weights.shape[:-1] + (query.shape[-1],)\n attn_output = torch.zeros(shape, dtype=torch.float16, device=device)\n self.cache_kernels.vecquant8matmul_batched_column_compression_faster_old(\n attn_weights.contiguous() if attn_weights.dtype == torch.float16 else attn_weights.to(torch.float16).contiguous(),\n qv.contiguous(), # dtype: int32\n attn_output,\n qv_scale.contiguous() if qv_scale.dtype == torch.float16 else qv_scale.to(torch.float16).contiguous(),\n qv_zero.contiguous() if qv_zero.dtype == torch.float16 else qv_zero.to(torch.float16).contiguous())\n if attn_output.dtype != query.dtype:\n attn_output = attn_output.to(query.dtype)\n attn_weights = attn_weights.to(query.dtype)\n else:\n value = dequantize_cache_torch(qv, qv_scale, qv_zero)\n attn_output = torch.matmul(attn_weights, value)\n else:\n attn_output = torch.matmul(attn_weights, value)\n\n attn_output = attn_output.transpose(1, 2)\n\n return attn_output, attn_weights\n\n def _upcast_and_reordered_attn(\n self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None\n ):\n bsz, num_heads, q_seq_len, dk = query.size()\n _, _, k_seq_len, _ = key.size()\n\n attn_weights = torch.empty(\n bsz * num_heads,\n q_seq_len,\n k_seq_len,\n dtype=torch.float32,\n device=query.device,\n )\n\n scale_factor = 1.0\n if self.scale_attn_weights:\n scale_factor /= float(value.size(-1)) ** 0.5\n\n with autocast(enabled=False):\n q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(\n -1, dk, k_seq_len\n )\n attn_weights = torch.baddbmm(\n attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor\n )\n attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)\n\n query_length, key_length = query.size(-2), key.size(-2)\n causal_mask = registered_causal_mask[\n :, :, key_length - query_length: key_length, :key_length\n ]\n mask_value = torch.finfo(attn_weights.dtype).min\n mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(\n attn_weights.device\n )\n attn_weights = torch.where(causal_mask, attn_weights, mask_value)\n\n if attention_mask is not None:\n attn_weights = attn_weights + attention_mask\n\n attn_weights = nn.functional.softmax(attn_weights, dim=-1)\n\n if attn_weights.dtype != torch.float32:\n raise RuntimeError(\n \"Error with upcasting, attn_weights does not have dtype torch.float32\"\n )\n attn_weights = attn_weights.type(value.dtype)\n attn_weights = self.attn_dropout(attn_weights)\n\n if head_mask is not None:\n attn_weights = attn_weights * head_mask\n\n attn_output = torch.matmul(attn_weights, value)\n\n return attn_output, attn_weights\n\n def _split_heads(self, tensor, num_heads, attn_head_size):\n new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)\n tensor = tensor.view(new_shape)\n return tensor\n\n def _merge_heads(self, tensor, num_heads, attn_head_size):\n tensor = tensor.contiguous()\n new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)\n return tensor.view(new_shape)\n\n def forward(\n self,\n hidden_states: Optional[Tuple[torch.FloatTensor]],\n rotary_pos_emb_list: Optional[List[List[torch.Tensor]]] = None,\n registered_causal_mask: Optional[torch.Tensor] = None,\n layer_past: Optional[Tuple[torch.Tensor]] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n output_attentions: Optional[bool] = False,\n use_cache: Optional[bool] = False,\n ):\n mixed_x_layer = self.c_attn(hidden_states)\n\n query, key, value = mixed_x_layer.split(self.split_size, dim=2)\n\n query = self._split_heads(query, self.num_heads, self.head_dim)\n key = self._split_heads(key, self.num_heads, self.head_dim)\n value = self._split_heads(value, self.num_heads, self.head_dim)\n\n if rotary_pos_emb_list is not None:\n cur_len = query.shape[1]\n if len(rotary_pos_emb_list) == 1:\n rotary_pos_emb = rotary_pos_emb_list[0]\n rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]\n rotary_pos_emb = (rotary_pos_emb,) * 2\n q_pos_emb, k_pos_emb = rotary_pos_emb\n # Slice the pos emb for current inference\n query = apply_rotary_pos_emb(query, q_pos_emb)\n key = apply_rotary_pos_emb(key, k_pos_emb)\n else:\n query_list = []\n key_list = []\n for i, rotary_pos_emb in enumerate(rotary_pos_emb_list):\n rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]\n rotary_pos_emb = (rotary_pos_emb,) * 2\n q_pos_emb, k_pos_emb = rotary_pos_emb\n # Slice the pos emb for current inference\n query_list += [apply_rotary_pos_emb(query[i:i + 1, :, :], q_pos_emb)]\n key_list += [apply_rotary_pos_emb(key[i:i + 1, :, :], k_pos_emb)]\n query = torch.cat(query_list, dim=0)\n key = torch.cat(key_list, dim=0)\n\n if self.use_cache_quantization:\n key = quantize_cache_v(key.permute(0, 2, 1, 3),\n bits=8,\n qmin=self.cache_qmin,\n qmax=self.cache_qmax)\n value = quantize_cache_v(value.permute(0, 2, 1, 3),\n bits=8,\n qmin=self.cache_qmin,\n qmax=self.cache_qmax)\n\n if layer_past is not None:\n past_key, past_value = layer_past[0], layer_past[1]\n if self.use_cache_quantization:\n # use_cache_quantization:\n # present=((q_key,key_scale,key_zero_point),\n # (q_value,value_scale,value_zero_point))\n key = (torch.cat((past_key[0], key[0]), dim=2),\n torch.cat((past_key[1], key[1]), dim=2),\n torch.cat((past_key[2], key[2]), dim=2))\n value = (torch.cat((past_value[0], value[0]), dim=2),\n torch.cat((past_value[1], value[1]), dim=2),\n torch.cat((past_value[2], value[2]), dim=2))\n else:\n # not use_cache_quantization:\n # present=(key,value)\n key = torch.cat((past_key, key), dim=1)\n value = torch.cat((past_value, value), dim=1)\n\n if use_cache:\n present = (key, value)\n else:\n present = None\n\n if self.use_logn_attn and not self.training:\n if self.use_cache_quantization:\n seq_start = key[0].size(2) - query.size(1)\n seq_end = key[0].size(2)\n else:\n seq_start = key.size(1) - query.size(1)\n seq_end = key.size(1)\n logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :].type_as(query)\n query = query * logn_tensor.expand_as(query)\n\n if (\n self.use_flash_attn\n and flash_attn_unpadded_func is not None\n and not self.is_fp32\n and query.is_cuda\n ):\n q, k, v = query, key, value\n attn_output = self.core_attention_flash(q, k, v, attention_mask=attention_mask)\n else:\n query = query.permute(0, 2, 1, 3)\n if not self.use_cache_quantization:\n key = key.permute(0, 2, 1, 3)\n value = value.permute(0, 2, 1, 3)\n if (\n registered_causal_mask is None\n and self.use_flash_attn\n and flash_attn_unpadded_func is not None\n and not self.is_fp32\n and not query.is_cuda\n ):\n raise Exception(_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED)\n\n if not self.use_cache_quantization and SUPPORT_TORCH2:\n causal_mask = registered_causal_mask[\n :, :, key.size(-2) - query.size(-2): key.size(-2), :key.size(-2)\n ]\n if attention_mask is not None:\n attention_mask = attention_mask.expand(\n -1, -1, causal_mask.size(2), -1\n ).masked_fill(~causal_mask, torch.finfo(query.dtype).min)\n else:\n attention_mask = causal_mask\n attn_output = F.scaled_dot_product_attention(\n query, key, value, attn_mask=attention_mask\n ).transpose(1, 2)\n attn_weight = None\n else:\n attn_output, attn_weight = self._attn(\n query, key, value, registered_causal_mask, attention_mask, head_mask\n )\n context_layer = self._merge_heads(\n attn_output, self.num_heads, self.head_dim\n )\n\n attn_output = self.c_proj(context_layer)\n\n outputs = (attn_output, present)\n if output_attentions:\n if (\n self.use_flash_attn\n and flash_attn_unpadded_func is not None\n and not self.is_fp32\n ):\n raise ValueError(\"Cannot output attentions while using flash-attn\")\n else:\n outputs += (attn_weight,)\n\n return outputs" }, { "identifier": "QWenModel", "path": "llm/models/hf_models/qwen/modeling_qwen.py", "snippet": "class QWenModel(QWenPreTrainedModel):\n _keys_to_ignore_on_load_missing = [\"attn.masked_bias\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.vocab_size = config.vocab_size\n self.num_hidden_layers = config.num_hidden_layers\n self.embed_dim = config.hidden_size\n self.use_cache_quantization = self.config.use_cache_quantization if hasattr(\n self.config, 'use_cache_quantization') else False\n\n self.gradient_checkpointing = False\n self.use_dynamic_ntk = config.use_dynamic_ntk\n self.seq_length = config.seq_length\n\n self.wte = nn.Embedding(self.vocab_size, self.embed_dim)\n\n self.drop = nn.Dropout(config.emb_dropout_prob)\n\n if config.rotary_pct == 1.0:\n self.rotary_ndims = None\n else:\n assert config.rotary_pct < 1\n self.rotary_ndims = int(\n config.kv_channels * config.rotary_pct\n )\n dim = (\n self.rotary_ndims\n if self.rotary_ndims is not None\n else config.kv_channels\n )\n self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)\n\n self.use_flash_attn = config.use_flash_attn\n self.is_fp32 = not (config.bf16 or config.fp16)\n if (\n self.use_flash_attn\n and flash_attn_unpadded_func is not None\n and not self.is_fp32\n ):\n self.registered_causal_mask = None\n else:\n max_positions = config.max_position_embeddings\n self.register_buffer(\n \"registered_causal_mask\",\n torch.tril(\n torch.ones((max_positions, max_positions), dtype=torch.bool)\n ).view(1, 1, max_positions, max_positions),\n persistent=False,\n )\n\n self.h = nn.ModuleList(\n [\n QWenBlock(\n config\n )\n for i in range(config.num_hidden_layers)\n ]\n )\n self.ln_f = RMSNorm(\n self.embed_dim,\n eps=config.layer_norm_epsilon,\n )\n\n self.post_init()\n\n def get_input_embeddings(self):\n return self.wte\n\n def set_input_embeddings(self, new_embeddings):\n self.wte = new_embeddings\n\n def get_ntk_alpha(self, true_seq_len):\n context_value = math.log(true_seq_len / self.seq_length, 2) + 1\n ntk_alpha = 2 ** math.ceil(context_value) - 1\n ntk_alpha = max(ntk_alpha, 1)\n return ntk_alpha\n\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ):\n output_attentions = (\n output_attentions\n if output_attentions is not None\n else self.config.output_attentions\n )\n output_hidden_states = (\n output_hidden_states\n if output_hidden_states is not None\n else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = (\n return_dict if return_dict is not None else self.config.use_return_dict\n )\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\n \"You cannot specify both input_ids and inputs_embeds at the same time\"\n )\n elif input_ids is not None:\n input_shape = input_ids.size()\n input_ids = input_ids.view(-1, input_shape[-1])\n batch_size = input_ids.shape[0]\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n batch_size = inputs_embeds.shape[0]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n if token_type_ids is not None:\n token_type_ids = token_type_ids.view(-1, input_shape[-1])\n if position_ids is not None:\n position_ids = position_ids.view(-1, input_shape[-1])\n\n if past_key_values is None:\n past_length = 0\n past_key_values = tuple([None] * len(self.h))\n else:\n if self.use_cache_quantization:\n past_length = past_key_values[0][0][0].size(2)\n else:\n past_length = past_key_values[0][0].size(-2)\n if position_ids is None:\n position_ids = torch.arange(\n past_length,\n input_shape[-1] + past_length,\n dtype=torch.long,\n device=device,\n )\n position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])\n\n if attention_mask is not None:\n if batch_size <= 0:\n raise ValueError(\"batch_size has to be defined and > 0\")\n attention_mask = attention_mask.view(batch_size, -1)\n attention_mask = attention_mask[:, None, None, :]\n attention_mask = attention_mask.to(dtype=self.dtype)\n attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min\n\n encoder_attention_mask = None\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n if inputs_embeds is None:\n inputs_embeds = self.wte(input_ids)\n hidden_states = inputs_embeds\n\n kv_seq_len = hidden_states.size()[1]\n if past_key_values[0] is not None:\n # past key values[0][0] shape: bs * seq_len * head_num * dim\n if self.use_cache_quantization:\n kv_seq_len += past_key_values[0][0][0].shape[2]\n else:\n kv_seq_len += past_key_values[0][0].shape[1]\n\n if self.training or not self.use_dynamic_ntk:\n ntk_alpha_list = [1.0]\n elif kv_seq_len != hidden_states.size()[1]:\n ntk_alpha_list = self.rotary_emb._ntk_alpha_cached_list\n else:\n ntk_alpha_list = []\n if attention_mask is not None and kv_seq_len > self.seq_length:\n true_seq_lens = attention_mask.squeeze(1).squeeze(1).eq(0).sum(dim=-1, dtype=torch.int32)\n for i in range(hidden_states.size()[0]):\n true_seq_len = true_seq_lens[i].item()\n ntk_alpha = self.get_ntk_alpha(true_seq_len)\n ntk_alpha_list.append(ntk_alpha)\n else:\n ntk_alpha = self.get_ntk_alpha(kv_seq_len)\n ntk_alpha_list.append(ntk_alpha)\n self.rotary_emb._ntk_alpha_cached_list = ntk_alpha_list\n rotary_pos_emb_list = [\n self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha) for ntk_alpha in ntk_alpha_list\n ]\n\n hidden_states = self.drop(hidden_states)\n output_shape = input_shape + (hidden_states.size(-1),)\n\n if self.gradient_checkpointing and self.training:\n if use_cache:\n logger.warning_once(\n \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...\"\n )\n use_cache = False\n\n presents = () if use_cache else None\n all_self_attentions = () if output_attentions else None\n all_hidden_states = () if output_hidden_states else None\n for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n # None for past_key_value\n return module(*inputs, use_cache, output_attentions)\n\n return custom_forward\n\n outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(block),\n hidden_states,\n rotary_pos_emb_list,\n self.registered_causal_mask,\n None,\n attention_mask,\n head_mask[i],\n encoder_hidden_states,\n encoder_attention_mask,\n )\n else:\n outputs = block(\n hidden_states,\n layer_past=layer_past,\n rotary_pos_emb_list=rotary_pos_emb_list,\n registered_causal_mask=self.registered_causal_mask,\n attention_mask=attention_mask,\n head_mask=head_mask[i],\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n )\n\n hidden_states = outputs[0]\n if use_cache is True:\n presents = presents + (outputs[1],)\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)\n\n hidden_states = self.ln_f(hidden_states)\n hidden_states = hidden_states.view(output_shape)\n # Add last hidden state\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(\n v for v in [hidden_states, presents, all_hidden_states] if v is not None\n )\n\n return BaseModelOutputWithPast(\n last_hidden_state=hidden_states,\n past_key_values=presents,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n )" }, { "identifier": "QWenLMHeadModel", "path": "llm/models/hf_models/qwen/modeling_qwen.py", "snippet": "class QWenLMHeadModel(QWenPreTrainedModel):\n _keys_to_ignore_on_load_missing = [r\"h\\.\\d+\\.attn\\.rotary_emb\\.inv_freq\"]\n _keys_to_ignore_on_load_unexpected = [r\"h\\.\\d+\\.attn\\.masked_bias\"]\n\n def __init__(self, config):\n super().__init__(config)\n assert (\n config.bf16 + config.fp16 + config.fp32 <= 1\n ), \"Only one of \\\"bf16\\\", \\\"fp16\\\", \\\"fp32\\\" can be true\"\n logger.warn(\n \"Warning: please make sure that you are using the latest codes and checkpoints, \"\n \"especially if you used Qwen-7B before 09.25.2023.\"\n \"请使用最新模型和代码,尤其如果你在9月25日前已经开始使用Qwen-7B,千万注意不要使用错误代码和模型。\"\n )\n\n autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0\n\n if autoset_precision:\n if SUPPORT_BF16:\n logger.warn(\n \"The model is automatically converting to bf16 for faster inference. \"\n \"If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \\\"AutoModelForCausalLM.from_pretrained\\\".\" # noqa\n )\n config.bf16 = True\n elif SUPPORT_FP16:\n logger.warn(\n \"The model is automatically converting to fp16 for faster inference. \"\n \"If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \\\"AutoModelForCausalLM.from_pretrained\\\".\" # noqa\n )\n config.fp16 = True\n else:\n config.fp32 = True\n\n if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:\n logger.warn(\n \"Your device does NOT seem to support bf16, you can switch to fp16 or fp32 by by passing fp16/fp32=True in \\\"AutoModelForCausalLM.from_pretrained\\\".\") # noqa\n if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:\n logger.warn(\n \"Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster\")\n if config.fp32:\n if SUPPORT_BF16:\n logger.warn(\n \"Your device support faster inference by passing bf16=True in \\\"AutoModelForCausalLM.from_pretrained\\\".\")\n elif SUPPORT_FP16:\n logger.warn(\n \"Your device support faster inference by passing fp16=True in \\\"AutoModelForCausalLM.from_pretrained\\\".\")\n\n if config.use_flash_attn == \"auto\":\n if config.bf16 or config.fp16:\n logger.warn(\"Try importing flash-attention for faster inference...\")\n config.use_flash_attn = True\n else:\n config.use_flash_attn = False\n if config.use_flash_attn and config.fp32:\n logger.warn(\"Flash attention will be disabled because it does NOT support fp32.\")\n\n if config.use_flash_attn:\n _import_flash_attn()\n\n self.transformer = QWenModel(config)\n self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n if config.bf16:\n self.transformer.bfloat16()\n self.lm_head.bfloat16()\n if config.fp16:\n self.transformer.half()\n self.lm_head.half()\n self.post_init()\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def set_output_embeddings(self, new_embeddings):\n self.lm_head = new_embeddings\n\n def prepare_inputs_for_generation(\n self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs\n ):\n token_type_ids = kwargs.get(\"token_type_ids\", None)\n if past_key_values:\n input_ids = input_ids[:, -1].unsqueeze(-1)\n if token_type_ids is not None:\n token_type_ids = token_type_ids[:, -1].unsqueeze(-1)\n\n attention_mask = kwargs.get(\"attention_mask\", None)\n position_ids = kwargs.get(\"position_ids\", None)\n\n if attention_mask is not None and position_ids is None:\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n if past_key_values:\n position_ids = position_ids[:, -1].unsqueeze(-1)\n else:\n position_ids = None\n\n if inputs_embeds is not None and past_key_values is None:\n model_inputs = {\"inputs_embeds\": inputs_embeds}\n else:\n model_inputs = {\"input_ids\": input_ids}\n\n model_inputs.update(\n {\n \"past_key_values\": past_key_values,\n \"use_cache\": kwargs.get(\"use_cache\"),\n \"position_ids\": position_ids,\n \"attention_mask\": attention_mask,\n \"token_type_ids\": token_type_ids,\n }\n )\n return model_inputs\n\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n token_type_ids: Optional[torch.LongTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n encoder_hidden_states: Optional[torch.Tensor] = None,\n encoder_attention_mask: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithPast]:\n\n return_dict = (\n return_dict if return_dict is not None else self.config.use_return_dict\n )\n\n transformer_outputs = self.transformer(\n input_ids,\n past_key_values=past_key_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = transformer_outputs[0]\n\n lm_logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n labels = labels.to(lm_logits.device)\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(\n shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)\n )\n\n if not return_dict:\n output = (lm_logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return CausalLMOutputWithPast(\n loss=loss,\n logits=lm_logits,\n past_key_values=transformer_outputs.past_key_values,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n\n @staticmethod\n def _reorder_cache(\n past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor\n ) -> Tuple[Tuple[torch.Tensor]]:\n\n return tuple(\n tuple(\n past_state.index_select(0, beam_idx.to(past_state.device))\n for past_state in layer_past\n )\n for layer_past in past_key_values\n )\n\n def chat(\n self,\n tokenizer: PreTrainedTokenizer,\n query: str,\n history: Optional[HistoryType],\n system: str = \"You are a helpful assistant.\",\n append_history: bool = True,\n stream: Optional[bool] = _SENTINEL,\n stop_words_ids: Optional[List[List[int]]] = None,\n generation_config: Optional[GenerationConfig] = None,\n **kwargs,\n ) -> Tuple[str, HistoryType]:\n generation_config = generation_config if generation_config is not None else self.generation_config\n\n assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT\n assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT\n if history is None:\n history = []\n if stop_words_ids is None:\n stop_words_ids = []\n\n max_window_size = kwargs.get('max_window_size', None)\n if max_window_size is None:\n max_window_size = generation_config.max_window_size\n raw_text, context_tokens = make_context(\n tokenizer,\n query,\n history=history,\n system=system,\n max_window_size=max_window_size,\n chat_format=generation_config.chat_format,\n )\n\n stop_words_ids.extend(get_stop_words_ids(\n generation_config.chat_format, tokenizer\n ))\n input_ids = torch.tensor([context_tokens]).to(self.device)\n outputs = self.generate(\n input_ids,\n stop_words_ids=stop_words_ids,\n return_dict_in_generate=False,\n generation_config=generation_config,\n **kwargs,\n )\n\n response = decode_tokens(\n outputs[0],\n tokenizer,\n raw_text_len=len(raw_text),\n context_length=len(context_tokens),\n chat_format=generation_config.chat_format,\n verbose=False,\n errors='replace'\n )\n\n if append_history:\n history.append((query, response))\n\n return response, history\n\n def chat_stream(\n self,\n tokenizer: PreTrainedTokenizer,\n query: str,\n history: Optional[HistoryType],\n system: str = \"You are a helpful assistant.\",\n stop_words_ids: Optional[List[List[int]]] = None,\n logits_processor: Optional[LogitsProcessorList] = None,\n generation_config: Optional[GenerationConfig] = None,\n **kwargs,\n ) -> Generator[str, Any, None]:\n generation_config = generation_config if generation_config is not None else self.generation_config\n assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT\n if history is None:\n history = []\n if stop_words_ids is None:\n stop_words_ids = []\n\n max_window_size = kwargs.get('max_window_size', None)\n if max_window_size is None:\n max_window_size = generation_config.max_window_size\n raw_text, context_tokens = make_context(\n tokenizer,\n query,\n history=history,\n system=system,\n max_window_size=max_window_size,\n chat_format=generation_config.chat_format,\n )\n\n stop_words_ids.extend(get_stop_words_ids(\n generation_config.chat_format, tokenizer\n ))\n if stop_words_ids is not None:\n stop_words_logits_processor = StopWordsLogitsProcessor(\n stop_words_ids=stop_words_ids,\n eos_token_id=generation_config.eos_token_id,\n )\n if logits_processor is None:\n logits_processor = LogitsProcessorList([stop_words_logits_processor])\n else:\n logits_processor.append(stop_words_logits_processor)\n input_ids = torch.tensor([context_tokens]).to(self.device)\n\n from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig\n self.__class__.generate_stream = NewGenerationMixin.generate\n self.__class__.sample_stream = NewGenerationMixin.sample_stream\n stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)\n\n def stream_generator():\n outputs = []\n for token in self.generate_stream(\n input_ids,\n return_dict_in_generate=False,\n generation_config=stream_config,\n logits_processor=logits_processor,\n seed=-1,\n **kwargs):\n outputs.append(token.item())\n yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore')\n\n return stream_generator()\n\n def generate(\n self,\n inputs: Optional[torch.Tensor] = None,\n generation_config: Optional[GenerationConfig] = None,\n logits_processor: Optional[LogitsProcessorList] = None,\n stopping_criteria: Optional[StoppingCriteriaList] = None,\n prefix_allowed_tokens_fn: Optional[\n Callable[[int, torch.Tensor], List[int]]\n ] = None,\n synced_gpus: Optional[bool] = None,\n assistant_model: Optional[\"PreTrainedModel\"] = None,\n streamer: Optional[\"BaseStreamer\"] = None,\n **kwargs,\n ) -> Union[GenerateOutput, torch.LongTensor]:\n generation_config = generation_config if generation_config is not None else self.generation_config\n\n # Process stop_words_ids.\n stop_words_ids = kwargs.pop(\"stop_words_ids\", None)\n if stop_words_ids is None and generation_config is not None:\n stop_words_ids = getattr(generation_config, \"stop_words_ids\", None)\n if stop_words_ids is None:\n stop_words_ids = getattr(generation_config, \"stop_words_ids\", None)\n\n if stop_words_ids is not None:\n stop_words_logits_processor = StopWordsLogitsProcessor(\n stop_words_ids=stop_words_ids,\n eos_token_id=generation_config.eos_token_id,\n )\n if logits_processor is None:\n logits_processor = LogitsProcessorList([stop_words_logits_processor])\n else:\n logits_processor.append(stop_words_logits_processor)\n\n return super().generate(\n inputs,\n generation_config=generation_config,\n logits_processor=logits_processor,\n stopping_criteria=stopping_criteria,\n prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n synced_gpus=synced_gpus,\n assistant_model=assistant_model,\n streamer=streamer,\n **kwargs,\n )" } ]
import importlib import math import torch # noqa import torch.nn.functional as F # noqa import torch.utils.checkpoint # noqa from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union, Callable, List, Any, Generator # noqa from torch.cuda.amp import autocast # noqa from torch.nn import CrossEntropyLoss from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList # noqa from transformers.generation.logits_process import LogitsProcessorList # noqa from transformers.generation.streamers import BaseStreamer # noqa from transformers.generation.utils import GenerateOutput # noqa from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel # noqa from transformers.utils import logging from einops import rearrange from torch import nn from .configuration_qwen import QWenConfig # noqa from .qwen_generation_utils import ( make_context, ) # noqa from llm.models.hf_models.qwen.qwen_generation_utils import ( HistoryType, decode_tokens, get_stop_words_ids, ) from .visual import VisionTransformer from llm.models.hf_models.qwen.modeling_qwen import RMSNorm, apply_rotary_pos_emb, QWenMLP from llm.models.hf_models.qwen.modeling_qwen import QWenAttention as QWenAttention_chat from llm.models.hf_models.qwen.modeling_qwen import QWenModel as QWenModel_chat from llm.models.hf_models.qwen.modeling_qwen import QWenLMHeadModel as QWenLMHeadModel_chat from einops import rearrange
16,115
return tuple( v for v in [hidden_states, presents, all_hidden_states] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions, ) class QWenLMHeadModel(QWenLMHeadModel_chat): _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"] _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"] def __init__(self, config): config.use_flash_attn = False config.softmax_in_fp32 = False config.use_cache_kernel = False config.use_cache_quantization = False super().__init__(config) self.transformer = QWenModel(config) if config.bf16: self.transformer.bfloat16() self.lm_head.bfloat16() if config.fp16: self.transformer.half() self.lm_head.half() self.post_init() def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] lm_logits = self.lm_head(hidden_states) loss = None if labels is not None: labels = labels.to(lm_logits.device) shift_logits = lm_logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss_fct = CrossEntropyLoss() loss = loss_fct( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1) ) if not return_dict: output = (lm_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def chat( self, tokenizer: PreTrainedTokenizer, query: str, history: Optional[HistoryType], system: str = "You are a helpful assistant.", append_history: bool = True, stream: Optional[bool] = _SENTINEL, stop_words_ids: Optional[List[List[int]]] = None, generation_cfg: Dict = {}, **kwargs, ) -> Tuple[str, HistoryType]: if generation_cfg: if "chat_format" not in generation_cfg: generation_cfg['chat_format'] = 'chatml' generation_config = GenerationConfig(**generation_cfg) else: generation_config = self.generation_config assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT if history is None: history = [] if stop_words_ids is None: stop_words_ids = [] max_window_size = kwargs.get('max_window_size', None) if max_window_size is None: max_window_size = generation_config.max_window_size if max_window_size in generation_cfg else 2048
# Copyright (c) Alibaba Cloud. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. if TYPE_CHECKING: try: except ImportError: rearrange = None SUPPORT_CUDA = torch.cuda.is_available() SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported() SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7 logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "qwen" _CONFIG_FOR_DOC = "QWenConfig" QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"] _ERROR_BAD_CHAT_FORMAT = """\ We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml". If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat(). 我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。 如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。 """ _SENTINEL = object() _ERROR_STREAM_IN_CHAT = """\ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True). 向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。 """ apply_rotary_emb_func = None rms_norm = None # Copied from transformers.models.bart.modeling_bart._make_causal_mask def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 ): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) # Copied from transformers.models.bart.modeling_bart._expand_mask def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) class QWenAttention(QWenAttention_chat): def __init__(self, config): super().__init__(config) def _attn(self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None): attn_weights = torch.matmul(query, key.transpose(-1, -2)) if self.scale_attn_weights: attn_weights = attn_weights / torch.full( [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device, ) attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_weights = attn_weights.type(value.dtype) attn_weights = self.attn_dropout(attn_weights) if head_mask is not None: attn_weights = attn_weights * head_mask attn_output = torch.matmul(attn_weights, value) attn_output = attn_output.transpose(1, 2) return attn_output, attn_weights def forward( self, hidden_states: Optional[Tuple[torch.FloatTensor]], rotary_pos_emb: Optional[List[torch.Tensor]] = None, registered_causal_mask: Optional[torch.Tensor] = None, layer_past: Optional[Tuple[torch.Tensor]] = None, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, ): mixed_x_layer = self.c_attn(hidden_states) query, key, value = mixed_x_layer.split(self.split_size, dim=2) query = self._split_heads(query, self.num_heads, self.head_dim) key = self._split_heads(key, self.num_heads, self.head_dim) value = self._split_heads(value, self.num_heads, self.head_dim) if rotary_pos_emb is not None: cur_len = query.shape[1] rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb] rotary_pos_emb = (rotary_pos_emb,) * 2 q_pos_emb, k_pos_emb = rotary_pos_emb # Slice the pos emb for current inference query = apply_rotary_pos_emb(query, q_pos_emb) key = apply_rotary_pos_emb(key, k_pos_emb) if layer_past is not None: past_key, past_value = layer_past[0], layer_past[1] key = torch.cat((past_key, key), dim=1) value = torch.cat((past_value, value), dim=1) if use_cache: present = (key, value) else: present = None if self.use_logn_attn and not self.training: if self.logn_tensor.device != query.device or self.logn_tensor.dtype != query.dtype: self.logn_tensor = self.logn_tensor.to(query.device).type_as(query) seq_start = key.size(1) - query.size(1) seq_end = key.size(1) logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :] query = query * logn_tensor.expand_as(query) query = query.permute(0, 2, 1, 3) key = key.permute(0, 2, 1, 3) value = value.permute(0, 2, 1, 3) attn_output, attn_weight = self._attn( query, key, value, registered_causal_mask, attention_mask, head_mask ) context_layer = self._merge_heads( attn_output, self.num_heads, self.head_dim ) attn_output = self.c_proj(context_layer) outputs = (attn_output, present) if output_attentions: outputs += (attn_weight,) return outputs class QWenBlock(nn.Module): def __init__(self, config): super().__init__() hidden_size = config.hidden_size self.bf16 = config.bf16 self.ln_1 = RMSNorm( hidden_size, eps=config.layer_norm_epsilon, ) self.attn = QWenAttention(config) self.ln_2 = RMSNorm( hidden_size, eps=config.layer_norm_epsilon, ) self.mlp = QWenMLP(config) def forward( self, hidden_states: Optional[Tuple[torch.FloatTensor]], rotary_pos_emb: Optional[List[torch.Tensor]] = None, registered_causal_mask: Optional[torch.Tensor] = None, layer_past: Optional[Tuple[torch.Tensor]] = None, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = False, output_attentions: Optional[bool] = False, ): layernorm_output = self.ln_1(hidden_states) attn_outputs = self.attn( layernorm_output, rotary_pos_emb, registered_causal_mask=registered_causal_mask, layer_past=layer_past, attention_mask=attention_mask, head_mask=head_mask, use_cache=use_cache, output_attentions=output_attentions, ) attn_output = attn_outputs[0] outputs = attn_outputs[1:] residual = hidden_states layernorm_input = attn_output + residual layernorm_output = self.ln_2(layernorm_input) residual = layernorm_input mlp_output = self.mlp(layernorm_output) hidden_states = residual + mlp_output if use_cache: outputs = (hidden_states,) + outputs else: outputs = (hidden_states,) + outputs[1:] return outputs class QWenModel(QWenModel_chat): _keys_to_ignore_on_load_missing = ["attn.masked_bias"] def __init__(self, config): super().__init__(config) dim = ( self.rotary_ndims if self.rotary_ndims is not None else config.kv_channels ) self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base) self.registered_causal_mask = None self.h = nn.ModuleList( [ QWenBlock( config ) for i in range(config.num_hidden_layers) ] ) self.visual = VisionTransformer(**config.visual) def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): combined_attention_mask = None if input_shape[-1] > 1: combined_attention_mask = _make_causal_mask( input_shape, inputs_embeds.dtype, device=inputs_embeds.device, past_key_values_length=past_key_values_length, ) if attention_mask is not None: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( inputs_embeds.device ) combined_attention_mask = ( expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask ) return combined_attention_mask def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ): if past_key_values is None and torch.any(input_ids == self.config.visual['image_start_id']): bos_pos = torch.where(input_ids == self.config.visual['image_start_id']) eos_pos = torch.where(input_ids == self.config.visual['image_start_id'] + 1) assert (bos_pos[0] == eos_pos[0]).all() img_pos = torch.stack((bos_pos[0], bos_pos[1], eos_pos[1]), dim=1) images = [] for i, a, b in img_pos: image = input_ids[i][a + 1 : b - 1].tolist() image = image[: image.index(self.config.visual['image_start_id'] + 2)] images.append(bytes(image).decode('utf-8')) images = self.visual.encode(images) assert images.shape[0] == len(images) fake_images = None elif self.training: fake_images = torch.zeros(1, 3, 224, 224).to( dtype=self.visual.conv1.weight.dtype, device=self.visual.conv1.weight.device) images = self.visual(fake_images) else: fake_images = None images = None output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) batch_size = input_ids.shape[0] elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] batch_size = inputs_embeds.shape[0] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if token_type_ids is not None: token_type_ids = token_type_ids.view(-1, input_shape[-1]) if position_ids is not None: position_ids = position_ids.view(-1, input_shape[-1]) if past_key_values is None: past_length = 0 past_key_values = tuple([None] * len(self.h)) else: past_length = past_key_values[0][0].size(-2) if position_ids is None: position_ids = torch.arange( past_length, input_shape[-1] + past_length, dtype=torch.long, device=device, ) position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1]) encoder_attention_mask = None head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) if inputs_embeds is None: inputs_embeds = self.wte(input_ids) if batch_size <= 0: raise ValueError("batch_size has to be defined and > 0") attention_mask = self._prepare_decoder_attention_mask( attention_mask, input_shape, inputs_embeds, past_length ) hidden_states = inputs_embeds kv_seq_len = hidden_states.size()[1] if past_key_values[0] is not None: # past key values[0][0] shape: bs * seq_len * head_num * dim kv_seq_len += past_key_values[0][0].shape[1] if ( self.use_dynamic_ntk and kv_seq_len == hidden_states.size()[1] and not self.training ): context_value = math.log(kv_seq_len / self.seq_length, 2) + 1 ntk_alpha = 2 ** math.ceil(context_value) - 1 ntk_alpha = max(ntk_alpha, 1) else: ntk_alpha = self.rotary_emb._ntk_alpha_cached rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha) for idx in range(len(rotary_pos_emb)): rotary_pos_emb[idx] = rotary_pos_emb[idx].to(hidden_states.device) hidden_states = self.drop(hidden_states).clone() if fake_images is not None: hidden_states = hidden_states + images.mean() * 0 elif images is not None: for idx, (i, a, b) in enumerate(img_pos): hidden_states[i][a + 1 : b] = images[idx] output_shape = input_shape + (hidden_states.size(-1),) if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False presents = () if use_cache else None all_self_attentions = () if output_attentions else None all_hidden_states = () if output_hidden_states else None for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if self.gradient_checkpointing and self.training: def create_custom_forward(module): def custom_forward(*inputs): # None for past_key_value return module(*inputs, use_cache, output_attentions) return custom_forward outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(block), hidden_states, rotary_pos_emb, self.registered_causal_mask, None, attention_mask, head_mask[i], encoder_hidden_states, encoder_attention_mask, ) else: outputs = block( hidden_states, layer_past=layer_past, rotary_pos_emb=rotary_pos_emb, registered_causal_mask=self.registered_causal_mask, attention_mask=attention_mask, head_mask=head_mask[i], encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=use_cache, output_attentions=output_attentions, ) hidden_states = outputs[0] if use_cache is True: presents = presents + (outputs[1],) if output_attentions: all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],) hidden_states = self.ln_f(hidden_states) hidden_states = hidden_states.view(output_shape) # Add last hidden state if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [hidden_states, presents, all_hidden_states] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions, ) class QWenLMHeadModel(QWenLMHeadModel_chat): _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"] _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"] def __init__(self, config): config.use_flash_attn = False config.softmax_in_fp32 = False config.use_cache_kernel = False config.use_cache_quantization = False super().__init__(config) self.transformer = QWenModel(config) if config.bf16: self.transformer.bfloat16() self.lm_head.bfloat16() if config.fp16: self.transformer.half() self.lm_head.half() self.post_init() def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] lm_logits = self.lm_head(hidden_states) loss = None if labels is not None: labels = labels.to(lm_logits.device) shift_logits = lm_logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss_fct = CrossEntropyLoss() loss = loss_fct( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1) ) if not return_dict: output = (lm_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def chat( self, tokenizer: PreTrainedTokenizer, query: str, history: Optional[HistoryType], system: str = "You are a helpful assistant.", append_history: bool = True, stream: Optional[bool] = _SENTINEL, stop_words_ids: Optional[List[List[int]]] = None, generation_cfg: Dict = {}, **kwargs, ) -> Tuple[str, HistoryType]: if generation_cfg: if "chat_format" not in generation_cfg: generation_cfg['chat_format'] = 'chatml' generation_config = GenerationConfig(**generation_cfg) else: generation_config = self.generation_config assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT if history is None: history = [] if stop_words_ids is None: stop_words_ids = [] max_window_size = kwargs.get('max_window_size', None) if max_window_size is None: max_window_size = generation_config.max_window_size if max_window_size in generation_cfg else 2048
raw_text, context_tokens = make_context(
1
2023-11-26 10:12:52+00:00
24k
danilonumeroso/conar
models/tsp_reasoner.py
[ { "identifier": "vmapped_beam_search_rollout", "path": "baselines/beam_search.py", "snippet": "BEAM_WIDTH = 128\ndef expand_single(beam_vis, beam_last, beam_cost, beam_par, W):\ndef beam_search_rollout_step(W, beam_width, i, tpl):\ndef beam_search_rollout(start_route, W, num_nodes, beam_width):\ndef beam_search_baseline(data, return_ratio=True):" }, { "identifier": "AlgorithmReasoner", "path": "models/algorithm_reasoner.py", "snippet": "class AlgorithmReasoner(nn.Module):\n @staticmethod\n def prepare_batch(batch):\n batch = batch.clone()\n for name, tensor in batch.items():\n if not torch.is_tensor(tensor):\n continue\n if name.endswith('_temporal') and 'index' not in name:\n tensor = tensor.transpose(1, 0)\n batch[name] = tensor\n return batch\n\n @staticmethod\n def get_masks(train, batch, continue_logits, enforced_mask):\n mask = continue_logits[batch.batch] > 0\n mask_cp = (continue_logits > 0.0).bool()\n mask_edges = mask[batch.edge_index[0]]\n if not train and enforced_mask is not None:\n enforced_mask_ids = enforced_mask[batch.batch]\n mask &= enforced_mask_ids\n mask_cp &= enforced_mask\n return mask_cp, mask, mask_edges\n\n def add_encoder(self, stage, name, loc, data_type, data_sample, bias):\n if name == 'adj': # we use edge indices\n return\n if data_type == Type.SCALAR or data_type == Type.MASK or data_type == Type.MASK_ONE:\n self.encoders[stage][name] = nn.Linear(1, self.latent_features, bias=bias)\n\n if data_type == Type.CATEGORICAL:\n in_shape = data_sample.shape[-1]\n self.encoders[stage][name] = nn.Linear(in_shape, self.latent_features, bias=bias)\n\n if loc == Location.NODE and data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]: # pointers are 1-hot encoded on the edges\n self.encoders[stage][name] = nn.Linear(1, self.latent_features, bias=bias)\n if loc == Location.EDGE and data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n self.encoders[stage][name] = nn.ModuleList([\n nn.Linear(1, self.latent_features, bias=bias),\n nn.Linear(1, self.latent_features, bias=bias)\n ])\n\n def add_decoder(self, stage, name, loc, data_type, data_sample, bias):\n assert name != 'adj', 'Adjacency matrix should not be decoded'\n dec = None\n if loc == Location.NODE:\n if data_type in (Type.SCALAR, Type.MASK, Type.MASK_ONE):\n dec = nn.Linear(2*self.latent_features, 1, bias=bias)\n\n if data_type == Type.CATEGORICAL:\n in_shape = data_sample.shape[-1]\n dec = nn.Linear(2*self.latent_features, in_shape, bias=bias)\n\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]: # pointers are decoded from both node and edge information\n dec = nn.ModuleList([\n nn.Linear(2*self.latent_features, self.latent_features, bias=bias),\n nn.Linear(2*self.latent_features, self.latent_features, bias=bias),\n nn.Linear(self.latent_features, self.latent_features, bias=bias),\n nn.Linear(self.latent_features, 1, bias=bias),\n ])\n if loc == Location.GRAPH:\n if data_type in [Type.MASK, Type.SCALAR, Type.CATEGORICAL, Type.MASK_ONE]:\n in_shape = data_sample.shape[-1] if data_type == Type.CATEGORICAL else 1\n dec = nn.ModuleList([\n nn.Linear(2*self.latent_features, in_shape, bias=bias),\n nn.Linear(self.latent_features, in_shape, bias=bias),\n ])\n\n if loc == Location.EDGE:\n if data_type in (Type.SCALAR, Type.MASK, Type.MASK_ONE):\n dec = nn.ModuleList([\n nn.Linear(2*self.latent_features, 1, bias=bias),\n nn.Linear(2*self.latent_features, 1, bias=bias),\n nn.Linear(self.latent_features, 1, bias=bias),\n ])\n if data_type == Type.CATEGORICAL:\n in_shape = data_sample.shape[-1]\n dec = nn.ModuleList([\n nn.Linear(2*self.latent_features, in_shape, bias=bias),\n nn.Linear(2*self.latent_features, in_shape, bias=bias),\n nn.Linear(self.latent_features, in_shape, bias=bias),\n ])\n if data_type == Type.POINTER:\n dec = nn.ModuleList([\n nn.Linear(2*self.latent_features, self.latent_features, bias=bias),\n nn.Linear(2*self.latent_features, self.latent_features, bias=bias),\n nn.Linear(self.latent_features, self.latent_features, bias=bias),\n nn.Linear(2*self.latent_features, self.latent_features, bias=bias),\n nn.Linear(self.latent_features, 1, bias=bias),\n ])\n assert dec is not None, breakpoint()\n self.decoders[stage][name] = dec\n\n\n\n\n def __init__(self,\n spec,\n data,\n latent_features,\n algo_processor,\n bias=True,\n use_TF=False,\n use_sinkhorn=True,\n L1_loss=False,\n xavier_on_scalars=True,\n global_termination_pool='max', #'predinet',\n get_attention=False,\n use_batch_norm=False,\n transferring=False,\n timeit=True,\n **kwargs):\n\n super().__init__()\n self.step_idx = 0\n self.latent_features = latent_features\n self.assert_checks = False\n self.timeit = timeit\n self.debug = False\n self.debug_epoch_threshold = 1e9\n self.L1_loss = L1_loss\n self.global_termination_pool = global_termination_pool\n self.next_step_pool = True\n self.processor = algo_processor\n self.triplet_reasoning = False\n if isinstance(self.processor.processors[0].processor, TripletMPNN):\n self.triplet_reasoning = True\n self.triplet_reductor = nn.Linear(2*latent_features, latent_features, bias=bias)\n self.use_TF = use_TF\n self.use_sinkhorn = use_sinkhorn\n self.get_attention = get_attention\n self.lambda_mul = 1 # 0.0001\n self.transferring = transferring\n self.node_encoder = nn.Sequential(\n nn.Linear(2*latent_features, latent_features, bias=bias),\n )\n self.encoders = nn.ModuleDict({\n 'input': nn.ModuleDict({\n }),\n 'hint': nn.ModuleDict({\n }),\n })\n self.decoders = nn.ModuleDict({\n 'hint': nn.ModuleDict({\n }),\n 'output': nn.ModuleDict({\n })\n })\n for name, (stage, loc, datatype) in spec.items():\n if name == 'adj': # we use edge indices\n continue\n if stage == 'input':\n self.add_encoder(stage, name, loc, datatype, getattr(data, name), bias)\n if stage == 'output':\n self.add_decoder(stage, name, loc, datatype, getattr(data, name), bias)\n if stage == 'hint':\n self.add_encoder(stage, name, loc, datatype, getattr(data, name), bias)\n self.add_decoder(stage, name, loc, datatype, getattr(data, name), bias)\n\n self.node_pointer_vec = nn.Parameter(torch.randn(latent_features))\n if xavier_on_scalars:\n assert False, \"NEEDS REFACTORING\"\n torch.nn.init.trunc_normal_(self.encoders['input']['edge_attr'].weight, std=1/torch.sqrt(torch.tensor(latent_features)))\n\n if global_termination_pool == 'attention':\n inp_dim = latent_features\n self.global_attn = GlobalAttentionPlusCoef(\n nn.Sequential(\n nn.Linear(inp_dim, latent_features, bias=bias),\n nn.LeakyReLU(),\n nn.Linear(latent_features, 1, bias=bias)\n ),\n nn=None)\n\n if global_termination_pool == 'predinet':\n lf = latent_features\n self.predinet = PrediNet(lf, 1, lf, lf, flatten_pooling=torch_geometric.nn.glob.global_max_pool)\n\n self.termination_network = nn.Sequential(\n nn.BatchNorm1d(latent_features) if use_batch_norm else nn.Identity(),\n nn.Linear(latent_features, 1, bias=bias),\n )\n\n def get_continue_logits(self, batch_ids, latent_nodes, sth_else=None):\n if self.global_termination_pool == 'mean':\n graph_latent = torch_geometric.nn.global_mean_pool(latent_nodes, batch_ids)\n if self.global_termination_pool == 'max':\n graph_latent = torch_geometric.nn.global_max_pool(latent_nodes, batch_ids)\n if self.global_termination_pool == 'attention':\n graph_latent, coef = self.global_attn(latent_nodes, batch_ids)\n if self.get_attention:\n self.attentions[self.step_idx] = coef.clone().detach()\n self.per_step_latent[self.step_idx] = sth_else\n\n if self.global_termination_pool == 'predinet':\n assert not torch.isnan(latent_nodes).any()\n graph_latent = self.predinet(latent_nodes, batch_ids)\n\n if self.get_attention:\n self.attentions[self.step_idx] = latent_nodes\n continue_logits = self.termination_network(graph_latent).view(-1)\n return continue_logits\n\n def zero_termination(self):\n self.true_positive = 0\n self.false_positive = 0\n self.false_negative = 0\n self.true_negative = 0\n\n def zero_steps(self):\n self.sum_of_processed_nodes = 0\n self.sum_of_processed_edges = 0\n self.step_idx = 0\n self.sum_of_steps = 0\n self.cnt = 0\n\n @staticmethod\n def convert_logits_to_outputs(spec,\n logits,\n fr,\n to,\n num_nodes,\n batch_ids,\n include_probabilities=True,\n dbg=False):\n outs = defaultdict(dict)\n\n for stage in logits.keys():\n for name in logits[stage].keys():\n if name not in logits[stage] or name not in spec:\n continue\n stage, loc, data_type = spec[name]\n assert stage != Stage.INPUT\n if data_type == Type.SOFT_POINTER:\n assert False, f\"Not yet added, please add {name}\"\n if data_type in [Type.CATEGORICAL]:\n indices = logits[stage][name].argmax(-1)\n outshape = logits[stage][name].shape[-1]\n outs[stage][name] = F.one_hot(indices, num_classes=outshape).float()\n if data_type == Type.MASK_ONE:\n _, amax = torch_scatter.scatter_max(logits[stage][name], batch_ids, dim=0)\n amax = amax.squeeze(-1)\n outs[stage][name] = torch.zeros_like(logits[stage][name])\n outs[stage][name][amax] = 1\n if data_type == Type.MASK:\n outs[stage][name] = (logits[stage][name] > 0).float()\n if data_type == Type.SCALAR:\n outs[stage][name] = logits[stage][name]\n if loc == Location.NODE and data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n pointer_logits = logits[stage][name]\n _, pointers = torch_scatter.scatter_max(pointer_logits, fr, dim_size=num_nodes)\n pointers = to[pointers]\n pointer_probabilities = torch_geometric.utils.softmax(pointer_logits, fr, num_nodes=num_nodes)\n outs[stage][name] = pointers\n if include_probabilities:\n outs[stage][f'{name}_probabilities'] = pointer_probabilities\n if loc == Location.EDGE and data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n pointer_logits = logits[stage][name]\n pointers = pointer_logits.argmax(-1)\n pointer_probabilities = F.softmax(pointer_logits, dim=-1)\n outs[stage][name] = pointers\n if include_probabilities:\n outs[stage][f'{name}_probabilities'] = pointer_probabilities\n return outs\n\n def set_initial_states(self, batch, init_last_latent=None):\n self.processor.zero_lstm(batch.num_nodes) # NO-OP if processor(s) don't use LSTM\n self.last_latent = torch.zeros(batch.num_nodes, self.latent_features, device=batch.edge_index.device)\n if init_last_latent is not None:\n self.last_latent = init_last_latent\n self.last_latent_edges = torch.zeros(batch.num_edges, self.latent_features, device=batch.edge_index.device)\n self.last_continue_logits = torch.ones(batch.num_graphs, device=batch.edge_index.device)\n self.last_logits = defaultdict(dict)\n\n\n for name, (stage, loc, data_type) in self.dataset_spec.items():\n if stage == Stage.INPUT:\n continue\n if name not in self.decoders[stage]:\n continue\n if stage == Stage.OUTPUT:\n\n if loc in [Location.NODE, Location.GRAPH]:\n if data_type == Type.CATEGORICAL:\n self.last_logits[stage][name] = getattr(batch, name)\n if data_type == Type.SCALAR:\n self.last_logits[stage][name] = getattr(batch, name).unsqueeze(-1)\n if data_type in [Type.MASK, Type.MASK_ONE]:\n self.last_logits[stage][name] = torch.where(getattr(batch, name).bool(), 1e9, -1e9).unsqueeze(-1)\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n self.last_logits[stage][name] = torch.where(batch.edge_index[0, :] == batch.edge_index[1, :], 1e9, -1e9).to(batch.edge_index.device) # self-loops\n\n if loc == Location.EDGE:\n if data_type == Type.CATEGORICAL:\n self.last_logits[stage][name] = getattr(batch, name)\n elif data_type in [Type.MASK, Type.MASK_ONE]:\n self.last_logits[stage][name] = torch.where(getattr(batch, name).bool(), 1e9, -1e9).unsqueeze(-1)\n elif data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n ptrs = getattr(batch, name).int()\n starts_edge = batch.ptr[:-1][batch.batch[batch.edge_index[0]]]\n ptrs = ptrs - starts_edge\n self.last_logits[stage][name] = torch.full((batch.edge_index.shape[1], int(ptrs.max().item())+1), -1e9).to(batch.edge_index.device)\n self.last_logits[stage][name][torch.arange(ptrs.shape[0]), ptrs] = 1e9\n else:\n assert False, breakpoint()\n\n if stage == Stage.HINT:\n\n if loc in [Location.NODE, Location.GRAPH]:\n if data_type == Type.CATEGORICAL:\n self.last_logits[stage][name] = getattr(batch, name)[0]\n elif data_type == Type.SCALAR:\n self.last_logits[stage][name] = getattr(batch, name)[0].unsqueeze(-1)\n elif data_type in [Type.MASK, Type.MASK_ONE]:\n self.last_logits[stage][name] = torch.where(getattr(batch, name)[0, :].bool(), 1e9, -1e9).unsqueeze(-1)\n elif data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n self.last_logits[stage][name] = torch.where(batch.edge_index[0, :] == batch.edge_index[1, :], 1e9, -1e9).to(batch.edge_index.device) # self-loops\n else:\n assert False, breakpoint()\n\n if loc == Location.EDGE:\n if data_type == Type.CATEGORICAL:\n self.last_logits[stage][name] = getattr(batch, name)[0]\n elif data_type in [Type.MASK, Type.MASK_ONE]:\n self.last_logits[stage][name] = torch.where(getattr(batch, name)[0, :].bool(), 1e9, -1e9).unsqueeze(-1)\n elif data_type == Type.SCALAR:\n self.last_logits[stage][name] = getattr(batch, name)[0, :].unsqueeze(-1)\n elif data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n ptrs = getattr(batch, name)[0, :].int()\n starts_edge = batch.ptr[:-1][batch.batch[batch.edge_index[0]]]\n ptrs = ptrs - starts_edge\n self.max_nodes_in_graph = int(ptrs.max().item())+1 # FIXME try another way to infer\n self.last_logits[stage][name] = torch.where(edge_one_hot_encode_pointers_edge(ptrs, batch, self.max_nodes_in_graph).bool(), 1e9, -1e9).to(batch.edge_index.device)\n else:\n assert False, breakpoint()\n\n self.all_hint_logits = []\n self.all_masks_graph = []\n\n def update_per_mask(self, before, after, mask=None):\n # NOTE: this does expansion of the mask, if you do\n # NOT use expansion, use torch.where\n if mask is None:\n mask = self.mask\n mask = mask.unsqueeze(-1).expand_as(before)\n return torch.where(mask, after, before)\n\n def update_state_dict(self, before, after):\n new_before = defaultdict(dict)\n for stage in after.keys():\n for name in after[stage].keys():\n _, loc, data_type = self.dataset_spec[name]\n if loc == Location.GRAPH:\n new_before[stage][name] = self.update_per_mask(before[stage][name], after[stage][name], mask=self.mask_cp)\n if loc == Location.EDGE:\n if data_type in [Type.MASK, Type.MASK_ONE, Type.SCALAR, Type.CATEGORICAL, Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n new_before[stage][name] = self.update_per_mask(before[stage][name], after[stage][name], mask=self.mask_edges)\n else:\n assert False, \"Please implement\"\n if loc == Location.NODE:\n if data_type in [Type.MASK, Type.MASK_ONE, Type.SCALAR, Type.CATEGORICAL]:\n new_before[stage][name] = self.update_per_mask(before[stage][name], after[stage][name])\n elif data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n new_before[stage][name] = torch.where(self.mask_edges, after[stage][name], before[stage][name])\n else:\n assert False, breakpoint()\n return new_before\n\n def update_states(self, batch, current_latent, edges_current_latent,\n logits, continue_logits):\n self.last_continue_logits = torch.where(self.mask_cp, continue_logits,\n self.last_continue_logits)\n self.last_latent = self.update_per_mask(self.last_latent, current_latent)\n self.last_latent_edges = self.update_per_mask(self.last_latent_edges, edges_current_latent, mask=self.mask_edges)\n self.last_logits = self.update_state_dict(self.last_logits, logits)\n self.all_hint_logits.append(self.last_logits['hint'])\n self.all_masks_graph.append(self.mask_cp)\n preds = type(self).convert_logits_to_outputs(\n self.dataset_spec, self.last_logits, batch.edge_index[0],\n batch.edge_index[1], batch.num_nodes, batch.batch,\n self.epoch > self.debug_epoch_threshold)\n self.last_hint = preds['hint']\n self.last_output = preds['output']\n\n def prepare_initial_masks(self, batch):\n self.mask = torch.ones_like(batch.batch, dtype=torch.bool, device=batch.edge_index.device)\n self.mask_cp = torch.ones(batch.num_graphs, dtype=torch.bool, device=batch.edge_index.device)\n self.mask_edges = torch.ones_like(batch.edge_index[0], dtype=torch.bool, device=batch.edge_index.device)\n\n def loop_condition(self, termination, STEPS_SIZE):\n return (((not self.training and termination.any()) or\n (self.training and termination.any())) and\n self.step_idx+1 < STEPS_SIZE)\n\n def loop_body(self,\n batch,\n node_fts,\n edge_fts,\n graph_fts,\n hint_inp_curr,\n hint_out_curr,\n true_termination,\n first_n_processors=1000):\n\n current_latent, edges_current_latent, preds, continue_logits =\\\n self.forward(\n batch,\n node_fts,\n edge_fts,\n graph_fts,\n first_n_processors=first_n_processors,\n )\n termination = continue_logits\n\n self.debug_batch = batch\n self.debug_hint_out_curr = hint_out_curr\n if self.timeit:\n st = time.time()\n self.update_states(batch, current_latent, edges_current_latent, preds, termination)\n if self.timeit:\n print(f'updating states: {time.time()-st}')\n\n def get_step_input(self, x_curr, batch):\n if self.training and self.use_TF or self.hardcode_outputs:\n return x_curr\n return type(self).convert_logits_to_outputs(\n self.dataset_spec, self.last_logits, batch.edge_index[0],\n batch.edge_index[1], batch.num_nodes, batch.batch,\n self.epoch > self.debug_epoch_threshold)['hint']\n\n def encode_inputs(self, batch):\n node_fts = torch.zeros(batch.num_nodes, self.latent_features, device=batch.edge_index.device)\n edge_fts = torch.zeros(batch.num_edges, self.latent_features, device=batch.edge_index.device)\n for name, (stage, loc, data_type) in self.dataset_spec.items():\n if stage != Stage.INPUT:\n continue\n if name not in self.encoders[stage]:\n continue\n data = getattr(batch, name)\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n assert False, breakpoint() # we don't have it for now (B-F/MST), will figure out later\n if data_type != Type.CATEGORICAL:\n data = data.unsqueeze(-1)\n if loc == Location.EDGE:\n edge_fts += self.encoders[stage][name](data)\n if loc == Location.NODE:\n node_fts += self.encoders[stage][name](data)\n return node_fts, edge_fts\n\n def encode_hints(self, hints, batch):\n node_fts = torch.zeros(batch.num_nodes, self.latent_features, device=batch.edge_index.device)\n edge_fts = torch.zeros(batch.num_edges, self.latent_features, device=batch.edge_index.device)\n graph_fts = torch.zeros(batch.num_graphs, self.latent_features, device=batch.edge_index.device)\n\n for name, (stage, loc, data_type) in self.dataset_spec.items():\n if stage != Stage.HINT:\n continue\n if name not in self.encoders[stage]:\n continue\n hint = hints[name]\n if loc == Location.NODE and data_type in [Type.MASK, Type.MASK_ONE, Type.SCALAR, Type.CATEGORICAL]:\n node_fts = node_fts + self.encoders['hint'][name](hint)\n if loc == Location.EDGE and data_type in [Type.MASK, Type.MASK_ONE, Type.SCALAR, Type.CATEGORICAL]:\n edge_fts = edge_fts + self.encoders['hint'][name](hint)\n if loc == Location.NODE and data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n pred_gt_one_hot = edge_one_hot_encode_pointers(hint, batch.edge_index)\n edge_fts = edge_fts + self.encoders['hint'][name](pred_gt_one_hot.unsqueeze(-1))\n if loc == Location.EDGE and data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n pred_gt_one_hot = edge_one_hot_encode_pointers_edge(hint, batch, self.max_nodes_in_graph)\n starts_edge = batch.ptr[:-1][batch.batch[batch.edge_index[0]]]\n encoding = self.encoders['hint'][name][0](pred_gt_one_hot.unsqueeze(-1))\n encoding_2 = self.encoders['hint'][name][1](pred_gt_one_hot.unsqueeze(-1))\n encoding_sparse = SparseTensor(row=batch.edge_index[0], col=batch.edge_index[1], value=encoding)\n res_1 = encoding_sparse.mean(1)[batch.edge_index[0], batch.edge_index[1]-starts_edge]\n res_2 = encoding_2.mean(1)\n edge_fts += res_1 + res_2 # INPLACE\n if loc == Location.GRAPH and data_type in [Type.CATEGORICAL, Type.SCALAR, Type.MASK]:\n graph_fts = graph_fts + self.encoders['hint'][name](hint)\n return node_fts, edge_fts, graph_fts\n\n def get_input_output_hints(self, batch):\n hint_inp_curr = {}\n hint_out_curr = {}\n for name, (stage, loc, data_type) in self.dataset_spec.items():\n if stage != Stage.HINT:\n continue\n hint_inp_curr[name] = getattr(batch, name)[self.step_idx]\n hint_out_curr[name] = getattr(batch, name)[self.step_idx+1]\n if 'mask' in data_type or data_type == Type.SCALAR:\n hint_inp_curr[name] = hint_inp_curr[name].unsqueeze(-1)\n hint_out_curr[name] = hint_out_curr[name].unsqueeze(-1)\n return hint_inp_curr, hint_out_curr\n\n def process(\n self,\n batch,\n EPSILON=0,\n enforced_mask=None,\n hardcode_outputs=False,\n debug=False,\n first_n_processors=1000,\n init_last_latent=None,\n **kwargs):\n\n SIZE, STEPS_SIZE = prepare_constants(batch)\n self.hardcode_outputs = hardcode_outputs\n\n # Pytorch Geometric batches along the node dimension, but we execute\n # along the temporal (step) dimension, hence we need to transpose\n # a few tensors. Done by `prepare_batch`.\n if self.assert_checks:\n check_edge_index_sorted(batch.edge_index)\n if self.epoch > self.debug_epoch_threshold:\n breakpoint()\n self.zero_steps()\n batch = type(self).prepare_batch(batch)\n # When we want to calculate last step metrics/accuracies\n # we need to take into account again different termination per graph\n # hence we save last step tensors (e.g. outputs) into their\n # corresponding tensor. The function below prepares these tensors\n # (all set to zeros, except masking for computation, which are ones)\n self.set_initial_states(batch, init_last_latent=init_last_latent)\n # Prepare masking tensors (each graph does at least 1 iteration of the algo)\n self.prepare_initial_masks(batch)\n # A flag if we had a wrong graph in the batch. Used for visualisation\n # of what went wrong\n self.wrong_flag = False\n assert self.mask_cp.all(), self.mask_cp\n if self.timeit:\n st = time.time()\n node_fts_inp, edge_fts_inp = self.encode_inputs(batch)\n if self.timeit:\n print(f'encoding inputs: {time.time()-st}')\n\n while True:\n hint_inp_curr, hint_out_curr = self.get_input_output_hints(batch)\n if not self.training:\n assert (self.last_continue_logits > 0).any() or True\n\n # Some algorithms output fewer values than they take\n # so if we reuse our last step outputs, they need to be fed back in.\n if self.timeit:\n st = time.time()\n hint_inp_curr = self.get_step_input(hint_inp_curr, batch)\n if self.timeit:\n print(f'getting step input : {time.time()-st}')\n st = time.time()\n node_fts_hint, edge_fts_hint, graph_fts = self.encode_hints(hint_inp_curr, batch)\n node_fts = node_fts_inp + node_fts_hint\n edge_fts = edge_fts_inp + edge_fts_hint\n if self.timeit:\n print(f'encoding hints: {time.time()-st}')\n\n true_termination = torch.where(self.step_idx+1 >= batch.lengths-1, -1e9, 1e9)\n\n # Does one iteration of the algo and accumulates statistics\n self.loop_body(batch,\n node_fts,\n edge_fts,\n graph_fts,\n hint_inp_curr,\n hint_out_curr,\n true_termination,\n first_n_processors=first_n_processors)\n # And calculate what graphs would execute on the next step.\n self.mask_cp, self.mask, self.mask_edges = type(self).get_masks(self.training, batch, true_termination if self.training else self.last_continue_logits, enforced_mask)\n if not self.loop_condition(\n self.mask_cp,\n STEPS_SIZE):\n break\n assert self.mask_cp.any()\n self.step_idx += 1\n\n return self.all_hint_logits, self.last_logits, self.all_masks_graph\n\n def decode(self, batch, encoded_nodes, hidden, edge_fts, graph_fts):\n catted = torch.cat((encoded_nodes, hidden), dim=1)\n outs = defaultdict(dict)\n for name, (stage, loc, data_type) in self.dataset_spec.items():\n if stage == Stage.INPUT:\n continue\n\n if loc == Location.NODE:\n\n if data_type in [Type.MASK, Type.SCALAR, Type.CATEGORICAL, Type.MASK_ONE]:\n outs[stage][name] = self.decoders[stage][name](catted)\n\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n fr = self.decoders[stage][name][0](catted[batch.edge_index[0]])\n to = self.decoders[stage][name][1](catted[batch.edge_index[1]])\n edge = self.decoders[stage][name][2](edge_fts)\n prod = self.decoders[stage][name][3](to.max(fr+edge)).squeeze(-1)\n if data_type in [Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION] and self.use_sinkhorn:\n prod = torch.maximum(prod, self.decoders[stage][name][3](fr.max(to+edge)).squeeze(-1))\n prod = sinkhorn_normalize(batch, prod, temperature=0.1, steps=10 if self.training else 60, add_noise=self.training)\n outs[stage][name] = prod\n\n if loc == Location.GRAPH:\n aggr_node_fts = torch_scatter.scatter_max(catted, batch.batch, dim=0)[0]\n if data_type in [Type.MASK, Type.SCALAR, Type.CATEGORICAL, Type.MASK_ONE]:\n outs[stage][name] = self.decoders[stage][name][0](aggr_node_fts) + self.decoders[stage][name][1](graph_fts)\n else:\n assert False\n\n if loc == Location.EDGE:\n fr = self.decoders[stage][name][0](catted[batch.edge_index[0]])\n to = self.decoders[stage][name][1](catted[batch.edge_index[1]])\n edge = self.decoders[stage][name][2](edge_fts)\n if data_type in (Type.CATEGORICAL, Type.MASK, Type.SCALAR):\n outs[stage][name] = fr + to + edge\n elif data_type == Type.POINTER:\n pred = fr + to + edge\n pred_2 = self.decoders[stage][name][3](catted)\n ebatch = batch.edge_index_batch\n st = batch.ptr[ebatch]\n en = batch.ptr[ebatch+1]\n dense_pred_2, mask_pred_2 = tg_utils.to_dense_batch(pred_2, batch=batch.batch)\n edge_pred_2 = dense_pred_2[ebatch]\n mask_edge_pred_2 = mask_pred_2[ebatch]\n probs_logits = self.decoders[stage][name][4](torch.maximum(pred[:, None, :], edge_pred_2)).squeeze(-1)\n probs_logits[~mask_edge_pred_2] = -1e9\n outs[stage][name] = probs_logits\n else:\n assert False\n\n return outs\n\n def encode_nodes(self, current_input, last_latent):\n return torch.cat((current_input, last_latent), dim=1)\n\n def forward(self, batch, node_fts, edge_fts, graph_fts, first_n_processors=1000):\n if torch.isnan(node_fts).any():\n breakpoint()\n assert not torch.isnan(self.last_latent).any()\n assert not torch.isnan(node_fts).any()\n if self.timeit:\n st = time.time()\n if self.timeit:\n print(f'projecting nodes: {time.time()-st}')\n\n if self.timeit:\n st = time.time()\n edge_index = batch.edge_index\n hidden, edges_hidden = self.processor(node_fts, edge_fts, graph_fts, edge_index, self.last_latent, self.last_latent_edges, first_n_processors=first_n_processors, batch=batch)\n if self.timeit:\n print(f'message passing: {time.time()-st}')\n assert not torch.isnan(hidden).any()\n if self.timeit:\n st = time.time()\n if self.triplet_reasoning:\n edge_fts = self.triplet_reductor(torch.cat([edge_fts, edges_hidden], dim=-1))\n outs = self.decode(batch, node_fts, hidden, edge_fts, graph_fts)\n if self.timeit:\n print(f'decoding hints: {time.time()-st}')\n continue_logits = torch.where(self.step_idx+1 >= batch.lengths-1, -1e9, 1e9)\n return hidden, edges_hidden, outs, continue_logits" }, { "identifier": "LitAlgorithmReasoner", "path": "models/algorithm_reasoner.py", "snippet": "class LitAlgorithmReasoner(pl.LightningModule):\n def __init__(self,\n hidden_dim,\n algo_processor,\n dataset_class,\n dataset_root,\n dataset_kwargs,\n algorithm='mst_prim',\n update_edges_hidden=False,\n use_TF=False,\n use_sinkhorn=True,\n xavier_on_scalars=True,\n learning_rate=get_hyperparameters()['lr'],\n weight_decay=get_hyperparameters()['weight_decay'],\n test_with_val=False,\n test_with_val_every_n_epoch=20,\n test_train_every_n_epoch=20,\n **algorithm_base_kwargs):\n super().__init__()\n self.hidden_dim = hidden_dim\n self.algorithm_base_kwargs = algorithm_base_kwargs\n self.dataset_class = dataset_class\n self.dataset_root = dataset_root\n self.dataset_kwargs = dataset_kwargs\n self.learning_rate = learning_rate\n self.weight_decay = weight_decay\n self.timeit = False\n self.update_edges_hidden = update_edges_hidden\n self.use_TF = use_TF\n self.use_sinkhorn = use_sinkhorn\n self.algorithm_base_kwargs = algorithm_base_kwargs\n self.algorithm = algorithm\n self.xavier_on_scalars = xavier_on_scalars\n self.test_with_val = test_with_val\n self.test_with_val_every_n_epoch = test_with_val_every_n_epoch\n self.test_train_every_n_epoch = test_train_every_n_epoch\n self._datasets = {}\n if self.test_with_val:\n self.val_dataloader = self.val_dataloader_alt\n self.validation_step = self.validation_step_alt\n self._current_epoch = 0\n self.load_dataset('train')\n\n self.algorithm_module = AlgorithmReasoner(self.dataset.spec,\n self.dataset[0],\n hidden_dim,\n algo_processor,\n update_edges_hidden=update_edges_hidden,\n use_TF=use_TF,\n use_sinkhorn=use_sinkhorn,\n timeit=self.timeit,\n xavier_on_scalars=xavier_on_scalars,\n **algorithm_base_kwargs)\n self.save_hyperparameters(ignore=['algo_processor'])\n\n @property\n def current_epoch(self) -> int:\n \"\"\"The current epoch in the ``Trainer``, or 0 if not attached.\"\"\"\n return self.trainer.current_epoch if self._trainer else self._current_epoch\n\n @current_epoch.setter\n def current_epoch(self, epoch) -> int:\n self._current_epoch = epoch\n\n def prepare_for_transfer(self):\n algo_processor = copy.deepcopy(self.algorithm_module.processor)\n self.algorithm_module = AlgorithmReasoner(self.hidden_dim,\n self.node_features,\n self.edge_features,\n self.output_features,\n algo_processor,\n use_TF=False,\n timeit=self.timeit,\n **self.algorithm_base_kwargs)\n for p in self.algorithm_module.processor.parameters():\n p.requires_grad = False\n\n @staticmethod\n def pointer_loss(predecessor_pred, predecessor_gt_edge_1h,\n softmax_idx, num_nodes):\n loss_unreduced = cross_entropy(predecessor_pred, softmax_idx, predecessor_gt_edge_1h, num_nodes)\n sum_loss = loss_unreduced.flatten().sum()\n cnt_loss = predecessor_gt_edge_1h.count_nonzero()\n return sum_loss / cnt_loss\n\n def single_prediction_loss(self, name, pred, pred_gt, batch, graph_mask,\n node_mask, edge_mask):\n loss = None\n stage, loc, data_type = self.dataset.spec[name]\n if loc == Location.GRAPH:\n if data_type == Type.CATEGORICAL:\n loss = F.cross_entropy(pred[graph_mask], pred_gt[graph_mask].argmax(-1))\n if data_type == Type.SCALAR:\n loss = F.mse_loss(\n pred[graph_mask].squeeze(-1),\n pred_gt[graph_mask])\n if data_type == Type.MASK:\n loss = F.binary_cross_entropy_with_logits(\n pred[graph_mask].squeeze(-1),\n pred_gt[graph_mask])\n\n if loc == Location.NODE:\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n pred_gt_one_hot = edge_one_hot_encode_pointers(pred_gt, batch.edge_index)\n loss = type(self).pointer_loss(\n pred[edge_mask],\n pred_gt_one_hot[edge_mask],\n batch.edge_index[0][edge_mask], batch.num_nodes)\n if data_type == Type.MASK:\n loss = F.binary_cross_entropy_with_logits(\n pred[node_mask].squeeze(-1),\n pred_gt[node_mask])\n if data_type == Type.MASK_ONE:\n lsms = torch_scatter.scatter_log_softmax(pred[node_mask], batch.batch[node_mask].unsqueeze(-1), dim=0)\n loss = (-lsms[(pred_gt[node_mask] == 1.)]).mean()\n if data_type == Type.SCALAR:\n loss = F.mse_loss(\n pred[node_mask].squeeze(-1),\n pred_gt[node_mask])\n if data_type == Type.CATEGORICAL:\n loss = F.cross_entropy(pred[node_mask], pred_gt[node_mask].argmax(-1))\n if loc == Location.EDGE:\n if data_type == Type.MASK:\n loss = F.binary_cross_entropy_with_logits(\n pred[edge_mask].squeeze(-1),\n pred_gt[edge_mask])\n if data_type == Type.CATEGORICAL:\n loss = F.cross_entropy(pred[edge_mask], pred_gt[edge_mask].argmax(-1))\n if data_type == Type.SCALAR:\n loss = F.mse_loss(\n pred[edge_mask].squeeze(-1),\n pred_gt[edge_mask])\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n starts_edge = batch.ptr[:-1][batch.batch[batch.edge_index[0]]]\n pred_gt = pred_gt.int() - starts_edge\n loss = F.cross_entropy(\n pred[edge_mask],\n pred_gt[edge_mask])\n assert loss is not None, f'{stage}/{name}/{loc}/{data_type}'\n return loss\n\n def get_step_loss(self,\n batch,\n all_hint_logits,\n output_logits,\n all_masks_graph):\n\n if self.timeit:\n st = time.time()\n batch = self.algorithm_module.prepare_batch(batch)\n losses_dict = defaultdict(list)\n for i, (pred, graph_mask) in enumerate(zip(all_hint_logits, all_masks_graph)):\n node_mask = graph_mask[batch.batch]\n edge_mask = node_mask[batch.edge_index[0]]\n assert graph_mask.any()\n for name in pred:\n stage, loc, data_type = self.dataset.spec[name]\n pred_gt = getattr(batch, name)[i+1]\n losses_dict[name].append(\n self.single_prediction_loss(name, pred[name], pred_gt,\n batch, graph_mask, node_mask,\n edge_mask))\n\n for name in output_logits:\n graph_mask = torch.ones(batch.num_graphs, dtype=torch.bool, device=self.device)\n node_mask = graph_mask[batch.batch]\n edge_mask = node_mask[batch.edge_index[0]]\n losses_dict[name].append(\n self.single_prediction_loss(name, output_logits[name],\n getattr(batch, name), batch,\n graph_mask, node_mask, edge_mask))\n\n for k, v in losses_dict.items():\n losses_dict[k] = torch.stack(v).mean()\n if self.timeit:\n print(f'loss calculation: {time.time()-st}')\n input()\n\n return losses_dict\n\n def single_prediction_acc(self, name, pred, pred_gt, batch, graph_mask,\n node_mask, edge_mask):\n acc = None\n stage, loc, data_type = self.dataset.spec[name]\n if loc == Location.NODE:\n if data_type == Type.MASK_ONE:\n # try:\n acc = (pred[node_mask].squeeze(-1).nonzero() == pred_gt[node_mask].nonzero()).float().mean()\n # except Exception as e:\n # breakpoint()\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION, Type.MASK]:\n acc = (pred[node_mask].squeeze(-1) == pred_gt[node_mask]).float().mean()\n if data_type == Type.SCALAR:\n acc = ((pred[node_mask].squeeze(-1) - pred_gt[node_mask])**2).mean()\n if data_type == Type.CATEGORICAL:\n acc = (pred[node_mask].argmax(-1) == pred_gt[node_mask].argmax(-1)).float().mean()\n if data_type == Type.MASK:\n acc = multiclass_f1_score(pred[node_mask].squeeze(-1), pred_gt[node_mask])\n\n if loc == Location.GRAPH:\n if data_type == Type.CATEGORICAL:\n acc = (pred[graph_mask].argmax(-1) == pred_gt[graph_mask].argmax(-1)).float().mean()\n if data_type == Type.SCALAR:\n acc = ((pred[graph_mask].squeeze(-1) - pred_gt[graph_mask])**2).mean()\n if data_type == Type.MASK:\n acc = multiclass_f1_score(pred[graph_mask].squeeze(-1), pred_gt[graph_mask])\n\n if loc == Location.EDGE:\n if data_type == Type.CATEGORICAL:\n acc = (pred[edge_mask].argmax(-1) == pred_gt[edge_mask].argmax(-1)).float().mean()\n if data_type == Type.MASK:\n acc = multiclass_f1_score(pred[edge_mask].squeeze(-1), pred_gt[edge_mask])\n if data_type == Type.SCALAR:\n acc = ((pred[edge_mask].squeeze(-1) - pred_gt[edge_mask])**2).mean()\n if data_type in [Type.POINTER, Type.PERMUTATION_POINTER, Type.SHOULD_BE_PERMUTATION]:\n starts_edge = batch.ptr[:-1][batch.batch[batch.edge_index[0]]]\n pred_gt = pred_gt.int() - starts_edge\n acc = (pred[edge_mask] == pred_gt[edge_mask]).float().mean()\n assert acc is not None, f\"Please implement {name}\"\n return acc\n\n def get_metrics(self,\n batch,\n all_hint_logits,\n output_logits,\n all_masks_graph):\n\n batch = self.algorithm_module.prepare_batch(batch)\n accs_dict = defaultdict(list)\n\n for i, (pred, graph_mask) in enumerate(zip(all_hint_logits, all_masks_graph)):\n node_mask = graph_mask[batch.batch]\n edge_mask = node_mask[batch.edge_index[0]]\n outputs = type(self.algorithm_module).convert_logits_to_outputs(\n self.dataset.spec, {'hint': pred},\n batch.edge_index[0],\n batch.edge_index[1],\n batch.num_nodes,\n batch.batch,\n include_probabilities=False)['hint']\n\n for name in outputs:\n acc = self.single_prediction_acc(\n name,\n outputs[name],\n getattr(batch, name)[i+1],\n batch,\n graph_mask,\n node_mask,\n edge_mask)\n accs_dict[name].append(acc)\n\n outputs = type(self.algorithm_module).convert_logits_to_outputs(\n self.dataset.spec,\n output_logits,\n batch.edge_index[0],\n batch.edge_index[1],\n batch.num_nodes,\n batch.batch,\n include_probabilities=False)['output']\n for name in outputs:\n graph_mask = torch.ones(batch.num_graphs, dtype=torch.bool, device=self.device)\n node_mask = graph_mask[batch.batch]\n edge_mask = node_mask[batch.edge_index[0]]\n accs_dict[name].append(\n self.single_prediction_acc(\n name,\n outputs[name],\n getattr(batch, name),\n batch,\n graph_mask,\n node_mask,\n edge_mask))\n\n for k, v in accs_dict.items():\n accs_dict[k] = torch.stack(v).mean()\n\n return accs_dict\n\n def fwd_step(self, batch, batch_idx):\n if self.timeit:\n st = time.time()\n self.algorithm_module.epoch = self.current_epoch\n all_hint_logits, output_logits, masks = self.algorithm_module.process(batch)\n if self.timeit:\n print(f'forward step: {time.time()-st}')\n input()\n return all_hint_logits, output_logits, masks\n\n def training_step(self, batch, batch_idx):\n all_hint_logits, output_logits, masks = self.fwd_step(batch, batch_idx)\n losses_dict = self.get_step_loss(batch, all_hint_logits, output_logits['output'], masks)\n self.log_dict(dict((f'train/loss/{k}', v) for k, v in losses_dict.items()), batch_size=batch.num_graphs)\n total_loss = sum(losses_dict.values()) / len(losses_dict)\n self.log('train/loss/average_loss', total_loss, prog_bar=False, on_step=True, on_epoch=True, batch_size=batch.num_graphs)\n accs_dict = {}\n if self.current_epoch % self.test_train_every_n_epoch == 0:\n accs_dict = self.get_metrics(batch, all_hint_logits, output_logits, masks)\n self.log_dict(dict((f'train/acc/{k}', v) for k, v in accs_dict.items()), batch_size=batch.num_graphs, add_dataloader_idx=False)\n # if sum(losses_dict.values()) > 1e5:\n # breakpoint()\n return {'loss': total_loss, 'losses_dict': losses_dict, 'accuracies': accs_dict}\n\n def valtest_step(self, batch, batch_idx, mode):\n all_hint_logits, output_logits, masks = self.fwd_step(batch, batch_idx)\n losses_dict = self.get_step_loss(batch, all_hint_logits, output_logits['output'], masks)\n self.log_dict(dict((f'{mode}/loss/{k}', v) for k, v in losses_dict.items()), batch_size=batch.num_graphs, add_dataloader_idx=False)\n if torch.isnan(sum(losses_dict.values())).any():\n breakpoint()\n self.log(f'{mode}/loss/average_loss', sum(losses_dict.values()) / len(losses_dict), batch_size=batch.num_graphs, add_dataloader_idx=False)\n accs_dict = self.get_metrics(batch, all_hint_logits, output_logits, masks)\n self.log_dict(dict((f'{mode}/acc/{k}', v) for k, v in accs_dict.items()), batch_size=batch.num_graphs, add_dataloader_idx=False)\n return {'losses': losses_dict, 'accuracies': accs_dict}\n\n def validation_step_alt(self, batch, batch_idx, dataloader_idx):\n if dataloader_idx == 1 and not self.trainer.state.stage == 'sanity_check' and self.current_epoch % self.test_with_val_every_n_epoch == 0:\n return self.valtest_step(batch, batch_idx, 'periodic_test')\n if dataloader_idx == 0:\n return self.valtest_step(batch, batch_idx, 'val')\n\n def validation_step(self, batch, batch_idx):\n return self.valtest_step(batch, batch_idx, 'val')\n\n def test_step(self, batch, batch_idx):\n return self.valtest_step(batch, batch_idx, 'test')\n\n def predict_step(self, batch, batch_idx):\n return self.fwd_step(batch, batch_idx)\n\n def load_dataset(self, split, suffix=''):\n split = split+suffix\n nn = CONFIGS[self.algorithm][split]['num_nodes']\n self.dataset_kwargs['split'] = split\n if (split, nn) not in self._datasets:\n self._datasets[(split, nn)] = self.dataset_class(\n self.dataset_root,\n nn,\n CONFIGS[self.algorithm][split]['num_samples'],\n algorithm=self.algorithm,\n **self.dataset_kwargs)\n self.dataset = self._datasets[(split, nn)]\n print(f'Loading {self.dataset=} (num nodes: {nn}) with kwargs')\n pprint(self.dataset_kwargs)\n print()\n\n def get_a_loader(self, split, suffix=''):\n self.load_dataset(split, suffix='')\n self.algorithm_module.dataset_spec = self.dataset.spec\n dl = DataLoader(self.dataset,\n batch_size=get_hyperparameters()['batch_size'],\n shuffle=True if split == 'train' else False,\n drop_last=False,\n follow_batch=['edge_index'],\n num_workers=1,\n persistent_workers=True)\n return dl\n\n def train_dataloader(self):\n return self.get_a_loader('train')\n\n def val_dataloader_alt(self):\n return [self.get_a_loader('val'), self.get_a_loader('test')]\n\n def val_dataloader(self):\n return self.get_a_loader('val')\n\n def test_dataloader(self, suffix=''):\n return self.get_a_loader('test'+suffix)\n\n def configure_optimizers(self):\n lr = self.learning_rate\n wd = self.weight_decay\n optimizer = optim.Adam(self.parameters(),\n weight_decay=wd,\n lr=lr)\n return optimizer" }, { "identifier": "get_hyperparameters", "path": "hyperparameters.py", "snippet": "def get_hyperparameters():\n return {\n 'dim_latent': 128,\n 'num_bits': 8,\n 'weight_decay': 0,\n 'lr': 0.0003,\n 'nee_warmup_steps': 4000,\n 'dim_nodes_mst_prim': 1,\n 'dim_target_mst_prim': 1,\n 'device': 'cuda',\n 'batch_size': 64,\n 'bias': True,\n 'seed': 47, # for dataset generation\n 'calculate_termination_statistics': False,\n }" }, { "identifier": "CONFIGS", "path": "datasets/_configs.py", "snippet": "CONFIGS = defaultdict(lambda: _DEFAULT_CONFIG)" }, { "identifier": "cross_entropy", "path": "utils_execution.py", "snippet": "def cross_entropy(pred, softmax_idx, truth_1h, num_nodes):\n lsm_pred = torch.log(torch_geometric.utils.softmax(pred, softmax_idx, num_nodes=num_nodes)+1e-9)\n # truth_1h = F.one_hot(truth, num_nodes)\n return (-truth_1h*lsm_pred)" }, { "identifier": "check_edge_index_sorted", "path": "utils_execution.py", "snippet": "def check_edge_index_sorted(ei):\n for i in range(ei.shape[1]-1):\n assert ei[0][i] <= ei[0][i+1]\n if ei[0][i] == ei[0][i+1]:\n assert ei[1][i] < ei[1][i+1]" }, { "identifier": "prepare_constants", "path": "utils_execution.py", "snippet": "def prepare_constants(batch):\n SIZE = batch.num_nodes\n STEPS_SIZE = batch.lengths.max()-1\n return SIZE, STEPS_SIZE" }, { "identifier": "edge_one_hot_encode_pointers", "path": "utils_execution.py", "snippet": "def edge_one_hot_encode_pointers(pred, edge_index):\n pred_ei = torch.stack((torch.arange(pred.shape[0]).to(pred), pred))\n amat = torch_geometric.utils.to_dense_adj(pred_ei)\n return amat[0, edge_index[0], edge_index[1]]" }, { "identifier": "get_number_of_nodes", "path": "utils_execution.py", "snippet": "def get_number_of_nodes(algorithm, split):\n nns = CONFIGS[algorithm][split]['num_nodes']\n if isinstance(nns, int):\n nns = [nns]\n return nns" } ]
from collections import defaultdict from pprint import pprint from torch_geometric.loader import DataLoader from pytorch_lightning.trainer.supporters import CombinedLoader from baselines.beam_search import vmapped_beam_search_rollout, BEAM_WIDTH from models.algorithm_reasoner import AlgorithmReasoner, LitAlgorithmReasoner from hyperparameters import get_hyperparameters from torch_geometric.utils import k_hop_subgraph from datasets._configs import CONFIGS from utils_execution import cross_entropy, check_edge_index_sorted, prepare_constants, edge_one_hot_encode_pointers, get_number_of_nodes from clrs import Type, Location, Stage import copy import itertools import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch_scatter import torch_geometric import pytorch_lightning as pl
14,872
dataset_kwargs, bias=bias, use_TF=use_TF, transferring=transferring, learning_rate=learning_rate, **algo_reasoner_kwargs) self.algorithm_module = TSPReasoner(self.dataset.spec, self.dataset[0], hidden_dim, algo_processor, bias=bias, use_TF=use_TF, transferring=transferring, timeit=self.timeit, double_process=double_process, **algo_reasoner_kwargs) self.ensure_permutation = ensure_permutation self.double_process = double_process self.save_hyperparameters(ignore=['algo_processor']) def training_step(self, batch, batch_idx): ret = {'loss': 0, 'losses_dict': defaultdict(list), 'accuracies': defaultdict(list)} for bb in batch: ans = super().training_step(bb, batch_idx) ret['loss'] += ans['loss'] for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k].append(v) ret['loss'] /= len(batch) for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k] = torch.tensor(v).mean() return ret def get_tour_metrics(self, output_logits, batch): def get_mask(edges): mask = torch.zeros_like(batch.edge_index[0]) j = 0 for i in range(batch.edge_index.shape[1]): u1, v1 = batch.edge_index[:, i] u2, v2 = edges[:, j] if u1 == u2 and v1 == v2: mask[i] = 1 j += 1 if j == edges.shape[1]: break assert j == edges.shape[1] return mask def get_mask_v2(edges): dense_edges = torch_geometric.utils.to_dense_adj(edges, batch=batch.batch).bool() dense_edges_batch = torch_geometric.utils.to_dense_adj(batch.edge_index, batch=batch.batch).bool() edge_index, mask = torch_geometric.utils.dense_to_sparse(((dense_edges & dense_edges_batch).float()+1)) mask = mask - 1 return mask acc = None # st = time.time() outputs = type(self.algorithm_module).convert_logits_to_outputs( self.dataset.spec, output_logits, batch.edge_index[0], batch.edge_index[1], batch.num_nodes, batch.batch, include_probabilities=False)['output'] for name in outputs: pred = outputs[name] pred_gt = getattr(batch, name) stage, loc, data_type = self.dataset.spec[name] if loc == Location.NODE: if name == 'predecessor_index': tours = torch.stack([torch.arange(pred.shape[0]).to(pred), pred]) mask = get_mask_v2(tours).bool() st = time.time() mattr = batch.edge_attr[mask] mbatch = batch.edge_index_batch[mask] msrc, mdst = batch.edge_index[:, mask] tour_len = torch_scatter.scatter_sum(mattr, mbatch) tour_correctness = torch_scatter.scatter_sum((msrc == mdst.sort().values), mbatch) assert sum(tour_correctness)/len(tour_correctness) == 1 return dict(tour_len=tour_len.mean(), tour_len_gt=batch.optimal_value.mean().item(), tour_correctness=sum(tour_correctness)/len(tour_correctness), tour_relative_error=((tour_len-batch.optimal_value)/batch.optimal_value).mean()) def process_TSP_tour_greedy(self, batch, output_logits): mask_active_nodes = torch.tensor(batch.start_route).bool() mask_edges_to_nodes_in_tour = torch.zeros_like(batch.edge_index[0]).bool() max_nodes_per_graph = batch.batch.unique(return_counts=True)[1].max() num_nodes_per_graph = batch.num_nodes // batch.num_graphs for _ in range(max_nodes_per_graph - 1): mask_active_edges = mask_active_nodes[batch.edge_index[0]] & ~mask_edges_to_nodes_in_tour # Any edge outwards of active nodes and not pointing to previously used node mask_edges_to_nodes_in_tour |= mask_active_nodes[batch.edge_index[1]] # any edge towards the active nodes should not be used in future iterations sloops = (batch.edge_index[0] == batch.edge_index[1]) preds = output_logits['output']['predecessor_index'].clone() preds = preds.masked_fill(~mask_active_edges | sloops, -1e6) # nudge the max value to ensure there is a unique maximum max_idxs = preds.reshape(-1, num_nodes_per_graph).argmax(-1) max_idxs = F.one_hot(max_idxs, num_nodes_per_graph) preds[max_idxs.bool().flatten()] = (preds.reshape(-1, num_nodes_per_graph)[max_idxs.bool()] + 1e-4).flatten() output_logits['output']['predecessor_index'][mask_active_nodes[batch.edge_index[0]]] = preds[mask_active_nodes[batch.edge_index[0]]] new_active_nodes = preds.reshape(-1, num_nodes_per_graph).argmax(-1)[mask_active_nodes.bool()].unsqueeze(-1) # NOTE the reshape/flatten mechanic may not work if graphs in the same batch are of different sizes (consider using torch_scatter.scatter_max) mask_active_nodes = F.one_hot(new_active_nodes, num_nodes_per_graph).flatten().bool() final_pred_mask = mask_active_nodes[batch.edge_index[0]] & batch.start_route.bool()[batch.edge_index[1]] output_logits['output']['predecessor_index'] = output_logits['output']['predecessor_index'].masked_fill(final_pred_mask, 1e8) return output_logits def process_TSP_tour_BS(self, batch, output_logits): start_route = torch_geometric.utils.to_dense_batch(batch.start_route, batch=batch.batch)[0] dens_logits = torch_geometric.utils.to_dense_adj(batch.edge_index, batch=batch.batch, edge_attr=output_logits['output']['predecessor_index']) num_nodes = start_route.shape[1] # st = time.time()
class TSPReasoner(AlgorithmReasoner): def __init__(self, spec, data, latent_features, algo_processor, bias=True, use_TF=False, L1_loss=False, global_termination_pool='max', #'predinet', get_attention=False, use_batch_norm=False, transferring=False, timeit=True, double_process=False, **algo_reasoner_kwargs): super().__init__( spec, data, latent_features, algo_processor, use_TF=use_TF, timeit=timeit, L1_loss=L1_loss, global_termination_pool=global_termination_pool, get_attention=get_attention, use_batch_norm=use_batch_norm, transferring=transferring, **algo_reasoner_kwargs, ) self.step_idx = 0 self.assert_checks = False self.debug = False self.debug_epoch_threshold = 1e9 self.next_step_pool = True self.double_process = double_process self.lambda_mul = 1# 0.0001 self.transferring = transferring def get_input_output_hints(self, batch): hint_inp_curr = dict() hint_out_curr = dict() return hint_inp_curr, hint_out_curr def process( self, *args, **kwargs): self.all_hint_logits, self.last_logits, self.all_masks_graph = super().process( *args, first_n_processors=1000 if not self.double_process else 1, **kwargs) if self.double_process: self.all_hint_logits, self.last_logits, self.all_masks_graph = super().process( *args, init_last_latent=self.last_latent, **kwargs) return self.all_hint_logits, self.last_logits, self.all_masks_graph class LitTSPReasoner(LitAlgorithmReasoner): def __init__(self, hidden_dim, algo_processor, dataset_class, dataset_root, dataset_kwargs, bias=True, use_TF=False, ensure_permutation='greedy', transferring=False, learning_rate=get_hyperparameters()['lr'], double_process=False, **algo_reasoner_kwargs): super().__init__(hidden_dim, algo_processor, dataset_class, dataset_root, dataset_kwargs, bias=bias, use_TF=use_TF, transferring=transferring, learning_rate=learning_rate, **algo_reasoner_kwargs) self.algorithm_module = TSPReasoner(self.dataset.spec, self.dataset[0], hidden_dim, algo_processor, bias=bias, use_TF=use_TF, transferring=transferring, timeit=self.timeit, double_process=double_process, **algo_reasoner_kwargs) self.ensure_permutation = ensure_permutation self.double_process = double_process self.save_hyperparameters(ignore=['algo_processor']) def training_step(self, batch, batch_idx): ret = {'loss': 0, 'losses_dict': defaultdict(list), 'accuracies': defaultdict(list)} for bb in batch: ans = super().training_step(bb, batch_idx) ret['loss'] += ans['loss'] for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k].append(v) ret['loss'] /= len(batch) for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k] = torch.tensor(v).mean() return ret def get_tour_metrics(self, output_logits, batch): def get_mask(edges): mask = torch.zeros_like(batch.edge_index[0]) j = 0 for i in range(batch.edge_index.shape[1]): u1, v1 = batch.edge_index[:, i] u2, v2 = edges[:, j] if u1 == u2 and v1 == v2: mask[i] = 1 j += 1 if j == edges.shape[1]: break assert j == edges.shape[1] return mask def get_mask_v2(edges): dense_edges = torch_geometric.utils.to_dense_adj(edges, batch=batch.batch).bool() dense_edges_batch = torch_geometric.utils.to_dense_adj(batch.edge_index, batch=batch.batch).bool() edge_index, mask = torch_geometric.utils.dense_to_sparse(((dense_edges & dense_edges_batch).float()+1)) mask = mask - 1 return mask acc = None # st = time.time() outputs = type(self.algorithm_module).convert_logits_to_outputs( self.dataset.spec, output_logits, batch.edge_index[0], batch.edge_index[1], batch.num_nodes, batch.batch, include_probabilities=False)['output'] for name in outputs: pred = outputs[name] pred_gt = getattr(batch, name) stage, loc, data_type = self.dataset.spec[name] if loc == Location.NODE: if name == 'predecessor_index': tours = torch.stack([torch.arange(pred.shape[0]).to(pred), pred]) mask = get_mask_v2(tours).bool() st = time.time() mattr = batch.edge_attr[mask] mbatch = batch.edge_index_batch[mask] msrc, mdst = batch.edge_index[:, mask] tour_len = torch_scatter.scatter_sum(mattr, mbatch) tour_correctness = torch_scatter.scatter_sum((msrc == mdst.sort().values), mbatch) assert sum(tour_correctness)/len(tour_correctness) == 1 return dict(tour_len=tour_len.mean(), tour_len_gt=batch.optimal_value.mean().item(), tour_correctness=sum(tour_correctness)/len(tour_correctness), tour_relative_error=((tour_len-batch.optimal_value)/batch.optimal_value).mean()) def process_TSP_tour_greedy(self, batch, output_logits): mask_active_nodes = torch.tensor(batch.start_route).bool() mask_edges_to_nodes_in_tour = torch.zeros_like(batch.edge_index[0]).bool() max_nodes_per_graph = batch.batch.unique(return_counts=True)[1].max() num_nodes_per_graph = batch.num_nodes // batch.num_graphs for _ in range(max_nodes_per_graph - 1): mask_active_edges = mask_active_nodes[batch.edge_index[0]] & ~mask_edges_to_nodes_in_tour # Any edge outwards of active nodes and not pointing to previously used node mask_edges_to_nodes_in_tour |= mask_active_nodes[batch.edge_index[1]] # any edge towards the active nodes should not be used in future iterations sloops = (batch.edge_index[0] == batch.edge_index[1]) preds = output_logits['output']['predecessor_index'].clone() preds = preds.masked_fill(~mask_active_edges | sloops, -1e6) # nudge the max value to ensure there is a unique maximum max_idxs = preds.reshape(-1, num_nodes_per_graph).argmax(-1) max_idxs = F.one_hot(max_idxs, num_nodes_per_graph) preds[max_idxs.bool().flatten()] = (preds.reshape(-1, num_nodes_per_graph)[max_idxs.bool()] + 1e-4).flatten() output_logits['output']['predecessor_index'][mask_active_nodes[batch.edge_index[0]]] = preds[mask_active_nodes[batch.edge_index[0]]] new_active_nodes = preds.reshape(-1, num_nodes_per_graph).argmax(-1)[mask_active_nodes.bool()].unsqueeze(-1) # NOTE the reshape/flatten mechanic may not work if graphs in the same batch are of different sizes (consider using torch_scatter.scatter_max) mask_active_nodes = F.one_hot(new_active_nodes, num_nodes_per_graph).flatten().bool() final_pred_mask = mask_active_nodes[batch.edge_index[0]] & batch.start_route.bool()[batch.edge_index[1]] output_logits['output']['predecessor_index'] = output_logits['output']['predecessor_index'].masked_fill(final_pred_mask, 1e8) return output_logits def process_TSP_tour_BS(self, batch, output_logits): start_route = torch_geometric.utils.to_dense_batch(batch.start_route, batch=batch.batch)[0] dens_logits = torch_geometric.utils.to_dense_adj(batch.edge_index, batch=batch.batch, edge_attr=output_logits['output']['predecessor_index']) num_nodes = start_route.shape[1] # st = time.time()
tours = torch.tensor(np.array(vmapped_beam_search_rollout(
0
2023-11-20 15:32:43+00:00
24k
bearyi26/DCPT
lib/train/base_functions.py
[ { "identifier": "Lasot", "path": "lib/train/dataset/lasot.py", "snippet": "class Lasot(BaseVideoDataset):\n \"\"\" LaSOT dataset.\n\n Publication:\n LaSOT: A High-quality Benchmark for Large-scale Single Object Tracking\n Heng Fan, Liting Lin, Fan Yang, Peng Chu, Ge Deng, Sijia Yu, Hexin Bai, Yong Xu, Chunyuan Liao and Haibin Ling\n CVPR, 2019\n https://arxiv.org/pdf/1809.07845.pdf\n\n Download the dataset from https://cis.temple.edu/lasot/download.html\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the lasot dataset.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\n videos with subscripts -1, -3, and -5 from each class will be used for training.\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\n vid_ids or split option can be used at a time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().lasot_dir if root is None else root\n super().__init__('LaSOT', root, image_loader)\n\n # Keep a list of all classes\n self.class_list = [f for f in os.listdir(self.root)]\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\n\n self.sequence_list = self._build_sequence_list(vid_ids, split)\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.seq_per_class = self._build_class_list()\n\n def _build_sequence_list(self, vid_ids=None, split=None):\n if split is not None:\n if vid_ids is not None:\n raise ValueError('Cannot set both split_name and vid_ids.')\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\n else:\n raise ValueError('Unknown split name.')\n # sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\n sequence_list = pandas.read_csv(file_path, header=None).squeeze(\"columns\").values.tolist()\n elif vid_ids is not None:\n sequence_list = [c+'-'+str(v) for c in self.class_list for v in vid_ids]\n else:\n raise ValueError('Set either split_name or vid_ids.')\n\n return sequence_list\n\n def _build_class_list(self):\n seq_per_class = {}\n for seq_id, seq_name in enumerate(self.sequence_list):\n class_name = seq_name.split('-')[0]\n if class_name in seq_per_class:\n seq_per_class[class_name].append(seq_id)\n else:\n seq_per_class[class_name] = [seq_id]\n\n return seq_per_class\n\n def get_name(self):\n return 'lasot'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False, low_memory=False).values\n return torch.tensor(gt)\n\n def _read_target_visible(self, seq_path):\n # Read full occlusion and out_of_view\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\n\n with open(occlusion_file, 'r', newline='') as f:\n occlusion = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\n with open(out_of_view_file, 'r') as f:\n out_of_view = torch.ByteTensor([int(v) for v in list(csv.reader(f))[0]])\n\n target_visible = ~occlusion & ~out_of_view\n\n return target_visible\n\n def _get_sequence_path(self, seq_id):\n seq_name = self.sequence_list[seq_id]\n class_name = seq_name.split('-')[0]\n vid_id = seq_name.split('-')[1]\n\n return os.path.join(self.root, class_name, class_name + '-' + vid_id)\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = self._read_target_visible(seq_path) & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\n\n def _get_class(self, seq_path):\n raw_class = seq_path.split('/')[-2]\n return raw_class\n\n def get_class_name(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n obj_class = self._get_class(seq_path)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n\n obj_class = self._get_class(seq_path)\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "Got10k", "path": "lib/train/dataset/got10k.py", "snippet": "class Got10k(BaseVideoDataset):\n \"\"\" GOT-10k dataset.\n\n Publication:\n GOT-10k: A Large High-Diversity Benchmark for Generic Object Tracking in the Wild\n Lianghua Huang, Xin Zhao, and Kaiqi Huang\n arXiv:1810.11981, 2018\n https://arxiv.org/pdf/1810.11981.pdf\n\n Download dataset from http://got-10k.aitestunion.com/downloads\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\n not NOT the official got-10k validation split. To use the official validation split, provide that as\n the root folder instead.\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\n options can be used at the same time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().got10k_dir if root is None else root\n super().__init__('GOT10k', root, image_loader)\n\n # all folders inside the root\n self.sequence_list = self._get_sequence_list()\n\n # seq_id is the index of the folder inside the got10k root path\n if split is not None:\n if seq_ids is not None:\n raise ValueError('Cannot set both split_name and seq_ids.')\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_split.txt')\n elif split == 'val':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_val_split.txt')\n elif split == 'train_full':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_full_split.txt')\n elif split == 'vottrain':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_train_split.txt')\n elif split == 'votval':\n file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_val_split.txt')\n else:\n raise ValueError('Unknown split name.')\n # seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\n seq_ids = pandas.read_csv(file_path, header=None, dtype=np.int64).squeeze(\"columns\").values.tolist()\n elif seq_ids is None:\n seq_ids = list(range(0, len(self.sequence_list)))\n\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.sequence_meta_info = self._load_meta_info()\n self.seq_per_class = self._build_seq_per_class()\n\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def get_name(self):\n return 'got10k'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def _load_meta_info(self):\n sequence_meta_info = {s: self._read_meta(os.path.join(self.root, s)) for s in self.sequence_list}\n return sequence_meta_info\n\n def _read_meta(self, seq_path):\n try:\n with open(os.path.join(seq_path, 'meta_info.ini')) as f:\n meta_info = f.readlines()\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1][:-1],\n 'motion_class': meta_info[6].split(': ')[-1][:-1],\n 'major_class': meta_info[7].split(': ')[-1][:-1],\n 'root_class': meta_info[8].split(': ')[-1][:-1],\n 'motion_adverb': meta_info[9].split(': ')[-1][:-1]})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n\n for i, s in enumerate(self.sequence_list):\n object_class = self.sequence_meta_info[s]['object_class_name']\n if object_class in seq_per_class:\n seq_per_class[object_class].append(i)\n else:\n seq_per_class[object_class] = [i]\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _get_sequence_list(self):\n with open(os.path.join(self.root, 'list.txt')) as f:\n dir_list = list(csv.reader(f))\n dir_list = [dir_name[0] for dir_name in dir_list]\n return dir_list\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False, low_memory=False).values\n return torch.tensor(gt)\n\n def _read_target_visible(self, seq_path):\n # Read full occlusion and out_of_view\n occlusion_file = os.path.join(seq_path, \"absence.label\")\n cover_file = os.path.join(seq_path, \"cover.label\")\n\n with open(occlusion_file, 'r', newline='') as f:\n occlusion = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\n with open(cover_file, 'r', newline='') as f:\n cover = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])\n\n target_visible = ~occlusion & (cover>0).byte()\n\n visible_ratio = cover.float() / 8\n return target_visible, visible_ratio\n\n def _get_sequence_path(self, seq_id):\n return os.path.join(self.root, self.sequence_list[seq_id])\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible, visible_ratio = self._read_target_visible(seq_path)\n visible = visible & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return self.image_loader(self._get_frame_path(seq_path, frame_id))\n\n def get_class_name(self, seq_id):\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n return obj_meta['object_class_name']\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n return frame_list, anno_frames, obj_meta" }, { "identifier": "TrackingNet", "path": "lib/train/dataset/tracking_net.py", "snippet": "class TrackingNet(BaseVideoDataset):\n \"\"\" TrackingNet dataset.\n\n Publication:\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\n ECCV, 2018\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\n\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - The path to the TrackingNet folder, containing the training sets.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\n sets (0 - 11) will be used.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().trackingnet_dir if root is None else root\n super().__init__('TrackingNet', root, image_loader)\n\n if set_ids is None:\n set_ids = [i for i in range(12)]\n\n self.set_ids = set_ids\n\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\n # video_name for each sequence\n self.sequence_list = list_sequences(self.root, self.set_ids)\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\n\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\n\n # we do not have the class_lists for the tracking net\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def _load_class_info(self):\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\n\n with open(class_map_path, 'r') as f:\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\n\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_to_class_map, seq_per_class\n\n def get_name(self):\n return 'trackingnet'\n\n def has_class_info(self):\n return True\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n bb_anno_file = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"anno\", vid_name + \".txt\")\n gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,\n low_memory=False).values\n return torch.tensor(gt)\n\n def get_sequence_info(self, seq_id):\n bbox = self._read_bb_anno(seq_id)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = valid.clone().byte()\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, seq_id, frame_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n frame_path = os.path.join(self.root, \"TRAIN_\" + str(set_id), \"frames\", vid_name, str(frame_id) + \".jpg\")\n return self.image_loader(frame_path)\n\n def _get_class(self, seq_id):\n seq_name = self.sequence_list[seq_id][1]\n return self.seq_to_class_map[seq_name]\n\n def get_class_name(self, seq_id):\n obj_class = self._get_class(seq_id)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n obj_class = self._get_class(seq_id)\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "ImagenetVID", "path": "lib/train/dataset/imagenetvid.py", "snippet": "class ImagenetVID(BaseVideoDataset):\n \"\"\" Imagenet VID dataset.\n\n Publication:\n ImageNet Large Scale Visual Recognition Challenge\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\n IJCV, 2015\n https://arxiv.org/pdf/1409.0575.pdf\n\n Download the dataset from http://image-net.org/\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1):\n \"\"\"\n args:\n root - path to the imagenet vid dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n min_length - Minimum allowed sequence length.\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\n which cover complete image.\n \"\"\"\n root = env_settings().imagenet_dir if root is None else root\n super().__init__(\"imagenetvid\", root, image_loader)\n\n cache_file = os.path.join(root, 'cache.json')\n if os.path.isfile(cache_file):\n # If available, load the pre-processed cache file containing meta-info for each sequence\n with open(cache_file, 'r') as f:\n sequence_list_dict = json.load(f)\n\n self.sequence_list = sequence_list_dict\n else:\n # Else process the imagenet annotations and generate the cache file\n self.sequence_list = self._process_anno(root)\n\n with open(cache_file, 'w') as f:\n json.dump(self.sequence_list, f)\n\n # Filter the sequences based on min_length and max_target_area in the first frame\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\n get_target_to_image_ratio(x) < max_target_area]\n\n def get_name(self):\n return 'imagenetvid'\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_sequence_info(self, seq_id):\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, sequence, frame_id):\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\n frame_number = frame_id + sequence['start_frame']\n frame_path = os.path.join(self.root, 'Data', 'VID', 'train', set_name, vid_name,\n '{:06d}.JPEG'.format(frame_number))\n return self.image_loader(frame_path)\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n sequence = self.sequence_list[seq_id]\n\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n # Create anno dict\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n # added the class info to the meta info\n object_meta = OrderedDict({'object_class': sequence['class_name'],\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta\n\n def _process_anno(self, root):\n # Builds individual tracklets\n base_vid_anno_path = os.path.join(root, 'Annotations', 'VID', 'train')\n\n all_sequences = []\n for set in sorted(os.listdir(base_vid_anno_path)):\n set_id = int(set.split('_')[-1])\n for vid in sorted(os.listdir(os.path.join(base_vid_anno_path, set))):\n\n vid_id = int(vid.split('_')[-1])\n anno_files = sorted(os.listdir(os.path.join(base_vid_anno_path, set, vid)))\n\n frame1_anno = ET.parse(os.path.join(base_vid_anno_path, set, vid, anno_files[0]))\n image_size = [int(frame1_anno.find('size/width').text), int(frame1_anno.find('size/height').text)]\n\n objects = [ET.ElementTree(file=os.path.join(base_vid_anno_path, set, vid, f)).findall('object')\n for f in anno_files]\n\n tracklets = {}\n\n # Find all tracklets along with start frame\n for f_id, all_targets in enumerate(objects):\n for target in all_targets:\n tracklet_id = target.find('trackid').text\n if tracklet_id not in tracklets:\n tracklets[tracklet_id] = f_id\n\n for tracklet_id, tracklet_start in tracklets.items():\n tracklet_anno = []\n target_visible = []\n class_name_id = None\n\n for f_id in range(tracklet_start, len(objects)):\n found = False\n for target in objects[f_id]:\n if target.find('trackid').text == tracklet_id:\n if not class_name_id:\n class_name_id = target.find('name').text\n x1 = int(target.find('bndbox/xmin').text)\n y1 = int(target.find('bndbox/ymin').text)\n x2 = int(target.find('bndbox/xmax').text)\n y2 = int(target.find('bndbox/ymax').text)\n\n tracklet_anno.append([x1, y1, x2 - x1, y2 - y1])\n target_visible.append(target.find('occluded').text == '0')\n\n found = True\n break\n if not found:\n break\n\n new_sequence = {'set_id': set_id, 'vid_id': vid_id, 'class_name': class_name_id,\n 'start_frame': tracklet_start, 'anno': tracklet_anno,\n 'target_visible': target_visible, 'image_size': image_size}\n all_sequences.append(new_sequence)\n\n return all_sequences" }, { "identifier": "MSCOCOSeq", "path": "lib/train/dataset/coco_seq.py", "snippet": "class MSCOCOSeq(BaseVideoDataset):\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\n\n Publication:\n Microsoft COCO: Common Objects in Context.\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\n ECCV, 2014\n https://arxiv.org/pdf/1405.0312.pdf\n\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\n organized as follows.\n - coco_root\n - annotations\n - instances_train2014.json\n - instances_train2017.json\n - images\n - train2014\n - train2017\n\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\"):\n \"\"\"\n args:\n root - path to the coco dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\n images will be used\n split - 'train' or 'val'.\n version - version of coco dataset (2014 or 2017)\n \"\"\"\n root = env_settings().coco_dir if root is None else root\n super().__init__('COCO', root, image_loader)\n\n self.img_pth = os.path.join(root, 'images/{}{}/'.format(split, version))\n self.anno_path = os.path.join(root, 'annotations/instances_{}{}.json'.format(split, version))\n\n # Load the COCO set.\n self.coco_set = COCO(self.anno_path)\n\n self.cats = self.coco_set.cats\n\n self.class_list = self.get_class_list()\n\n self.sequence_list = self._get_sequence_list()\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n self.seq_per_class = self._build_seq_per_class()\n\n def _get_sequence_list(self):\n ann_list = list(self.coco_set.anns.keys())\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\n\n return seq_list\n\n def is_video_sequence(self):\n return False\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_name(self):\n return 'coco'\n\n def has_class_info(self):\n return True\n\n def get_class_list(self):\n class_list = []\n for cat_id in self.cats.keys():\n class_list.append(self.cats[cat_id]['name'])\n return class_list\n\n def has_segmentation_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def get_sequence_info(self, seq_id):\n anno = self._get_anno(seq_id)\n\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\n\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\n\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\n\n visible = valid.clone().byte()\n\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\n\n def _get_anno(self, seq_id):\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\n\n return anno\n\n def _get_frames(self, seq_id):\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\n img = self.image_loader(os.path.join(self.img_pth, path))\n return img\n\n def get_meta_info(self, seq_id):\n try:\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\n 'motion_class': None,\n 'major_class': cat_dict_current['supercategory'],\n 'root_class': None,\n 'motion_adverb': None})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta\n\n\n def get_class_name(self, seq_id):\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n return cat_dict_current['name']\n\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\n # list containing these replicated images.\n frame = self._get_frames(seq_id)\n\n frame_list = [frame.copy() for _ in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\n\n object_meta = self.get_meta_info(seq_id)\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "BDD100K_Night", "path": "lib/train/dataset/bdd100k_night.py", "snippet": "class BDD100K_Night(BaseVideoDataset):\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None):\n root = env_settings().bdd100k_dir if root is None else root\n super().__init__('bdd100k_night', root, image_loader)\n\n self.img_pth = os.path.join(root, 'images/')\n self.anno_path = os.path.join(root, 'annotations/bdd100k_night.json')\n\n # load dataset\n self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()\n self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)\n if not self.anno_path == None:\n print('loading annotations into memory...')\n tic = time.time()\n with open(self.anno_path, 'r') as f:\n dataset = json.load(f)\n print('Done (t={:0.2f}s)'.format(time.time()- tic))\n self.dataset = dataset\n self.sequence_list = self._get_sequence_list()\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n\n #得到序列\n def _get_sequence_list(self):\n anns = {}\n for picture in self.dataset:\n for box in picture['labels']:\n anns[box['id']] = box\n anns[box['id']]['name'] = picture['name']\n self.anns = anns\n\n #anns对应的是每一个框\n seq_list = list(anns.keys())\n\n return seq_list\n\n def _get_anno(self, seq_id):\n anno = self.anns[self.sequence_list[seq_id]]\n return anno\n\n\n #得到图片帧\n def _get_frames(self, seq_id):\n path = self.anns[self.sequence_list[seq_id]]['name']\n img = self.image_loader(os.path.join(self.img_pth, path))\n return img\n\n #得到每一帧的bounding box\n def get_sequence_info(self, seq_id):\n anno = self._get_anno(seq_id)\n\n x = anno['box2d']['x1']\n y = anno['box2d']['y1']\n width = anno['box2d']['x2'] - anno['box2d']['x1']\n height = anno['box2d']['y2'] - anno['box2d']['y1']\n\n bbox = torch.Tensor([x,y,width,height]).view(1, 4)\n\n '''v0.4 BDD100K_Night avoid too small bounding boxes'''\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\n\n visible = valid.clone().byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def is_video_sequence(self):\n return False\n\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\n # BDD100K is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\n # list containing these replicated images.\n frame = self._get_frames(seq_id)\n\n frame_list = [frame.copy() for _ in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\n\n object_meta = self.get_meta_info(seq_id)\n\n return frame_list, anno_frames, object_meta\n\n def get_name(self):\n return 'bdd100k_night'\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_meta_info(self, seq_id):\n try:\n cat_dict_current = self.anns[self.sequence_list[seq_id]]['category']\n object_meta = OrderedDict({'object_class_name': cat_dict_current,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta" }, { "identifier": "SHIFT_Night", "path": "lib/train/dataset/shift_night.py", "snippet": "class SHIFT_Night(BaseVideoDataset):\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None):\n \"\"\"\n SHIFT_NIGHT Dataset\n \"\"\"\n root = env_settings().shift_dir if root is None else root\n super().__init__('shift_night', root, image_loader)\n\n sequence_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n sequence_path = os.path.join(sequence_path, 'data_specs', 'shift_info_1fps.json')\n with open(sequence_path, 'r') as f:\n info = json.load(f)\n self.info = info\n\n self.sequence_list = self._build_sequence_list()\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n def _build_sequence_list(self):\n sequence_list = [sequence for sequence in self.info.keys()]\n return sequence_list\n\n def _get_sequence_path(self, seq_id):\n seq_name = self.sequence_list[seq_id]\n video_name = seq_name.split('/')[0]\n return os.path.join(self.root, video_name), seq_name\n\n def _get_frame_path(self, seq_path, seq_name, frame_id):\n frame = self.info[seq_name]['frame'][frame_id]\n return os.path.join(seq_path, frame) # frames extracted from info.json\n\n def _get_frame(self, seq_path, seq_name, frame_id):\n return self.image_loader(self._get_frame_path(seq_path, seq_name, frame_id))\n\n def _read_bb_anno(self, seq_path, seq_name):\n bbox_all = []\n for bbox in self.info[seq_name]['box2d']:\n x = bbox['x1']\n y = bbox['y1']\n width = bbox['x2'] - bbox['x1']\n height = bbox['y2'] - bbox['y1']\n bbox_np = np.array([[x,y,width,height]])\n bbox_all.append(bbox_np)\n bbox_all_np = np.concatenate([bbox for bbox in bbox_all],axis=0)\n return torch.tensor(bbox_all_np)\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_sequence_info(self, seq_id):\n seq_path, seq_name = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path, seq_name)\n\n '''v0.4 Shift avoid too small bounding boxes'''\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\n visible = valid.clone().byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def get_name(self):\n return 'shift_night'\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path, seq_name = self._get_sequence_path(seq_id)\n\n frame_list = [self._get_frame(seq_path, seq_name, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n object_meta = OrderedDict({'object_class_name': self.info[seq_name]['category'],\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "ExDark", "path": "lib/train/dataset/exdark.py", "snippet": "class ExDark(BaseVideoDataset):\n \"\"\" The ExDark dataset. ExDark is an image dataset. Thus, we treat each image as a sequence of length 1.\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None):\n \"\"\"\n args:\n root - path to the coco dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\n images will be used\n split - 'train' or 'val'.\n \"\"\"\n root = env_settings().exdark_dir if root is None else root\n super().__init__('exdark', root, image_loader)\n\n self.img_pth = os.path.join(root, 'images/')\n self.anno_path = os.path.join(root, 'annotations/annotations.json')\n\n # Load the COCO set.\n self.coco_set = COCO(self.anno_path)\n\n self.cats = self.coco_set.cats\n\n self.class_list = self.get_class_list()\n\n self.sequence_list = self._get_sequence_list()\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n self.seq_per_class = self._build_seq_per_class()\n\n def _get_sequence_list(self):\n ann_list = list(self.coco_set.anns.keys())\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\n\n return seq_list\n\n def is_video_sequence(self):\n return False\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_name(self):\n return 'exdark'\n\n def has_class_info(self):\n return True\n\n def get_class_list(self):\n class_list = []\n for cat_id in self.cats.keys():\n class_list.append(self.cats[cat_id]['name'])\n return class_list\n\n def has_segmentation_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def get_sequence_info(self, seq_id):\n anno = self._get_anno(seq_id)\n\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\n\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\n\n '''v0.4 ExDark avoid too small bounding boxes'''\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\n\n visible = valid.clone().byte()\n\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\n\n def _get_anno(self, seq_id):\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\n\n return anno\n\n def _get_frames(self, seq_id):\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\n img = self.image_loader(os.path.join(self.img_pth, path))\n return img\n\n def get_meta_info(self, seq_id):\n try:\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\n 'motion_class': None,\n 'major_class': cat_dict_current['supercategory'],\n 'root_class': None,\n 'motion_adverb': None})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta\n\n\n def get_class_name(self, seq_id):\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n return cat_dict_current['name']\n\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\n # ExDark is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\n # list containing these replicated images.\n frame = self._get_frames(seq_id)\n\n frame_list = [frame.copy() for _ in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\n\n object_meta = self.get_meta_info(seq_id)\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "Got10k_lmdb", "path": "lib/train/dataset/got10k_lmdb.py", "snippet": "class Got10k_lmdb(BaseVideoDataset):\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,\n not NOT the official got-10k validation split. To use the official validation split, provide that as\n the root folder instead.\n seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'\n options can be used at the same time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n use_lmdb - whether the dataset is stored in lmdb format\n \"\"\"\n root = env_settings().got10k_lmdb_dir if root is None else root\n super().__init__('GOT10k_lmdb', root, image_loader)\n\n # all folders inside the root\n self.sequence_list = self._get_sequence_list()\n\n # seq_id is the index of the folder inside the got10k root path\n if split is not None:\n if seq_ids is not None:\n raise ValueError('Cannot set both split_name and seq_ids.')\n train_lib_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_split.txt')\n elif split == 'val':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_val_split.txt')\n elif split == 'train_full':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_train_full_split.txt')\n elif split == 'vottrain':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_train_split.txt')\n elif split == 'votval':\n file_path = os.path.join(train_lib_path, 'data_specs', 'got10k_vot_val_split.txt')\n else:\n raise ValueError('Unknown split name.')\n seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()\n elif seq_ids is None:\n seq_ids = list(range(0, len(self.sequence_list)))\n\n self.sequence_list = [self.sequence_list[i] for i in seq_ids]\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.sequence_meta_info = self._load_meta_info()\n self.seq_per_class = self._build_seq_per_class()\n\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def get_name(self):\n return 'got10k_lmdb'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def _load_meta_info(self):\n def _read_meta(meta_info):\n\n object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1],\n 'motion_class': meta_info[6].split(': ')[-1],\n 'major_class': meta_info[7].split(': ')[-1],\n 'root_class': meta_info[8].split(': ')[-1],\n 'motion_adverb': meta_info[9].split(': ')[-1]})\n\n return object_meta\n sequence_meta_info = {}\n for s in self.sequence_list:\n try:\n meta_str = decode_str(self.root, \"train/%s/meta_info.ini\" %s)\n sequence_meta_info[s] = _read_meta(meta_str.split('\\n'))\n except:\n sequence_meta_info[s] = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return sequence_meta_info\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n\n for i, s in enumerate(self.sequence_list):\n object_class = self.sequence_meta_info[s]['object_class_name']\n if object_class in seq_per_class:\n seq_per_class[object_class].append(i)\n else:\n seq_per_class[object_class] = [i]\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _get_sequence_list(self):\n dir_str = decode_str(self.root, 'train/list.txt')\n dir_list = dir_str.split('\\n')\n return dir_list\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line in got10k is empty\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\n gt_arr = np.array(gt_list).astype(np.float32)\n\n return torch.tensor(gt_arr)\n\n def _read_target_visible(self, seq_path):\n # full occlusion and out_of_view files\n occlusion_file = os.path.join(seq_path, \"absence.label\")\n cover_file = os.path.join(seq_path, \"cover.label\")\n # Read these files\n occ_list = list(map(int, decode_str(self.root, occlusion_file).split('\\n')[:-1])) # the last line in got10k is empty\n occlusion = torch.ByteTensor(occ_list)\n cover_list = list(map(int, decode_str(self.root, cover_file).split('\\n')[:-1])) # the last line in got10k is empty\n cover = torch.ByteTensor(cover_list)\n\n target_visible = ~occlusion & (cover>0).byte()\n\n visible_ratio = cover.float() / 8\n return target_visible, visible_ratio\n\n def _get_sequence_path(self, seq_id):\n return os.path.join(\"train\", self.sequence_list[seq_id])\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible, visible_ratio = self._read_target_visible(seq_path)\n visible = visible & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\n\n def get_class_name(self, seq_id):\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n return obj_meta['object_class_name']\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]\n\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n return frame_list, anno_frames, obj_meta" }, { "identifier": "Lasot_lmdb", "path": "lib/train/dataset/lasot_lmdb.py", "snippet": "class Lasot_lmdb(BaseVideoDataset):\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, vid_ids=None, split=None, data_fraction=None):\n \"\"\"\n args:\n root - path to the lasot dataset.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n vid_ids - List containing the ids of the videos (1 - 20) used for training. If vid_ids = [1, 3, 5], then the\n videos with subscripts -1, -3, and -5 from each class will be used for training.\n split - If split='train', the official train split (protocol-II) is used for training. Note: Only one of\n vid_ids or split option can be used at a time.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().lasot_lmdb_dir if root is None else root\n super().__init__('LaSOT_lmdb', root, image_loader)\n\n self.sequence_list = self._build_sequence_list(vid_ids, split)\n class_list = [seq_name.split('-')[0] for seq_name in self.sequence_list]\n self.class_list = []\n for ele in class_list:\n if ele not in self.class_list:\n self.class_list.append(ele)\n # Keep a list of all classes\n self.class_to_id = {cls_name: cls_id for cls_id, cls_name in enumerate(self.class_list)}\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n\n self.seq_per_class = self._build_class_list()\n\n def _build_sequence_list(self, vid_ids=None, split=None):\n if split is not None:\n if vid_ids is not None:\n raise ValueError('Cannot set both split_name and vid_ids.')\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n if split == 'train':\n file_path = os.path.join(ltr_path, 'data_specs', 'lasot_train_split.txt')\n else:\n raise ValueError('Unknown split name.')\n sequence_list = pandas.read_csv(file_path, header=None, squeeze=True).values.tolist()\n elif vid_ids is not None:\n sequence_list = [c+'-'+str(v) for c in self.class_list for v in vid_ids]\n else:\n raise ValueError('Set either split_name or vid_ids.')\n\n return sequence_list\n\n def _build_class_list(self):\n seq_per_class = {}\n for seq_id, seq_name in enumerate(self.sequence_list):\n class_name = seq_name.split('-')[0]\n if class_name in seq_per_class:\n seq_per_class[class_name].append(seq_id)\n else:\n seq_per_class[class_name] = [seq_id]\n\n return seq_per_class\n\n def get_name(self):\n return 'lasot_lmdb'\n\n def has_class_info(self):\n return True\n\n def has_occlusion_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_path):\n bb_anno_file = os.path.join(seq_path, \"groundtruth.txt\")\n gt_str_list = decode_str(self.root, bb_anno_file).split('\\n')[:-1] # the last line is empty\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\n gt_arr = np.array(gt_list).astype(np.float32)\n return torch.tensor(gt_arr)\n\n def _read_target_visible(self, seq_path):\n # Read full occlusion and out_of_view\n occlusion_file = os.path.join(seq_path, \"full_occlusion.txt\")\n out_of_view_file = os.path.join(seq_path, \"out_of_view.txt\")\n\n occ_list = list(map(int, decode_str(self.root, occlusion_file).split(',')))\n occlusion = torch.ByteTensor(occ_list)\n out_view_list = list(map(int, decode_str(self.root, out_of_view_file).split(',')))\n out_of_view = torch.ByteTensor(out_view_list)\n\n target_visible = ~occlusion & ~out_of_view\n\n return target_visible\n\n def _get_sequence_path(self, seq_id):\n seq_name = self.sequence_list[seq_id]\n class_name = seq_name.split('-')[0]\n vid_id = seq_name.split('-')[1]\n\n return os.path.join(class_name, class_name + '-' + vid_id)\n\n def get_sequence_info(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n bbox = self._read_bb_anno(seq_path)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = self._read_target_visible(seq_path) & valid.byte()\n\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame_path(self, seq_path, frame_id):\n return os.path.join(seq_path, 'img', '{:08}.jpg'.format(frame_id+1)) # frames start from 1\n\n def _get_frame(self, seq_path, frame_id):\n return decode_img(self.root, self._get_frame_path(seq_path, frame_id))\n\n def _get_class(self, seq_path):\n raw_class = seq_path.split('/')[-2]\n return raw_class\n\n def get_class_name(self, seq_id):\n seq_path = self._get_sequence_path(seq_id)\n obj_class = self._get_class(seq_path)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n seq_path = self._get_sequence_path(seq_id)\n\n obj_class = self._get_class(seq_path)\n frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "ImagenetVID_lmdb", "path": "lib/train/dataset/imagenetvid_lmdb.py", "snippet": "class ImagenetVID_lmdb(BaseVideoDataset):\n \"\"\" Imagenet VID dataset.\n\n Publication:\n ImageNet Large Scale Visual Recognition Challenge\n Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,\n Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei\n IJCV, 2015\n https://arxiv.org/pdf/1409.0575.pdf\n\n Download the dataset from http://image-net.org/\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, min_length=0, max_target_area=1):\n \"\"\"\n args:\n root - path to the imagenet vid dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n min_length - Minimum allowed sequence length.\n max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets\n which cover complete image.\n \"\"\"\n root = env_settings().imagenet_dir if root is None else root\n super().__init__(\"imagenetvid_lmdb\", root, image_loader)\n\n sequence_list_dict = decode_json(root, \"cache.json\")\n self.sequence_list = sequence_list_dict\n\n # Filter the sequences based on min_length and max_target_area in the first frame\n self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and\n get_target_to_image_ratio(x) < max_target_area]\n\n def get_name(self):\n return 'imagenetvid_lmdb'\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def get_sequence_info(self, seq_id):\n bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])\n valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)\n visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()\n return {'bbox': bb_anno, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, sequence, frame_id):\n set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])\n vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])\n frame_number = frame_id + sequence['start_frame']\n frame_path = os.path.join('Data', 'VID', 'train', set_name, vid_name,\n '{:06d}.JPEG'.format(frame_number))\n return decode_img(self.root, frame_path)\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n sequence = self.sequence_list[seq_id]\n\n frame_list = [self._get_frame(sequence, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n # Create anno dict\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n # added the class info to the meta info\n object_meta = OrderedDict({'object_class': sequence['class_name'],\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "MSCOCOSeq_lmdb", "path": "lib/train/dataset/coco_seq_lmdb.py", "snippet": "class MSCOCOSeq_lmdb(BaseVideoDataset):\n \"\"\" The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.\n\n Publication:\n Microsoft COCO: Common Objects in Context.\n Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,\n Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick\n ECCV, 2014\n https://arxiv.org/pdf/1405.0312.pdf\n\n Download the images along with annotations from http://cocodataset.org/#download. The root folder should be\n organized as follows.\n - coco_root\n - annotations\n - instances_train2014.json\n - instances_train2017.json\n - images\n - train2014\n - train2017\n\n Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.\n \"\"\"\n\n def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split=\"train\", version=\"2014\"):\n \"\"\"\n args:\n root - path to the coco dataset.\n image_loader (default_image_loader) - The function to read the images. If installed,\n jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,\n opencv's imread is used.\n data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the\n images will be used\n split - 'train' or 'val'.\n version - version of coco dataset (2014 or 2017)\n \"\"\"\n root = env_settings().coco_dir if root is None else root\n super().__init__('COCO_lmdb', root, image_loader)\n self.root = root\n self.img_pth = 'images/{}{}/'.format(split, version)\n self.anno_path = 'annotations/instances_{}{}.json'.format(split, version)\n\n # Load the COCO set.\n print('loading annotations into memory...')\n tic = time.time()\n coco_json = decode_json(root, self.anno_path)\n print('Done (t={:0.2f}s)'.format(time.time() - tic))\n\n self.coco_set = COCO(coco_json)\n\n self.cats = self.coco_set.cats\n\n self.class_list = self.get_class_list()\n\n self.sequence_list = self._get_sequence_list()\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))\n self.seq_per_class = self._build_seq_per_class()\n\n def _get_sequence_list(self):\n ann_list = list(self.coco_set.anns.keys())\n seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]\n\n return seq_list\n\n def is_video_sequence(self):\n return False\n\n def get_num_classes(self):\n return len(self.class_list)\n\n def get_name(self):\n return 'coco_lmdb'\n\n def has_class_info(self):\n return True\n\n def get_class_list(self):\n class_list = []\n for cat_id in self.cats.keys():\n class_list.append(self.cats[cat_id]['name'])\n return class_list\n\n def has_segmentation_info(self):\n return True\n\n def get_num_sequences(self):\n return len(self.sequence_list)\n\n def _build_seq_per_class(self):\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_per_class\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def get_sequence_info(self, seq_id):\n anno = self._get_anno(seq_id)\n\n bbox = torch.Tensor(anno['bbox']).view(1, 4)\n\n mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)\n\n '''2021.1.3 To avoid too small bounding boxes. Here we change the threshold to 50 pixels'''\n valid = (bbox[:, 2] > 50) & (bbox[:, 3] > 50)\n\n visible = valid.clone().byte()\n\n return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}\n\n def _get_anno(self, seq_id):\n anno = self.coco_set.anns[self.sequence_list[seq_id]]\n\n return anno\n\n def _get_frames(self, seq_id):\n path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']\n # img = self.image_loader(os.path.join(self.img_pth, path))\n img = decode_img(self.root, os.path.join(self.img_pth, path))\n return img\n\n def get_meta_info(self, seq_id):\n try:\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],\n 'motion_class': None,\n 'major_class': cat_dict_current['supercategory'],\n 'root_class': None,\n 'motion_adverb': None})\n except:\n object_meta = OrderedDict({'object_class_name': None,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n return object_meta\n\n\n def get_class_name(self, seq_id):\n cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]\n return cat_dict_current['name']\n\n def get_frames(self, seq_id=None, frame_ids=None, anno=None):\n # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a\n # list containing these replicated images.\n frame = self._get_frames(seq_id)\n\n frame_list = [frame.copy() for _ in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[0, ...] for _ in frame_ids]\n\n object_meta = self.get_meta_info(seq_id)\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "TrackingNet_lmdb", "path": "lib/train/dataset/tracking_net_lmdb.py", "snippet": "class TrackingNet_lmdb(BaseVideoDataset):\n \"\"\" TrackingNet dataset.\n\n Publication:\n TrackingNet: A Large-Scale Dataset and Benchmark for Object Tracking in the Wild.\n Matthias Mueller,Adel Bibi, Silvio Giancola, Salman Al-Subaihi and Bernard Ghanem\n ECCV, 2018\n https://ivul.kaust.edu.sa/Documents/Publications/2018/TrackingNet%20A%20Large%20Scale%20Dataset%20and%20Benchmark%20for%20Object%20Tracking%20in%20the%20Wild.pdf\n\n Download the dataset using the toolkit https://github.com/SilvioGiancola/TrackingNet-devkit.\n \"\"\"\n def __init__(self, root=None, image_loader=jpeg4py_loader, set_ids=None, data_fraction=None):\n \"\"\"\n args:\n root - The path to the TrackingNet folder, containing the training sets.\n image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)\n is used by default.\n set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the\n sets (0 - 11) will be used.\n data_fraction - Fraction of dataset to be used. The complete dataset is used by default\n \"\"\"\n root = env_settings().trackingnet_lmdb_dir if root is None else root\n super().__init__('TrackingNet_lmdb', root, image_loader)\n\n if set_ids is None:\n set_ids = [i for i in range(12)]\n\n self.set_ids = set_ids\n\n # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and\n # video_name for each sequence\n self.sequence_list = list_sequences(self.root)\n\n if data_fraction is not None:\n self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))\n\n self.seq_to_class_map, self.seq_per_class = self._load_class_info()\n\n # we do not have the class_lists for the tracking net\n self.class_list = list(self.seq_per_class.keys())\n self.class_list.sort()\n\n def _load_class_info(self):\n ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')\n class_map_path = os.path.join(ltr_path, 'data_specs', 'trackingnet_classmap.txt')\n\n with open(class_map_path, 'r') as f:\n seq_to_class_map = {seq_class.split('\\t')[0]: seq_class.rstrip().split('\\t')[1] for seq_class in f}\n\n seq_per_class = {}\n for i, seq in enumerate(self.sequence_list):\n class_name = seq_to_class_map.get(seq[1], 'Unknown')\n if class_name not in seq_per_class:\n seq_per_class[class_name] = [i]\n else:\n seq_per_class[class_name].append(i)\n\n return seq_to_class_map, seq_per_class\n\n def get_name(self):\n return 'trackingnet_lmdb'\n\n def has_class_info(self):\n return True\n\n def get_sequences_in_class(self, class_name):\n return self.seq_per_class[class_name]\n\n def _read_bb_anno(self, seq_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n gt_str_list = decode_str(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\n os.path.join(\"anno\", vid_name + \".txt\")).split('\\n')[:-1]\n gt_list = [list(map(float, line.split(','))) for line in gt_str_list]\n gt_arr = np.array(gt_list).astype(np.float32)\n return torch.tensor(gt_arr)\n\n def get_sequence_info(self, seq_id):\n bbox = self._read_bb_anno(seq_id)\n\n valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)\n visible = valid.clone().byte()\n return {'bbox': bbox, 'valid': valid, 'visible': visible}\n\n def _get_frame(self, seq_id, frame_id):\n set_id = self.sequence_list[seq_id][0]\n vid_name = self.sequence_list[seq_id][1]\n return decode_img(os.path.join(self.root, \"TRAIN_%d_lmdb\" % set_id),\n os.path.join(\"frames\", vid_name, str(frame_id) + \".jpg\"))\n\n def _get_class(self, seq_id):\n seq_name = self.sequence_list[seq_id][1]\n return self.seq_to_class_map[seq_name]\n\n def get_class_name(self, seq_id):\n obj_class = self._get_class(seq_id)\n\n return obj_class\n\n def get_frames(self, seq_id, frame_ids, anno=None):\n frame_list = [self._get_frame(seq_id, f) for f in frame_ids]\n\n if anno is None:\n anno = self.get_sequence_info(seq_id)\n\n anno_frames = {}\n for key, value in anno.items():\n anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]\n\n obj_class = self._get_class(seq_id)\n\n object_meta = OrderedDict({'object_class_name': obj_class,\n 'motion_class': None,\n 'major_class': None,\n 'root_class': None,\n 'motion_adverb': None})\n\n return frame_list, anno_frames, object_meta" }, { "identifier": "sampler", "path": "lib/train/data/sampler.py", "snippet": "def no_processing(data):\n def __init__(self, datasets, p_datasets, samples_per_epoch, max_gap,\n num_search_frames, num_template_frames=1, processing=no_processing, frame_sample_mode='causal',\n train_cls=False, pos_prob=0.5):\n def __len__(self):\n def _sample_visible_ids(self, visible, num_ids=1, min_id=None, max_id=None,\n allow_invisible=False, force_invisible=False):\n def __getitem__(self, index):\n def getitem(self):\n def getitem_cls(self):\n def get_center_box(self, H, W, ratio=1/8):\n def sample_seq_from_dataset(self, dataset, is_video_dataset):\n def get_one_search(self):\n def get_frame_ids_trident(self, visible):\n def get_frame_ids_stark(self, visible, valid):\nclass TrackingSampler(torch.utils.data.Dataset):\n H, W, _ = template_frames[0].shape\n H, W, _ = template_frames[0].shape\n H, W, _ = search_frames[0].shape" }, { "identifier": "processing", "path": "lib/train/data/processing.py", "snippet": "def stack_tensors(x):\n def __init__(self, transform=transforms.ToTensor(), template_transform=None, search_transform=None, joint_transform=None):\n def __call__(self, data: TensorDict):\n def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor,\n mode='pair', settings=None, *args, **kwargs):\n def _get_jittered_box(self, box, mode):\n def __call__(self, data: TensorDict):\nclass BaseProcessing:\nclass STARKProcessing(BaseProcessing):" }, { "identifier": "LTRLoader", "path": "lib/train/data/loader.py", "snippet": "class LTRLoader(torch.utils.data.dataloader.DataLoader):\n \"\"\"\n Data loader. Combines a dataset and a sampler, and provides\n single- or multi-process iterators over the dataset.\n\n Note: The only difference with default pytorch DataLoader is that an additional option stack_dim is available to\n select along which dimension the data should be stacked to form a batch.\n\n Arguments:\n dataset (Dataset): dataset from which to load the data.\n batch_size (int, optional): how many samples per batch to load\n (default: 1).\n shuffle (bool, optional): set to ``True`` to have the data reshuffled\n at every epoch (default: False).\n sampler (Sampler, optional): defines the strategy to draw samples from\n the dataset. If specified, ``shuffle`` must be False.\n batch_sampler (Sampler, optional): like sampler, but returns a batch of\n indices at a time. Mutually exclusive with batch_size, shuffle,\n sampler, and drop_last.\n num_workers (int, optional): how many subprocesses to use for data\n loading. 0 means that the data will be loaded in the main process.\n (default: 0)\n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\n stack_dim (int): Dimension along which to stack to form the batch. (default: 0)\n pin_memory (bool, optional): If ``True``, the data loader will copy tensors\n into CUDA pinned memory before returning them.\n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,\n if the dataset size is not divisible by the batch size. If ``False`` and\n the size of dataset is not divisible by the batch size, then the last batch\n will be smaller. (default: False)\n timeout (numeric, optional): if positive, the timeout value for collecting a batch\n from workers. Should always be non-negative. (default: 0)\n worker_init_fn (callable, optional): If not None, this will be called on each\n worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as\n input, after seeding and before data loading. (default: None)\n\n .. note:: By default, each worker will have its PyTorch seed set to\n ``base_seed + worker_id``, where ``base_seed`` is a long generated\n by main process using its RNG. However, seeds for other libraries\n may be duplicated upon initializing workers (w.g., NumPy), causing\n each worker to return identical random numbers. (See\n :ref:`dataloader-workers-random-seed` section in FAQ.) You may\n use ``torch.initial_seed()`` to access the PyTorch seed for each\n worker in :attr:`worker_init_fn`, and use it to set other seeds\n before data loading.\n\n .. warning:: If ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an\n unpicklable object, e.g., a lambda function.\n \"\"\"\n\n __initialized = False\n\n def __init__(self, name, dataset, training=True, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,\n num_workers=0, epoch_interval=1, collate_fn=None, stack_dim=0, pin_memory=False, drop_last=False,\n timeout=0, worker_init_fn=None):\n if collate_fn is None:\n if stack_dim == 0:\n collate_fn = ltr_collate\n elif stack_dim == 1:\n collate_fn = ltr_collate_stack1\n else:\n raise ValueError('Stack dim no supported. Must be 0 or 1.')\n\n super(LTRLoader, self).__init__(dataset, batch_size, shuffle, sampler, batch_sampler,\n num_workers, collate_fn, pin_memory, drop_last,\n timeout, worker_init_fn)\n\n self.name = name\n self.training = training\n self.epoch_interval = epoch_interval\n self.stack_dim = stack_dim" }, { "identifier": "opencv_loader", "path": "lib/train/data/image_loader.py", "snippet": "def opencv_loader(path):\n \"\"\" Read image using opencv's imread function and returns it in rgb format\"\"\"\n try:\n im = cv.imread(path, cv.IMREAD_COLOR)\n\n # convert to rgb and return\n return cv.cvtColor(im, cv.COLOR_BGR2RGB)\n except Exception as e:\n print('ERROR: Could not read image \"{}\"'.format(path))\n print(e)\n return None" }, { "identifier": "is_main_process", "path": "lib/utils/misc.py", "snippet": "def is_main_process():\n return get_rank() == 0" } ]
import torch import lib.train.data.transforms as tfm from torch.utils.data.distributed import DistributedSampler from lib.train.dataset import Lasot, Got10k, MSCOCOSeq, ImagenetVID, TrackingNet, BDD100K_Night, SHIFT_Night, ExDark from lib.train.dataset import Lasot_lmdb, Got10k_lmdb, MSCOCOSeq_lmdb, ImagenetVID_lmdb, TrackingNet_lmdb from lib.train.data import sampler, opencv_loader, processing, LTRLoader from lib.utils.misc import is_main_process
21,590
# datasets related def update_settings(settings, cfg): settings.print_interval = cfg.TRAIN.PRINT_INTERVAL settings.search_area_factor = {'template': cfg.DATA.TEMPLATE.FACTOR, 'search': cfg.DATA.SEARCH.FACTOR} settings.output_sz = {'template': cfg.DATA.TEMPLATE.SIZE, 'search': cfg.DATA.SEARCH.SIZE} settings.center_jitter_factor = {'template': cfg.DATA.TEMPLATE.CENTER_JITTER, 'search': cfg.DATA.SEARCH.CENTER_JITTER} settings.scale_jitter_factor = {'template': cfg.DATA.TEMPLATE.SCALE_JITTER, 'search': cfg.DATA.SEARCH.SCALE_JITTER} settings.grad_clip_norm = cfg.TRAIN.GRAD_CLIP_NORM settings.print_stats = None settings.batchsize = cfg.TRAIN.BATCH_SIZE settings.scheduler_type = cfg.TRAIN.SCHEDULER.TYPE def names2datasets(name_list: list, settings, image_loader): assert isinstance(name_list, list) datasets = [] for name in name_list: assert name in ["LASOT", "GOT10K_vottrain", "GOT10K_votval", "GOT10K_train_full", "GOT10K_official_val", "COCO17", "VID", "TRACKINGNET", "BDD100K_NIGHT", "SHIFT_NIGHT", "ExDark"] if name == "LASOT": if settings.use_lmdb: print("Building lasot dataset from lmdb") datasets.append(Lasot_lmdb(settings.env.lasot_lmdb_dir, split='train', image_loader=image_loader)) else: datasets.append(Lasot(settings.env.lasot_dir, split='train', image_loader=image_loader)) if name == "GOT10K_vottrain": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='vottrain', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='vottrain', image_loader=image_loader)) if name == "GOT10K_train_full": if settings.use_lmdb: print("Building got10k_train_full from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='train_full', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='train_full', image_loader=image_loader)) if name == "GOT10K_votval": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='votval', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='votval', image_loader=image_loader)) if name == "GOT10K_official_val": if settings.use_lmdb: raise ValueError("Not implement") else: datasets.append(Got10k(settings.env.got10k_val_dir, split=None, image_loader=image_loader)) if name == "COCO17": if settings.use_lmdb: print("Building COCO2017 from lmdb") datasets.append(MSCOCOSeq_lmdb(settings.env.coco_lmdb_dir, version="2017", image_loader=image_loader)) else: datasets.append(MSCOCOSeq(settings.env.coco_dir, version="2017", image_loader=image_loader)) if name == "VID": if settings.use_lmdb: print("Building VID from lmdb") datasets.append(ImagenetVID_lmdb(settings.env.imagenet_lmdb_dir, image_loader=image_loader)) else: datasets.append(ImagenetVID(settings.env.imagenet_dir, image_loader=image_loader)) if name == "TRACKINGNET": if settings.use_lmdb: print("Building TrackingNet from lmdb") datasets.append(TrackingNet_lmdb(settings.env.trackingnet_lmdb_dir, image_loader=image_loader)) else: # raise ValueError("NOW WE CAN ONLY USE TRACKINGNET FROM LMDB") datasets.append(TrackingNet(settings.env.trackingnet_dir, image_loader=image_loader)) if name == "BDD100K_NIGHT":
# datasets related def update_settings(settings, cfg): settings.print_interval = cfg.TRAIN.PRINT_INTERVAL settings.search_area_factor = {'template': cfg.DATA.TEMPLATE.FACTOR, 'search': cfg.DATA.SEARCH.FACTOR} settings.output_sz = {'template': cfg.DATA.TEMPLATE.SIZE, 'search': cfg.DATA.SEARCH.SIZE} settings.center_jitter_factor = {'template': cfg.DATA.TEMPLATE.CENTER_JITTER, 'search': cfg.DATA.SEARCH.CENTER_JITTER} settings.scale_jitter_factor = {'template': cfg.DATA.TEMPLATE.SCALE_JITTER, 'search': cfg.DATA.SEARCH.SCALE_JITTER} settings.grad_clip_norm = cfg.TRAIN.GRAD_CLIP_NORM settings.print_stats = None settings.batchsize = cfg.TRAIN.BATCH_SIZE settings.scheduler_type = cfg.TRAIN.SCHEDULER.TYPE def names2datasets(name_list: list, settings, image_loader): assert isinstance(name_list, list) datasets = [] for name in name_list: assert name in ["LASOT", "GOT10K_vottrain", "GOT10K_votval", "GOT10K_train_full", "GOT10K_official_val", "COCO17", "VID", "TRACKINGNET", "BDD100K_NIGHT", "SHIFT_NIGHT", "ExDark"] if name == "LASOT": if settings.use_lmdb: print("Building lasot dataset from lmdb") datasets.append(Lasot_lmdb(settings.env.lasot_lmdb_dir, split='train', image_loader=image_loader)) else: datasets.append(Lasot(settings.env.lasot_dir, split='train', image_loader=image_loader)) if name == "GOT10K_vottrain": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='vottrain', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='vottrain', image_loader=image_loader)) if name == "GOT10K_train_full": if settings.use_lmdb: print("Building got10k_train_full from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='train_full', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='train_full', image_loader=image_loader)) if name == "GOT10K_votval": if settings.use_lmdb: print("Building got10k from lmdb") datasets.append(Got10k_lmdb(settings.env.got10k_lmdb_dir, split='votval', image_loader=image_loader)) else: datasets.append(Got10k(settings.env.got10k_dir, split='votval', image_loader=image_loader)) if name == "GOT10K_official_val": if settings.use_lmdb: raise ValueError("Not implement") else: datasets.append(Got10k(settings.env.got10k_val_dir, split=None, image_loader=image_loader)) if name == "COCO17": if settings.use_lmdb: print("Building COCO2017 from lmdb") datasets.append(MSCOCOSeq_lmdb(settings.env.coco_lmdb_dir, version="2017", image_loader=image_loader)) else: datasets.append(MSCOCOSeq(settings.env.coco_dir, version="2017", image_loader=image_loader)) if name == "VID": if settings.use_lmdb: print("Building VID from lmdb") datasets.append(ImagenetVID_lmdb(settings.env.imagenet_lmdb_dir, image_loader=image_loader)) else: datasets.append(ImagenetVID(settings.env.imagenet_dir, image_loader=image_loader)) if name == "TRACKINGNET": if settings.use_lmdb: print("Building TrackingNet from lmdb") datasets.append(TrackingNet_lmdb(settings.env.trackingnet_lmdb_dir, image_loader=image_loader)) else: # raise ValueError("NOW WE CAN ONLY USE TRACKINGNET FROM LMDB") datasets.append(TrackingNet(settings.env.trackingnet_dir, image_loader=image_loader)) if name == "BDD100K_NIGHT":
datasets.append(BDD100K_Night(settings.env.bdd100k_dir, image_loader = image_loader))
5
2023-11-20 06:41:15+00:00
24k
shercoo/RGDiffSR
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n draw = ImageDraw.Draw(txt)\n font = ImageFont.truetype('data/DejaVuSans.ttf', size=size)\n nc = int(40 * (wh[0] / 256))\n lines = \"\\n\".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))\n\n try:\n draw.text((0, 0), lines, fill=\"black\", font=font)\n except UnicodeEncodeError:\n print(\"Cant encode string for logging. Skipping.\")\n\n txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0\n txts.append(txt)\n txts = np.stack(txts)\n txts = torch.tensor(txts)\n return txts" }, { "identifier": "exists", "path": "ldm/util.py", "snippet": "def exists(x):\n return x is not None" }, { "identifier": "default", "path": "ldm/util.py", "snippet": "def default(val, d):\n if exists(val):\n return val\n return d() if isfunction(d) else d" }, { "identifier": "ismap", "path": "ldm/util.py", "snippet": "def ismap(x):\n if not isinstance(x, torch.Tensor):\n return False\n return (len(x.shape) == 4) and (x.shape[1] > 3)" }, { "identifier": "isimage", "path": "ldm/util.py", "snippet": "def isimage(x):\n if not isinstance(x, torch.Tensor):\n return False\n return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)" }, { "identifier": "mean_flat", "path": "ldm/util.py", "snippet": "def mean_flat(tensor):\n \"\"\"\n https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86\n Take the mean over all non-batch dimensions.\n \"\"\"\n return tensor.mean(dim=list(range(1, len(tensor.shape))))" }, { "identifier": "count_params", "path": "ldm/util.py", "snippet": "def count_params(model, verbose=False):\n total_params = sum(p.numel() for p in model.parameters())\n if verbose:\n print(f\"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.\")\n return total_params" }, { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n raise KeyError(\"Expected key `target` to instantiate.\")\n return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))" }, { "identifier": "LitEma", "path": "ldm/modules/ema.py", "snippet": "class LitEma(nn.Module):\n def __init__(self, model, decay=0.9999, use_num_upates=True):\n super().__init__()\n if decay < 0.0 or decay > 1.0:\n raise ValueError('Decay must be between 0 and 1')\n\n self.m_name2s_name = {}\n self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))\n self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates\n else torch.tensor(-1,dtype=torch.int))\n\n for name, p in model.named_parameters():\n if p.requires_grad:\n #remove as '.'-character is not allowed in buffers\n s_name = name.replace('.','')\n self.m_name2s_name.update({name:s_name})\n self.register_buffer(s_name,p.clone().detach().data)\n\n self.collected_params = []\n\n def forward(self,model):\n decay = self.decay\n\n if self.num_updates >= 0:\n self.num_updates += 1\n decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))\n\n one_minus_decay = 1.0 - decay\n\n with torch.no_grad():\n m_param = dict(model.named_parameters())\n shadow_params = dict(self.named_buffers())\n\n for key in m_param:\n if m_param[key].requires_grad:\n sname = self.m_name2s_name[key]\n shadow_params[sname] = shadow_params[sname].type_as(m_param[key])\n shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))\n else:\n assert not key in self.m_name2s_name\n\n def copy_to(self, model):\n m_param = dict(model.named_parameters())\n shadow_params = dict(self.named_buffers())\n for key in m_param:\n if m_param[key].requires_grad:\n m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)\n else:\n assert not key in self.m_name2s_name\n\n def store(self, parameters):\n \"\"\"\n Save the current parameters for restoring later.\n Args:\n parameters: Iterable of `torch.nn.Parameter`; the parameters to be\n temporarily stored.\n \"\"\"\n self.collected_params = [param.clone() for param in parameters]\n\n def restore(self, parameters):\n \"\"\"\n Restore the parameters stored with the `store` method.\n Useful to validate the model with EMA parameters without affecting the\n original optimization process. Store the parameters before the\n `copy_to` method. After validation (or model saving), use this to\n restore the former parameters.\n Args:\n parameters: Iterable of `torch.nn.Parameter`; the parameters to be\n updated with the stored parameters.\n \"\"\"\n for c_param, param in zip(self.collected_params, parameters):\n param.data.copy_(c_param.data)" }, { "identifier": "normal_kl", "path": "ldm/modules/distributions/distributions.py", "snippet": "def normal_kl(mean1, logvar1, mean2, logvar2):\n \"\"\"\n source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12\n Compute the KL divergence between two gaussians.\n Shapes are automatically broadcasted, so batches can be compared to\n scalars, among other use cases.\n \"\"\"\n tensor = None\n for obj in (mean1, logvar1, mean2, logvar2):\n if isinstance(obj, torch.Tensor):\n tensor = obj\n break\n assert tensor is not None, \"at least one argument must be a Tensor\"\n\n # Force variances to be Tensors. Broadcasting helps convert scalars to\n # Tensors, but it does not work for torch.exp().\n logvar1, logvar2 = [\n x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)\n for x in (logvar1, logvar2)\n ]\n\n return 0.5 * (\n -1.0\n + logvar2\n - logvar1\n + torch.exp(logvar1 - logvar2)\n + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)\n )" }, { "identifier": "DiagonalGaussianDistribution", "path": "ldm/modules/distributions/distributions.py", "snippet": "class DiagonalGaussianDistribution(object):\n def __init__(self, parameters, deterministic=False):\n self.parameters = parameters\n self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)\n self.logvar = torch.clamp(self.logvar, -30.0, 20.0)\n self.deterministic = deterministic\n self.std = torch.exp(0.5 * self.logvar)\n self.var = torch.exp(self.logvar)\n if self.deterministic:\n self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)\n\n def sample(self):\n x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)\n return x\n\n def kl(self, other=None):\n if self.deterministic:\n return torch.Tensor([0.])\n else:\n if other is None:\n return 0.5 * torch.sum(torch.pow(self.mean, 2)\n + self.var - 1.0 - self.logvar,\n dim=[1, 2, 3])\n else:\n return 0.5 * torch.sum(\n torch.pow(self.mean - other.mean, 2) / other.var\n + self.var / other.var - 1.0 - self.logvar + other.logvar,\n dim=[1, 2, 3])\n\n def nll(self, sample, dims=[1,2,3]):\n if self.deterministic:\n return torch.Tensor([0.])\n logtwopi = np.log(2.0 * np.pi)\n return 0.5 * torch.sum(\n logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,\n dim=dims)\n\n def mode(self):\n return self.mean" }, { "identifier": "VQModelInterface", "path": "ldm/models/autoencoder.py", "snippet": "class VQModelInterface(VQModel):\n def __init__(self, embed_dim, *args, **kwargs):\n super().__init__(embed_dim=embed_dim, *args, **kwargs)\n self.embed_dim = embed_dim\n\n def encode(self, x):\n # print('************************encoder shape',x.shape)\n\n h = self.encoder(x)\n h = self.quant_conv(h)\n return h\n\n def decode(self, h, force_not_quantize=False):\n # also go through quantization layer\n if not force_not_quantize:\n quant, emb_loss, info = self.quantize(h)\n else:\n quant = h\n quant = self.post_quant_conv(quant)\n dec = self.decoder(quant)\n return dec" }, { "identifier": "IdentityFirstStage", "path": "ldm/models/autoencoder.py", "snippet": "class IdentityFirstStage(torch.nn.Module):\n def __init__(self, *args, vq_interface=False, **kwargs):\n self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff\n super().__init__()\n\n def encode(self, x, *args, **kwargs):\n return x\n\n def decode(self, x, *args, **kwargs):\n return x\n\n def quantize(self, x, *args, **kwargs):\n if self.vq_interface:\n return x, None, [None, None, None]\n return x\n\n def forward(self, x, *args, **kwargs):\n return x" }, { "identifier": "AutoencoderKL", "path": "ldm/models/autoencoder.py", "snippet": "class AutoencoderKL(pl.LightningModule):\n def __init__(self,\n ddconfig,\n lossconfig,\n embed_dim,\n ckpt_path=None,\n ignore_keys=[],\n image_key=\"image\",\n colorize_nlabels=None,\n monitor=None,\n ):\n super().__init__()\n self.image_key = image_key\n self.encoder = Encoder(**ddconfig)\n self.decoder = Decoder(**ddconfig)\n self.loss = instantiate_from_config(lossconfig)\n assert ddconfig[\"double_z\"]\n self.quant_conv = torch.nn.Conv2d(2*ddconfig[\"z_channels\"], 2*embed_dim, 1)\n self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig[\"z_channels\"], 1)\n self.embed_dim = embed_dim\n if colorize_nlabels is not None:\n assert type(colorize_nlabels)==int\n self.register_buffer(\"colorize\", torch.randn(3, colorize_nlabels, 1, 1))\n if monitor is not None:\n self.monitor = monitor\n if ckpt_path is not None:\n self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)\n\n def init_from_ckpt(self, path, ignore_keys=list()):\n sd = torch.load(path, map_location=\"cpu\")[\"state_dict\"]\n keys = list(sd.keys())\n for k in keys:\n for ik in ignore_keys:\n if k.startswith(ik):\n print(\"Deleting key {} from state_dict.\".format(k))\n del sd[k]\n self.load_state_dict(sd, strict=False)\n print(f\"Restored from {path}\")\n\n def encode(self, x):\n h = self.encoder(x)\n moments = self.quant_conv(h)\n posterior = DiagonalGaussianDistribution(moments)\n return posterior\n\n def decode(self, z):\n z = self.post_quant_conv(z)\n dec = self.decoder(z)\n return dec\n\n def forward(self, input, sample_posterior=True):\n posterior = self.encode(input)\n if sample_posterior:\n z = posterior.sample()\n else:\n z = posterior.mode()\n dec = self.decode(z)\n return dec, posterior\n\n def get_input(self, batch, k):\n x = batch[k]\n if len(x.shape) == 3:\n x = x[..., None]\n x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()\n return x\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n inputs = self.get_input(batch, self.image_key)\n reconstructions, posterior = self(inputs)\n\n if optimizer_idx == 0:\n # train encoder+decoder+logvar\n aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,\n last_layer=self.get_last_layer(), split=\"train\")\n self.log(\"aeloss\", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)\n self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)\n return aeloss\n\n if optimizer_idx == 1:\n # train the discriminator\n discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,\n last_layer=self.get_last_layer(), split=\"train\")\n\n self.log(\"discloss\", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)\n self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)\n return discloss\n\n def validation_step(self, batch, batch_idx):\n inputs = self.get_input(batch, self.image_key)\n reconstructions, posterior = self(inputs)\n aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,\n last_layer=self.get_last_layer(), split=\"val\")\n\n discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,\n last_layer=self.get_last_layer(), split=\"val\")\n\n self.log(\"val/rec_loss\", log_dict_ae[\"val/rec_loss\"])\n self.log_dict(log_dict_ae)\n self.log_dict(log_dict_disc)\n return self.log_dict\n\n def configure_optimizers(self):\n lr = self.learning_rate\n opt_ae = torch.optim.Adam(list(self.encoder.parameters())+\n list(self.decoder.parameters())+\n list(self.quant_conv.parameters())+\n list(self.post_quant_conv.parameters()),\n lr=lr, betas=(0.5, 0.9))\n opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),\n lr=lr, betas=(0.5, 0.9))\n return [opt_ae, opt_disc], []\n\n def get_last_layer(self):\n return self.decoder.conv_out.weight\n\n @torch.no_grad()\n def log_images(self, batch, only_inputs=False, **kwargs):\n log = dict()\n x = self.get_input(batch, self.image_key)\n x = x.to(self.device)\n if not only_inputs:\n xrec, posterior = self(x)\n if x.shape[1] > 3:\n # colorize with random projection\n assert xrec.shape[1] > 3\n x = self.to_rgb(x)\n xrec = self.to_rgb(xrec)\n log[\"samples\"] = self.decode(torch.randn_like(posterior.sample()))\n log[\"reconstructions\"] = xrec\n log[\"inputs\"] = x\n return log\n\n def to_rgb(self, x):\n assert self.image_key == \"segmentation\"\n if not hasattr(self, \"colorize\"):\n self.register_buffer(\"colorize\", torch.randn(3, x.shape[1], 1, 1).to(x))\n x = F.conv2d(x, weight=self.colorize)\n x = 2.*(x-x.min())/(x.max()-x.min()) - 1.\n return x" }, { "identifier": "make_beta_schedule", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):\n if schedule == \"linear\":\n betas = (\n torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2\n )\n\n elif schedule == \"cosine\":\n timesteps = (\n torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s\n )\n alphas = timesteps / (1 + cosine_s) * np.pi / 2\n alphas = torch.cos(alphas).pow(2)\n alphas = alphas / alphas[0]\n betas = 1 - alphas[1:] / alphas[:-1]\n betas = np.clip(betas, a_min=0, a_max=0.999)\n\n elif schedule == \"sqrt_linear\":\n betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)\n elif schedule == \"sqrt\":\n betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5\n else:\n raise ValueError(f\"schedule '{schedule}' unknown.\")\n return betas.numpy()" }, { "identifier": "extract_into_tensor", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def extract_into_tensor(a, t, x_shape):\n b, *_ = t.shape\n out = a.gather(-1, t)\n return out.reshape(b, *((1,) * (len(x_shape) - 1)))" }, { "identifier": "noise_like", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def noise_like(shape, device, repeat=False):\n repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))\n noise = lambda: torch.randn(shape, device=device)\n return repeat_noise() if repeat else noise()" }, { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n def __init__(self, model, schedule=\"linear\", **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedule = schedule\n\n def register_buffer(self, name, attr):\n if type(attr) == torch.Tensor:\n if attr.device != torch.device(\"cuda\"):\n attr = attr.to(torch.device(\"cuda\"))\n setattr(self, name, attr)\n\n def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n alphas_cumprod = self.model.alphas_cumprod\n assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n\n self.register_buffer('betas', to_torch(self.model.betas))\n self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n\n # ddim sampling parameters\n ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n ddim_timesteps=self.ddim_timesteps,\n eta=ddim_eta,verbose=verbose)\n self.register_buffer('ddim_sigmas', ddim_sigmas)\n self.register_buffer('ddim_alphas', ddim_alphas)\n self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n\n @torch.no_grad()\n def sample(self,\n S,\n batch_size,\n shape,\n conditioning=None,\n callback=None,\n normals_sequence=None,\n img_callback=None,\n quantize_x0=False,\n eta=0.,\n mask=None,\n x0=None,\n temperature=1.,\n noise_dropout=0.,\n score_corrector=None,\n corrector_kwargs=None,\n verbose=True,\n x_T=None,\n log_every_t=100,\n unconditional_guidance_scale=1.,\n unconditional_conditioning=None,\n # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...\n **kwargs\n ):\n\n\n if conditioning is not None:\n if isinstance(conditioning, dict):\n if isinstance(list(conditioning.values())[0],list):\n cbs = conditioning[list(conditioning.keys())[0]][0].shape[0]\n else:\n cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n if cbs != batch_size:\n print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n else:\n if conditioning.shape[0] != batch_size:\n print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n\n self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n # sampling\n C, H, W = shape\n size = (batch_size, C, H, W)\n print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n\n samples, intermediates = self.ddim_sampling(conditioning, size,\n callback=callback,\n img_callback=img_callback,\n quantize_denoised=quantize_x0,\n mask=mask, x0=x0,\n ddim_use_original_steps=False,\n noise_dropout=noise_dropout,\n temperature=temperature,\n score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n x_T=x_T,\n log_every_t=log_every_t,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning,\n )\n return samples, intermediates\n\n @torch.no_grad()\n def ddim_sampling(self, cond, shape,\n x_T=None, ddim_use_original_steps=False,\n callback=None, timesteps=None, quantize_denoised=False,\n mask=None, x0=None, img_callback=None, log_every_t=100,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None,):\n device = self.model.betas.device\n b = shape[0]\n if x_T is None:\n img = torch.randn(shape, device=device)\n else:\n img = x_T\n\n if timesteps is None:\n timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n elif timesteps is not None and not ddim_use_original_steps:\n subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n timesteps = self.ddim_timesteps[:subset_end]\n\n intermediates = {'x_inter': [img], 'pred_x0': [img]}\n time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n print(f\"Running DDIM Sampling with {total_steps} timesteps\")\n\n iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)\n\n for i, step in enumerate(iterator):\n index = total_steps - i - 1\n ts = torch.full((b,), step, device=device, dtype=torch.long)\n\n if mask is not None:\n assert x0 is not None\n img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n img = img_orig * mask + (1. - mask) * img\n\n outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n quantize_denoised=quantize_denoised, temperature=temperature,\n noise_dropout=noise_dropout, score_corrector=score_corrector,\n corrector_kwargs=corrector_kwargs,\n unconditional_guidance_scale=unconditional_guidance_scale,\n unconditional_conditioning=unconditional_conditioning)\n img, pred_x0 = outs\n if callback: callback(i)\n if img_callback: img_callback(pred_x0, i)\n\n if index % log_every_t == 0 or index == total_steps - 1:\n intermediates['x_inter'].append(img)\n intermediates['pred_x0'].append(pred_x0)\n\n return img, intermediates\n\n @torch.no_grad()\n def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,\n unconditional_guidance_scale=1., unconditional_conditioning=None):\n b, *_, device = *x.shape, x.device\n\n if unconditional_conditioning is None or unconditional_guidance_scale == 1.:\n e_t = self.model.apply_model(x, t, c)\n else:\n x_in = torch.cat([x] * 2)\n t_in = torch.cat([t] * 2)\n c_in = torch.cat([unconditional_conditioning, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)\n\n if score_corrector is not None:\n assert self.model.parameterization == \"eps\"\n e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n\n alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n # select parameters corresponding to the currently considered timestep\n a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n\n # current prediction for x_0\n pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n if quantize_denoised:\n pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n # direction pointing to x_t\n dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n if noise_dropout > 0.:\n noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n return x_prev, pred_x0" }, { "identifier": "Attention_AR_counter", "path": "text_super_resolution/model/VisionLAN/utils.py", "snippet": "class Attention_AR_counter():\n def __init__(self, display_string, dict_file, case_sensitive):\n self.correct = 0\n self.total_samples = 0.\n self.distance_C = 0\n self.total_C = 0.\n self.distance_W = 0\n self.total_W = 0.\n self.display_string = display_string\n self.case_sensitive = case_sensitive\n self.de = cha_encdec(dict_file, case_sensitive)\n\n def clear(self):\n self.correct = 0\n self.total_samples = 0.\n self.distance_C = 0\n self.total_C = 0.\n self.distance_W = 0\n self.total_W = 0.\n \n def add_iter(self, output, out_length, label_length, labels):\n self.total_samples += label_length.size()[0]\n prdt_texts, prdt_prob = self.de.decode(output, out_length)\n for i in range(0, len(prdt_texts)):\n if not self.case_sensitive:\n prdt_texts[i] = prdt_texts[i].lower()\n labels[i] = labels[i].lower()\n all_words = []\n for w in labels[i].split('|') + prdt_texts[i].split('|'):\n if w not in all_words:\n all_words.append(w)\n l_words = [all_words.index(_) for _ in labels[i].split('|')]\n p_words = [all_words.index(_) for _ in prdt_texts[i].split('|')]\n self.distance_C += ed.eval(labels[i], prdt_texts[i])\n self.distance_W += ed.eval(l_words, p_words)\n self.total_C += len(labels[i])\n self.total_W += len(l_words)\n self.correct = self.correct + 1 if labels[i] == prdt_texts[i] else self.correct\n return prdt_texts, labels\n\n def show(self):\n print(self.display_string)\n if self.total_samples == 0:\n pass\n print('Accuracy: {:.6f}, AR: {:.6f}, CER: {:.6f}, WER: {:.6f}'.format(\n self.correct / self.total_samples,\n 1 - self.distance_C / self.total_C,\n self.distance_C / self.total_C,\n self.distance_W / self.total_W))\n self.clear()\n def show_test(self,best_acc, change= False):\n print(self.display_string)\n if self.total_samples == 0:\n pass\n if (self.correct / self.total_samples) > best_acc:\n best_acc = np.copy(self.correct / self.total_samples)\n change = True\n print('Accuracy: {:.6f}, AR: {:.6f}, CER: {:.6f}, WER: {:.6f}, best_acc: {:.6f}'.format(\n self.correct / self.total_samples,\n 1 - self.distance_C / self.total_C,\n self.distance_C / self.total_C,\n self.distance_W / self.total_W, best_acc))\n\n self.clear()\n return best_acc, change\n \n def convert(self, output, out_length):\n prdt_texts, prdt_prob = self.de.decode(output, out_length)\n prdt_prob = prdt_prob.cpu().unsqueeze(0)\n MAX_LEN = 25\n length = prdt_prob.size(1)\n if length >= MAX_LEN:\n return prdt_prob[:, :MAX_LEN, :], prdt_prob\n pad = torch.zeros([prdt_prob.shape[0], MAX_LEN - length, prdt_prob.shape[2]])\n prdt_prob = torch.cat([prdt_prob, pad], dim=1)\n return prdt_texts, prdt_prob" }, { "identifier": "TPSSpatialTransformer", "path": "text_super_resolution/model/tps_spatial_transformer.py", "snippet": "class TPSSpatialTransformer(nn.Module):\n\n def __init__(self, output_image_size=None, num_control_points=None, margins=None):\n super(TPSSpatialTransformer, self).__init__()\n self.output_image_size = output_image_size\n self.num_control_points = num_control_points\n self.margins = margins\n\n self.target_height, self.target_width = output_image_size\n target_control_points = build_output_control_points(num_control_points, margins)\n N = num_control_points\n # N = N - 4\n\n # create padded kernel matrix\n forward_kernel = torch.zeros(N + 3, N + 3)\n target_control_partial_repr = compute_partial_repr(target_control_points, target_control_points)\n forward_kernel[:N, :N].copy_(target_control_partial_repr)\n forward_kernel[:N, -3].fill_(1)\n forward_kernel[-3, :N].fill_(1)\n forward_kernel[:N, -2:].copy_(target_control_points)\n forward_kernel[-2:, :N].copy_(target_control_points.transpose(0, 1))\n # compute inverse matrix\n inverse_kernel = torch.inverse(forward_kernel)\n\n # create target cordinate matrix\n HW = self.target_height * self.target_width\n target_coordinate = list(itertools.product(range(self.target_height), range(self.target_width)))\n target_coordinate = torch.Tensor(target_coordinate) # HW x 2\n Y, X = target_coordinate.split(1, dim = 1)\n Y = Y / (self.target_height - 1)\n X = X / (self.target_width - 1)\n target_coordinate = torch.cat([X, Y], dim = 1) # convert from (y, x) to (x, y)\n target_coordinate_partial_repr = compute_partial_repr(target_coordinate, target_control_points)\n target_coordinate_repr = torch.cat([\n target_coordinate_partial_repr, torch.ones(HW, 1), target_coordinate\n ], dim = 1)\n\n # register precomputed matrices\n self.register_buffer('inverse_kernel', inverse_kernel)\n self.register_buffer('padding_matrix', torch.zeros(3, 2))\n self.register_buffer('target_coordinate_repr', target_coordinate_repr)\n self.register_buffer('target_control_points', target_control_points)\n\n def forward(self, input, source_control_points):\n assert source_control_points.ndimension() == 3\n assert source_control_points.size(1) == self.num_control_points\n assert source_control_points.size(2) == 2\n batch_size = source_control_points.size(0)\n\n Y = torch.cat([source_control_points, self.padding_matrix.expand(batch_size, 3, 2)], 1)\n mapping_matrix = torch.matmul(self.inverse_kernel, Y)\n source_coordinate = torch.matmul(self.target_coordinate_repr, mapping_matrix)\n\n grid = source_coordinate.view(-1, self.target_height, self.target_width, 2)\n grid = torch.clamp(grid, 0, 1) # the source_control_points may be out of [0, 1].\n # the input to grid_sample is normalized [-1, 1], but what we get is [0, 1]\n grid = 2.0 * grid - 1.0\n output_maps = grid_sample(input, grid, canvas=None)\n return output_maps, source_coordinate" }, { "identifier": "STNHead", "path": "text_super_resolution/model/stn_head.py", "snippet": "class STNHead(nn.Module):\n def __init__(self, in_planes, num_ctrlpoints, activation='none', input_size=(16, 64)):\n super(STNHead, self).__init__()\n\n self.in_planes = in_planes\n self.num_ctrlpoints = num_ctrlpoints\n self.activation = activation\n self.stn_convnet = nn.Sequential(\n # conv3x3_block(in_planes, 32), # 32*128\n # nn.MaxPool2d(kernel_size=2, stride=2),\n conv3x3_block(in_planes, 32), # 16*64\n nn.MaxPool2d(kernel_size=2, stride=2),\n conv3x3_block(32, 64), # 8*32\n nn.MaxPool2d(kernel_size=2, stride=2),\n conv3x3_block(64, 128), # 4*16\n nn.MaxPool2d(kernel_size=2, stride=2),\n conv3x3_block(128, 256), # 2*8\n nn.MaxPool2d(kernel_size=2, stride=2),\n conv3x3_block(256, 256), # 1*4,\n nn.MaxPool2d(kernel_size=(1,2), stride=(1,2)),\n conv3x3_block(256, 256)) # 1*2\n\n flatten_width = int(input_size[1] / 32)\n # print(\"flw:\", input_size[1] / 32)\n self.stn_fc1 = nn.Sequential(\n nn.Linear(512, 512), #flatten_width*256\n nn.BatchNorm1d(512),\n nn.ReLU(inplace=True))\n self.stn_fc2 = nn.Linear(512, num_ctrlpoints*2)\n\n self.init_weights(self.stn_convnet)\n self.init_weights(self.stn_fc1)\n self.init_stn(self.stn_fc2)\n\n def init_weights(self, module):\n for m in module.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.001)\n m.bias.data.zero_()\n\n def init_stn(self, stn_fc2):\n margin = 0.01\n sampling_num_per_side = int(self.num_ctrlpoints / 2)\n ctrl_pts_x = np.linspace(margin, 1.-margin, sampling_num_per_side)\n ctrl_pts_y_top = np.ones(sampling_num_per_side) * margin\n ctrl_pts_y_bottom = np.ones(sampling_num_per_side) * (1-margin)\n ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)\n ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)\n ctrl_points = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0).astype(np.float32)\n # print(ctrl_points.shape)\n if self.activation is 'none':\n pass\n elif self.activation == 'sigmoid':\n ctrl_points = -np.log(1. / ctrl_points - 1.)\n elif self.activation == 'relu':\n ctrl_points = F.relu(torch.Tensor(ctrl_points))\n stn_fc2.weight.data.zero_()\n stn_fc2.bias.data = torch.Tensor(ctrl_points).view(-1)\n\n def forward(self, x):\n x = self.stn_convnet(x)\n batch_size, _, h, w = x.size()\n x = x.view(batch_size, -1)\n\n # print(\"x:\", x.shape)\n\n img_feat = self.stn_fc1(x)\n x = self.stn_fc2(0.1 * img_feat)\n if self.activation == 'sigmoid':\n x = torch.sigmoid(x)\n if self.activation == 'relu':\n x = F.relu(x)\n x = x.view(-1, self.num_ctrlpoints, 2)\n return img_feat, x" }, { "identifier": "VisionLAN", "path": "text_super_resolution/model/VisionLAN/VisionLAN.py", "snippet": "class VisionLAN(nn.Module):\n '''\n Architecture of VisionLAN\n input\n input: input image\n label_pos: character index\n output\n text_pre: word-level prediction from VRM\n test_rem: remaining string prediction from MLM\n text_mas: occluded character prediction from MLM\n '''\n def __init__(self, strides, input_shape):\n super(VisionLAN, self).__init__()\n self.backbone = resnet.resnet45(strides, compress_layer=False)\n self.input_shape = input_shape\n self.MLM_VRM = MLM_VRM()\n def forward(self, input, label_pos, training_stp, Train_in = True):\n # extract features\n features = self.backbone(input)\n # MLM + VRM\n if Train_in:\n text_pre, test_rem, text_mas, mask_map = self.MLM_VRM(features[-1], label_pos, training_stp, is_Train=Train_in)\n return text_pre, test_rem, text_mas, mask_map\n else:\n output, out_length = self.MLM_VRM(features[-1], label_pos, training_stp, is_Train=Train_in)\n return output, out_length" }, { "identifier": "SemanticLoss", "path": "text_super_resolution/loss/semantic_loss.py", "snippet": "class SemanticLoss(nn.Module):\n def __init__(self, margin=0.1):\n super(SemanticLoss, self).__init__()\n self.cos_sim = nn.CosineSimilarity(dim=-1, eps=1e-8)\n self.margin = margin\n\n self.lambda1 = 1.0\n self.lambda2 = 1.0\n\n self.kl_loss = torch.nn.KLDivLoss()\n\n def forward(self, pred_vec, gt_vec):\n # pred_vec: [N, C]\n # gt_vec: [N, C]\n # mean_sim = torch.mean(self.cos_sim(gt_vec, pred_vec))\n # sim_loss = 1 - mean_sim\n \n #noise = Variable(torch.rand(pred_vec.shape)) * 0.1 - 0.05\n\n #normed_pred_vec = pred_vec + noise.to(pred_vec.device)\n # print(\"pred_vec:\", pred_vec.shape)\n norm_vec = torch.abs(gt_vec - pred_vec)\n margin_loss = torch.mean(norm_vec) #\n\n # pr int(\"sem_loss:\", float(margin_loss.data), \"sim_loss:\", float(sim_loss.data))\n ce_loss = self.kl_loss(torch.log(pred_vec + 1e-20), gt_vec + 1e-20)\n # print(\"sem_loss:\", float(margin_loss.data), \"sim_loss:\", float(sim_loss.data))\n\n return self.lambda1 * margin_loss + self.lambda2 * ce_loss# ce_loss #margin_loss # + ce_loss # + sim_loss #margin_loss +\n\n def cross_entropy(self, pred_vec, gt_vec, l=1e-5):\n cal = gt_vec * torch.log(pred_vec+l) + (1 - gt_vec) * torch.log(1 - pred_vec+l)\n #print(\"cal:\", cal)\n return -cal" }, { "identifier": "ssim_psnr", "path": "text_super_resolution/utils/ssim_psnr.py", "snippet": "def calculate_psnr(img1, img2):\ndef weighted_calculate_psnr(img1, img2, weighted_mask):\ndef gaussian(window_size, sigma):\ndef create_window(window_size, channel):\ndef create_rect_window(window_H, window_W, channel):\ndef _ssim_weighted(img1_, img2_, window, window_size, channel, weighted_mask, size_average=True):\ndef _ssim(img1, img2, window, window_size, channel, size_average=True):\ndef _tri_ssim(img1, img2, img3, window, window_size, channel, size_average=True):\ndef _ssim_rect(img1, img2, window, window_size, channel, size_average=True):\n def __init__(self, size_average=True):\n def forward(self, img1, img2):\n def __init__(self, window_size=11, size_average=True):\n def forward(self, img1, img2):\n def __init__(self, window_size=11, size_average=True):\n def forward(self, img1, img2, img3):\n def __init__(self, window_size=11, size_average=True):\n def forward(self, img1, img2, weighted_mask):\n def __init__(self, window_size=11, size_average=True):\n def forward(self, img1, img2):\ndef ssim(img1, img2, window_size=11, size_average=True):\ndef ssim_weighted(img1, img2, weighted_mask, window_size=11, size_average=True):\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n H, W = window_size\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\nclass Distorted_SSIM(torch.nn.Module):\nclass SSIM(torch.nn.Module):\nclass TRI_SSIM(torch.nn.Module):\nclass SSIM_WEIGHTED(torch.nn.Module):\nclass SSIM_TSR(torch.nn.Module):" } ]
import datetime import math import cv2 import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import pygame from collections import OrderedDict from matplotlib import pyplot as plt from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from torchvision import transforms from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler from text_super_resolution.model.VisionLAN.utils import Attention_AR_counter from text_super_resolution.model.tps_spatial_transformer import TPSSpatialTransformer from text_super_resolution.model.stn_head import STNHead from text_super_resolution.model.VisionLAN.VisionLAN import VisionLAN from utils.render_standard_text import * from text_super_resolution.loss.semantic_loss import SemanticLoss from text_super_resolution.utils import ssim_psnr from pygame import freetype from utils.metrics import *
14,597
img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim: ddim_sampler = DDIMSampler(self) # print(cond.shape) if self.text_prior_enable: if isinstance(cond, dict): shape = (self.channels, cond['c_concat'][0].shape[2], cond['c_concat'][0].shape[3]) elif isinstance(cond, list): shape = (self.channels, cond[0].shape[2], cond[0].shape[3]) else: shape = (self.channels, cond.shape[2], cond.shape[3]) else: shape = (self.channels, cond.shape[2], cond.shape[3]) # shape = (self.channels, self.image_size, self.image_size) samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs) return samples, intermediates @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) # print('**********************c shape',c.shape) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption"]: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"]) log["conditioning"] = xc elif self.cond_stage_key == 'class_label': xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"]) log['conditioning'] = xc elif isimage(xc): log["conditioning"] = xc if ismap(xc): log["original_conditioning"] = self.to_rgb(xc) if plot_diffusion_rows: # get diffusion row diffusion_row = list() z_start = z[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(z_start) z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) diffusion_row.append(self.decode_first_stage(z_noisy)) diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) log["diffusion_row"] = diffusion_grid if sample: # get denoise row with self.ema_scope("Plotting"): samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} sem_loss = SemanticLoss() def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) else: raise NotImplementedError("mu not supported") # TODO how to choose this term lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") print(sd.keys()) print(sd['epoch']) print(sd['global_step']) print(sd['callbacks']) # print(sd['optimizer_states']) # print(sd['lr_schedulers']) # print(sd['state_dict'].keys()) # exit(0) if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys: {missing}") if len(unexpected) > 0: print(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start else: raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): # print('************************fuck',k) x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): # print('******************************in validation') _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, text_prior_enable=False, image_height=32, image_width=128, STN_enable=False, standard_text=False, VL_pretrained_path=None, fid_eval=False, visualize=False, down_sample_rate=2, recog_loss_enable=False, font_path=None, *args, **kwargs): self.fid_eval = fid_eval self.visualize = visualize self.text_prior_enable = text_prior_enable self.recog_loss_enable = recog_loss_enable self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__': conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True self.image_height = image_height self.image_width = image_width self.stn = STN_enable if self.stn: self.tps_inputsize = [image_height // down_sample_rate, image_width // down_sample_rate] tps_outputsize = [image_height // down_sample_rate, image_width // down_sample_rate] num_control_points = 20 tps_margins = [0.05, 0.05] self.tps = TPSSpatialTransformer( output_image_size=tuple(tps_outputsize), num_control_points=num_control_points, margins=tuple(tps_margins)) self.stn_head = STNHead( in_planes=3, num_ctrlpoints=num_control_points, activation='none', input_size=self.tps_inputsize) self.standard_text = standard_text if self.standard_text: # self.VL_model = self.VisionLAN_init(VL_pretrained_path) # self.test_acc_counter = Attention_AR_counter('\ntest accuracy: ', # '/home/zhouyuxuan/latent-diffusion/dic_36.txt', False) self.font_path = font_path pygame.init() freetype.init() self.cal_psnr = ssim_psnr.calculate_psnr self.cal_ssim = ssim_psnr.SSIM() def VisionLAN_init(self, path=None): cfg = {'args': { 'strides': [(1, 1), (2, 2), (2, 2), (2, 2), (1, 1), (1, 1)], 'input_shape': [3, 64, 256], # C x H x W }, 'init_state_dict': '/home/zhouyuxuan/latent-diffusion/visionlan.pth', } model_VL = VisionLAN(**cfg['args']) model_path = cfg['init_state_dict'] if path is None else path print('load pre_trained VisionLAN model from %s' % model_path) model_VL = model_VL.to(self.device) model_VL = nn.DataParallel(model_VL) if cfg['init_state_dict'] != None: fe_state_dict_ori = torch.load(model_path) fe_state_dict = OrderedDict() for k, v in fe_state_dict_ori.items(): if 'module' not in k: k = 'module.' + k else: k = k.replace('features.module.', 'module.features.') fe_state_dict[k] = v model_dict_fe = model_VL.state_dict() state_dict_fe = {k: v for k, v in fe_state_dict.items() if k in model_dict_fe.keys()} model_dict_fe.update(state_dict_fe) model_VL.load_state_dict(model_dict_fe) return model_VL def parse_visionlan_data(self, imgs_input): imgs_input = transforms.ToPILImage()(imgs_input).convert('RGB') imgs_input = cv2.resize(np.array(imgs_input), (256, 64)) imgs_input = transforms.ToTensor()(imgs_input).unsqueeze(0) imgs_input = imgs_input.to(self.device) return imgs_input def make_cond_schedule(self, ): self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids def on_save_checkpoint(self, checkpoint): if not isinstance(self.cond_stage_model, torch.nn.Identity): self.cond_stage_model.save_state_dict( '/home/zhouyuxuan/latent-diffusion/crnn_ckpt/', self.current_epoch) @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx, dataloader_idx): # only for very first batch if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt: assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously' # set rescale weight to 1./std of encodings print("### USING STD-RESCALING ###") x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer('scale_factor', 1. / z.flatten().std()) print(f"setting self.scale_factor to {self.scale_factor}") print("### USING STD-RESCALING ###") def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append(self.decode_first_stage(zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented") return self.scale_factor * z def get_learned_conditioning(self, c): if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip(L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"]) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # print(x.shape) # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[1] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) # print('weighting',weighting.shape,Ly,Lx) normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[1] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox']: xc = batch[cond_key] elif cond_key == 'class_label': xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: # if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): # import pudb; pudb.set_trace() c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) if self.text_prior_enable: c = self.get_additional_cond(xc, c) # c = {'c_concat': [xc], 'c_crossattn': [c]} else: c = xc if bs is not None: if isinstance(c, dict): for k, v in c.items(): c[k] = [v[0][:bs]] else: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] # print('fuck',c.shape) if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z if hasattr(self, "split_input_params"): if self.split_input_params["patch_distributed_vq"]: ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) uf = self.split_input_params["vqf"] bs, nc, h, w = z.shape print('decode z shape', z.shape) if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print("reducing stride") print(ks, stride, uf) fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf) z = unfold(z) # (bn, nc * prod(**ks), L) # 1. Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) # 2. apply model loop over last dim if isinstance(self.first_stage_model, VQModelInterface): output_list = [self.first_stage_model.decode(z[:, :, :, :, i], force_not_quantize=predict_cids or force_not_quantize) for i in range(z.shape[-1])] else: output_list = [self.first_stage_model.decode(z[:, :, :, :, i]) for i in range(z.shape[-1])] o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L) o = o * weighting # Reverse 1. reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together decoded = fold(o) decoded = decoded / normalization # norm is shape (1, 1, h, w) return decoded else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) # same as above but without decorator def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z if hasattr(self, "split_input_params"): if self.split_input_params["patch_distributed_vq"]: ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) uf = self.split_input_params["vqf"] bs, nc, h, w = z.shape if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print("reducing stride") fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf) z = unfold(z) # (bn, nc * prod(**ks), L) # 1. Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) # 2. apply model loop over last dim if isinstance(self.first_stage_model, VQModelInterface): output_list = [self.first_stage_model.decode(z[:, :, :, :, i], force_not_quantize=predict_cids or force_not_quantize) for i in range(z.shape[-1])] else: output_list = [self.first_stage_model.decode(z[:, :, :, :, i]) for i in range(z.shape[-1])] o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L) o = o * weighting # Reverse 1. reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together decoded = fold(o) decoded = decoded / normalization # norm is shape (1, 1, h, w) return decoded else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): if hasattr(self, "split_input_params"): if self.split_input_params["patch_distributed_vq"]: ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) df = self.split_input_params["vqf"] self.split_input_params['original_image_size'] = x.shape[-2:] bs, nc, h, w = x.shape print('encode x shape', x.shape) print('ks', ks, 'stride', stride, 'df', df) if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print("reducing stride") fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df) z = unfold(x) # (bn, nc * prod(**ks), L) # Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) print('encode z shape', z.shape) output_list = [self.first_stage_model.encode(z[:, :, :, :, i]) for i in range(z.shape[-1])] o = torch.stack(output_list, axis=-1) o = o * weighting # Reverse reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together decoded = fold(o) decoded = decoded / normalization return decoded else: return self.first_stage_model.encode(x) else: return self.first_stage_model.encode(x) def on_validation_start(self) -> None: print(f'******************************in validation {self.current_epoch}') def validation_step(self, batch, batch_idx): # print('******************************in validation') _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) if self.fid_eval and self.current_epoch % 10 == 0: results = self.recognize_sample(batch, N=114514, inpaint=False) rec_image = results['samples'] target = batch[self.first_stage_key] target = rearrange(target, 'b h w c -> b c h w') cond = batch[self.cond_stage_key] cond = rearrange(cond, 'b h w c -> b c h w') if self.visualize: batchlen = rec_image.shape[0] rc = int(math.sqrt(batchlen)) f, axs = plt.subplots(rc, rc, figsize=(16, 4), sharex=True, sharey=True) plt.subplots_adjust(wspace=0, hspace=0) print(len(axs), batchlen, int(math.sqrt(batchlen))) assert len(axs) ** 2 == batchlen for i in range(batchlen): axs[i // rc, i % rc].set_xticklabels([]) axs[i // rc, i % rc].set_yticklabels([]) axs[i // rc, i % rc].set_aspect('equal') axs[i // rc, i % rc].imshow(rec_image[i, :3, :, :].cpu().numpy().transpose(1, 2, 0)) axs[i // rc, i % rc].axis('off') plt.savefig(f'/home/zhouyuxuan/res/sample_{batch_idx}.jpg') plt.cla() f, axs = plt.subplots(rc, rc, figsize=(16, 4), sharex=True, sharey=True) plt.subplots_adjust(wspace=0, hspace=0) for i in range(batchlen): axs[i // rc, i % rc].imshow(target[i, :3, :, :].cpu().numpy().transpose(1, 2, 0)) axs[i // rc, i % rc].axis('off') plt.savefig(f'/home/zhouyuxuan/res/target_{batch_idx}.jpg') plt.cla() f, axs = plt.subplots(rc, rc, figsize=(16, 4), sharex=True, sharey=True) plt.subplots_adjust(wspace=0, hspace=0) for i in range(batchlen): axs[i // rc, i % rc].imshow(cond[i, :3, :, :].cpu().numpy().transpose(1, 2, 0)) axs[i // rc, i % rc].axis('off') plt.savefig(f'/home/zhouyuxuan/res/input_{batch_idx}.jpg') PSNR = self.cal_psnr(rec_image[:, :3], target[:, :3]) SSIM = self.cal_ssim(rec_image[:, :3], target[:, :3]) self.log_dict({'PSNR': PSNR, 'SSIM': SSIM}, prog_bar=False, logger=True, on_step=False, on_epoch=True) def shared_step(self, batch, **kwargs): # print('*******************************************************batch',batch['image'].shape) # print('*******************************************************batch',batch['image'].shape) # if hasattr(self, "split_input_params"): # print(self.split_input_params) # else: # print('fuck') x, c = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x, c) if self.recog_loss_enable: HR = batch['image'] HR = rearrange(HR, 'b h w c -> b c h w') HR = HR.to(memory_format=torch.contiguous_format).float() LR = c label_vecs = self.get_learned_conditioning(c).permute(1, 0, 2) label_vecs_hr = self.get_learned_conditioning(HR).permute(1, 0, 2) loss_recog_distill = sem_loss(label_vecs, label_vecs_hr) * 100 # 100 loss = loss + loss_recog_distill loss_dict.update({f'loss_recog': loss_recog_distill}) # return loss + loss_recog_distill, loss_dict # # else: return loss, loss_dict def get_additional_cond(self, c, tp): if self.stn: _, ctrl_points_c = self.stn_head(c) c, _ = self.tps(c, ctrl_points_c) if self.standard_text: x_q = torch.empty(1, 2, c.shape[2], c.shape[3]) # prob_lr = torch.empty(1, 25, 37) rec_results = get_string_crnn(tp.permute(1, 0, 2), False) for i in range(c.shape[0]): # visionlan_dict_lr = self.parse_visionlan_data(c[i, :3, :, :]) # target = '' # label_lr, label_length = self.VL_model(visionlan_dict_lr, target, '', False) # pred_str_lr, pred_prob = self.test_acc_counter.convert(label_lr, label_length) # s = pred_str_lr[0] # prob_lr = torch.cat([prob_lr, pred_prob], dim=0) s = rec_results[i] if s == "" or type(s) == torch.Tensor: s = "\t" lower_case = s.lower() upper_case = s.upper() i_t_lower = make_standard_text(self.font_path, lower_case, (c.shape[2], c.shape[3])) i_t_lower_tensor = torch.from_numpy(i_t_lower).unsqueeze(0).unsqueeze(0) i_t_upper = make_standard_text(self.font_path, upper_case, (c.shape[2], c.shape[3])) i_t_upper_tensor = torch.from_numpy(i_t_upper).unsqueeze(0).unsqueeze(0) i_t_tensor = torch.cat([i_t_lower_tensor, i_t_upper_tensor], dim=1) x_q = torch.cat([x_q, i_t_tensor], dim=0) x_q = x_q[1:] # prob_lr = prob_lr[1:] x_q = x_q.to(self.device) # prob_lr = prob_lr.to(self.device) c = torch.cat([c, x_q], dim=1) return {'c_concat': [c], 'c_crossattn': [tp]} def forward(self, x, c, *args, **kwargs): t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() if self.model.conditioning_key is not None: assert c is not None if self.text_prior_enable and self.model.conditioning_key == 'hybrid': tp = self.get_learned_conditioning(c) c = self.get_additional_cond(c, tp) else: if self.cond_stage_trainable: c = self.get_learned_conditioning(c) if self.shorten_cond_schedule: # TODO: drop this option tc = self.cond_ids[t].to(self.device) c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) return self.p_losses(x, c, t, *args, **kwargs) def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset def rescale_bbox(bbox): x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2]) y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3]) w = min(bbox[2] / crop_coordinates[2], 1 - x0) h = min(bbox[3] / crop_coordinates[3], 1 - y0) return x0, y0, w, h return [rescale_bbox(b) for b in bboxes] def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is exptected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} if hasattr(self, "split_input_params"): assert len(cond) == 1 # todo can only deal with one conditioning atm assert not return_ids ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) h, w = x_noisy.shape[-2:] if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) # print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) # print("reducing stride") # print('ddpm','x_noisy shape',x_noisy.shape,'ks',ks,'stride',stride) fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride) z = unfold(x_noisy) # (bn, nc * prod(**ks), L) # Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])] if self.cond_stage_key in ["image", "LR_image", "segmentation", 'bbox_img'] and self.model.conditioning_key: # todo check for completeness c_key = next(iter(cond.keys())) # get key c = next(iter(cond.values())) # get value assert (len(c) == 1) # todo extend to list with more than one elem c = c[0] # get element c = unfold(c) c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L ) cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])] elif self.cond_stage_key == 'coordinates_bbox': assert 'original_image_size' in self.split_input_params, 'BoudingBoxRescaling is missing original_image_size' # assuming padding of unfold is always 0 and its dilation is always 1 n_patches_per_row = int((w - ks[0]) / stride[0] + 1) full_img_h, full_img_w = self.split_input_params['original_image_size'] # as we are operating on latents, we need the factor from the original image size to the # spatial latent size to properly rescale the crops for regenerating the bbox annotations num_downs = self.first_stage_model.encoder.num_resolutions - 1 rescale_latent = 2 ** (num_downs) # get top left postions of patches as conforming for the bbbox tokenizer, therefore we # need to rescale the tl patch coordinates to be in between (0,1) tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w, rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h) for patch_nr in range(z.shape[-1])] # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w) patch_limits = [(x_tl, y_tl, rescale_latent * ks[0] / full_img_w, rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates] # patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates] # tokenize crop coordinates for the bounding boxes of the respective patches patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device) for bbox in patch_limits] # list of length l with tensors of shape (1, 2) print(patch_limits_tknzd[0].shape) # cut tknzd crop position from conditioning assert isinstance(cond, dict), 'cond must be dict to be fed into model' cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device) print(cut_cond.shape) adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd]) adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n') print(adapted_cond.shape) adapted_cond = self.get_learned_conditioning(adapted_cond) print(adapted_cond.shape) adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1]) print(adapted_cond.shape) cond_list = [{'c_crossattn': [e]} for e in adapted_cond] else: cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient # apply model by loop over crops output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])] assert not isinstance(output_list[0], tuple) # todo cant deal with multiple model outputs check this never happens o = torch.stack(output_list, axis=-1) o = o * weighting # Reverse reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together x_recon = fold(o) / normalization else: x_recon = self.model(x_noisy, t, **cond) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0) return mean_flat(kl_prior) / np.log(2.0) def p_losses(self, x_start, cond, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_output = self.apply_model(x_noisy, t, cond) loss_dict = {} prefix = 'train' if self.training else 'val' if self.parameterization == "x0": target = x_start elif self.parameterization == "eps": target = noise else: raise NotImplementedError() loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3]) loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()}) self.logvar = self.logvar.to(self.device) logvar_t = self.logvar[t].to(self.device) loss = loss_simple / torch.exp(logvar_t) + logvar_t # loss = loss_simple / torch.exp(self.logvar) + self.logvar if self.learn_logvar: loss_dict.update({f'{prefix}/loss_gamma': loss.mean()}) loss_dict.update({'logvar': self.logvar.data.mean()}) loss = self.l_simple_weight * loss.mean() loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3)) loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean() loss_dict.update({f'{prefix}/loss_vlb': loss_vlb}) loss += (self.original_elbo_weight * loss_vlb) loss_dict.update({f'{prefix}/loss': loss}) return loss, loss_dict def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False, return_x0=False, score_corrector=None, corrector_kwargs=None): t_in = t model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) if score_corrector is not None: assert self.parameterization == "eps" model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs) if return_codebook_ids: model_out, logits = model_out if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out else: raise NotImplementedError() if clip_denoised: x_recon.clamp_(-1., 1.) if quantize_denoised: x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) if return_codebook_ids: return model_mean, posterior_variance, posterior_log_variance, logits elif return_x0: return model_mean, posterior_variance, posterior_log_variance, x_recon else: return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_codebook_ids=False, quantize_denoised=False, return_x0=False, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): b, *_, device = *x.shape, x.device outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_codebook_ids=return_codebook_ids, quantize_denoised=quantize_denoised, return_x0=return_x0, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if return_codebook_ids: raise DeprecationWarning("Support dropped.") model_mean, _, model_log_variance, logits = outputs elif return_x0: model_mean, _, model_log_variance, x0 = outputs else: model_mean, _, model_log_variance = outputs noise = noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) if return_codebook_ids: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1) if return_x0: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0 else: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False, img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t timesteps = self.num_timesteps if batch_size is not None: b = batch_size if batch_size is not None else shape[0] shape = [batch_size] + list(shape) else: b = batch_size = shape[0] if x_T is None: img = torch.randn(shape, device=self.device) else: img = x_T intermediates = [] if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation', total=timesteps) if verbose else reversed( range(0, timesteps)) if type(temperature) == float: temperature = [temperature] * timesteps for i in iterator: ts = torch.full((b,), i, device=self.device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img, x0_partial = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, return_x0=True, temperature=temperature[i], noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if mask is not None: assert x0 is not None img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(x0_partial) if callback: callback(i) if img_callback: img_callback(img, i) return img, intermediates @torch.no_grad() def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t device = self.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim: ddim_sampler = DDIMSampler(self) # print(cond.shape) if self.text_prior_enable: if isinstance(cond, dict): shape = (self.channels, cond['c_concat'][0].shape[2], cond['c_concat'][0].shape[3]) elif isinstance(cond, list): shape = (self.channels, cond[0].shape[2], cond[0].shape[3]) else: shape = (self.channels, cond.shape[2], cond.shape[3]) else: shape = (self.channels, cond.shape[2], cond.shape[3]) # shape = (self.channels, self.image_size, self.image_size) samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs) return samples, intermediates @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) # print('**********************c shape',c.shape) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption"]: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"]) log["conditioning"] = xc elif self.cond_stage_key == 'class_label': xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"]) log['conditioning'] = xc elif isimage(xc): log["conditioning"] = xc if ismap(xc): log["original_conditioning"] = self.to_rgb(xc) if plot_diffusion_rows: # get diffusion row diffusion_row = list() z_start = z[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(z_start) z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) diffusion_row.append(self.decode_first_stage(z_noisy)) diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) log["diffusion_row"] = diffusion_grid if sample: # get denoise row with self.ema_scope("Plotting"): samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
self.first_stage_model, IdentityFirstStage):
12
2023-11-20 06:34:21+00:00
24k
microsoft/Project-BayesDAG
src/causica/models_factory.py
[ { "identifier": "Variables", "path": "src/causica/datasets/variables.py", "snippet": "class Variables:\n \"\"\"\n This class represents any variables present in a model.\n \"\"\"\n\n def __init__(\n self,\n variables: List[Variable],\n auxiliary_variables: Optional[List[Variable]] = None,\n used_cols: Optional[List[int]] = None,\n ) -> None:\n \"\"\"\n Args:\n variables: A list Variable objects.\n auxiliary_variables: A list of Variable objects only used for input into VAE,\n not produced in output.\n These are assumed to be appended onto the end of the variables in the data.\n Defaults to None - no aux variables present.\n used_cols: A list of column ids that were used when processing the original data.\n \"\"\"\n if not auxiliary_variables:\n auxiliary_variables = []\n self.auxiliary_variables = auxiliary_variables\n self._variables = variables\n\n self._deduplicate_names()\n\n # Dictionary mapping from variable name to variable index.\n self.name_to_idx = {var.name: idx for idx, var in enumerate(self._variables)}\n\n # Lists containing query and target variable indices\n self.target_var_idxs = []\n self.not_target_var_idxs = []\n self.query_var_idxs = []\n self.not_query_var_idxs = []\n for idx, var in enumerate(self._variables):\n if var.query:\n self.query_var_idxs.append(idx)\n else:\n self.not_query_var_idxs.append(idx)\n if var.target:\n self.target_var_idxs.append(idx)\n else:\n self.not_target_var_idxs.append(idx)\n\n if len(self.target_var_idxs) > 0 and all(idx in self.query_var_idxs for idx in self.target_var_idxs):\n warnings.warn(\n \"All target variables are marked as queriable, it is likely that active learning will always \"\n \"select these variables first.\"\n )\n\n # Lists containing continuous (including text) and binary/categorical variable indices\n self.var_idxs_by_type: DefaultDict[str, List[int]] = defaultdict(list)\n for idx, var in enumerate(self._variables + self.auxiliary_variables):\n self.var_idxs_by_type[var.type_].append(idx)\n\n # List of lists, where self.unprocessed_cols[i] gives the columns occupied by the ith variable in the unprocessed\n # data.\n self.unprocessed_cols = []\n start_col = 0\n for var in self._all_variables:\n end_col = start_col + var.unprocessed_dim\n self.unprocessed_cols.append(list(range(start_col, end_col)))\n start_col = end_col\n\n # List of lists, where self.unprocessed_non_aux_cols[i] gives the columns occupied by the ith variable in the unprocessed\n # data (non-auxiliary).\n self.unprocessed_non_aux_cols = []\n start_col = 0\n for var in self._variables:\n end_col = start_col + var.unprocessed_dim\n self.unprocessed_non_aux_cols.append(list(range(start_col, end_col)))\n start_col = end_col\n\n # List of lists, where self.processed_cols[i] gives the columns occupied by the ith variable in the processed\n # data.\n self.processed_cols = []\n start_col = 0\n for var in self._all_variables:\n end_col = start_col + var.processed_dim\n self.processed_cols.append(list(range(start_col, end_col)))\n start_col = end_col\n\n # List of lists, where self.processed_non_aux_cols[i] gives the columns occupied by the ith variable in the processed\n # data (non-auxiliary).\n self.processed_non_aux_cols = []\n start_col = 0\n for var in self._variables:\n end_col = start_col + var.processed_dim\n self.processed_non_aux_cols.append(list(range(start_col, end_col)))\n start_col = end_col\n\n # Set of all query group names, maintaining order in which they are first encountered when iterating through\n # the variables list. This is the simplest way to do this since dictionaries are guaranteed to be\n # insertion-ordered since Python 3.7\n self.group_names = list(dict.fromkeys([var.group_name for var in self._variables]))\n\n # List containing indices for each query group, where the query group names are assumed to be in the same order\n # as self.group_names\n self.group_idxs = [\n [idx for idx, var in enumerate(self._variables) if var.group_name == group_name]\n for group_name in self.group_names\n ]\n\n # Remove groups containing no queriable variables from self.group_names and self.group_idxs, as\n # we can guarantee that we will never query these groups.\n is_group_queriable = [any(self._variables[idx].query for idx in idxs) for idxs in self.group_idxs]\n\n self.group_names = [name for group_idx, name in enumerate(self.group_names) if is_group_queriable[group_idx]]\n self.group_idxs = [idxs for group_idx, idxs in enumerate(self.group_idxs) if is_group_queriable[group_idx]]\n\n # Save the list of observed column ids\n default_used_cols = list(range(len(self._variables) + len(auxiliary_variables))) # All columns observed\n self.used_cols = used_cols if used_cols is not None else default_used_cols\n assert len(self.used_cols) == len(self._variables) + len(self.auxiliary_variables)\n\n self.col_id_to_var_index = {old: new for new, old in enumerate(self.used_cols)}\n\n def __repr__(self):\n return str(self._variables)\n\n def __iter__(self) -> Iterator[Variable]:\n \"\"\"\n Iterate through the variables within the container.\n Note - Now it iterate through all the variables within the container\n (including auxiliary variables, if they are present)\n \"\"\"\n for var in self._all_variables:\n yield var\n\n def __getitem__(self, idx):\n return (self._all_variables)[idx]\n\n def __len__(self) -> int:\n return len(self._variables) + len(self.auxiliary_variables)\n\n @classmethod\n def create_from_json(cls, path: str) -> Variables:\n return cls.create_from_dict(read_json_as(path, dict))\n\n @classmethod\n def create_from_dict(cls, variables_dict: Dict[str, List[Any]]) -> Variables:\n \"\"\"\n Create variables object from a dictionary\n \"\"\"\n variables = variables_dict[\"variables\"]\n for var in variables:\n # remove deprecated \"id\" key if present\n var.pop(\"id\", None)\n var_obj_list = [Variable(**var) for var in variables]\n\n auxiliary_vars = variables_dict.get(\"auxiliary_variables\", [])\n if len(auxiliary_vars) == 0:\n auxiliary_vars_obj = None\n else:\n for var in auxiliary_vars:\n # remove deprecated \"id\" key if present\n var.pop(\"id\", None)\n\n auxiliary_vars_obj = [Variable(**var) for var in auxiliary_vars]\n\n used_cols = variables_dict.get(\"used_cols\", None)\n\n return cls(var_obj_list, auxiliary_vars_obj, used_cols)\n\n @classmethod\n def create_from_data_and_dict(\n cls, data: np.ndarray, mask: np.ndarray, variables_dict: Optional[Dict[str, Any]] = None\n ) -> Variables:\n \"\"\"\n Create variables object from an input dictionary, inferring missing fields using `data` and `mask`.\n \"\"\"\n # Infer missing fields in variables_dict\n variables_dict = cls.infer_from_data(data, mask, variables_dict, True)\n variables = cls.create_from_dict(variables_dict)\n return variables\n\n @staticmethod\n def _metadata_from_dict(\n data, mask, variables_dict, variables_type=\"variables\"\n ) -> Tuple[List[Any], Union[List[Any], None]]:\n \"\"\"\n Infer variables_metadata from input data\n\n Args:\n data: NumPy array containing data\n mask: NumPy array containing 1 for observed data values, 0 for unobserved data values.\n variables_dict: Dictionary containing metadata for each variable (column) in the input data. Missing variables,\n or missing fields for a particular variable, will attempt to be inferred from the input data.\n variables_type: is it aux variables, or normal variables\n Returns:\n varaibles_metadata: inferred metadata from input data\n A list of column ids that were used when processing the original data.\n \"\"\"\n\n variables_metadata = []\n # Use None rather than {} as default since mutable default args are dangerous in Python.\n used_cols = variables_dict.get(\"used_cols\", None)\n if used_cols:\n used_cols = cast(List[int], used_cols)\n assert len(used_cols) == data.shape[1]\n\n for idx, variable_metadata in enumerate(variables_dict[variables_type]):\n if not all(\n k in variable_metadata for k in [\"name\", \"type\", \"lower\", \"upper\", \"query\", \"target\", \"always_observed\"]\n ):\n # If variable metadata fully specified, do not try to infer, as doing column indexing can be expensive\n # for CSR sparse matrices.\n var_data = data[:, idx]\n var_mask = mask[:, idx]\n if issparse(var_data):\n var_data = var_data.toarray()\n var_mask = var_mask.toarray()\n\n if \"name\" not in variable_metadata:\n if used_cols:\n variable_metadata[\"name\"] = str(used_cols[idx])\n else:\n variable_metadata[\"name\"] = f\"Column {idx}\"\n\n # If data type/min max/num categories specified explicitly, overwrite variables file\n if \"type\" not in variable_metadata:\n # Test if all unmasked elements are integers\n\n if np.all((var_data * var_mask) // 1 == var_data * var_mask):\n if (var_data * var_mask).max() <= 1:\n print(\n f'Type of variable {variable_metadata[\"name\"]} inferred as binary. This can be '\n \"changed manually in the dataset's variables.json file\"\n )\n variable_metadata[\"type\"] = \"binary\"\n else:\n # Note that we always infer integer values with a max value > 1 as categorical. This may want to be\n # reconsidered if support for ordinal variables is introduced at a later date.\n print(\n f'Type of variable {variable_metadata[\"name\"]} inferred as categorical. This can be'\n \" changed manually in the dataset's variables.json file\"\n )\n variable_metadata[\"type\"] = \"categorical\"\n else:\n variable_metadata[\"type\"] = \"continuous\"\n\n if \"lower\" not in variable_metadata:\n if variable_metadata[\"type\"] == \"binary\":\n inferred_lower = 0\n else:\n inferred_lower = min(var_data[np.where(var_mask == 1)]).item()\n variable_metadata[\"lower\"] = inferred_lower\n print(\n f'Minimum value of variable {variable_metadata[\"name\"]} inferred as {inferred_lower}. This'\n \" can be changed manually in the dataset's variables.json file\"\n )\n\n if \"upper\" not in variable_metadata:\n if variable_metadata[\"type\"] == \"binary\":\n inferred_upper = 1\n else:\n inferred_upper = max(var_data[np.where(var_mask == 1)]).item()\n variable_metadata[\"upper\"] = inferred_upper\n print(\n f'Max value of variable {variable_metadata[\"name\"]} inferred as {inferred_upper}. This can '\n \"be changed manually in the dataset's variables.json file\"\n )\n\n if \"query\" not in variable_metadata:\n # By default, assume all variables can be queried unless specified otherwise.\n if variables_type == \"auxiliary_variables\":\n variable_metadata[\"query\"] = False\n print(\n f'Variable {variable_metadata[\"name\"]} inferred to be a non-queriable variable. '\n 'This can be changed manually in the dataset\\'s variables.json file by updating the \"query\" field.'\n )\n else:\n variable_metadata[\"query\"] = True\n print(\n f'Variable {variable_metadata[\"name\"]} inferred to be a queriable variable. '\n 'This can be changed manually in the dataset\\'s variables.json file by updating the \"query\" field.'\n )\n\n if \"target\" not in variable_metadata:\n # By default, assume variable is a target if and only if it is not queriable.\n variable_metadata[\"target\"] = not variable_metadata[\"query\"]\n fill_string = \"not \" if not variable_metadata[\"target\"] else \"\"\n print(\n f'Variable {variable_metadata[\"name\"]} inferred as {fill_string}an active learning target variable. '\n 'This can be changed manually in the dataset\\'s variables.json file by updating the \"target\" field.'\n )\n\n if \"always_observed\" not in variable_metadata:\n # By default, assume variable is always observed if there is no missing in the mask.\n if np.sum((var_mask - 1) ** 2) == 0:\n variable_metadata[\"always_observed\"] = True\n else:\n variable_metadata[\"always_observed\"] = False\n fill_string = \"not \" if not variable_metadata[\"always_observed\"] else \"\"\n print(\n f'Variable {variable_metadata[\"name\"]} inferred as {fill_string}an always observed target variable. '\n 'This can be changed manually in the dataset\\'s variables.json file by updating the \"always_observed\" field.'\n )\n\n variables_metadata.append(variable_metadata)\n\n return variables_metadata, used_cols\n\n @staticmethod\n def infer_from_data(data, mask, variables_dict=None, infer_aux_variables=False) -> Dict[str, List[Any]]:\n \"\"\"\n Infer missing values in an input variables dictionary, using the input data.\n\n Args:\n data: NumPy array containing data\n mask: NumPy array containing 1 for observed data values, 0 for unobserved data values.\n variables_dict: Dictionary containing metadata for each variable (column) in the input data. Missing variables,\n or missing fields for a particular variable, will attempt to be inferred from the input data.\n infer_aux_variables: infer auxiliary variables for GINA or not.\n Returns:\n variables_dict: Updated version of the input variables_dict, with missing variables and fields inferred from the\n data.\n \"\"\"\n\n if variables_dict is None:\n variables_dict = {}\n\n # NOTE this assumes all variables have only one column in unprocessed data, which should always be the case when\n # inferring from a dataset.\n if \"auxiliary_variables\" not in variables_dict:\n variables_dict[\"auxiliary_variables\"] = []\n\n if \"variables\" not in variables_dict or variables_dict[\"variables\"] == []:\n num_var_cols = data.shape[1] - len(variables_dict[\"auxiliary_variables\"])\n variables_dict[\"variables\"] = [{} for _ in range(num_var_cols)]\n\n variables_metadata, used_cols = Variables._metadata_from_dict(\n data, mask, variables_dict, variables_type=\"variables\"\n )\n variables_dict = {\n \"variables\": variables_metadata,\n \"auxiliary_variables\": variables_dict[\"auxiliary_variables\"],\n \"used_cols\": used_cols,\n }\n if infer_aux_variables:\n aux_variables_metadata, used_cols = Variables._metadata_from_dict(\n data, mask, variables_dict, variables_type=\"auxiliary_variables\"\n )\n variables_dict = {\n \"variables\": variables_metadata,\n \"auxiliary_variables\": aux_variables_metadata,\n \"used_cols\": used_cols,\n }\n\n return variables_dict\n\n @property\n def _all_variables(self):\n return self._variables + self.auxiliary_variables\n\n @property\n def has_auxiliary(self) -> bool:\n \"\"\"\n True if there are aux variables present.\n \"\"\"\n return len(self.auxiliary_variables) > 0\n\n @property\n def binary_idxs(self) -> List[int]:\n \"\"\"\n Return a list of the indices of all binary variables.\n \"\"\"\n return self.var_idxs_by_type[\"binary\"]\n\n @property\n def categorical_idxs(self) -> List[int]:\n \"\"\"\n Return a list of the indices of all categorical variables.\n \"\"\"\n return self.var_idxs_by_type[\"categorical\"]\n\n @property\n def discrete_idxs(self) -> List[int]:\n \"\"\"\n Return a list of the indices of all discrete (i.e. binary or categorical) variables. We sort to ensure that the\n combined list is in ascending order.\n \"\"\"\n return sorted(self.var_idxs_by_type[\"categorical\"] + self.var_idxs_by_type[\"binary\"])\n\n @property\n def continuous_idxs(self) -> List[int]:\n \"\"\"\n Return a list of the indices of all continuous variables.\n \"\"\"\n return self.var_idxs_by_type[\"continuous\"]\n\n @property\n def text_idxs(self) -> List[int]:\n \"\"\"\n Return a list of the indices of all text variables.\n \"\"\"\n return self.var_idxs_by_type[\"text\"]\n\n @property\n def non_text_idxs(self) -> List[bool]:\n \"\"\"Helper method. Returns list of booleans, where an element\n at index i indicates whether a variable at index i is non-text or not\n e.g. For Variables object of [...\"continous\"..., ...\"text\"..., \"continuous\"],\n the result would be [True, False, True]\n \"\"\"\n unproc_cols_by_type = self.unprocessed_cols_by_type\n if \"text\" not in unproc_cols_by_type:\n return [True for _ in range(len(self))]\n return (~np.in1d(range(len(self)), unproc_cols_by_type[\"text\"])).tolist()\n\n @property\n def num_unprocessed_cols(self) -> int:\n \"\"\"\n Return number of columns in the unprocessed data represented by all variables\n \"\"\"\n return sum(len(idxs) for idxs in self.unprocessed_cols)\n\n @property\n def num_unprocessed_non_aux_cols(self) -> int:\n \"\"\"\n Return number of columns in the unprocessed data represented by non auxiliary variables\n \"\"\"\n return sum(len(idxs) for idxs in self.unprocessed_non_aux_cols)\n\n @property\n def num_processed_cols(self) -> int:\n \"\"\"\n Return number of columns in the processed data represented by all variables\n \"\"\"\n return sum(len(idxs) for idxs in self.processed_cols)\n\n @property\n def num_processed_non_aux_cols(self) -> int:\n \"\"\"\n Return number of columns in the processed data represented by non auxiliary variables\n \"\"\"\n return sum(len(idxs) for idxs in self.processed_non_aux_cols)\n\n @property\n def num_groups(self) -> int:\n \"\"\"\n Return the number of unique query groups in the variables object.\n \"\"\"\n return len(self.group_names)\n\n @property\n def group_mask(self) -> np.ndarray:\n \"\"\"\n Return a mask of shape (num_groups, num_processed_cols) indicating which column\n corresponds to which group.\n \"\"\"\n mask = np.zeros((self.num_groups, self.num_processed_cols), dtype=bool)\n for group_idx, group in enumerate(self.group_idxs):\n for var in group:\n for proc_col in self.processed_cols[var]:\n mask[group_idx, proc_col] = 1\n return mask\n\n @property\n def proc_always_observed_list(self) -> List[Optional[bool]]:\n \"\"\"\n The mask that indicates if the variable is always observed (for processed data)\n \"\"\"\n return sum(([var.always_observed] * var.processed_dim for var in self._all_variables), [])\n\n @property\n def processed_cols_by_type(self) -> Dict[str, List[List[int]]]:\n \"\"\"\n Return a dictionary mapping each type of data (e.g. continuous, binary, ...) to a list of lists, where each\n sublist represents indices in the processed (i.e. one-hot) data associated with each variable of that type.\n\n E.g. for a two categorical variables each taking 3 values, followed by a binary variable, return\n {'categorical': [[0,1,2], [3,4,5]], 'binary': [[6]]}.\n \"\"\"\n grouped_vars: DefaultDict[str, List[List[int]]] = defaultdict(list)\n for var, cols in zip(self._all_variables, self.processed_cols):\n grouped_vars[var.type_].append(cols)\n return grouped_vars\n\n @property\n def processed_non_aux_cols_by_type(self) -> Dict[str, List[List[int]]]:\n \"\"\"\n Return a dictionary mapping each type of data (e.g. continuous, binary, ...) to a list of lists, where each\n sublist represents indices in the processed (i.e. one-hot) data (w/o aux variables) associated with each\n variable of that type.\n E.g. for a two categorical variables each taking 3 values, followed by a binary variable, return\n {'categorical': [[0,1,2], [3,4,5]], 'binary': [[6]]}.\n \"\"\"\n grouped_vars: DefaultDict[str, List[List[int]]] = defaultdict(list)\n for var, cols in zip(self._variables, self.processed_cols):\n grouped_vars[var.type_].append(cols)\n return grouped_vars\n\n @property\n def unprocessed_cols_by_type(self) -> DefaultDict[str, List[int]]:\n \"\"\"\n Return a dictionary mapping each type of data (e.g. continuous, binary, ...) to a list containing the column\n indices in the unprocessed data for all variables of that type.\n\n E.g. for a two categorical variables each taking 3 values, followed by a binary variable, return\n {'categorical': [0, 1], 'binary': [2]}.\n \"\"\"\n grouped_vars: DefaultDict[str, List[int]] = defaultdict(list)\n i = 0\n for var, cols in zip(self._all_variables, self.unprocessed_cols):\n grouped_vars[var.type_] += cols\n i += var.unprocessed_dim\n return grouped_vars\n\n @property\n def unprocessed_non_aux_cols_by_type(self) -> DefaultDict[str, List[int]]:\n \"\"\"\n Return a dictionary mapping each type of data (e.g. continuous, binary, ...) to a list containing the column\n indices in the unprocessed data for all variables of that type.\n\n E.g. for a two categorical variables each taking 3 values, followed by a binary variable, return\n {'categorical': [0, 1], 'binary': [2]}.\n \"\"\"\n grouped_vars: DefaultDict[str, List[int]] = defaultdict(list)\n i = 0\n for var, cols in zip(self._variables, self.unprocessed_cols):\n grouped_vars[var.type_] += cols\n i += var.unprocessed_dim\n return grouped_vars\n\n def subset(self, idxs: List[int], auxiliary_idxs: Optional[List[int]] = None) -> Variables:\n \"\"\"\n Returns a new Variables object containing only the Variable objects whose indices are given in `idxs`.\n Note that this currently ignores metadata variables.\n \"\"\"\n if auxiliary_idxs is None:\n auxiliary_idxs = []\n\n variables_list = [self._variables[idx] for idx in idxs]\n auxiliary_variables_list = [self.auxiliary_variables[idx] for idx in auxiliary_idxs]\n return Variables(variables_list, auxiliary_variables_list)\n\n def to_dict(self) -> Dict[str, Any]:\n variables_list = [var.to_json() for var in self._variables]\n if self.auxiliary_variables is None:\n auxiliary_vars_list = []\n else:\n auxiliary_vars_list = [var.to_json() for var in self.auxiliary_variables]\n\n variables_json = {\n \"variables\": variables_list,\n \"auxiliary_variables\": auxiliary_vars_list,\n \"used_cols\": [int(col) for col in self.used_cols],\n }\n return variables_json\n\n def save(self, path: str) -> None:\n variables_json = self.to_dict()\n save_json(variables_json, path)\n\n def as_list(self) -> List[Variable]:\n return self._variables\n\n def get_idxs_from_name_list(self, variable_names: List[Union[str, int]]) -> np.ndarray:\n \"\"\"\n Get a binary array of shape (variable_count,), where for each index the array value is 1 if the corresponding\n variable is named in `variable_names`, and 0 otherwise.\n \"\"\"\n variables_to_query = np.zeros((len(self._variables),))\n # Look up indices of specified variables and mark as queriable.\n for variable_name in variable_names:\n # Cast name to string in case numeric names (e.g. question ids) have been input as integers.\n variable_name = str(variable_name)\n variable_idx = self.name_to_idx[variable_name]\n variables_to_query[variable_idx] = 1\n\n return variables_to_query\n\n def get_observable_groups(self, data_mask_row: np.ndarray, obs_mask_row: np.ndarray) -> List[int]:\n \"\"\"\n Get list of indices for groups that are still observable in the current row\n Args:\n data_mask_row: 1D numpy array containing 1 for observed variables and 0 for unobserved in the underlying data\n obs_mask_row: 1D numpy array containing 1 for variables observed during active learning and 0 for ones unobserved\n\n Returns:\n list of indices of groups that can be observed, where the indices correspond to the corresponding group\n names in `self.group_names`.\n \"\"\"\n observable_variables_idxs = self.get_observable_variable_idxs(data_mask_row, obs_mask_row)\n observable_groups_idxs: List[int] = []\n for group_idx, idxs in enumerate(self.group_idxs):\n if any(i in observable_variables_idxs for i in idxs):\n observable_groups_idxs.append(group_idx)\n return observable_groups_idxs\n\n def get_observable_variable_idxs(self, data_mask_row: np.ndarray, obs_mask_row: np.ndarray) -> List[int]:\n \"\"\"\n Get list of variable idxs for variables that are still observable in the current row.\n Args:\n data_mask_row: 1D numpy array containing 1 for observed variables and 0 for unobserved in the underlying data\n obs_mask_row: 1D numpy array containing 1 for variables observed during active learning and 0 for ones unobserved\n\n Returns:\n observable_vars: List of indices of variables that can be observed.\n \"\"\"\n if data_mask_row.ndim != 1:\n raise ValueError(f\"Test mask should be 1D, had {data_mask_row.ndim} dims and shape {data_mask_row.shape}.\")\n if obs_mask_row.ndim != 1:\n raise ValueError(\n f\"Observation mask should be 1D, had {obs_mask_row.ndim} dims and shape {obs_mask_row.shape}.\"\n )\n if len(obs_mask_row) != len(data_mask_row) or len(data_mask_row) != len(self._variables):\n # One likely cause is accidentally passing 'processed' masks, which may be longer\n # if some variables are categorical.\n raise ValueError(\n f\"Lengths of obs_mask_row {len(obs_mask_row)}, data_mask_row {len(data_mask_row)}, \"\n f\"and variables list {len(self._variables)} should all be the same.\"\n )\n # Get ids where there is an underlying data value (test_mask == 1) and that we haven't yet queried (obs_mask == 0)\n unobserved_idxs = np.where((data_mask_row == 1) & (obs_mask_row == 0))[0]\n\n # Intersection of these and query_var_idxs.\n observable_idx_set = set(unobserved_idxs).intersection(set(self.query_var_idxs))\n return list(observable_idx_set)\n\n def get_var_cols_from_data(self, var_idx, data):\n \"\"\"\n Get data from an array for a single variable only.\n\n Args:\n var_idx: Index of variable we want data for.\n data (shape (batch_size, variable_count)): Array to get variable info from.\n\n Returns:\n var_data (shape (observed_count, processed_dim)): Values only for\n the corresponding variable.\n \"\"\"\n return data[:, self.processed_cols[var_idx]]\n\n def get_variables_to_observe(self, data_mask: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Return a boolean tensor of length num_variables, where each element indicates whether the corresponding variable\n can be queried during active learning (i.e. the variable is queriable and has at least one observed value in\n the data).\n Args:\n data_mask (shape (batch_size, num_processed_cols)): Processed mask\n\n Returns:\n torch.Tensor (shape (variable_count,)): True where it's a query-able variable and we have at least one\n observed value\n \"\"\"\n cols_with_data = data_mask.sum(dim=0).to(torch.bool)\n\n # data_mask may have multiple columns for a single variable, if it's a categorical variable. Pick first entry per variable\n ii = torch.tensor([cols[0] for cols in self.processed_cols], dtype=torch.long, device=cols_with_data.device)\n cols_with_data = torch.index_select(cols_with_data, 0, ii)\n is_query_id = torch.zeros(len(self), dtype=torch.bool, device=cols_with_data.device)\n is_query_id[\n tuple(self.query_var_idxs),\n ] = True\n return is_query_id * cols_with_data\n\n def _deduplicate_names(self):\n # Produce warning if var name is reused and add an increasing integer to the end until it is unique.\n var_names = set()\n for var in self._all_variables:\n i = 2\n original_name = var.name\n while var.name in var_names:\n new_name = f\"{original_name}_{i}\"\n var.name = new_name\n i += 1\n if var.name != original_name:\n # Do the warning in a separate block to the while loop so that we only raise one warning if we have to\n # try appending several different integers to the name.\n warnings.warn(\n f\"Name {original_name} has already been used, renaming to {var.name}\",\n UserWarning,\n )\n var_names.add(var.name)\n\n # TODO: Maybe create Variables.Utils for methods like the below one\n @staticmethod\n def create_empty_data(variables: Variables) -> np.ndarray:\n var_count = len(variables)\n empty_data = np.zeros((1, var_count), dtype=object)\n for i in range(var_count):\n if variables[i].type_ == \"text\":\n empty_data[:, i] = \"empty str\"\n return empty_data" }, { "identifier": "BayesDAGLinear", "path": "src/causica/models/bayesdag/bayesdag_linear.py", "snippet": "class BayesDAGLinear(BayesDAGNonLinear):\n \"\"\"\n Approximate Bayesian inference over the graph in a Gaussian linear ANM based on the BayesDAG result. Any DAG G is represented as G = W * Step(grad (p))\n where W is a discrete matrix W in {0, 1} ^ {d, d} and p in R^d. Inference over DAGs G then corresponds to inference over W and p\n as the transformation is determinstic. This can be converted to inference over W and p by using the Gumbel-Sinkhorn trick.\n \"\"\"\n\n def __init__(\n self,\n model_id: str,\n variables: Variables,\n save_dir: str,\n device: torch.device,\n lambda_sparse: float = 1.0,\n num_chains: int = 10,\n sinkhorn_n_iter: int = 3000,\n scale_noise: float = 0.1,\n scale_noise_p: float = 1.0,\n VI_norm: bool = False,\n input_perm:bool = False,\n sparse_init:bool = False,\n ):\n \"\"\"\n Args:\n model_id: Unique model ID for this model instance of training.\n variables: Information about variables/features used by this model.\n save_dir: Location to save any information about this model, including training data.\n device: Device to load model to.\n lambda_sparse: Coefficient for the prior term that enforces sparsity.\n norm_layers: bool indicating whether all MLPs should use layer norm\n res_connection: bool indicating whether all MLPs should use layer norm\n num_chains: Number of chains to use for SG-MCMC\n sinkhorn_n_iter: Number of iterations for Sinkhorn\n scale_noise: Hyperparameter of the Adam SGMCMC for sampling theta\n scale_noise_p: Hyperparameter of the Adam SGMCMC for sampling p\n sparse_init: Whether to initialize the W matrix to be sparse\n input_perm: Whether to use the input permutation to generate the adjacency matrix\n VI_norm: Whether to use layer norm in the helper network\n \"\"\"\n super().__init__(\n model_id=model_id,\n variables=variables,\n save_dir=save_dir,\n device=device,\n lambda_sparse=lambda_sparse,\n num_chains=num_chains,\n sinkhorn_n_iter=sinkhorn_n_iter,\n scale_noise=scale_noise,\n scale_noise_p=scale_noise_p,\n model_type=\"linear\",\n VI_norm=VI_norm,\n input_perm=input_perm,\n sparse_init=sparse_init\n )\n @classmethod\n def name(cls) -> str:\n return \"bayesdag_linear\"" }, { "identifier": "BayesDAGNonLinear", "path": "src/causica/models/bayesdag/bayesdag_nonlinear.py", "snippet": "class BayesDAGNonLinear(BayesDAG):\n \"\"\"\n Approximate Bayesian inference over the graph in a Gaussian nonlinear ANM based on the BayesDAG result. Any DAG G is represented as G = W * Step(grad (p))\n where W is a discrete matrix W in {0, 1} ^ {d, d} and p in R^d. Inference over DAGs G then corresponds to inference over W and p\n as the transformation is determinstic. This can be converted to inference over W and p by using the Gumbel-Sinkhorn trick.\n \"\"\"\n\n def __init__(\n self,\n model_id: str,\n variables: Variables,\n save_dir: str,\n device: torch.device,\n lambda_sparse: float = 1.0,\n norm_layers: bool = False,\n res_connection: bool = False,\n num_chains: int = 10,\n sinkhorn_n_iter: int = 3000,\n scale_noise: float = 0.1,\n scale_noise_p: float = 1.0,\n model_type: str = \"nonlinear\",\n sparse_init: bool = False,\n input_perm: bool = False,\n VI_norm: bool = False,\n ):\n \"\"\"\n Args:\n model_id: Unique model ID for this model instance of training.\n variables: Information about variables/features used by this model.\n save_dir: Location to save any information about this model, including training data.\n device: Device to load model to.\n lambda_sparse: Coefficient for the prior term that enforces sparsity.\n norm_layers: bool indicating whether all MLPs should use layer norm\n res_connection: bool indicating whether all MLPs should use layer norm\n num_chains: Number of chains to use for SG-MCMC\n sinkhorn_n_iter: Number of iterations for Sinkhorn\n scale_noise: Hyperparameter of the Adam SGMCMC for sampling theta\n scale_noise_p: Hyperparameter of the Adam SGMCMC for sampling p\n model_type: Type of model to use. Admits {\"linear\", \"nonlinear\"}\n sparse_init: Whether to initialize the W matrix to be sparse\n input_perm: Whether to use the input permutation to generate the adjacency matrix\n VI_norm: Whether to use layer norm in the helper network\n \"\"\"\n super().__init__(\n model_id=model_id,\n variables=variables,\n save_dir=save_dir,\n device=device,\n lambda_sparse=lambda_sparse,\n base_distribution_type=\"gaussian\",\n norm_layers=norm_layers,\n res_connection=res_connection,\n num_chains=num_chains,\n scale_noise=scale_noise,\n scale_noise_p=scale_noise_p,\n model_type=model_type,\n )\n self.input_perm = input_perm\n self.sparse_init = sparse_init\n self.VI_norm = VI_norm\n if self.sparse_init:\n self.logit_const = -1\n else:\n self.logit_const = 0\n \n if self.input_perm:\n hidden_size = 128\n layer_norm = partial(torch.nn.LayerNorm, elementwise_affine=True)\n self.helper_network = generate_fully_connected(\n input_dim=self.num_nodes*self.num_nodes,\n output_dim=(self.num_nodes * self.num_nodes),\n hidden_dims=[hidden_size, hidden_size],\n non_linearity=nn.ReLU,\n activation=None,\n device=device,\n res_connection=True,\n normalization=layer_norm\n )\n else:\n layer_norm = partial(torch.nn.LayerNorm, elementwise_affine=True)\n hidden_size = 48\n self.helper_network = generate_fully_connected(\n input_dim=self.num_nodes,\n output_dim=(self.num_nodes * self.num_nodes),\n hidden_dims=[hidden_size, hidden_size],\n non_linearity=nn.ReLU,\n activation=None,\n device=device,\n res_connection=True,\n normalization=layer_norm if self.VI_norm else None\n )\n \n if self.VI_norm:\n self.layer_norm = nn.LayerNorm(self.num_nodes, elementwise_affine=False)\n else:\n self.layer_norm = lambda x: x\n \n self.num_chains = num_chains\n self.o_scale = 10\n self.p_scale = 0.01\n self.p_buffer = deque(maxlen=5000)\n self.weights_buffer = deque(maxlen=5000)\n self.buffers_buffer = deque(maxlen=5000)\n self.p_steps = 0\n self.weights_steps = 0\n self.sinkhorn_n_iter = sinkhorn_n_iter\n self.num_burnin_steps = 1\n self.p = self.p_scale * torch.randn((self.num_chains, self.num_nodes), device=self.device)\n self.p.requires_grad = True\n\n self.p_opt = Adam_SGMCMC([self.p],\n lr=0.0003,\n betas=(0.9,0.99),\n dataset_size=5000,\n scale_noise=self.scale_noise_p,\n )\n #\n self.W_opt = torch.optim.Adam(list(self.helper_network.parameters())+[self.likelihoods[\"continuous\"].logscale_base] , lr=0.005)\n self.weights_opt = Adam_SGMCMC(self.icgnn_params,\n lr=0.0003,\n betas=(0.9,0.99),\n dataset_size=5000,\n scale_noise=self.scale_noise,\n )\n\n @classmethod\n def name(cls) -> str:\n return \"bayesdag_nonlinear\"\n\n def compute_perm_hard(self, p:torch.Tensor):\n def log_sinkhorn_norm(log_alpha: torch.Tensor, tol= 1e-3):\n for _ in range(self.sinkhorn_n_iter):\n log_alpha = log_alpha - torch.logsumexp(log_alpha, -1, keepdim=True)\n log_alpha = log_alpha - torch.logsumexp(log_alpha, -2, keepdim=True)\n exp_log_alpha = log_alpha.exp()\n if torch.abs(1.-exp_log_alpha.sum(-1)).max()<tol and torch.abs(1.-exp_log_alpha.sum(-2)).max()<tol:\n break\n return log_alpha.exp()\n\n O = self.o_scale * torch.arange(1, self.num_nodes+1, dtype=p.dtype, device=p.device).expand(1, -1)\n X = torch.matmul(p.unsqueeze(-1), O.unsqueeze(-2))\n \n perm = log_sinkhorn_norm(X / 0.2)\n \n perm_matrix = torch.zeros_like(perm)\n for i in range(perm.shape[0]):\n row_ind, col_ind = linear_sum_assignment(-perm[i].squeeze().cpu().detach().numpy())\n perm_indices = list(zip(row_ind, col_ind)) \n perm_indices = [(i,) + idx for idx in perm_indices]\n perm_indices = tuple(zip(*perm_indices))\n perm_matrix[perm_indices] = 1.0\n perm_matrix_hard = (perm_matrix - perm).detach() + perm # Straight Through\n return perm_matrix_hard, perm\n \n def transform_adj(self, p: torch.Tensor, detach_W: bool = False):\n \"\"\"\n Takes in p and returns the adjacency matrix G = W * Step(grad (p)), equivalent to doing G = W* [sigma(p) x L x sigma(p)^T]\n See Theorem 3.2 in https://arxiv.org/abs/2307.13917.\n Args:\n p: Tensor of shape (num_chains, num_nodes) representing the p vector\n detach_W: Whether to detach the W matrix from the computation graph\n \"\"\"\n perm_matrix_hard, perm = self.compute_perm_hard(p)\n \n if self.input_perm:\n helper_input = perm_matrix_hard.view(perm_matrix_hard.shape[0],-1)\n else:\n helper_input = self.layer_norm(p)\n\n W_vec_ = torch.distributions.RelaxedBernoulli(logits=self.helper_network(helper_input)+self.logit_const, temperature=0.2).rsample()\n if detach_W:\n W_vec_.detach()\n W_vec_hard = W_vec_.round()\n W_vec = (W_vec_hard - W_vec_).detach() + W_vec_\n W = W_vec.reshape(perm.shape[0], self.num_nodes, self.num_nodes)\n full_lower = torch.ones(perm.shape[0], int((self.num_nodes - 1) * self.num_nodes / 2)).to(p.device)\n adj_matrix = W * torch.matmul(\n torch.matmul(perm_matrix_hard, fill_triangular(full_lower)), perm_matrix_hard.transpose(-1, -2)\n )\n\n return adj_matrix\n \n def extract_icgnn_weights(self, use_param_weights, num_particles):\n if use_param_weights or len(self.weights_buffer)==0:\n params, buffers = self.icgnn_params, self.icgnn_buffers\n else:\n tuple_tensor=tuple(self.weights_buffer.pop() for _ in range(num_particles))\n params = transpose_stack(tuple_tensor)\n tuple_tensor=tuple(self.buffers_buffer.pop() for _ in range(num_particles))\n buffers = transpose_stack(tuple_tensor)\n return params, buffers\n\n def data_likelihood(self, X: torch.Tensor, A_samples: torch.Tensor, dataset_size:int, use_param_weights=False, return_prior: bool = False):\n \"\"\"\n Computes the log likelihood of the data under the model, i.e. p(X | G:={w,p}, theta, sigma)\n Args:\n X: Tensor of shape (batch_size, num_nodes) representing the data\n A_samples: Tensor of shape (num_chains, num_nodes, num_nodes) representing the adjacency matrix\n return_prior: Whether to return the prior term as well\n \"\"\"\n params, buffers = self.extract_icgnn_weights(use_param_weights=use_param_weights, num_particles=A_samples.shape[0])\n params_flat = torch.cat([param.view(A_samples.shape[0],-1) for param in params], dim=-1)\n if return_prior:\n theta_prior = 1/ dataset_size * (torch.distributions.normal.Normal(loc=torch.tensor(0.), scale=torch.tensor(1.)).log_prob(\n params_flat) ).sum(-1) # num_chains\n p_prior = 1/dataset_size * (torch.distributions.normal.Normal(loc=torch.tensor(0.), scale=torch.tensor(0.1)).log_prob(self.p)).sum(-1) # chain\n\n sparse_loss = -(1/dataset_size) * self.lambda_sparse* A_samples.abs().sum(-1).sum(-1) # chain\n\n W_adj = A_samples * vmap(self.ICGNN.get_weighted_adjacency)(params, buffers)\n predict = vmap(self.ICGNN.predict, in_dims=(0, 0, None, 0))(params, buffers, X, W_adj)# N x num_chain x D #chain x N x 1 x D\n\n log_p_base = self._log_prob(\n X, predict, W=A_samples if self.base_distribution_type == \"conditional_spline\" else None\n ).transpose(0,1) # N x num_chains\n if return_prior:\n return log_p_base, theta_prior, p_prior, sparse_loss\n\n return log_p_base\n\n def compute_W_prior_entropy(self, p: torch.Tensor, dataset_size: int):\n \"\"\"\n Computes the prior and entropy terms for the W matrix (for VI).\n Args:\n p: Tensor of shape (num_chains, num_nodes) representing the p vector\n dataset_size: Size of the dataset\n \"\"\"\n if self.input_perm:\n perm_matrix_hard, _ = self.compute_perm_hard(p)\n helper_input = perm_matrix_hard.view(perm_matrix_hard.shape[0],-1)\n logits = self.helper_network(helper_input)\n else:\n logits = self.helper_network(self.layer_norm(p)) # chain x( D x D)\n\n # draw hard samples\n W_vec_ = torch.distributions.RelaxedBernoulli(logits=logits+self.logit_const, temperature=0.2).rsample()\n W_vec_hard = W_vec_.round()\n W_vec = (W_vec_hard - W_vec_).detach() + W_vec_\n W = W_vec.reshape(p.shape[0], self.num_nodes, self.num_nodes) # chain x D x D\n prior = 1./dataset_size*torch.distributions.Bernoulli(probs=torch.tensor(0.5).to(device=W.device)).log_prob(W).sum(-1).sum(-1) # chain\n # compute entropy\n entropy = 1./dataset_size*torch.distributions.Bernoulli(logits=logits).entropy().sum(-1).sum(-1) # chain\n return prior, entropy\n\n def process_dataset(\n self,\n dataset: Dataset,\n train_config_dict: Optional[Dict[str, Any]] = None,\n variables: Optional[Variables] = None,\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generates the training data and mask.\n Args:\n dataset: Dataset to use.\n train_config_dict: Dictionary with training hyperparameters.\n variables: Information about variables/features used by this model.\n Returns:\n Tuple with data and mask arrays.\n \"\"\"\n if train_config_dict is None:\n train_config_dict = {}\n if variables is None:\n variables = self.variables\n\n self.data_processor = DataProcessor(\n variables,\n unit_scale_continuous=False,\n standardize_data_mean=train_config_dict.get(\"standardize_data_mean\", False),\n standardize_data_std=train_config_dict.get(\"standardize_data_std\", False),\n )\n processed_dataset = self.data_processor.process_dataset(dataset)\n\n data, mask = processed_dataset.train_data_and_mask\n data = data.astype(np.float32)\n return data, mask\n\n def _posterior_p_sample(self, data: torch.Tensor, dataset_size:int, num_samples: int = 1, writer: Optional[SummaryWriter] = None, interval:int=1) -> torch.Tensor:\n \"\"\"\n SG-MCMC step for sampling p.\n Args:\n data: Tensor of shape (batch_size, num_nodes) representing the data\n num_samples: Number of samples to return.\n writer: Optional tensorboard SummaryWriter.\n dataset_size: Size of the dataset\n interval: Number of steps between logging to tensorboard\n \"\"\"\n num_steps = num_samples * interval\n if self.p_steps < self.num_burnin_steps:\n num_steps = self.num_burnin_steps - self.p_steps + num_samples\n total_loss = 0.\n for cur_step in range(num_steps):\n self.weights_opt.zero_grad()\n self.W_opt.zero_grad()\n self.p_opt.zero_grad()\n A_samples = self.transform_adj(self.p, detach_W=False)\n ll_eltwise, _, p_prior, sparse_loss = self.data_likelihood(data, A_samples, dataset_size=dataset_size, use_param_weights=True, return_prior=True)\n loss = -(ll_eltwise+p_prior+1*sparse_loss).mean() # 1 averaged over num_chains, batch sizes\n total_loss+= loss.detach()\n loss.backward()\n self.p_opt.step()\n if writer is not None:\n for jj in range(self.p.shape[0]):\n writer_dict = {}\n for j in range(self.p.shape[-1]):\n writer_dict[str(j)] = self.p[jj, j].detach().cpu().numpy()\n writer.add_scalars(f\"p_chain_{jj}\", writer_dict, self.p_steps) # tensorboard\n self.p_steps += 1\n \n if self.p_steps >= self.num_burnin_steps and (cur_step+1)%interval == 0:\n for i in range(len(self.p)):\n self.p_buffer.append(self.p[i].detach().clone())\n\n return total_loss/num_steps\n \n def _posterior_weights_sample(self, data: torch.Tensor, dataset_size:int, num_samples: int = 1) -> torch.Tensor:\n \"\"\"\n SG-MCMC step for sampling the weights.\n Args:\n data: Tensor of shape (batch_size, num_nodes) representing the data\n num_samples: Number of samples to return.\n dataset_size: Size of the dataset\n \"\"\"\n num_steps = num_samples\n if self.weights_steps < self.num_burnin_steps:\n num_steps = self.num_burnin_steps - self.weights_steps + num_samples\n\n total_loss = 0.\n for _ in range(num_steps):\n self.weights_opt.zero_grad()\n self.W_opt.zero_grad()\n self.p_opt.zero_grad()\n A_samples = self.transform_adj(self.p)\n ll_eltwise, theta_prior, _, sparse_loss = self.data_likelihood(data, A_samples, dataset_size=dataset_size, use_param_weights=True, return_prior=True)# batch x chain, num_chain\n \n loss = -(ll_eltwise+theta_prior+sparse_loss).mean() #[]\n total_loss += loss.detach()\n loss.backward()\n self.weights_opt.step()\n self.weights_steps += 1\n\n if self.weights_steps >= self.num_burnin_steps:\n for i in range(self.num_chains):\n self.weights_buffer.append(untranspose_stack(self.icgnn_params, i, clone=True))\n self.buffers_buffer.append(untranspose_stack(self.icgnn_buffers, i, clone=True))\n return total_loss/num_steps\n \n def _train_helper_network(self, data: torch.Tensor, dataset_size, num_iters: int = 1)-> torch.Tensor:\n \"\"\"\n VI step for training the helper network to generate W conditioned on p.\n Args:\n data: Tensor of shape (batch_size, num_nodes) representing the data\n num_iters: Number of iterations to train for.\n dataset_size: Size of the dataset\n \"\"\"\n total_loss = 0.\n for _ in range(num_iters):\n self.weights_opt.zero_grad()\n self.W_opt.zero_grad()\n self.p_opt.zero_grad()\n A_samples = self.transform_adj(self.p)\n ll_eltwise,_,_,sparse_loss = self.data_likelihood(data, A_samples, dataset_size=dataset_size, use_param_weights=True, return_prior=True) # batch x chain\n prior, entropy = self.compute_W_prior_entropy(self.p, dataset_size=dataset_size) # chain\n loss = -(ll_eltwise+prior + entropy+sparse_loss).mean() #\n total_loss += loss.detach()\n loss.backward()\n self.W_opt.step()\n return total_loss/num_iters\n\n def run_train(\n self,\n dataset: Dataset,\n train_config_dict: Optional[Dict[str, Any]] = None,\n report_progress_callback: Optional[Callable[[str, int, int], None]] = None,\n ) -> None:\n \"\"\"\n Runs training.\n Args:\n dataset: Dataset to use.\n train_config_dict: Dictionary with training hyperparameters.\n report_progress_callback: Optional callback function to report training progress.\n \"\"\"\n if train_config_dict is None:\n train_config_dict = {}\n dataloader, _ = self._create_dataset_for_bayesdag(dataset, train_config_dict)\n\n # initialise logging machinery\n train_output_dir = os.path.join(self.save_dir, \"train_output\")\n os.makedirs(train_output_dir, exist_ok=True)\n log_path = os.path.join(train_output_dir, \"summary\")\n writer = SummaryWriter(log_path, flush_secs=1)\n\n print(\"Saving logs to\", log_path, flush=True)\n tracker_loss_terms: Dict = defaultdict(list)\n \n self.dataset_size = dataset._train_data.shape[0]\n self.train_data, _ = to_tensors(*dataset.train_data_and_mask,device=self.device)\n\n best_loss = np.inf\n self.p_opt.update_dataset_size(self.dataset_size)\n self.weights_opt.update_dataset_size(self.dataset_size)\n # Outer optimization loop\n inner_opt_count = 0\n prev_best = 0\n for step in range(train_config_dict[\"max_epochs\"]):\n loss_epoch = 0.\n \n for (x, _) in dataloader:\n p_loss = self._posterior_p_sample(data=x, dataset_size=self.dataset_size, num_samples=1, writer=writer)\n \n W_loss = self._train_helper_network(data=x, dataset_size=self.dataset_size,num_iters=1)\n weights_loss = self._posterior_weights_sample(data=x, dataset_size=self.dataset_size ,num_samples=1)\n loss = (p_loss+W_loss+weights_loss)/3\n loss_epoch += loss\n tracker_loss_terms[\"loss\"].append(loss.mean().item())\n tracker_loss_terms[\"p_loss\"].append(p_loss.item())\n tracker_loss_terms[\"W_loss\"].append(W_loss.item())\n tracker_loss_terms[\"weights_loss\"].append(weights_loss.item())\n inner_opt_count+=1\n if loss_epoch.item() < best_loss:\n best_loss = loss_epoch.item()\n print(\"New best model found. Saving Checkpoint\")\n prev_best = 0\n self.save(best=True)\n else:\n prev_best +=1\n if step % 4 == 0:\n if (\n isinstance(dataset, CausalDataset)\n and dataset.has_adjacency_data_matrix\n and not hasattr(self, \"latent_variables\")\n ):\n \n adj_metrics = self.evaluate_metrics(dataset=dataset)\n else:\n adj_metrics = None\n self.print_tracker_sgld(step, tracker_loss_terms, adj_metrics)\n \n _log_epoch_metrics(writer=writer, tracker_loss_terms=tracker_loss_terms, adj_metrics=adj_metrics, step=step)\n\n \n def print_tracker_sgld(self, step: int, tracker: dict, adj_metrics: Optional[dict]) -> None:\n \"\"\"Prints formatted contents of loss terms that are being tracked.\n Args:\n inner_step: Current step.\n tracker: Dictionary with loss terms.\n adj_metrics: Dictionary with adjacency matrix discovery metrics.\n \"\"\"\n tracker_copy = tracker.copy()\n\n loss = np.mean(tracker_copy.pop(\"loss\")[-100:])\n if adj_metrics is not None:\n adj_metrics_cp = adj_metrics.copy()\n shd = adj_metrics_cp.pop(\"shd\")\n nnz = adj_metrics_cp.pop(\"nnz\")\n cpdag_shd = adj_metrics_cp.pop(\"cpdag-shd\", float(\"nan\"))\n nll_val = adj_metrics_cp.pop(\"nll_val\", float(\"nan\"))\n nll_train = adj_metrics_cp.pop(\"nll_train\", float(\"nan\"))\n o_fscore = adj_metrics_cp.pop(\"orientation_fscore\", float(\"nan\"))\n mmd_tp = adj_metrics_cp.pop(\"mmd-tp\", float(\"nan\"))\n else:\n shd = float(\"nan\")\n nnz = float(\"nan\")\n nll_val = float(\"nan\")\n cpdag_shd = float(\"nan\")\n nll_train = float(\"nan\")\n mmd_tp =float(\"nan\")\n o_fscore = float(\"nan\")\n\n print(\n f\"Step: {step}, loss: {loss:.2f}, shd: {shd:.2f}, o_fscore:{o_fscore:.2f}, cpdag-shd: {cpdag_shd:.2f} nnz: {nnz:.2f} NLL-Validation: {nll_val:.4f} NLL-Train: {nll_train:.4f} MMD-TP: {mmd_tp:.4f} P_grad_norm:{torch.norm(self.p.grad).item()}\", flush=True\n )\n \n \n def get_adj_matrix_tensor(\n self,\n samples: int = 5,\n ) -> torch.Tensor: \n \"\"\"\n Returns the adjacency matrix (or several) as a torch tensor.\n Args:\n samples: Number of samples to return.\n \"\"\"\n batch_size = 500\n num_steps = int(np.ceil(samples/self.num_chains))\n for _ in range(num_steps):\n indices = torch.randperm(self.train_data.shape[0])[:batch_size]\n input_data = self.train_data[indices]\n self._posterior_p_sample(data=input_data, num_samples=1, dataset_size=self.dataset_size, interval=1)\n self._posterior_weights_sample(data=input_data,dataset_size=self.dataset_size, num_samples=1)\n\n p_vec= []\n for _ in range(samples):\n p_vec.append(self.p_buffer.pop())\n p_eval = torch.stack(p_vec)\n adj_matrix = self.transform_adj(p_eval) != 0.0\n return adj_matrix, torch.ones(samples)\n\n def get_adj_matrix(\n self,\n samples: int = 100,\n squeeze: bool = False,\n ) -> np.ndarray:\n \"\"\"\n Returns the adjacency matrix (or several) as a numpy array.\n Args:\n samples: Number of samples to return.\n squeeze: Whether to squeeze the first dimension if samples == 1.\n \"\"\"\n adj_matrix, is_dag = self.get_adj_matrix_tensor(samples=samples)\n if squeeze and samples == 1:\n adj_matrix = adj_matrix.squeeze(0)\n return adj_matrix.detach().cpu().numpy().astype(np.float64), is_dag.detach().cpu().numpy().astype(bool)" }, { "identifier": "IModel", "path": "src/causica/models/imodel.py", "snippet": "class IModel(ABC):\n \"\"\"\n Interface for model:\n create: Create an instance of the concrete class.\n load: Load an instance of the concrete class from a given directory.\n save: Save any data needed to load the model.\n name: Name of objective, to use when finding model to use from string.\n run_train: Train the model.\n impute: Impute missing values:\n \"\"\"\n\n def __init__(self, model_id: str, variables: Variables, save_dir: str) -> None:\n \"\"\"\n Args:\n model_id: Unique model ID for referencing this model instance.\n variables: Information about variables/features used by this model.\n save_dir: Location to save any information about this model, including training data.\n It will be created if it doesn't exist.\n \"\"\"\n self.model_id = model_id\n self.save_dir = save_dir\n self.variables = variables\n self.data_processor = DataProcessor(variables)\n\n @classmethod\n @abstractmethod\n def create(\n cls,\n model_id: str,\n save_dir: str,\n variables: Variables,\n model_config_dict: Dict[str, Any],\n device: Union[str, int],\n ) -> IModel:\n \"\"\"\n Create a new instance of a model with given type.\n\n Args:\n model_id (str): Unique model ID for referencing this model instance.\n save_dir (str): Location to save all model information to.\n device (str or int): Name of device to load the model on. Valid options are 'cpu', 'gpu', or a device ID\n (e.g. 0 or 1 on a two-GPU machine).\n variables (Variables): Information about variables/features used\n by this model.\n model_config_dict (dictionary): Any other parameters needed by a specific concrete class. Of\n the form {arg_name: arg_value}. e.g. {\"embedding_dim\": 10, \"latent_dim\": 20}\n\n Returns:\n model: Instance of concrete implementation of `Model` class.\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n @abstractmethod\n def load(cls, model_id: str, save_dir: str, device: Union[str, int]) -> IModel:\n \"\"\"\n Load an instance of a model.\n\n Args:\n model_id (str): Unique model ID for referencing this model instance.\n save_dir (str): Save directory for this model.\n device (str or int): Name of device to load the model on. Valid options are 'cpu', 'gpu', or a device ID\n (e.g. 0 or 1 on a two-GPU machine).\n variables (Variables): Information about variables/features used\n by this model.\n\n Returns:\n Instance of concrete implementation of `Model` class.\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n @abstractmethod\n def name(cls) -> str:\n \"\"\"\n Name of the model implemented in abstract class.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def save(self) -> None:\n \"\"\"\n Save the model.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def run_train(\n self,\n dataset: Dataset,\n train_config_dict: Optional[Dict[str, Any]] = None,\n report_progress_callback: Optional[Callable[[str, int, int], None]] = None,\n ) -> None:\n \"\"\"\n Train the model.\n Training results will be saved.\n\n Args:\n dataset: Dataset object with data and masks in unprocessed form.\n train_config_dict (dictionary): Any other parameters needed by a specific concrete class. Of\n the form {arg_name: arg_value}. e.g. {\"learning_rate\": 1e-3, \"epochs\": 100}\n report_progress_callback: Function to report model progress for API.\n \"\"\"\n raise NotImplementedError()" } ]
import os from typing import Any, Dict, Type, Union from uuid import uuid4 from .datasets.variables import Variables from .models.bayesdag.bayesdag_linear import BayesDAGLinear from .models.bayesdag.bayesdag_nonlinear import BayesDAGNonLinear from .models.imodel import IModel
14,869
MODEL_SUBCLASSES: Dict[str, Type[IModel]] = { model.name(): model # type: ignore for model in ( # Models
MODEL_SUBCLASSES: Dict[str, Type[IModel]] = { model.name(): model # type: ignore for model in ( # Models
BayesDAGLinear,
1
2023-11-21 12:55:08+00:00
24k
jiawei-ren/dreamgaussian4d
diffusers/src/diffusers/models/autoencoder_tiny.py
[ { "identifier": "ConfigMixin", "path": "diffusers/src/diffusers/configuration_utils.py", "snippet": "class ConfigMixin:\n r\"\"\"\n Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also\n provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and\n saving classes that inherit from [`ConfigMixin`].\n\n Class attributes:\n - **config_name** (`str`) -- A filename under which the config should stored when calling\n [`~ConfigMixin.save_config`] (should be overridden by parent class).\n - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be\n overridden by subclass).\n - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).\n - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function\n should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by\n subclass).\n \"\"\"\n\n config_name = None\n ignore_for_config = []\n has_compatibles = False\n\n _deprecated_kwargs = []\n\n def register_to_config(self, **kwargs):\n if self.config_name is None:\n raise NotImplementedError(f\"Make sure that {self.__class__} has defined a class name `config_name`\")\n # Special case for `kwargs` used in deprecation warning added to schedulers\n # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,\n # or solve in a more general way.\n kwargs.pop(\"kwargs\", None)\n\n if not hasattr(self, \"_internal_dict\"):\n internal_dict = kwargs\n else:\n previous_dict = dict(self._internal_dict)\n internal_dict = {**self._internal_dict, **kwargs}\n logger.debug(f\"Updating config from {previous_dict} to {internal_dict}\")\n\n self._internal_dict = FrozenDict(internal_dict)\n\n def __getattr__(self, name: str) -> Any:\n \"\"\"The only reason we overwrite `getattr` here is to gracefully deprecate accessing\n config attributes directly. See https://github.com/huggingface/diffusers/pull/3129\n\n Tihs funtion is mostly copied from PyTorch's __getattr__ overwrite:\n https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module\n \"\"\"\n\n is_in_config = \"_internal_dict\" in self.__dict__ and hasattr(self.__dict__[\"_internal_dict\"], name)\n is_attribute = name in self.__dict__\n\n if is_in_config and not is_attribute:\n deprecation_message = f\"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'.\"\n deprecate(\"direct config name access\", \"1.0.0\", deprecation_message, standard_warn=False)\n return self._internal_dict[name]\n\n raise AttributeError(f\"'{type(self).__name__}' object has no attribute '{name}'\")\n\n def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):\n \"\"\"\n Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the\n [`~ConfigMixin.from_config`] class method.\n\n Args:\n save_directory (`str` or `os.PathLike`):\n Directory where the configuration JSON file is saved (will be created if it does not exist).\n push_to_hub (`bool`, *optional*, defaults to `False`):\n Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the\n repository you want to push to with `repo_id` (will default to the name of `save_directory` in your\n namespace).\n kwargs (`Dict[str, Any]`, *optional*):\n Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.\n \"\"\"\n if os.path.isfile(save_directory):\n raise AssertionError(f\"Provided path ({save_directory}) should be a directory, not a file\")\n\n os.makedirs(save_directory, exist_ok=True)\n\n # If we save using the predefined names, we can load using `from_config`\n output_config_file = os.path.join(save_directory, self.config_name)\n\n self.to_json_file(output_config_file)\n logger.info(f\"Configuration saved in {output_config_file}\")\n\n if push_to_hub:\n commit_message = kwargs.pop(\"commit_message\", None)\n private = kwargs.pop(\"private\", False)\n create_pr = kwargs.pop(\"create_pr\", False)\n token = kwargs.pop(\"token\", None)\n repo_id = kwargs.pop(\"repo_id\", save_directory.split(os.path.sep)[-1])\n repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id\n\n self._upload_folder(\n save_directory,\n repo_id,\n token=token,\n commit_message=commit_message,\n create_pr=create_pr,\n )\n\n @classmethod\n def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):\n r\"\"\"\n Instantiate a Python class from a config dictionary.\n\n Parameters:\n config (`Dict[str, Any]`):\n A config dictionary from which the Python class is instantiated. Make sure to only load configuration\n files of compatible classes.\n return_unused_kwargs (`bool`, *optional*, defaults to `False`):\n Whether kwargs that are not consumed by the Python class should be returned or not.\n kwargs (remaining dictionary of keyword arguments, *optional*):\n Can be used to update the configuration object (after it is loaded) and initiate the Python class.\n `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually\n overwrite the same named arguments in `config`.\n\n Returns:\n [`ModelMixin`] or [`SchedulerMixin`]:\n A model or scheduler object instantiated from a config dictionary.\n\n Examples:\n\n ```python\n >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler\n\n >>> # Download scheduler from huggingface.co and cache.\n >>> scheduler = DDPMScheduler.from_pretrained(\"google/ddpm-cifar10-32\")\n\n >>> # Instantiate DDIM scheduler class with same config as DDPM\n >>> scheduler = DDIMScheduler.from_config(scheduler.config)\n\n >>> # Instantiate PNDM scheduler class with same config as DDPM\n >>> scheduler = PNDMScheduler.from_config(scheduler.config)\n ```\n \"\"\"\n # <===== TO BE REMOVED WITH DEPRECATION\n # TODO(Patrick) - make sure to remove the following lines when config==\"model_path\" is deprecated\n if \"pretrained_model_name_or_path\" in kwargs:\n config = kwargs.pop(\"pretrained_model_name_or_path\")\n\n if config is None:\n raise ValueError(\"Please make sure to provide a config as the first positional argument.\")\n # ======>\n\n if not isinstance(config, dict):\n deprecation_message = \"It is deprecated to pass a pretrained model name or path to `from_config`.\"\n if \"Scheduler\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead.\"\n \" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will\"\n \" be removed in v1.0.0.\"\n )\n elif \"Model\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a model, please use {cls}.load_config(...) followed by\"\n f\" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary\"\n \" instead. This functionality will be removed in v1.0.0.\"\n )\n deprecate(\"config-passed-as-path\", \"1.0.0\", deprecation_message, standard_warn=False)\n config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)\n\n init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)\n\n # Allow dtype to be specified on initialization\n if \"dtype\" in unused_kwargs:\n init_dict[\"dtype\"] = unused_kwargs.pop(\"dtype\")\n\n # add possible deprecated kwargs\n for deprecated_kwarg in cls._deprecated_kwargs:\n if deprecated_kwarg in unused_kwargs:\n init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)\n\n # Return model and optionally state and/or unused_kwargs\n model = cls(**init_dict)\n\n # make sure to also save config parameters that might be used for compatible classes\n model.register_to_config(**hidden_dict)\n\n # add hidden kwargs of compatible classes to unused_kwargs\n unused_kwargs = {**unused_kwargs, **hidden_dict}\n\n if return_unused_kwargs:\n return (model, unused_kwargs)\n else:\n return model\n\n @classmethod\n def get_config_dict(cls, *args, **kwargs):\n deprecation_message = (\n f\" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be\"\n \" removed in version v1.0.0\"\n )\n deprecate(\"get_config_dict\", \"1.0.0\", deprecation_message, standard_warn=False)\n return cls.load_config(*args, **kwargs)\n\n @classmethod\n def load_config(\n cls,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n return_unused_kwargs=False,\n return_commit_hash=False,\n **kwargs,\n ) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n r\"\"\"\n Load a model or scheduler configuration.\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):\n Can be either:\n\n - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on\n the Hub.\n - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with\n [`~ConfigMixin.save_config`].\n\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory where a downloaded pretrained model configuration is cached if the standard cache\n is not used.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to resume downloading the model weights and configuration files. If set to `False`, any\n incompletely downloaded files are deleted.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n output_loading_info(`bool`, *optional*, defaults to `False`):\n Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.\n local_files_only (`bool`, *optional*, defaults to `False`):\n Whether to only load local model weights and configuration files or not. If set to `True`, the model\n won't be downloaded from the Hub.\n use_auth_token (`str` or *bool*, *optional*):\n The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from\n `diffusers-cli login` (stored in `~/.huggingface`) is used.\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier\n allowed by Git.\n subfolder (`str`, *optional*, defaults to `\"\"`):\n The subfolder location of a model file within a larger model repository on the Hub or locally.\n return_unused_kwargs (`bool`, *optional*, defaults to `False):\n Whether unused keyword arguments of the config are returned.\n return_commit_hash (`bool`, *optional*, defaults to `False):\n Whether the `commit_hash` of the loaded configuration are returned.\n\n Returns:\n `dict`:\n A dictionary of all the parameters stored in a JSON configuration file.\n\n \"\"\"\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n force_download = kwargs.pop(\"force_download\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n revision = kwargs.pop(\"revision\", None)\n _ = kwargs.pop(\"mirror\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n user_agent = kwargs.pop(\"user_agent\", {})\n\n user_agent = {**user_agent, \"file_type\": \"config\"}\n user_agent = http_user_agent(user_agent)\n\n pretrained_model_name_or_path = str(pretrained_model_name_or_path)\n\n if cls.config_name is None:\n raise ValueError(\n \"`self.config_name` is not defined. Note that one should not load a config from \"\n \"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`\"\n )\n\n if os.path.isfile(pretrained_model_name_or_path):\n config_file = pretrained_model_name_or_path\n elif os.path.isdir(pretrained_model_name_or_path):\n if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):\n # Load from a PyTorch checkpoint\n config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)\n elif subfolder is not None and os.path.isfile(\n os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n ):\n config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n else:\n raise EnvironmentError(\n f\"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}.\"\n )\n else:\n try:\n # Load from URL or cache if already cached\n config_file = hf_hub_download(\n pretrained_model_name_or_path,\n filename=cls.config_name,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n user_agent=user_agent,\n subfolder=subfolder,\n revision=revision,\n )\n except RepositoryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier\"\n \" listed on 'https://huggingface.co/models'\\nIf this is a private repository, make sure to pass a\"\n \" token having permission to this repo with `use_auth_token` or log in with `huggingface-cli\"\n \" login`.\"\n )\n except RevisionNotFoundError:\n raise EnvironmentError(\n f\"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for\"\n \" this model name. Check the model page at\"\n f\" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.\"\n )\n except EntryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}.\"\n )\n except HTTPError as err:\n raise EnvironmentError(\n \"There was a specific connection error when trying to load\"\n f\" {pretrained_model_name_or_path}:\\n{err}\"\n )\n except ValueError:\n raise EnvironmentError(\n f\"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it\"\n f\" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a\"\n f\" directory containing a {cls.config_name} file.\\nCheckout your internet connection or see how to\"\n \" run the library in offline mode at\"\n \" 'https://huggingface.co/docs/diffusers/installation#offline-mode'.\"\n )\n except EnvironmentError:\n raise EnvironmentError(\n f\"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from \"\n \"'https://huggingface.co/models', make sure you don't have a local directory with the same name. \"\n f\"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory \"\n f\"containing a {cls.config_name} file\"\n )\n\n try:\n # Load config dict\n config_dict = cls._dict_from_json_file(config_file)\n\n commit_hash = extract_commit_hash(config_file)\n except (json.JSONDecodeError, UnicodeDecodeError):\n raise EnvironmentError(f\"It looks like the config file at '{config_file}' is not a valid JSON file.\")\n\n if not (return_unused_kwargs or return_commit_hash):\n return config_dict\n\n outputs = (config_dict,)\n\n if return_unused_kwargs:\n outputs += (kwargs,)\n\n if return_commit_hash:\n outputs += (commit_hash,)\n\n return outputs\n\n @staticmethod\n def _get_init_keys(cls):\n return set(dict(inspect.signature(cls.__init__).parameters).keys())\n\n @classmethod\n def extract_init_dict(cls, config_dict, **kwargs):\n # Skip keys that were not present in the original config, so default __init__ values were used\n used_defaults = config_dict.get(\"_use_default_values\", [])\n config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != \"_use_default_values\"}\n\n # 0. Copy origin config dict\n original_dict = dict(config_dict.items())\n\n # 1. Retrieve expected config attributes from __init__ signature\n expected_keys = cls._get_init_keys(cls)\n expected_keys.remove(\"self\")\n # remove general kwargs if present in dict\n if \"kwargs\" in expected_keys:\n expected_keys.remove(\"kwargs\")\n # remove flax internal keys\n if hasattr(cls, \"_flax_internal_args\"):\n for arg in cls._flax_internal_args:\n expected_keys.remove(arg)\n\n # 2. Remove attributes that cannot be expected from expected config attributes\n # remove keys to be ignored\n if len(cls.ignore_for_config) > 0:\n expected_keys = expected_keys - set(cls.ignore_for_config)\n\n # load diffusers library to import compatible and original scheduler\n diffusers_library = importlib.import_module(__name__.split(\".\")[0])\n\n if cls.has_compatibles:\n compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]\n else:\n compatible_classes = []\n\n expected_keys_comp_cls = set()\n for c in compatible_classes:\n expected_keys_c = cls._get_init_keys(c)\n expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)\n expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)\n config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}\n\n # remove attributes from orig class that cannot be expected\n orig_cls_name = config_dict.pop(\"_class_name\", cls.__name__)\n if (\n isinstance(orig_cls_name, str)\n and orig_cls_name != cls.__name__\n and hasattr(diffusers_library, orig_cls_name)\n ):\n orig_cls = getattr(diffusers_library, orig_cls_name)\n unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys\n config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}\n elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):\n raise ValueError(\n \"Make sure that the `_class_name` is of type string or list of string (for custom pipelines).\"\n )\n\n # remove private attributes\n config_dict = {k: v for k, v in config_dict.items() if not k.startswith(\"_\")}\n\n # 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments\n init_dict = {}\n for key in expected_keys:\n # if config param is passed to kwarg and is present in config dict\n # it should overwrite existing config dict key\n if key in kwargs and key in config_dict:\n config_dict[key] = kwargs.pop(key)\n\n if key in kwargs:\n # overwrite key\n init_dict[key] = kwargs.pop(key)\n elif key in config_dict:\n # use value from config dict\n init_dict[key] = config_dict.pop(key)\n\n # 4. Give nice warning if unexpected values have been passed\n if len(config_dict) > 0:\n logger.warning(\n f\"The config attributes {config_dict} were passed to {cls.__name__}, \"\n \"but are not expected and will be ignored. Please verify your \"\n f\"{cls.config_name} configuration file.\"\n )\n\n # 5. Give nice info if config attributes are initiliazed to default because they have not been passed\n passed_keys = set(init_dict.keys())\n if len(expected_keys - passed_keys) > 0:\n logger.info(\n f\"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values.\"\n )\n\n # 6. Define unused keyword arguments\n unused_kwargs = {**config_dict, **kwargs}\n\n # 7. Define \"hidden\" config parameters that were saved for compatible classes\n hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}\n\n return init_dict, unused_kwargs, hidden_config_dict\n\n @classmethod\n def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):\n with open(json_file, \"r\", encoding=\"utf-8\") as reader:\n text = reader.read()\n return json.loads(text)\n\n def __repr__(self):\n return f\"{self.__class__.__name__} {self.to_json_string()}\"\n\n @property\n def config(self) -> Dict[str, Any]:\n \"\"\"\n Returns the config of the class as a frozen dictionary\n\n Returns:\n `Dict[str, Any]`: Config of the class.\n \"\"\"\n return self._internal_dict\n\n def to_json_string(self) -> str:\n \"\"\"\n Serializes the configuration instance to a JSON string.\n\n Returns:\n `str`:\n String containing all the attributes that make up the configuration instance in JSON format.\n \"\"\"\n config_dict = self._internal_dict if hasattr(self, \"_internal_dict\") else {}\n config_dict[\"_class_name\"] = self.__class__.__name__\n config_dict[\"_diffusers_version\"] = __version__\n\n def to_json_saveable(value):\n if isinstance(value, np.ndarray):\n value = value.tolist()\n elif isinstance(value, PosixPath):\n value = str(value)\n return value\n\n config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}\n # Don't save \"_ignore_files\" or \"_use_default_values\"\n config_dict.pop(\"_ignore_files\", None)\n config_dict.pop(\"_use_default_values\", None)\n\n return json.dumps(config_dict, indent=2, sort_keys=True) + \"\\n\"\n\n def to_json_file(self, json_file_path: Union[str, os.PathLike]):\n \"\"\"\n Save the configuration instance's parameters to a JSON file.\n\n Args:\n json_file_path (`str` or `os.PathLike`):\n Path to the JSON file to save a configuration instance's parameters.\n \"\"\"\n with open(json_file_path, \"w\", encoding=\"utf-8\") as writer:\n writer.write(self.to_json_string())" }, { "identifier": "register_to_config", "path": "diffusers/src/diffusers/configuration_utils.py", "snippet": "def register_to_config(self, **kwargs):\n if self.config_name is None:\n raise NotImplementedError(f\"Make sure that {self.__class__} has defined a class name `config_name`\")\n # Special case for `kwargs` used in deprecation warning added to schedulers\n # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,\n # or solve in a more general way.\n kwargs.pop(\"kwargs\", None)\n\n if not hasattr(self, \"_internal_dict\"):\n internal_dict = kwargs\n else:\n previous_dict = dict(self._internal_dict)\n internal_dict = {**self._internal_dict, **kwargs}\n logger.debug(f\"Updating config from {previous_dict} to {internal_dict}\")\n\n self._internal_dict = FrozenDict(internal_dict)" }, { "identifier": "BaseOutput", "path": "diffusers/src/diffusers/utils/outputs.py", "snippet": "class BaseOutput(OrderedDict):\n \"\"\"\n Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a\n tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular\n Python dictionary.\n\n <Tip warning={true}>\n\n You can't unpack a [`BaseOutput`] directly. Use the [`~utils.BaseOutput.to_tuple`] method to convert it to a tuple\n first.\n\n </Tip>\n \"\"\"\n\n def __init_subclass__(cls) -> None:\n \"\"\"Register subclasses as pytree nodes.\n\n This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with\n `static_graph=True` with modules that output `ModelOutput` subclasses.\n \"\"\"\n if is_torch_available():\n import torch.utils._pytree\n\n torch.utils._pytree._register_pytree_node(\n cls,\n torch.utils._pytree._dict_flatten,\n lambda values, context: cls(**torch.utils._pytree._dict_unflatten(values, context)),\n )\n\n def __post_init__(self) -> None:\n class_fields = fields(self)\n\n # Safety and consistency checks\n if not len(class_fields):\n raise ValueError(f\"{self.__class__.__name__} has no fields.\")\n\n first_field = getattr(self, class_fields[0].name)\n other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])\n\n if other_fields_are_none and isinstance(first_field, dict):\n for key, value in first_field.items():\n self[key] = value\n else:\n for field in class_fields:\n v = getattr(self, field.name)\n if v is not None:\n self[field.name] = v\n\n def __delitem__(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.\")\n\n def setdefault(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.\")\n\n def pop(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``pop`` on a {self.__class__.__name__} instance.\")\n\n def update(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``update`` on a {self.__class__.__name__} instance.\")\n\n def __getitem__(self, k: Any) -> Any:\n if isinstance(k, str):\n inner_dict = dict(self.items())\n return inner_dict[k]\n else:\n return self.to_tuple()[k]\n\n def __setattr__(self, name: Any, value: Any) -> None:\n if name in self.keys() and value is not None:\n # Don't call self.__setitem__ to avoid recursion errors\n super().__setitem__(name, value)\n super().__setattr__(name, value)\n\n def __setitem__(self, key, value):\n # Will raise a KeyException if needed\n super().__setitem__(key, value)\n # Don't call self.__setattr__ to avoid recursion errors\n super().__setattr__(key, value)\n\n def __reduce__(self):\n if not is_dataclass(self):\n return super().__reduce__()\n callable, _args, *remaining = super().__reduce__()\n args = tuple(getattr(self, field.name) for field in fields(self))\n return callable, args, *remaining\n\n def to_tuple(self) -> Tuple[Any, ...]:\n \"\"\"\n Convert self to a tuple containing all the attributes/keys that are not `None`.\n \"\"\"\n return tuple(self[k] for k in self.keys())" }, { "identifier": "apply_forward_hook", "path": "diffusers/src/diffusers/utils/accelerate_utils.py", "snippet": "def apply_forward_hook(method):\n \"\"\"\n Decorator that applies a registered CpuOffload hook to an arbitrary function rather than `forward`. This is useful\n for cases where a PyTorch module provides functions other than `forward` that should trigger a move to the\n appropriate acceleration device. This is the case for `encode` and `decode` in [`AutoencoderKL`].\n\n This decorator looks inside the internal `_hf_hook` property to find a registered offload hook.\n\n :param method: The method to decorate. This method should be a method of a PyTorch module.\n \"\"\"\n if not is_accelerate_available():\n return method\n accelerate_version = version.parse(accelerate.__version__).base_version\n if version.parse(accelerate_version) < version.parse(\"0.17.0\"):\n return method\n\n def wrapper(self, *args, **kwargs):\n if hasattr(self, \"_hf_hook\") and hasattr(self._hf_hook, \"pre_forward\"):\n self._hf_hook.pre_forward(self)\n return method(self, *args, **kwargs)\n\n return wrapper" }, { "identifier": "ModelMixin", "path": "diffusers/src/diffusers/models/modeling_utils.py", "snippet": "class ModelMixin(torch.nn.Module, PushToHubMixin):\n r\"\"\"\n Base class for all models.\n\n [`ModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and\n saving models.\n\n - **config_name** ([`str`]) -- Filename to save a model to when calling [`~models.ModelMixin.save_pretrained`].\n \"\"\"\n\n config_name = CONFIG_NAME\n _automatically_saved_args = [\"_diffusers_version\", \"_class_name\", \"_name_or_path\"]\n _supports_gradient_checkpointing = False\n _keys_to_ignore_on_load_unexpected = None\n _hf_peft_config_loaded = False\n\n def __init__(self):\n super().__init__()\n\n def __getattr__(self, name: str) -> Any:\n \"\"\"The only reason we overwrite `getattr` here is to gracefully deprecate accessing\n config attributes directly. See https://github.com/huggingface/diffusers/pull/3129 We need to overwrite\n __getattr__ here in addition so that we don't trigger `torch.nn.Module`'s __getattr__':\n https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module\n \"\"\"\n\n is_in_config = \"_internal_dict\" in self.__dict__ and hasattr(self.__dict__[\"_internal_dict\"], name)\n is_attribute = name in self.__dict__\n\n if is_in_config and not is_attribute:\n deprecation_message = f\"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'unet.config.{name}'.\"\n deprecate(\"direct config name access\", \"1.0.0\", deprecation_message, standard_warn=False, stacklevel=3)\n return self._internal_dict[name]\n\n # call PyTorch's https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module\n return super().__getattr__(name)\n\n @property\n def is_gradient_checkpointing(self) -> bool:\n \"\"\"\n Whether gradient checkpointing is activated for this model or not.\n \"\"\"\n return any(hasattr(m, \"gradient_checkpointing\") and m.gradient_checkpointing for m in self.modules())\n\n def enable_gradient_checkpointing(self) -> None:\n \"\"\"\n Activates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or\n *checkpoint activations* in other frameworks).\n \"\"\"\n if not self._supports_gradient_checkpointing:\n raise ValueError(f\"{self.__class__.__name__} does not support gradient checkpointing.\")\n self.apply(partial(self._set_gradient_checkpointing, value=True))\n\n def disable_gradient_checkpointing(self) -> None:\n \"\"\"\n Deactivates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or\n *checkpoint activations* in other frameworks).\n \"\"\"\n if self._supports_gradient_checkpointing:\n self.apply(partial(self._set_gradient_checkpointing, value=False))\n\n def set_use_memory_efficient_attention_xformers(\n self, valid: bool, attention_op: Optional[Callable] = None\n ) -> None:\n # Recursively walk through all the children.\n # Any children which exposes the set_use_memory_efficient_attention_xformers method\n # gets the message\n def fn_recursive_set_mem_eff(module: torch.nn.Module):\n if hasattr(module, \"set_use_memory_efficient_attention_xformers\"):\n module.set_use_memory_efficient_attention_xformers(valid, attention_op)\n\n for child in module.children():\n fn_recursive_set_mem_eff(child)\n\n for module in self.children():\n if isinstance(module, torch.nn.Module):\n fn_recursive_set_mem_eff(module)\n\n def enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None) -> None:\n r\"\"\"\n Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).\n\n When this option is enabled, you should observe lower GPU memory usage and a potential speed up during\n inference. Speed up during training is not guaranteed.\n\n <Tip warning={true}>\n\n ⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes\n precedent.\n\n </Tip>\n\n Parameters:\n attention_op (`Callable`, *optional*):\n Override the default `None` operator for use as `op` argument to the\n [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)\n function of xFormers.\n\n Examples:\n\n ```py\n >>> import torch\n >>> from diffusers import UNet2DConditionModel\n >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp\n\n >>> model = UNet2DConditionModel.from_pretrained(\n ... \"stabilityai/stable-diffusion-2-1\", subfolder=\"unet\", torch_dtype=torch.float16\n ... )\n >>> model = model.to(\"cuda\")\n >>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)\n ```\n \"\"\"\n self.set_use_memory_efficient_attention_xformers(True, attention_op)\n\n def disable_xformers_memory_efficient_attention(self) -> None:\n r\"\"\"\n Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).\n \"\"\"\n self.set_use_memory_efficient_attention_xformers(False)\n\n def add_adapter(self, adapter_config, adapter_name: str = \"default\") -> None:\n r\"\"\"\n Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned\n to the adapter to follow the convention of the PEFT library.\n\n If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT\n [documentation](https://huggingface.co/docs/peft).\n\n Args:\n adapter_config (`[~peft.PeftConfig]`):\n The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt\n methods.\n adapter_name (`str`, *optional*, defaults to `\"default\"`):\n The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.\n \"\"\"\n check_peft_version(min_version=MIN_PEFT_VERSION)\n\n from peft import PeftConfig, inject_adapter_in_model\n\n if not self._hf_peft_config_loaded:\n self._hf_peft_config_loaded = True\n elif adapter_name in self.peft_config:\n raise ValueError(f\"Adapter with name {adapter_name} already exists. Please use a different name.\")\n\n if not isinstance(adapter_config, PeftConfig):\n raise ValueError(\n f\"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.\"\n )\n\n # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is\n # handled by the `load_lora_layers` or `LoraLoaderMixin`. Therefore we set it to `None` here.\n adapter_config.base_model_name_or_path = None\n inject_adapter_in_model(adapter_config, self, adapter_name)\n self.set_adapter(adapter_name)\n\n def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:\n \"\"\"\n Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.\n\n If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT\n official documentation: https://huggingface.co/docs/peft\n\n Args:\n adapter_name (Union[str, List[str]])):\n The list of adapters to set or the adapter name in case of single adapter.\n \"\"\"\n check_peft_version(min_version=MIN_PEFT_VERSION)\n\n if not self._hf_peft_config_loaded:\n raise ValueError(\"No adapter loaded. Please load an adapter first.\")\n\n if isinstance(adapter_name, str):\n adapter_name = [adapter_name]\n\n missing = set(adapter_name) - set(self.peft_config)\n if len(missing) > 0:\n raise ValueError(\n f\"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s).\"\n f\" current loaded adapters are: {list(self.peft_config.keys())}\"\n )\n\n from peft.tuners.tuners_utils import BaseTunerLayer\n\n _adapters_has_been_set = False\n\n for _, module in self.named_modules():\n if isinstance(module, BaseTunerLayer):\n if hasattr(module, \"set_adapter\"):\n module.set_adapter(adapter_name)\n # Previous versions of PEFT does not support multi-adapter inference\n elif not hasattr(module, \"set_adapter\") and len(adapter_name) != 1:\n raise ValueError(\n \"You are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT.\"\n \" `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`\"\n )\n else:\n module.active_adapter = adapter_name\n _adapters_has_been_set = True\n\n if not _adapters_has_been_set:\n raise ValueError(\n \"Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters.\"\n )\n\n def disable_adapters(self) -> None:\n r\"\"\"\n Disable all adapters attached to the model and fallback to inference with the base model only.\n\n If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT\n official documentation: https://huggingface.co/docs/peft\n \"\"\"\n check_peft_version(min_version=MIN_PEFT_VERSION)\n\n if not self._hf_peft_config_loaded:\n raise ValueError(\"No adapter loaded. Please load an adapter first.\")\n\n from peft.tuners.tuners_utils import BaseTunerLayer\n\n for _, module in self.named_modules():\n if isinstance(module, BaseTunerLayer):\n if hasattr(module, \"enable_adapters\"):\n module.enable_adapters(enabled=False)\n else:\n # support for older PEFT versions\n module.disable_adapters = True\n\n def enable_adapters(self) -> None:\n \"\"\"\n Enable adapters that are attached to the model. The model will use `self.active_adapters()` to retrieve the\n list of adapters to enable.\n\n If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT\n official documentation: https://huggingface.co/docs/peft\n \"\"\"\n check_peft_version(min_version=MIN_PEFT_VERSION)\n\n if not self._hf_peft_config_loaded:\n raise ValueError(\"No adapter loaded. Please load an adapter first.\")\n\n from peft.tuners.tuners_utils import BaseTunerLayer\n\n for _, module in self.named_modules():\n if isinstance(module, BaseTunerLayer):\n if hasattr(module, \"enable_adapters\"):\n module.enable_adapters(enabled=True)\n else:\n # support for older PEFT versions\n module.disable_adapters = False\n\n def active_adapters(self) -> List[str]:\n \"\"\"\n Gets the current list of active adapters of the model.\n\n If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT\n official documentation: https://huggingface.co/docs/peft\n \"\"\"\n check_peft_version(min_version=MIN_PEFT_VERSION)\n\n if not self._hf_peft_config_loaded:\n raise ValueError(\"No adapter loaded. Please load an adapter first.\")\n\n from peft.tuners.tuners_utils import BaseTunerLayer\n\n for _, module in self.named_modules():\n if isinstance(module, BaseTunerLayer):\n return module.active_adapter\n\n def save_pretrained(\n self,\n save_directory: Union[str, os.PathLike],\n is_main_process: bool = True,\n save_function: Optional[Callable] = None,\n safe_serialization: bool = True,\n variant: Optional[str] = None,\n push_to_hub: bool = False,\n **kwargs,\n ):\n \"\"\"\n Save a model and its configuration file to a directory so that it can be reloaded using the\n [`~models.ModelMixin.from_pretrained`] class method.\n\n Arguments:\n save_directory (`str` or `os.PathLike`):\n Directory to save a model and its configuration file to. Will be created if it doesn't exist.\n is_main_process (`bool`, *optional*, defaults to `True`):\n Whether the process calling this is the main process or not. Useful during distributed training and you\n need to call this function on all processes. In this case, set `is_main_process=True` only on the main\n process to avoid race conditions.\n save_function (`Callable`):\n The function to use to save the state dictionary. Useful during distributed training when you need to\n replace `torch.save` with another method. Can be configured with the environment variable\n `DIFFUSERS_SAVE_MODE`.\n safe_serialization (`bool`, *optional*, defaults to `True`):\n Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.\n variant (`str`, *optional*):\n If specified, weights are saved in the format `pytorch_model.<variant>.bin`.\n push_to_hub (`bool`, *optional*, defaults to `False`):\n Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the\n repository you want to push to with `repo_id` (will default to the name of `save_directory` in your\n namespace).\n kwargs (`Dict[str, Any]`, *optional*):\n Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.\n \"\"\"\n if os.path.isfile(save_directory):\n logger.error(f\"Provided path ({save_directory}) should be a directory, not a file\")\n return\n\n os.makedirs(save_directory, exist_ok=True)\n\n if push_to_hub:\n commit_message = kwargs.pop(\"commit_message\", None)\n private = kwargs.pop(\"private\", False)\n create_pr = kwargs.pop(\"create_pr\", False)\n token = kwargs.pop(\"token\", None)\n repo_id = kwargs.pop(\"repo_id\", save_directory.split(os.path.sep)[-1])\n repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id\n\n # Only save the model itself if we are using distributed training\n model_to_save = self\n\n # Attach architecture to the config\n # Save the config\n if is_main_process:\n model_to_save.save_config(save_directory)\n\n # Save the model\n state_dict = model_to_save.state_dict()\n\n weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME\n weights_name = _add_variant(weights_name, variant)\n\n # Save the model\n if safe_serialization:\n safetensors.torch.save_file(\n state_dict, os.path.join(save_directory, weights_name), metadata={\"format\": \"pt\"}\n )\n else:\n torch.save(state_dict, os.path.join(save_directory, weights_name))\n\n logger.info(f\"Model weights saved in {os.path.join(save_directory, weights_name)}\")\n\n if push_to_hub:\n self._upload_folder(\n save_directory,\n repo_id,\n token=token,\n commit_message=commit_message,\n create_pr=create_pr,\n )\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):\n r\"\"\"\n Instantiate a pretrained PyTorch model from a pretrained model configuration.\n\n The model is set in evaluation mode - `model.eval()` - by default, and dropout modules are deactivated. To\n train the model, set it back in training mode with `model.train()`.\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):\n Can be either:\n\n - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on\n the Hub.\n - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved\n with [`~ModelMixin.save_pretrained`].\n\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory where a downloaded pretrained model configuration is cached if the standard cache\n is not used.\n torch_dtype (`str` or `torch.dtype`, *optional*):\n Override the default `torch.dtype` and load the model with another dtype. If `\"auto\"` is passed, the\n dtype is automatically derived from the model's weights.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to resume downloading the model weights and configuration files. If set to `False`, any\n incompletely downloaded files are deleted.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n output_loading_info (`bool`, *optional*, defaults to `False`):\n Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.\n local_files_only(`bool`, *optional*, defaults to `False`):\n Whether to only load local model weights and configuration files or not. If set to `True`, the model\n won't be downloaded from the Hub.\n use_auth_token (`str` or *bool*, *optional*):\n The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from\n `diffusers-cli login` (stored in `~/.huggingface`) is used.\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier\n allowed by Git.\n from_flax (`bool`, *optional*, defaults to `False`):\n Load the model weights from a Flax checkpoint save file.\n subfolder (`str`, *optional*, defaults to `\"\"`):\n The subfolder location of a model file within a larger model repository on the Hub or locally.\n mirror (`str`, *optional*):\n Mirror source to resolve accessibility issues if you're downloading a model in China. We do not\n guarantee the timeliness or safety of the source, and you should refer to the mirror site for more\n information.\n device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):\n A map that specifies where each submodule should go. It doesn't need to be defined for each\n parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the\n same device.\n\n Set `device_map=\"auto\"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For\n more information about each option see [designing a device\n map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).\n max_memory (`Dict`, *optional*):\n A dictionary device identifier for the maximum memory. Will default to the maximum memory available for\n each GPU and the available CPU RAM if unset.\n offload_folder (`str` or `os.PathLike`, *optional*):\n The path to offload weights if `device_map` contains the value `\"disk\"`.\n offload_state_dict (`bool`, *optional*):\n If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if\n the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`\n when there is some disk offload.\n low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):\n Speed up model loading only loading the pretrained weights and not initializing the weights. This also\n tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.\n Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this\n argument to `True` will raise an error.\n variant (`str`, *optional*):\n Load weights from a specified `variant` filename such as `\"fp16\"` or `\"ema\"`. This is ignored when\n loading `from_flax`.\n use_safetensors (`bool`, *optional*, defaults to `None`):\n If set to `None`, the `safetensors` weights are downloaded if they're available **and** if the\n `safetensors` library is installed. If set to `True`, the model is forcibly loaded from `safetensors`\n weights. If set to `False`, `safetensors` weights are not loaded.\n\n <Tip>\n\n To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with\n `huggingface-cli login`. You can also activate the special\n [\"offline-mode\"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a\n firewalled environment.\n\n </Tip>\n\n Example:\n\n ```py\n from diffusers import UNet2DConditionModel\n\n unet = UNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\", subfolder=\"unet\")\n ```\n\n If you get the error message below, you need to finetune the weights for your downstream task:\n\n ```bash\n Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:\n - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated\n You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n ```\n \"\"\"\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n ignore_mismatched_sizes = kwargs.pop(\"ignore_mismatched_sizes\", False)\n force_download = kwargs.pop(\"force_download\", False)\n from_flax = kwargs.pop(\"from_flax\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n output_loading_info = kwargs.pop(\"output_loading_info\", False)\n local_files_only = kwargs.pop(\"local_files_only\", HF_HUB_OFFLINE)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n revision = kwargs.pop(\"revision\", None)\n torch_dtype = kwargs.pop(\"torch_dtype\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n device_map = kwargs.pop(\"device_map\", None)\n max_memory = kwargs.pop(\"max_memory\", None)\n offload_folder = kwargs.pop(\"offload_folder\", None)\n offload_state_dict = kwargs.pop(\"offload_state_dict\", False)\n low_cpu_mem_usage = kwargs.pop(\"low_cpu_mem_usage\", _LOW_CPU_MEM_USAGE_DEFAULT)\n variant = kwargs.pop(\"variant\", None)\n use_safetensors = kwargs.pop(\"use_safetensors\", None)\n\n allow_pickle = False\n if use_safetensors is None:\n use_safetensors = True\n allow_pickle = True\n\n if low_cpu_mem_usage and not is_accelerate_available():\n low_cpu_mem_usage = False\n logger.warning(\n \"Cannot initialize model with low cpu memory usage because `accelerate` was not found in the\"\n \" environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install\"\n \" `accelerate` for faster and less memory-intense model loading. You can do so with: \\n```\\npip\"\n \" install accelerate\\n```\\n.\"\n )\n\n if device_map is not None and not is_accelerate_available():\n raise NotImplementedError(\n \"Loading and dispatching requires `accelerate`. Please make sure to install accelerate or set\"\n \" `device_map=None`. You can install accelerate with `pip install accelerate`.\"\n )\n\n # Check if we can handle device_map and dispatching the weights\n if device_map is not None and not is_torch_version(\">=\", \"1.9.0\"):\n raise NotImplementedError(\n \"Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set\"\n \" `device_map=None`.\"\n )\n\n if low_cpu_mem_usage is True and not is_torch_version(\">=\", \"1.9.0\"):\n raise NotImplementedError(\n \"Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set\"\n \" `low_cpu_mem_usage=False`.\"\n )\n\n if low_cpu_mem_usage is False and device_map is not None:\n raise ValueError(\n f\"You cannot set `low_cpu_mem_usage` to `False` while using device_map={device_map} for loading and\"\n \" dispatching. Please make sure to set `low_cpu_mem_usage=True`.\"\n )\n\n # Load config if we don't provide a configuration\n config_path = pretrained_model_name_or_path\n\n user_agent = {\n \"diffusers\": __version__,\n \"file_type\": \"model\",\n \"framework\": \"pytorch\",\n }\n\n # load config\n config, unused_kwargs, commit_hash = cls.load_config(\n config_path,\n cache_dir=cache_dir,\n return_unused_kwargs=True,\n return_commit_hash=True,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n revision=revision,\n subfolder=subfolder,\n device_map=device_map,\n max_memory=max_memory,\n offload_folder=offload_folder,\n offload_state_dict=offload_state_dict,\n user_agent=user_agent,\n **kwargs,\n )\n\n # load model\n model_file = None\n if from_flax:\n model_file = _get_model_file(\n pretrained_model_name_or_path,\n weights_name=FLAX_WEIGHTS_NAME,\n cache_dir=cache_dir,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n revision=revision,\n subfolder=subfolder,\n user_agent=user_agent,\n commit_hash=commit_hash,\n )\n model = cls.from_config(config, **unused_kwargs)\n\n # Convert the weights\n from .modeling_pytorch_flax_utils import load_flax_checkpoint_in_pytorch_model\n\n model = load_flax_checkpoint_in_pytorch_model(model, model_file)\n else:\n if use_safetensors:\n try:\n model_file = _get_model_file(\n pretrained_model_name_or_path,\n weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant),\n cache_dir=cache_dir,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n revision=revision,\n subfolder=subfolder,\n user_agent=user_agent,\n commit_hash=commit_hash,\n )\n except IOError as e:\n if not allow_pickle:\n raise e\n pass\n if model_file is None:\n model_file = _get_model_file(\n pretrained_model_name_or_path,\n weights_name=_add_variant(WEIGHTS_NAME, variant),\n cache_dir=cache_dir,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n revision=revision,\n subfolder=subfolder,\n user_agent=user_agent,\n commit_hash=commit_hash,\n )\n\n if low_cpu_mem_usage:\n # Instantiate model with empty weights\n with accelerate.init_empty_weights():\n model = cls.from_config(config, **unused_kwargs)\n\n # if device_map is None, load the state dict and move the params from meta device to the cpu\n if device_map is None:\n param_device = \"cpu\"\n state_dict = load_state_dict(model_file, variant=variant)\n model._convert_deprecated_attention_blocks(state_dict)\n # move the params from meta device to cpu\n missing_keys = set(model.state_dict().keys()) - set(state_dict.keys())\n if len(missing_keys) > 0:\n raise ValueError(\n f\"Cannot load {cls} from {pretrained_model_name_or_path} because the following keys are\"\n f\" missing: \\n {', '.join(missing_keys)}. \\n Please make sure to pass\"\n \" `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize\"\n \" those weights or else make sure your checkpoint file is correct.\"\n )\n\n unexpected_keys = load_model_dict_into_meta(\n model,\n state_dict,\n device=param_device,\n dtype=torch_dtype,\n model_name_or_path=pretrained_model_name_or_path,\n )\n\n if cls._keys_to_ignore_on_load_unexpected is not None:\n for pat in cls._keys_to_ignore_on_load_unexpected:\n unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]\n\n if len(unexpected_keys) > 0:\n logger.warn(\n f\"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \\n {[', '.join(unexpected_keys)]}\"\n )\n\n else: # else let accelerate handle loading and dispatching.\n # Load weights and dispatch according to the device_map\n # by default the device_map is None and the weights are loaded on the CPU\n try:\n accelerate.load_checkpoint_and_dispatch(\n model,\n model_file,\n device_map,\n max_memory=max_memory,\n offload_folder=offload_folder,\n offload_state_dict=offload_state_dict,\n dtype=torch_dtype,\n )\n except AttributeError as e:\n # When using accelerate loading, we do not have the ability to load the state\n # dict and rename the weight names manually. Additionally, accelerate skips\n # torch loading conventions and directly writes into `module.{_buffers, _parameters}`\n # (which look like they should be private variables?), so we can't use the standard hooks\n # to rename parameters on load. We need to mimic the original weight names so the correct\n # attributes are available. After we have loaded the weights, we convert the deprecated\n # names to the new non-deprecated names. Then we _greatly encourage_ the user to convert\n # the weights so we don't have to do this again.\n\n if \"'Attention' object has no attribute\" in str(e):\n logger.warn(\n f\"Taking `{str(e)}` while using `accelerate.load_checkpoint_and_dispatch` to mean {pretrained_model_name_or_path}\"\n \" was saved with deprecated attention block weight names. We will load it with the deprecated attention block\"\n \" names and convert them on the fly to the new attention block format. Please re-save the model after this conversion,\"\n \" so we don't have to do the on the fly renaming in the future. If the model is from a hub checkpoint,\"\n \" please also re-upload it or open a PR on the original repository.\"\n )\n model._temp_convert_self_to_deprecated_attention_blocks()\n accelerate.load_checkpoint_and_dispatch(\n model,\n model_file,\n device_map,\n max_memory=max_memory,\n offload_folder=offload_folder,\n offload_state_dict=offload_state_dict,\n dtype=torch_dtype,\n )\n model._undo_temp_convert_self_to_deprecated_attention_blocks()\n else:\n raise e\n\n loading_info = {\n \"missing_keys\": [],\n \"unexpected_keys\": [],\n \"mismatched_keys\": [],\n \"error_msgs\": [],\n }\n else:\n model = cls.from_config(config, **unused_kwargs)\n\n state_dict = load_state_dict(model_file, variant=variant)\n model._convert_deprecated_attention_blocks(state_dict)\n\n model, missing_keys, unexpected_keys, mismatched_keys, error_msgs = cls._load_pretrained_model(\n model,\n state_dict,\n model_file,\n pretrained_model_name_or_path,\n ignore_mismatched_sizes=ignore_mismatched_sizes,\n )\n\n loading_info = {\n \"missing_keys\": missing_keys,\n \"unexpected_keys\": unexpected_keys,\n \"mismatched_keys\": mismatched_keys,\n \"error_msgs\": error_msgs,\n }\n\n if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype):\n raise ValueError(\n f\"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}.\"\n )\n elif torch_dtype is not None:\n model = model.to(torch_dtype)\n\n model.register_to_config(_name_or_path=pretrained_model_name_or_path)\n\n # Set model in evaluation mode to deactivate DropOut modules by default\n model.eval()\n if output_loading_info:\n return model, loading_info\n\n return model\n\n @classmethod\n def _load_pretrained_model(\n cls,\n model,\n state_dict: OrderedDict,\n resolved_archive_file,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n ignore_mismatched_sizes: bool = False,\n ):\n # Retrieve missing & unexpected_keys\n model_state_dict = model.state_dict()\n loaded_keys = list(state_dict.keys())\n\n expected_keys = list(model_state_dict.keys())\n\n original_loaded_keys = loaded_keys\n\n missing_keys = list(set(expected_keys) - set(loaded_keys))\n unexpected_keys = list(set(loaded_keys) - set(expected_keys))\n\n # Make sure we are able to load base models as well as derived models (with heads)\n model_to_load = model\n\n def _find_mismatched_keys(\n state_dict,\n model_state_dict,\n loaded_keys,\n ignore_mismatched_sizes,\n ):\n mismatched_keys = []\n if ignore_mismatched_sizes:\n for checkpoint_key in loaded_keys:\n model_key = checkpoint_key\n\n if (\n model_key in model_state_dict\n and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape\n ):\n mismatched_keys.append(\n (checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape)\n )\n del state_dict[checkpoint_key]\n return mismatched_keys\n\n if state_dict is not None:\n # Whole checkpoint\n mismatched_keys = _find_mismatched_keys(\n state_dict,\n model_state_dict,\n original_loaded_keys,\n ignore_mismatched_sizes,\n )\n error_msgs = _load_state_dict_into_model(model_to_load, state_dict)\n\n if len(error_msgs) > 0:\n error_msg = \"\\n\\t\".join(error_msgs)\n if \"size mismatch\" in error_msg:\n error_msg += (\n \"\\n\\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method.\"\n )\n raise RuntimeError(f\"Error(s) in loading state_dict for {model.__class__.__name__}:\\n\\t{error_msg}\")\n\n if len(unexpected_keys) > 0:\n logger.warning(\n f\"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when\"\n f\" initializing {model.__class__.__name__}: {unexpected_keys}\\n- This IS expected if you are\"\n f\" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task\"\n \" or with another architecture (e.g. initializing a BertForSequenceClassification model from a\"\n \" BertForPreTraining model).\\n- This IS NOT expected if you are initializing\"\n f\" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly\"\n \" identical (initializing a BertForSequenceClassification model from a\"\n \" BertForSequenceClassification model).\"\n )\n else:\n logger.info(f\"All model checkpoint weights were used when initializing {model.__class__.__name__}.\\n\")\n if len(missing_keys) > 0:\n logger.warning(\n f\"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\\nYou should probably\"\n \" TRAIN this model on a down-stream task to be able to use it for predictions and inference.\"\n )\n elif len(mismatched_keys) == 0:\n logger.info(\n f\"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path}.\\nIf your task is similar to the task the model of the\"\n f\" checkpoint was trained on, you can already use {model.__class__.__name__} for predictions\"\n \" without further training.\"\n )\n if len(mismatched_keys) > 0:\n mismatched_warning = \"\\n\".join(\n [\n f\"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated\"\n for key, shape1, shape2 in mismatched_keys\n ]\n )\n logger.warning(\n f\"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path} and are newly initialized because the shapes did not\"\n f\" match:\\n{mismatched_warning}\\nYou should probably TRAIN this model on a down-stream task to be\"\n \" able to use it for predictions and inference.\"\n )\n\n return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs\n\n @property\n def device(self) -> torch.device:\n \"\"\"\n `torch.device`: The device on which the module is (assuming that all the module parameters are on the same\n device).\n \"\"\"\n return get_parameter_device(self)\n\n @property\n def dtype(self) -> torch.dtype:\n \"\"\"\n `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).\n \"\"\"\n return get_parameter_dtype(self)\n\n def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int:\n \"\"\"\n Get number of (trainable or non-embedding) parameters in the module.\n\n Args:\n only_trainable (`bool`, *optional*, defaults to `False`):\n Whether or not to return only the number of trainable parameters.\n exclude_embeddings (`bool`, *optional*, defaults to `False`):\n Whether or not to return only the number of non-embedding parameters.\n\n Returns:\n `int`: The number of parameters.\n\n Example:\n\n ```py\n from diffusers import UNet2DConditionModel\n\n model_id = \"runwayml/stable-diffusion-v1-5\"\n unet = UNet2DConditionModel.from_pretrained(model_id, subfolder=\"unet\")\n unet.num_parameters(only_trainable=True)\n 859520964\n ```\n \"\"\"\n\n if exclude_embeddings:\n embedding_param_names = [\n f\"{name}.weight\"\n for name, module_type in self.named_modules()\n if isinstance(module_type, torch.nn.Embedding)\n ]\n non_embedding_parameters = [\n parameter for name, parameter in self.named_parameters() if name not in embedding_param_names\n ]\n return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable)\n else:\n return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable)\n\n def _convert_deprecated_attention_blocks(self, state_dict: OrderedDict) -> None:\n deprecated_attention_block_paths = []\n\n def recursive_find_attn_block(name, module):\n if hasattr(module, \"_from_deprecated_attn_block\") and module._from_deprecated_attn_block:\n deprecated_attention_block_paths.append(name)\n\n for sub_name, sub_module in module.named_children():\n sub_name = sub_name if name == \"\" else f\"{name}.{sub_name}\"\n recursive_find_attn_block(sub_name, sub_module)\n\n recursive_find_attn_block(\"\", self)\n\n # NOTE: we have to check if the deprecated parameters are in the state dict\n # because it is possible we are loading from a state dict that was already\n # converted\n\n for path in deprecated_attention_block_paths:\n # group_norm path stays the same\n\n # query -> to_q\n if f\"{path}.query.weight\" in state_dict:\n state_dict[f\"{path}.to_q.weight\"] = state_dict.pop(f\"{path}.query.weight\")\n if f\"{path}.query.bias\" in state_dict:\n state_dict[f\"{path}.to_q.bias\"] = state_dict.pop(f\"{path}.query.bias\")\n\n # key -> to_k\n if f\"{path}.key.weight\" in state_dict:\n state_dict[f\"{path}.to_k.weight\"] = state_dict.pop(f\"{path}.key.weight\")\n if f\"{path}.key.bias\" in state_dict:\n state_dict[f\"{path}.to_k.bias\"] = state_dict.pop(f\"{path}.key.bias\")\n\n # value -> to_v\n if f\"{path}.value.weight\" in state_dict:\n state_dict[f\"{path}.to_v.weight\"] = state_dict.pop(f\"{path}.value.weight\")\n if f\"{path}.value.bias\" in state_dict:\n state_dict[f\"{path}.to_v.bias\"] = state_dict.pop(f\"{path}.value.bias\")\n\n # proj_attn -> to_out.0\n if f\"{path}.proj_attn.weight\" in state_dict:\n state_dict[f\"{path}.to_out.0.weight\"] = state_dict.pop(f\"{path}.proj_attn.weight\")\n if f\"{path}.proj_attn.bias\" in state_dict:\n state_dict[f\"{path}.to_out.0.bias\"] = state_dict.pop(f\"{path}.proj_attn.bias\")\n\n def _temp_convert_self_to_deprecated_attention_blocks(self) -> None:\n deprecated_attention_block_modules = []\n\n def recursive_find_attn_block(module):\n if hasattr(module, \"_from_deprecated_attn_block\") and module._from_deprecated_attn_block:\n deprecated_attention_block_modules.append(module)\n\n for sub_module in module.children():\n recursive_find_attn_block(sub_module)\n\n recursive_find_attn_block(self)\n\n for module in deprecated_attention_block_modules:\n module.query = module.to_q\n module.key = module.to_k\n module.value = module.to_v\n module.proj_attn = module.to_out[0]\n\n # We don't _have_ to delete the old attributes, but it's helpful to ensure\n # that _all_ the weights are loaded into the new attributes and we're not\n # making an incorrect assumption that this model should be converted when\n # it really shouldn't be.\n del module.to_q\n del module.to_k\n del module.to_v\n del module.to_out\n\n def _undo_temp_convert_self_to_deprecated_attention_blocks(self) -> None:\n deprecated_attention_block_modules = []\n\n def recursive_find_attn_block(module) -> None:\n if hasattr(module, \"_from_deprecated_attn_block\") and module._from_deprecated_attn_block:\n deprecated_attention_block_modules.append(module)\n\n for sub_module in module.children():\n recursive_find_attn_block(sub_module)\n\n recursive_find_attn_block(self)\n\n for module in deprecated_attention_block_modules:\n module.to_q = module.query\n module.to_k = module.key\n module.to_v = module.value\n module.to_out = nn.ModuleList([module.proj_attn, nn.Dropout(module.dropout)])\n\n del module.query\n del module.key\n del module.value\n del module.proj_attn" }, { "identifier": "DecoderOutput", "path": "diffusers/src/diffusers/models/vae.py", "snippet": "class DecoderOutput(BaseOutput):\n r\"\"\"\n Output of decoding method.\n\n Args:\n sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n The decoded output sample from the last layer of the model.\n \"\"\"\n\n sample: torch.FloatTensor" }, { "identifier": "DecoderTiny", "path": "diffusers/src/diffusers/models/vae.py", "snippet": "class DecoderTiny(nn.Module):\n r\"\"\"\n The `DecoderTiny` layer is a simpler version of the `Decoder` layer.\n\n Args:\n in_channels (`int`):\n The number of input channels.\n out_channels (`int`):\n The number of output channels.\n num_blocks (`Tuple[int, ...]`):\n Each value of the tuple represents a Conv2d layer followed by `value` number of `AutoencoderTinyBlock`'s to\n use.\n block_out_channels (`Tuple[int, ...]`):\n The number of output channels for each block.\n upsampling_scaling_factor (`int`):\n The scaling factor to use for upsampling.\n act_fn (`str`):\n The activation function to use. See `~diffusers.models.activations.get_activation` for available options.\n \"\"\"\n\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n num_blocks: Tuple[int, ...],\n block_out_channels: Tuple[int, ...],\n upsampling_scaling_factor: int,\n act_fn: str,\n ):\n super().__init__()\n\n layers = [\n nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=1),\n get_activation(act_fn),\n ]\n\n for i, num_block in enumerate(num_blocks):\n is_final_block = i == (len(num_blocks) - 1)\n num_channels = block_out_channels[i]\n\n for _ in range(num_block):\n layers.append(AutoencoderTinyBlock(num_channels, num_channels, act_fn))\n\n if not is_final_block:\n layers.append(nn.Upsample(scale_factor=upsampling_scaling_factor))\n\n conv_out_channel = num_channels if not is_final_block else out_channels\n layers.append(\n nn.Conv2d(\n num_channels,\n conv_out_channel,\n kernel_size=3,\n padding=1,\n bias=is_final_block,\n )\n )\n\n self.layers = nn.Sequential(*layers)\n self.gradient_checkpointing = False\n\n def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:\n r\"\"\"The forward method of the `DecoderTiny` class.\"\"\"\n # Clamp.\n x = torch.tanh(x / 3) * 3\n\n if self.training and self.gradient_checkpointing:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs)\n\n return custom_forward\n\n if is_torch_version(\">=\", \"1.11.0\"):\n x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x, use_reentrant=False)\n else:\n x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x)\n\n else:\n x = self.layers(x)\n\n # scale image from [0, 1] to [-1, 1] to match diffusers convention\n return x.mul(2).sub(1)" }, { "identifier": "EncoderTiny", "path": "diffusers/src/diffusers/models/vae.py", "snippet": "class EncoderTiny(nn.Module):\n r\"\"\"\n The `EncoderTiny` layer is a simpler version of the `Encoder` layer.\n\n Args:\n in_channels (`int`):\n The number of input channels.\n out_channels (`int`):\n The number of output channels.\n num_blocks (`Tuple[int, ...]`):\n Each value of the tuple represents a Conv2d layer followed by `value` number of `AutoencoderTinyBlock`'s to\n use.\n block_out_channels (`Tuple[int, ...]`):\n The number of output channels for each block.\n act_fn (`str`):\n The activation function to use. See `~diffusers.models.activations.get_activation` for available options.\n \"\"\"\n\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n num_blocks: Tuple[int, ...],\n block_out_channels: Tuple[int, ...],\n act_fn: str,\n ):\n super().__init__()\n\n layers = []\n for i, num_block in enumerate(num_blocks):\n num_channels = block_out_channels[i]\n\n if i == 0:\n layers.append(nn.Conv2d(in_channels, num_channels, kernel_size=3, padding=1))\n else:\n layers.append(\n nn.Conv2d(\n num_channels,\n num_channels,\n kernel_size=3,\n padding=1,\n stride=2,\n bias=False,\n )\n )\n\n for _ in range(num_block):\n layers.append(AutoencoderTinyBlock(num_channels, num_channels, act_fn))\n\n layers.append(nn.Conv2d(block_out_channels[-1], out_channels, kernel_size=3, padding=1))\n\n self.layers = nn.Sequential(*layers)\n self.gradient_checkpointing = False\n\n def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:\n r\"\"\"The forward method of the `EncoderTiny` class.\"\"\"\n if self.training and self.gradient_checkpointing:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs)\n\n return custom_forward\n\n if is_torch_version(\">=\", \"1.11.0\"):\n x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x, use_reentrant=False)\n else:\n x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x)\n\n else:\n # scale image from [-1, 1] to [0, 1] to match TAESD convention\n x = self.layers(x.add(1).div(2))\n\n return x" } ]
from dataclasses import dataclass from typing import Optional, Tuple, Union from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from ..utils.accelerate_utils import apply_forward_hook from .modeling_utils import ModelMixin from .vae import DecoderOutput, DecoderTiny, EncoderTiny import torch
20,875
# Copyright 2023 Ollin Boer Bohan and The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @dataclass class AutoencoderTinyOutput(BaseOutput): """ Output of AutoencoderTiny encoding method. Args: latents (`torch.Tensor`): Encoded outputs of the `Encoder`. """ latents: torch.Tensor class AutoencoderTiny(ModelMixin, ConfigMixin): r""" A tiny distilled VAE model for encoding images into latents and decoding latent representations into images. [`AutoencoderTiny`] is a wrapper around the original implementation of `TAESD`. This model inherits from [`ModelMixin`]. Check the superclass documentation for its generic methods implemented for all models (such as downloading or saving). Parameters: in_channels (`int`, *optional*, defaults to 3): Number of channels in the input image. out_channels (`int`, *optional*, defaults to 3): Number of channels in the output. encoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`): Tuple of integers representing the number of output channels for each encoder block. The length of the tuple should be equal to the number of encoder blocks. decoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`): Tuple of integers representing the number of output channels for each decoder block. The length of the tuple should be equal to the number of decoder blocks. act_fn (`str`, *optional*, defaults to `"relu"`): Activation function to be used throughout the model. latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent representation. The latent space acts as a compressed representation of the input image. upsampling_scaling_factor (`int`, *optional*, defaults to 2): Scaling factor for upsampling in the decoder. It determines the size of the output image during the upsampling process. num_encoder_blocks (`Tuple[int]`, *optional*, defaults to `(1, 3, 3, 3)`): Tuple of integers representing the number of encoder blocks at each stage of the encoding process. The length of the tuple should be equal to the number of stages in the encoder. Each stage has a different number of encoder blocks. num_decoder_blocks (`Tuple[int]`, *optional*, defaults to `(3, 3, 3, 1)`): Tuple of integers representing the number of decoder blocks at each stage of the decoding process. The length of the tuple should be equal to the number of stages in the decoder. Each stage has a different number of decoder blocks. latent_magnitude (`float`, *optional*, defaults to 3.0): Magnitude of the latent representation. This parameter scales the latent representation values to control the extent of information preservation. latent_shift (float, *optional*, defaults to 0.5): Shift applied to the latent representation. This parameter controls the center of the latent space. scaling_factor (`float`, *optional*, defaults to 1.0): The component-wise standard deviation of the trained latent space computed using the first batch of the training set. This is used to scale the latent space to have unit variance when training the diffusion model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper. For this Autoencoder, however, no such scaling factor was used, hence the value of 1.0 as the default. force_upcast (`bool`, *optional*, default to `False`): If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE can be fine-tuned / trained to a lower range without losing too much precision, in which case `force_upcast` can be set to `False` (see this fp16-friendly [AutoEncoder](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)). """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, in_channels: int = 3, out_channels: int = 3, encoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64), decoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64), act_fn: str = "relu", latent_channels: int = 4, upsampling_scaling_factor: int = 2, num_encoder_blocks: Tuple[int, ...] = (1, 3, 3, 3), num_decoder_blocks: Tuple[int, ...] = (3, 3, 3, 1), latent_magnitude: int = 3, latent_shift: float = 0.5, force_upcast: bool = False, scaling_factor: float = 1.0, ): super().__init__() if len(encoder_block_out_channels) != len(num_encoder_blocks): raise ValueError("`encoder_block_out_channels` should have the same length as `num_encoder_blocks`.") if len(decoder_block_out_channels) != len(num_decoder_blocks): raise ValueError("`decoder_block_out_channels` should have the same length as `num_decoder_blocks`.") self.encoder = EncoderTiny( in_channels=in_channels, out_channels=latent_channels, num_blocks=num_encoder_blocks, block_out_channels=encoder_block_out_channels, act_fn=act_fn, )
# Copyright 2023 Ollin Boer Bohan and The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @dataclass class AutoencoderTinyOutput(BaseOutput): """ Output of AutoencoderTiny encoding method. Args: latents (`torch.Tensor`): Encoded outputs of the `Encoder`. """ latents: torch.Tensor class AutoencoderTiny(ModelMixin, ConfigMixin): r""" A tiny distilled VAE model for encoding images into latents and decoding latent representations into images. [`AutoencoderTiny`] is a wrapper around the original implementation of `TAESD`. This model inherits from [`ModelMixin`]. Check the superclass documentation for its generic methods implemented for all models (such as downloading or saving). Parameters: in_channels (`int`, *optional*, defaults to 3): Number of channels in the input image. out_channels (`int`, *optional*, defaults to 3): Number of channels in the output. encoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`): Tuple of integers representing the number of output channels for each encoder block. The length of the tuple should be equal to the number of encoder blocks. decoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`): Tuple of integers representing the number of output channels for each decoder block. The length of the tuple should be equal to the number of decoder blocks. act_fn (`str`, *optional*, defaults to `"relu"`): Activation function to be used throughout the model. latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent representation. The latent space acts as a compressed representation of the input image. upsampling_scaling_factor (`int`, *optional*, defaults to 2): Scaling factor for upsampling in the decoder. It determines the size of the output image during the upsampling process. num_encoder_blocks (`Tuple[int]`, *optional*, defaults to `(1, 3, 3, 3)`): Tuple of integers representing the number of encoder blocks at each stage of the encoding process. The length of the tuple should be equal to the number of stages in the encoder. Each stage has a different number of encoder blocks. num_decoder_blocks (`Tuple[int]`, *optional*, defaults to `(3, 3, 3, 1)`): Tuple of integers representing the number of decoder blocks at each stage of the decoding process. The length of the tuple should be equal to the number of stages in the decoder. Each stage has a different number of decoder blocks. latent_magnitude (`float`, *optional*, defaults to 3.0): Magnitude of the latent representation. This parameter scales the latent representation values to control the extent of information preservation. latent_shift (float, *optional*, defaults to 0.5): Shift applied to the latent representation. This parameter controls the center of the latent space. scaling_factor (`float`, *optional*, defaults to 1.0): The component-wise standard deviation of the trained latent space computed using the first batch of the training set. This is used to scale the latent space to have unit variance when training the diffusion model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper. For this Autoencoder, however, no such scaling factor was used, hence the value of 1.0 as the default. force_upcast (`bool`, *optional*, default to `False`): If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE can be fine-tuned / trained to a lower range without losing too much precision, in which case `force_upcast` can be set to `False` (see this fp16-friendly [AutoEncoder](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)). """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, in_channels: int = 3, out_channels: int = 3, encoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64), decoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64), act_fn: str = "relu", latent_channels: int = 4, upsampling_scaling_factor: int = 2, num_encoder_blocks: Tuple[int, ...] = (1, 3, 3, 3), num_decoder_blocks: Tuple[int, ...] = (3, 3, 3, 1), latent_magnitude: int = 3, latent_shift: float = 0.5, force_upcast: bool = False, scaling_factor: float = 1.0, ): super().__init__() if len(encoder_block_out_channels) != len(num_encoder_blocks): raise ValueError("`encoder_block_out_channels` should have the same length as `num_encoder_blocks`.") if len(decoder_block_out_channels) != len(num_decoder_blocks): raise ValueError("`decoder_block_out_channels` should have the same length as `num_decoder_blocks`.") self.encoder = EncoderTiny( in_channels=in_channels, out_channels=latent_channels, num_blocks=num_encoder_blocks, block_out_channels=encoder_block_out_channels, act_fn=act_fn, )
self.decoder = DecoderTiny(
6
2023-12-28 08:17:40+00:00
24k
FoundationVision/UniRef
detectron2/utils/visualizer.py
[ { "identifier": "MetadataCatalog", "path": "detectron2/data/catalog.py", "snippet": "class _DatasetCatalog(UserDict):\nclass Metadata(types.SimpleNamespace):\nclass _MetadataCatalog(UserDict):\n def register(self, name, func):\n def get(self, name):\n def list(self) -> List[str]:\n def remove(self, name):\n def __str__(self):\n def __getattr__(self, key):\n def __setattr__(self, key, val):\n def as_dict(self):\n def set(self, **kwargs):\n def get(self, key, default=None):\n def get(self, name):\n def list(self):\n def remove(self, name):\n def __str__(self):\n _RENAMED = {\n \"class_names\": \"thing_classes\",\n \"dataset_id_to_contiguous_id\": \"thing_dataset_id_to_contiguous_id\",\n \"stuff_class_names\": \"stuff_classes\",\n }" }, { "identifier": "Boxes", "path": "detectron2/structures/boxes.py", "snippet": "class Boxes:\n \"\"\"\n This structure stores a list of boxes as a Nx4 torch.Tensor.\n It supports some common methods about boxes\n (`area`, `clip`, `nonempty`, etc),\n and also behaves like a Tensor\n (support indexing, `to(device)`, `.device`, and iteration over all boxes)\n\n Attributes:\n tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2).\n \"\"\"\n\n def __init__(self, tensor: torch.Tensor):\n \"\"\"\n Args:\n tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2).\n \"\"\"\n device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device(\"cpu\")\n tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device)\n if tensor.numel() == 0:\n # Use reshape, so we don't end up creating a new tensor that does not depend on\n # the inputs (and consequently confuses jit)\n tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32, device=device)\n assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size()\n\n self.tensor = tensor\n\n def clone(self) -> \"Boxes\":\n \"\"\"\n Clone the Boxes.\n\n Returns:\n Boxes\n \"\"\"\n return Boxes(self.tensor.clone())\n\n def to(self, device: torch.device):\n # Boxes are assumed float32 and does not support to(dtype)\n return Boxes(self.tensor.to(device=device))\n\n def area(self) -> torch.Tensor:\n \"\"\"\n Computes the area of all the boxes.\n\n Returns:\n torch.Tensor: a vector with areas of each box.\n \"\"\"\n box = self.tensor\n area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1])\n return area\n\n def clip(self, box_size: Tuple[int, int]) -> None:\n \"\"\"\n Clip (in place) the boxes by limiting x coordinates to the range [0, width]\n and y coordinates to the range [0, height].\n\n Args:\n box_size (height, width): The clipping box's size.\n \"\"\"\n assert torch.isfinite(self.tensor).all(), \"Box tensor contains infinite or NaN!\"\n h, w = box_size\n x1 = self.tensor[:, 0].clamp(min=0, max=w)\n y1 = self.tensor[:, 1].clamp(min=0, max=h)\n x2 = self.tensor[:, 2].clamp(min=0, max=w)\n y2 = self.tensor[:, 3].clamp(min=0, max=h)\n self.tensor = torch.stack((x1, y1, x2, y2), dim=-1)\n\n def nonempty(self, threshold: float = 0.0) -> torch.Tensor:\n \"\"\"\n Find boxes that are non-empty.\n A box is considered empty, if either of its side is no larger than threshold.\n\n Returns:\n Tensor:\n a binary vector which represents whether each box is empty\n (False) or non-empty (True).\n \"\"\"\n box = self.tensor\n widths = box[:, 2] - box[:, 0]\n heights = box[:, 3] - box[:, 1]\n keep = (widths > threshold) & (heights > threshold)\n return keep\n\n def __getitem__(self, item) -> \"Boxes\":\n \"\"\"\n Args:\n item: int, slice, or a BoolTensor\n\n Returns:\n Boxes: Create a new :class:`Boxes` by indexing.\n\n The following usage are allowed:\n\n 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box.\n 2. `new_boxes = boxes[2:10]`: return a slice of boxes.\n 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor\n with `length = len(boxes)`. Nonzero elements in the vector will be selected.\n\n Note that the returned Boxes might share storage with this Boxes,\n subject to Pytorch's indexing semantics.\n \"\"\"\n if isinstance(item, int):\n return Boxes(self.tensor[item].view(1, -1))\n b = self.tensor[item]\n assert b.dim() == 2, \"Indexing on Boxes with {} failed to return a matrix!\".format(item)\n return Boxes(b)\n\n def __len__(self) -> int:\n return self.tensor.shape[0]\n\n def __repr__(self) -> str:\n return \"Boxes(\" + str(self.tensor) + \")\"\n\n def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor:\n \"\"\"\n Args:\n box_size (height, width): Size of the reference box.\n boundary_threshold (int): Boxes that extend beyond the reference box\n boundary by more than boundary_threshold are considered \"outside\".\n\n Returns:\n a binary vector, indicating whether each box is inside the reference box.\n \"\"\"\n height, width = box_size\n inds_inside = (\n (self.tensor[..., 0] >= -boundary_threshold)\n & (self.tensor[..., 1] >= -boundary_threshold)\n & (self.tensor[..., 2] < width + boundary_threshold)\n & (self.tensor[..., 3] < height + boundary_threshold)\n )\n return inds_inside\n\n def get_centers(self) -> torch.Tensor:\n \"\"\"\n Returns:\n The box centers in a Nx2 array of (x, y).\n \"\"\"\n return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2\n\n def scale(self, scale_x: float, scale_y: float) -> None:\n \"\"\"\n Scale the box with horizontal and vertical scaling factors\n \"\"\"\n self.tensor[:, 0::2] *= scale_x\n self.tensor[:, 1::2] *= scale_y\n\n @classmethod\n def cat(cls, boxes_list: List[\"Boxes\"]) -> \"Boxes\":\n \"\"\"\n Concatenates a list of Boxes into a single Boxes\n\n Arguments:\n boxes_list (list[Boxes])\n\n Returns:\n Boxes: the concatenated Boxes\n \"\"\"\n assert isinstance(boxes_list, (list, tuple))\n if len(boxes_list) == 0:\n return cls(torch.empty(0))\n assert all([isinstance(box, Boxes) for box in boxes_list])\n\n # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input\n cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))\n return cat_boxes\n\n @property\n def device(self) -> device:\n return self.tensor.device\n\n # type \"Iterator[torch.Tensor]\", yield, and iter() not supported by torchscript\n # https://github.com/pytorch/pytorch/issues/18627\n @torch.jit.unused\n def __iter__(self):\n \"\"\"\n Yield a box as a Tensor of shape (4,) at a time.\n \"\"\"\n yield from self.tensor" }, { "identifier": "BoxMode", "path": "detectron2/structures/boxes.py", "snippet": "class BoxMode(IntEnum):\n \"\"\"\n Enum of different ways to represent a box.\n \"\"\"\n\n XYXY_ABS = 0\n \"\"\"\n (x0, y0, x1, y1) in absolute floating points coordinates.\n The coordinates in range [0, width or height].\n \"\"\"\n XYWH_ABS = 1\n \"\"\"\n (x0, y0, w, h) in absolute floating points coordinates.\n \"\"\"\n XYXY_REL = 2\n \"\"\"\n Not yet supported!\n (x0, y0, x1, y1) in range [0, 1]. They are relative to the size of the image.\n \"\"\"\n XYWH_REL = 3\n \"\"\"\n Not yet supported!\n (x0, y0, w, h) in range [0, 1]. They are relative to the size of the image.\n \"\"\"\n XYWHA_ABS = 4\n \"\"\"\n (xc, yc, w, h, a) in absolute floating points coordinates.\n (xc, yc) is the center of the rotated box, and the angle a is in degrees ccw.\n \"\"\"\n\n @staticmethod\n def convert(box: _RawBoxType, from_mode: \"BoxMode\", to_mode: \"BoxMode\") -> _RawBoxType:\n \"\"\"\n Args:\n box: can be a k-tuple, k-list or an Nxk array/tensor, where k = 4 or 5\n from_mode, to_mode (BoxMode)\n\n Returns:\n The converted box of the same type.\n \"\"\"\n if from_mode == to_mode:\n return box\n\n original_type = type(box)\n is_numpy = isinstance(box, np.ndarray)\n single_box = isinstance(box, (list, tuple))\n if single_box:\n assert len(box) == 4 or len(box) == 5, (\n \"BoxMode.convert takes either a k-tuple/list or an Nxk array/tensor,\"\n \" where k == 4 or 5\"\n )\n arr = torch.tensor(box)[None, :]\n else:\n # avoid modifying the input box\n if is_numpy:\n arr = torch.from_numpy(np.asarray(box)).clone()\n else:\n arr = box.clone()\n\n assert to_mode not in [BoxMode.XYXY_REL, BoxMode.XYWH_REL] and from_mode not in [\n BoxMode.XYXY_REL,\n BoxMode.XYWH_REL,\n ], \"Relative mode not yet supported!\"\n\n if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:\n assert (\n arr.shape[-1] == 5\n ), \"The last dimension of input shape must be 5 for XYWHA format\"\n original_dtype = arr.dtype\n arr = arr.double()\n\n w = arr[:, 2]\n h = arr[:, 3]\n a = arr[:, 4]\n c = torch.abs(torch.cos(a * math.pi / 180.0))\n s = torch.abs(torch.sin(a * math.pi / 180.0))\n # This basically computes the horizontal bounding rectangle of the rotated box\n new_w = c * w + s * h\n new_h = c * h + s * w\n\n # convert center to top-left corner\n arr[:, 0] -= new_w / 2.0\n arr[:, 1] -= new_h / 2.0\n # bottom-right corner\n arr[:, 2] = arr[:, 0] + new_w\n arr[:, 3] = arr[:, 1] + new_h\n\n arr = arr[:, :4].to(dtype=original_dtype)\n elif from_mode == BoxMode.XYWH_ABS and to_mode == BoxMode.XYWHA_ABS:\n original_dtype = arr.dtype\n arr = arr.double()\n arr[:, 0] += arr[:, 2] / 2.0\n arr[:, 1] += arr[:, 3] / 2.0\n angles = torch.zeros((arr.shape[0], 1), dtype=arr.dtype)\n arr = torch.cat((arr, angles), axis=1).to(dtype=original_dtype)\n else:\n if to_mode == BoxMode.XYXY_ABS and from_mode == BoxMode.XYWH_ABS:\n arr[:, 2] += arr[:, 0]\n arr[:, 3] += arr[:, 1]\n elif from_mode == BoxMode.XYXY_ABS and to_mode == BoxMode.XYWH_ABS:\n arr[:, 2] -= arr[:, 0]\n arr[:, 3] -= arr[:, 1]\n else:\n raise NotImplementedError(\n \"Conversion from BoxMode {} to {} is not supported yet\".format(\n from_mode, to_mode\n )\n )\n\n if single_box:\n return original_type(arr.flatten().tolist())\n if is_numpy:\n return arr.numpy()\n else:\n return arr" }, { "identifier": "Keypoints", "path": "detectron2/structures/keypoints.py", "snippet": "class Keypoints:\n \"\"\"\n Stores keypoint **annotation** data. GT Instances have a `gt_keypoints` property\n containing the x,y location and visibility flag of each keypoint. This tensor has shape\n (N, K, 3) where N is the number of instances and K is the number of keypoints per instance.\n\n The visibility flag follows the COCO format and must be one of three integers:\n\n * v=0: not labeled (in which case x=y=0)\n * v=1: labeled but not visible\n * v=2: labeled and visible\n \"\"\"\n\n def __init__(self, keypoints: Union[torch.Tensor, np.ndarray, List[List[float]]]):\n \"\"\"\n Arguments:\n keypoints: A Tensor, numpy array, or list of the x, y, and visibility of each keypoint.\n The shape should be (N, K, 3) where N is the number of\n instances, and K is the number of keypoints per instance.\n \"\"\"\n device = keypoints.device if isinstance(keypoints, torch.Tensor) else torch.device(\"cpu\")\n keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=device)\n assert keypoints.dim() == 3 and keypoints.shape[2] == 3, keypoints.shape\n self.tensor = keypoints\n\n def __len__(self) -> int:\n return self.tensor.size(0)\n\n def to(self, *args: Any, **kwargs: Any) -> \"Keypoints\":\n return type(self)(self.tensor.to(*args, **kwargs))\n\n @property\n def device(self) -> torch.device:\n return self.tensor.device\n\n def to_heatmap(self, boxes: torch.Tensor, heatmap_size: int) -> torch.Tensor:\n \"\"\"\n Convert keypoint annotations to a heatmap of one-hot labels for training,\n as described in :paper:`Mask R-CNN`.\n\n Arguments:\n boxes: Nx4 tensor, the boxes to draw the keypoints to\n\n Returns:\n heatmaps:\n A tensor of shape (N, K), each element is integer spatial label\n in the range [0, heatmap_size**2 - 1] for each keypoint in the input.\n valid:\n A tensor of shape (N, K) containing whether each keypoint is in the roi or not.\n \"\"\"\n return _keypoints_to_heatmap(self.tensor, boxes, heatmap_size)\n\n def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"Keypoints\":\n \"\"\"\n Create a new `Keypoints` by indexing on this `Keypoints`.\n\n The following usage are allowed:\n\n 1. `new_kpts = kpts[3]`: return a `Keypoints` which contains only one instance.\n 2. `new_kpts = kpts[2:10]`: return a slice of key points.\n 3. `new_kpts = kpts[vector]`, where vector is a torch.ByteTensor\n with `length = len(kpts)`. Nonzero elements in the vector will be selected.\n\n Note that the returned Keypoints might share storage with this Keypoints,\n subject to Pytorch's indexing semantics.\n \"\"\"\n if isinstance(item, int):\n return Keypoints([self.tensor[item]])\n return Keypoints(self.tensor[item])\n\n def __repr__(self) -> str:\n s = self.__class__.__name__ + \"(\"\n s += \"num_instances={})\".format(len(self.tensor))\n return s\n\n @staticmethod\n def cat(keypoints_list: List[\"Keypoints\"]) -> \"Keypoints\":\n \"\"\"\n Concatenates a list of Keypoints into a single Keypoints\n\n Arguments:\n keypoints_list (list[Keypoints])\n\n Returns:\n Keypoints: the concatenated Keypoints\n \"\"\"\n assert isinstance(keypoints_list, (list, tuple))\n assert len(keypoints_list) > 0\n assert all(isinstance(keypoints, Keypoints) for keypoints in keypoints_list)\n\n cat_kpts = type(keypoints_list[0])(\n torch.cat([kpts.tensor for kpts in keypoints_list], dim=0)\n )\n return cat_kpts" }, { "identifier": "BitMasks", "path": "detectron2/structures/masks.py", "snippet": "class BitMasks:\n \"\"\"\n This class stores the segmentation masks for all objects in one image, in\n the form of bitmaps.\n\n Attributes:\n tensor: bool Tensor of N,H,W, representing N instances in the image.\n \"\"\"\n\n def __init__(self, tensor: Union[torch.Tensor, np.ndarray]):\n \"\"\"\n Args:\n tensor: bool Tensor of N,H,W, representing N instances in the image.\n \"\"\"\n device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device(\"cpu\")\n tensor = torch.as_tensor(tensor, dtype=torch.bool, device=device)\n assert tensor.dim() == 3, tensor.size()\n self.image_size = tensor.shape[1:]\n self.tensor = tensor\n\n @torch.jit.unused\n def to(self, *args: Any, **kwargs: Any) -> \"BitMasks\":\n return BitMasks(self.tensor.to(*args, **kwargs))\n\n @property\n def device(self) -> torch.device:\n return self.tensor.device\n\n @torch.jit.unused\n def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"BitMasks\":\n \"\"\"\n Returns:\n BitMasks: Create a new :class:`BitMasks` by indexing.\n\n The following usage are allowed:\n\n 1. `new_masks = masks[3]`: return a `BitMasks` which contains only one mask.\n 2. `new_masks = masks[2:10]`: return a slice of masks.\n 3. `new_masks = masks[vector]`, where vector is a torch.BoolTensor\n with `length = len(masks)`. Nonzero elements in the vector will be selected.\n\n Note that the returned object might share storage with this object,\n subject to Pytorch's indexing semantics.\n \"\"\"\n if isinstance(item, int):\n return BitMasks(self.tensor[item].unsqueeze(0))\n m = self.tensor[item]\n assert m.dim() == 3, \"Indexing on BitMasks with {} returns a tensor with shape {}!\".format(\n item, m.shape\n )\n return BitMasks(m)\n\n @torch.jit.unused\n def __iter__(self) -> torch.Tensor:\n yield from self.tensor\n\n @torch.jit.unused\n def __repr__(self) -> str:\n s = self.__class__.__name__ + \"(\"\n s += \"num_instances={})\".format(len(self.tensor))\n return s\n\n def __len__(self) -> int:\n return self.tensor.shape[0]\n\n def nonempty(self) -> torch.Tensor:\n \"\"\"\n Find masks that are non-empty.\n\n Returns:\n Tensor: a BoolTensor which represents\n whether each mask is empty (False) or non-empty (True).\n \"\"\"\n return self.tensor.flatten(1).any(dim=1)\n\n @staticmethod\n def from_polygon_masks(\n polygon_masks: Union[\"PolygonMasks\", List[List[np.ndarray]]], height: int, width: int\n ) -> \"BitMasks\":\n \"\"\"\n Args:\n polygon_masks (list[list[ndarray]] or PolygonMasks)\n height, width (int)\n \"\"\"\n if isinstance(polygon_masks, PolygonMasks):\n polygon_masks = polygon_masks.polygons\n masks = [polygons_to_bitmask(p, height, width) for p in polygon_masks]\n if len(masks):\n return BitMasks(torch.stack([torch.from_numpy(x) for x in masks]))\n else:\n return BitMasks(torch.empty(0, height, width, dtype=torch.bool))\n\n @staticmethod\n def from_roi_masks(roi_masks: \"ROIMasks\", height: int, width: int) -> \"BitMasks\":\n \"\"\"\n Args:\n roi_masks:\n height, width (int):\n \"\"\"\n return roi_masks.to_bitmasks(height, width)\n\n def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:\n \"\"\"\n Crop each bitmask by the given box, and resize results to (mask_size, mask_size).\n This can be used to prepare training targets for Mask R-CNN.\n It has less reconstruction error compared to rasterization with polygons.\n However we observe no difference in accuracy,\n but BitMasks requires more memory to store all the masks.\n\n Args:\n boxes (Tensor): Nx4 tensor storing the boxes for each mask\n mask_size (int): the size of the rasterized mask.\n\n Returns:\n Tensor:\n A bool tensor of shape (N, mask_size, mask_size), where\n N is the number of predicted boxes for this image.\n \"\"\"\n assert len(boxes) == len(self), \"{} != {}\".format(len(boxes), len(self))\n device = self.tensor.device\n\n batch_inds = torch.arange(len(boxes), device=device).to(dtype=boxes.dtype)[:, None]\n rois = torch.cat([batch_inds, boxes], dim=1) # Nx5\n\n bit_masks = self.tensor.to(dtype=torch.float32)\n rois = rois.to(device=device)\n output = (\n ROIAlign((mask_size, mask_size), 1.0, 0, aligned=True)\n .forward(bit_masks[:, None, :, :], rois)\n .squeeze(1)\n )\n output = output >= 0.5\n return output\n\n def get_bounding_boxes(self) -> Boxes:\n \"\"\"\n Returns:\n Boxes: tight bounding boxes around bitmasks.\n If a mask is empty, it's bounding box will be all zero.\n \"\"\"\n boxes = torch.zeros(self.tensor.shape[0], 4, dtype=torch.float32)\n x_any = torch.any(self.tensor, dim=1)\n y_any = torch.any(self.tensor, dim=2)\n for idx in range(self.tensor.shape[0]):\n x = torch.where(x_any[idx, :])[0]\n y = torch.where(y_any[idx, :])[0]\n if len(x) > 0 and len(y) > 0:\n boxes[idx, :] = torch.as_tensor(\n [x[0], y[0], x[-1] + 1, y[-1] + 1], dtype=torch.float32\n )\n return Boxes(boxes)\n\n @staticmethod\n def cat(bitmasks_list: List[\"BitMasks\"]) -> \"BitMasks\":\n \"\"\"\n Concatenates a list of BitMasks into a single BitMasks\n\n Arguments:\n bitmasks_list (list[BitMasks])\n\n Returns:\n BitMasks: the concatenated BitMasks\n \"\"\"\n assert isinstance(bitmasks_list, (list, tuple))\n assert len(bitmasks_list) > 0\n assert all(isinstance(bitmask, BitMasks) for bitmask in bitmasks_list)\n\n cat_bitmasks = type(bitmasks_list[0])(torch.cat([bm.tensor for bm in bitmasks_list], dim=0))\n return cat_bitmasks" }, { "identifier": "PolygonMasks", "path": "detectron2/structures/masks.py", "snippet": "class PolygonMasks:\n \"\"\"\n This class stores the segmentation masks for all objects in one image, in the form of polygons.\n\n Attributes:\n polygons: list[list[ndarray]]. Each ndarray is a float64 vector representing a polygon.\n \"\"\"\n\n def __init__(self, polygons: List[List[Union[torch.Tensor, np.ndarray]]]):\n \"\"\"\n Arguments:\n polygons (list[list[np.ndarray]]): The first\n level of the list correspond to individual instances,\n the second level to all the polygons that compose the\n instance, and the third level to the polygon coordinates.\n The third level array should have the format of\n [x0, y0, x1, y1, ..., xn, yn] (n >= 3).\n \"\"\"\n if not isinstance(polygons, list):\n raise ValueError(\n \"Cannot create PolygonMasks: Expect a list of list of polygons per image. \"\n \"Got '{}' instead.\".format(type(polygons))\n )\n\n def _make_array(t: Union[torch.Tensor, np.ndarray]) -> np.ndarray:\n # Use float64 for higher precision, because why not?\n # Always put polygons on CPU (self.to is a no-op) since they\n # are supposed to be small tensors.\n # May need to change this assumption if GPU placement becomes useful\n if isinstance(t, torch.Tensor):\n t = t.cpu().numpy()\n return np.asarray(t).astype(\"float64\")\n\n def process_polygons(\n polygons_per_instance: List[Union[torch.Tensor, np.ndarray]]\n ) -> List[np.ndarray]:\n if not isinstance(polygons_per_instance, list):\n raise ValueError(\n \"Cannot create polygons: Expect a list of polygons per instance. \"\n \"Got '{}' instead.\".format(type(polygons_per_instance))\n )\n # transform each polygon to a numpy array\n polygons_per_instance = [_make_array(p) for p in polygons_per_instance]\n for polygon in polygons_per_instance:\n if len(polygon) % 2 != 0 or len(polygon) < 6:\n raise ValueError(f\"Cannot create a polygon from {len(polygon)} coordinates.\")\n return polygons_per_instance\n\n self.polygons: List[List[np.ndarray]] = [\n process_polygons(polygons_per_instance) for polygons_per_instance in polygons\n ]\n\n def to(self, *args: Any, **kwargs: Any) -> \"PolygonMasks\":\n return self\n\n @property\n def device(self) -> torch.device:\n return torch.device(\"cpu\")\n\n def get_bounding_boxes(self) -> Boxes:\n \"\"\"\n Returns:\n Boxes: tight bounding boxes around polygon masks.\n \"\"\"\n boxes = torch.zeros(len(self.polygons), 4, dtype=torch.float32)\n for idx, polygons_per_instance in enumerate(self.polygons):\n minxy = torch.as_tensor([float(\"inf\"), float(\"inf\")], dtype=torch.float32)\n maxxy = torch.zeros(2, dtype=torch.float32)\n for polygon in polygons_per_instance:\n coords = torch.from_numpy(polygon).view(-1, 2).to(dtype=torch.float32)\n minxy = torch.min(minxy, torch.min(coords, dim=0).values)\n maxxy = torch.max(maxxy, torch.max(coords, dim=0).values)\n boxes[idx, :2] = minxy\n boxes[idx, 2:] = maxxy\n return Boxes(boxes)\n\n def nonempty(self) -> torch.Tensor:\n \"\"\"\n Find masks that are non-empty.\n\n Returns:\n Tensor:\n a BoolTensor which represents whether each mask is empty (False) or not (True).\n \"\"\"\n keep = [1 if len(polygon) > 0 else 0 for polygon in self.polygons]\n return torch.from_numpy(np.asarray(keep, dtype=np.bool))\n\n def __getitem__(self, item: Union[int, slice, List[int], torch.BoolTensor]) -> \"PolygonMasks\":\n \"\"\"\n Support indexing over the instances and return a `PolygonMasks` object.\n `item` can be:\n\n 1. An integer. It will return an object with only one instance.\n 2. A slice. It will return an object with the selected instances.\n 3. A list[int]. It will return an object with the selected instances,\n correpsonding to the indices in the list.\n 4. A vector mask of type BoolTensor, whose length is num_instances.\n It will return an object with the instances whose mask is nonzero.\n \"\"\"\n if isinstance(item, int):\n selected_polygons = [self.polygons[item]]\n elif isinstance(item, slice):\n selected_polygons = self.polygons[item]\n elif isinstance(item, list):\n selected_polygons = [self.polygons[i] for i in item]\n elif isinstance(item, torch.Tensor):\n # Polygons is a list, so we have to move the indices back to CPU.\n if item.dtype == torch.bool:\n assert item.dim() == 1, item.shape\n item = item.nonzero().squeeze(1).cpu().numpy().tolist()\n elif item.dtype in [torch.int32, torch.int64]:\n item = item.cpu().numpy().tolist()\n else:\n raise ValueError(\"Unsupported tensor dtype={} for indexing!\".format(item.dtype))\n selected_polygons = [self.polygons[i] for i in item]\n return PolygonMasks(selected_polygons)\n\n def __iter__(self) -> Iterator[List[np.ndarray]]:\n \"\"\"\n Yields:\n list[ndarray]: the polygons for one instance.\n Each Tensor is a float64 vector representing a polygon.\n \"\"\"\n return iter(self.polygons)\n\n def __repr__(self) -> str:\n s = self.__class__.__name__ + \"(\"\n s += \"num_instances={})\".format(len(self.polygons))\n return s\n\n def __len__(self) -> int:\n return len(self.polygons)\n\n def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:\n \"\"\"\n Crop each mask by the given box, and resize results to (mask_size, mask_size).\n This can be used to prepare training targets for Mask R-CNN.\n\n Args:\n boxes (Tensor): Nx4 tensor storing the boxes for each mask\n mask_size (int): the size of the rasterized mask.\n\n Returns:\n Tensor: A bool tensor of shape (N, mask_size, mask_size), where\n N is the number of predicted boxes for this image.\n \"\"\"\n assert len(boxes) == len(self), \"{} != {}\".format(len(boxes), len(self))\n\n device = boxes.device\n # Put boxes on the CPU, as the polygon representation is not efficient GPU-wise\n # (several small tensors for representing a single instance mask)\n boxes = boxes.to(torch.device(\"cpu\"))\n\n results = [\n rasterize_polygons_within_box(poly, box.numpy(), mask_size)\n for poly, box in zip(self.polygons, boxes)\n ]\n \"\"\"\n poly: list[list[float]], the polygons for one instance\n box: a tensor of shape (4,)\n \"\"\"\n if len(results) == 0:\n return torch.empty(0, mask_size, mask_size, dtype=torch.bool, device=device)\n return torch.stack(results, dim=0).to(device=device)\n\n def area(self):\n \"\"\"\n Computes area of the mask.\n Only works with Polygons, using the shoelace formula:\n https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates\n\n Returns:\n Tensor: a vector, area for each instance\n \"\"\"\n\n area = []\n for polygons_per_instance in self.polygons:\n area_per_instance = 0\n for p in polygons_per_instance:\n area_per_instance += polygon_area(p[0::2], p[1::2])\n area.append(area_per_instance)\n\n return torch.tensor(area)\n\n @staticmethod\n def cat(polymasks_list: List[\"PolygonMasks\"]) -> \"PolygonMasks\":\n \"\"\"\n Concatenates a list of PolygonMasks into a single PolygonMasks\n\n Arguments:\n polymasks_list (list[PolygonMasks])\n\n Returns:\n PolygonMasks: the concatenated PolygonMasks\n \"\"\"\n assert isinstance(polymasks_list, (list, tuple))\n assert len(polymasks_list) > 0\n assert all(isinstance(polymask, PolygonMasks) for polymask in polymasks_list)\n\n cat_polymasks = type(polymasks_list[0])(\n list(itertools.chain.from_iterable(pm.polygons for pm in polymasks_list))\n )\n return cat_polymasks" }, { "identifier": "RotatedBoxes", "path": "detectron2/structures/rotated_boxes.py", "snippet": "class RotatedBoxes(Boxes):\n \"\"\"\n This structure stores a list of rotated boxes as a Nx5 torch.Tensor.\n It supports some common methods about boxes\n (`area`, `clip`, `nonempty`, etc),\n and also behaves like a Tensor\n (support indexing, `to(device)`, `.device`, and iteration over all boxes)\n \"\"\"\n\n def __init__(self, tensor: torch.Tensor):\n \"\"\"\n Args:\n tensor (Tensor[float]): a Nx5 matrix. Each row is\n (x_center, y_center, width, height, angle),\n in which angle is represented in degrees.\n While there's no strict range restriction for it,\n the recommended principal range is between [-180, 180) degrees.\n\n Assume we have a horizontal box B = (x_center, y_center, width, height),\n where width is along the x-axis and height is along the y-axis.\n The rotated box B_rot (x_center, y_center, width, height, angle)\n can be seen as:\n\n 1. When angle == 0:\n B_rot == B\n 2. When angle > 0:\n B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CCW;\n 3. When angle < 0:\n B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CW.\n\n Mathematically, since the right-handed coordinate system for image space\n is (y, x), where y is top->down and x is left->right, the 4 vertices of the\n rotated rectangle :math:`(yr_i, xr_i)` (i = 1, 2, 3, 4) can be obtained from\n the vertices of the horizontal rectangle :math:`(y_i, x_i)` (i = 1, 2, 3, 4)\n in the following way (:math:`\\\\theta = angle*\\\\pi/180` is the angle in radians,\n :math:`(y_c, x_c)` is the center of the rectangle):\n\n .. math::\n\n yr_i = \\\\cos(\\\\theta) (y_i - y_c) - \\\\sin(\\\\theta) (x_i - x_c) + y_c,\n\n xr_i = \\\\sin(\\\\theta) (y_i - y_c) + \\\\cos(\\\\theta) (x_i - x_c) + x_c,\n\n which is the standard rigid-body rotation transformation.\n\n Intuitively, the angle is\n (1) the rotation angle from y-axis in image space\n to the height vector (top->down in the box's local coordinate system)\n of the box in CCW, and\n (2) the rotation angle from x-axis in image space\n to the width vector (left->right in the box's local coordinate system)\n of the box in CCW.\n\n More intuitively, consider the following horizontal box ABCD represented\n in (x1, y1, x2, y2): (3, 2, 7, 4),\n covering the [3, 7] x [2, 4] region of the continuous coordinate system\n which looks like this:\n\n .. code:: none\n\n O--------> x\n |\n | A---B\n | | |\n | D---C\n |\n v y\n\n Note that each capital letter represents one 0-dimensional geometric point\n instead of a 'square pixel' here.\n\n In the example above, using (x, y) to represent a point we have:\n\n .. math::\n\n O = (0, 0), A = (3, 2), B = (7, 2), C = (7, 4), D = (3, 4)\n\n We name vector AB = vector DC as the width vector in box's local coordinate system, and\n vector AD = vector BC as the height vector in box's local coordinate system. Initially,\n when angle = 0 degree, they're aligned with the positive directions of x-axis and y-axis\n in the image space, respectively.\n\n For better illustration, we denote the center of the box as E,\n\n .. code:: none\n\n O--------> x\n |\n | A---B\n | | E |\n | D---C\n |\n v y\n\n where the center E = ((3+7)/2, (2+4)/2) = (5, 3).\n\n Also,\n\n .. math::\n\n width = |AB| = |CD| = 7 - 3 = 4,\n height = |AD| = |BC| = 4 - 2 = 2.\n\n Therefore, the corresponding representation for the same shape in rotated box in\n (x_center, y_center, width, height, angle) format is:\n\n (5, 3, 4, 2, 0),\n\n Now, let's consider (5, 3, 4, 2, 90), which is rotated by 90 degrees\n CCW (counter-clockwise) by definition. It looks like this:\n\n .. code:: none\n\n O--------> x\n | B-C\n | | |\n | |E|\n | | |\n | A-D\n v y\n\n The center E is still located at the same point (5, 3), while the vertices\n ABCD are rotated by 90 degrees CCW with regard to E:\n A = (4, 5), B = (4, 1), C = (6, 1), D = (6, 5)\n\n Here, 90 degrees can be seen as the CCW angle to rotate from y-axis to\n vector AD or vector BC (the top->down height vector in box's local coordinate system),\n or the CCW angle to rotate from x-axis to vector AB or vector DC (the left->right\n width vector in box's local coordinate system).\n\n .. math::\n\n width = |AB| = |CD| = 5 - 1 = 4,\n height = |AD| = |BC| = 6 - 4 = 2.\n\n Next, how about (5, 3, 4, 2, -90), which is rotated by 90 degrees CW (clockwise)\n by definition? It looks like this:\n\n .. code:: none\n\n O--------> x\n | D-A\n | | |\n | |E|\n | | |\n | C-B\n v y\n\n The center E is still located at the same point (5, 3), while the vertices\n ABCD are rotated by 90 degrees CW with regard to E:\n A = (6, 1), B = (6, 5), C = (4, 5), D = (4, 1)\n\n .. math::\n\n width = |AB| = |CD| = 5 - 1 = 4,\n height = |AD| = |BC| = 6 - 4 = 2.\n\n This covers exactly the same region as (5, 3, 4, 2, 90) does, and their IoU\n will be 1. However, these two will generate different RoI Pooling results and\n should not be treated as an identical box.\n\n On the other hand, it's easy to see that (X, Y, W, H, A) is identical to\n (X, Y, W, H, A+360N), for any integer N. For example (5, 3, 4, 2, 270) would be\n identical to (5, 3, 4, 2, -90), because rotating the shape 270 degrees CCW is\n equivalent to rotating the same shape 90 degrees CW.\n\n We could rotate further to get (5, 3, 4, 2, 180), or (5, 3, 4, 2, -180):\n\n .. code:: none\n\n O--------> x\n |\n | C---D\n | | E |\n | B---A\n |\n v y\n\n .. math::\n\n A = (7, 4), B = (3, 4), C = (3, 2), D = (7, 2),\n\n width = |AB| = |CD| = 7 - 3 = 4,\n height = |AD| = |BC| = 4 - 2 = 2.\n\n Finally, this is a very inaccurate (heavily quantized) illustration of\n how (5, 3, 4, 2, 60) looks like in case anyone wonders:\n\n .. code:: none\n\n O--------> x\n | B\\\n | / C\n | /E /\n | A /\n | `D\n v y\n\n It's still a rectangle with center of (5, 3), width of 4 and height of 2,\n but its angle (and thus orientation) is somewhere between\n (5, 3, 4, 2, 0) and (5, 3, 4, 2, 90).\n \"\"\"\n device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device(\"cpu\")\n tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device)\n if tensor.numel() == 0:\n # Use reshape, so we don't end up creating a new tensor that does not depend on\n # the inputs (and consequently confuses jit)\n tensor = tensor.reshape((0, 5)).to(dtype=torch.float32, device=device)\n assert tensor.dim() == 2 and tensor.size(-1) == 5, tensor.size()\n\n self.tensor = tensor\n\n def clone(self) -> \"RotatedBoxes\":\n \"\"\"\n Clone the RotatedBoxes.\n\n Returns:\n RotatedBoxes\n \"\"\"\n return RotatedBoxes(self.tensor.clone())\n\n def to(self, device: torch.device):\n # Boxes are assumed float32 and does not support to(dtype)\n return RotatedBoxes(self.tensor.to(device=device))\n\n def area(self) -> torch.Tensor:\n \"\"\"\n Computes the area of all the boxes.\n\n Returns:\n torch.Tensor: a vector with areas of each box.\n \"\"\"\n box = self.tensor\n area = box[:, 2] * box[:, 3]\n return area\n\n def normalize_angles(self) -> None:\n \"\"\"\n Restrict angles to the range of [-180, 180) degrees\n \"\"\"\n self.tensor[:, 4] = (self.tensor[:, 4] + 180.0) % 360.0 - 180.0\n\n def clip(self, box_size: Tuple[int, int], clip_angle_threshold: float = 1.0) -> None:\n \"\"\"\n Clip (in place) the boxes by limiting x coordinates to the range [0, width]\n and y coordinates to the range [0, height].\n\n For RRPN:\n Only clip boxes that are almost horizontal with a tolerance of\n clip_angle_threshold to maintain backward compatibility.\n\n Rotated boxes beyond this threshold are not clipped for two reasons:\n\n 1. There are potentially multiple ways to clip a rotated box to make it\n fit within the image.\n 2. It's tricky to make the entire rectangular box fit within the image\n and still be able to not leave out pixels of interest.\n\n Therefore we rely on ops like RoIAlignRotated to safely handle this.\n\n Args:\n box_size (height, width): The clipping box's size.\n clip_angle_threshold:\n Iff. abs(normalized(angle)) <= clip_angle_threshold (in degrees),\n we do the clipping as horizontal boxes.\n \"\"\"\n h, w = box_size\n\n # normalize angles to be within (-180, 180] degrees\n self.normalize_angles()\n\n idx = torch.where(torch.abs(self.tensor[:, 4]) <= clip_angle_threshold)[0]\n\n # convert to (x1, y1, x2, y2)\n x1 = self.tensor[idx, 0] - self.tensor[idx, 2] / 2.0\n y1 = self.tensor[idx, 1] - self.tensor[idx, 3] / 2.0\n x2 = self.tensor[idx, 0] + self.tensor[idx, 2] / 2.0\n y2 = self.tensor[idx, 1] + self.tensor[idx, 3] / 2.0\n\n # clip\n x1.clamp_(min=0, max=w)\n y1.clamp_(min=0, max=h)\n x2.clamp_(min=0, max=w)\n y2.clamp_(min=0, max=h)\n\n # convert back to (xc, yc, w, h)\n self.tensor[idx, 0] = (x1 + x2) / 2.0\n self.tensor[idx, 1] = (y1 + y2) / 2.0\n # make sure widths and heights do not increase due to numerical errors\n self.tensor[idx, 2] = torch.min(self.tensor[idx, 2], x2 - x1)\n self.tensor[idx, 3] = torch.min(self.tensor[idx, 3], y2 - y1)\n\n def nonempty(self, threshold: float = 0.0) -> torch.Tensor:\n \"\"\"\n Find boxes that are non-empty.\n A box is considered empty, if either of its side is no larger than threshold.\n\n Returns:\n Tensor: a binary vector which represents\n whether each box is empty (False) or non-empty (True).\n \"\"\"\n box = self.tensor\n widths = box[:, 2]\n heights = box[:, 3]\n keep = (widths > threshold) & (heights > threshold)\n return keep\n\n def __getitem__(self, item) -> \"RotatedBoxes\":\n \"\"\"\n Returns:\n RotatedBoxes: Create a new :class:`RotatedBoxes` by indexing.\n\n The following usage are allowed:\n\n 1. `new_boxes = boxes[3]`: return a `RotatedBoxes` which contains only one box.\n 2. `new_boxes = boxes[2:10]`: return a slice of boxes.\n 3. `new_boxes = boxes[vector]`, where vector is a torch.ByteTensor\n with `length = len(boxes)`. Nonzero elements in the vector will be selected.\n\n Note that the returned RotatedBoxes might share storage with this RotatedBoxes,\n subject to Pytorch's indexing semantics.\n \"\"\"\n if isinstance(item, int):\n return RotatedBoxes(self.tensor[item].view(1, -1))\n b = self.tensor[item]\n assert b.dim() == 2, \"Indexing on RotatedBoxes with {} failed to return a matrix!\".format(\n item\n )\n return RotatedBoxes(b)\n\n def __len__(self) -> int:\n return self.tensor.shape[0]\n\n def __repr__(self) -> str:\n return \"RotatedBoxes(\" + str(self.tensor) + \")\"\n\n def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor:\n \"\"\"\n Args:\n box_size (height, width): Size of the reference box covering\n [0, width] x [0, height]\n boundary_threshold (int): Boxes that extend beyond the reference box\n boundary by more than boundary_threshold are considered \"outside\".\n\n For RRPN, it might not be necessary to call this function since it's common\n for rotated box to extend to outside of the image boundaries\n (the clip function only clips the near-horizontal boxes)\n\n Returns:\n a binary vector, indicating whether each box is inside the reference box.\n \"\"\"\n height, width = box_size\n\n cnt_x = self.tensor[..., 0]\n cnt_y = self.tensor[..., 1]\n half_w = self.tensor[..., 2] / 2.0\n half_h = self.tensor[..., 3] / 2.0\n a = self.tensor[..., 4]\n c = torch.abs(torch.cos(a * math.pi / 180.0))\n s = torch.abs(torch.sin(a * math.pi / 180.0))\n # This basically computes the horizontal bounding rectangle of the rotated box\n max_rect_dx = c * half_w + s * half_h\n max_rect_dy = c * half_h + s * half_w\n\n inds_inside = (\n (cnt_x - max_rect_dx >= -boundary_threshold)\n & (cnt_y - max_rect_dy >= -boundary_threshold)\n & (cnt_x + max_rect_dx < width + boundary_threshold)\n & (cnt_y + max_rect_dy < height + boundary_threshold)\n )\n\n return inds_inside\n\n def get_centers(self) -> torch.Tensor:\n \"\"\"\n Returns:\n The box centers in a Nx2 array of (x, y).\n \"\"\"\n return self.tensor[:, :2]\n\n def scale(self, scale_x: float, scale_y: float) -> None:\n \"\"\"\n Scale the rotated box with horizontal and vertical scaling factors\n Note: when scale_factor_x != scale_factor_y,\n the rotated box does not preserve the rectangular shape when the angle\n is not a multiple of 90 degrees under resize transformation.\n Instead, the shape is a parallelogram (that has skew)\n Here we make an approximation by fitting a rotated rectangle to the parallelogram.\n \"\"\"\n self.tensor[:, 0] *= scale_x\n self.tensor[:, 1] *= scale_y\n theta = self.tensor[:, 4] * math.pi / 180.0\n c = torch.cos(theta)\n s = torch.sin(theta)\n\n # In image space, y is top->down and x is left->right\n # Consider the local coordintate system for the rotated box,\n # where the box center is located at (0, 0), and the four vertices ABCD are\n # A(-w / 2, -h / 2), B(w / 2, -h / 2), C(w / 2, h / 2), D(-w / 2, h / 2)\n # the midpoint of the left edge AD of the rotated box E is:\n # E = (A+D)/2 = (-w / 2, 0)\n # the midpoint of the top edge AB of the rotated box F is:\n # F(0, -h / 2)\n # To get the old coordinates in the global system, apply the rotation transformation\n # (Note: the right-handed coordinate system for image space is yOx):\n # (old_x, old_y) = (s * y + c * x, c * y - s * x)\n # E(old) = (s * 0 + c * (-w/2), c * 0 - s * (-w/2)) = (-c * w / 2, s * w / 2)\n # F(old) = (s * (-h / 2) + c * 0, c * (-h / 2) - s * 0) = (-s * h / 2, -c * h / 2)\n # After applying the scaling factor (sfx, sfy):\n # E(new) = (-sfx * c * w / 2, sfy * s * w / 2)\n # F(new) = (-sfx * s * h / 2, -sfy * c * h / 2)\n # The new width after scaling tranformation becomes:\n\n # w(new) = |E(new) - O| * 2\n # = sqrt[(sfx * c * w / 2)^2 + (sfy * s * w / 2)^2] * 2\n # = sqrt[(sfx * c)^2 + (sfy * s)^2] * w\n # i.e., scale_factor_w = sqrt[(sfx * c)^2 + (sfy * s)^2]\n #\n # For example,\n # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_w == scale_factor_x;\n # when |angle| = 90, c = 0, |s| = 1, scale_factor_w == scale_factor_y\n self.tensor[:, 2] *= torch.sqrt((scale_x * c) ** 2 + (scale_y * s) ** 2)\n\n # h(new) = |F(new) - O| * 2\n # = sqrt[(sfx * s * h / 2)^2 + (sfy * c * h / 2)^2] * 2\n # = sqrt[(sfx * s)^2 + (sfy * c)^2] * h\n # i.e., scale_factor_h = sqrt[(sfx * s)^2 + (sfy * c)^2]\n #\n # For example,\n # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_h == scale_factor_y;\n # when |angle| = 90, c = 0, |s| = 1, scale_factor_h == scale_factor_x\n self.tensor[:, 3] *= torch.sqrt((scale_x * s) ** 2 + (scale_y * c) ** 2)\n\n # The angle is the rotation angle from y-axis in image space to the height\n # vector (top->down in the box's local coordinate system) of the box in CCW.\n #\n # angle(new) = angle_yOx(O - F(new))\n # = angle_yOx( (sfx * s * h / 2, sfy * c * h / 2) )\n # = atan2(sfx * s * h / 2, sfy * c * h / 2)\n # = atan2(sfx * s, sfy * c)\n #\n # For example,\n # when sfx == sfy, angle(new) == atan2(s, c) == angle(old)\n self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi\n\n @classmethod\n def cat(cls, boxes_list: List[\"RotatedBoxes\"]) -> \"RotatedBoxes\":\n \"\"\"\n Concatenates a list of RotatedBoxes into a single RotatedBoxes\n\n Arguments:\n boxes_list (list[RotatedBoxes])\n\n Returns:\n RotatedBoxes: the concatenated RotatedBoxes\n \"\"\"\n assert isinstance(boxes_list, (list, tuple))\n if len(boxes_list) == 0:\n return cls(torch.empty(0))\n assert all([isinstance(box, RotatedBoxes) for box in boxes_list])\n\n # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input\n cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))\n return cat_boxes\n\n @property\n def device(self) -> torch.device:\n return self.tensor.device\n\n @torch.jit.unused\n def __iter__(self):\n \"\"\"\n Yield a box as a Tensor of shape (5,) at a time.\n \"\"\"\n yield from self.tensor" }, { "identifier": "PathManager", "path": "detectron2/utils/file_io.py", "snippet": "class Detectron2Handler(PathHandler):\n PREFIX = \"detectron2://\"\n S3_DETECTRON2_PREFIX = \"https://dl.fbaipublicfiles.com/detectron2/\"\n def _get_supported_prefixes(self):\n def _get_local_path(self, path, **kwargs):\n def _open(self, path, mode=\"r\", **kwargs):" }, { "identifier": "random_color", "path": "detectron2/utils/colormap.py", "snippet": "def random_color(rgb=False, maximum=255):\n \"\"\"\n Args:\n rgb (bool): whether to return RGB colors or BGR colors.\n maximum (int): either 255 or 1\n\n Returns:\n ndarray: a vector of 3 numbers\n \"\"\"\n idx = np.random.randint(0, len(_COLORS))\n ret = _COLORS[idx] * maximum\n if not rgb:\n ret = ret[::-1]\n return ret" } ]
import colorsys import logging import math import cv2 import matplotlib as mpl import matplotlib.colors as mplc import matplotlib.figure as mplfigure import numpy as np import pycocotools.mask as mask_util import torch from enum import Enum, unique from detectron2.data import MetadataCatalog from detectron2.structures import ( BitMasks, Boxes, BoxMode, Keypoints, PolygonMasks, RotatedBoxes, ) from detectron2.utils.file_io import PathManager from matplotlib.backends.backend_agg import FigureCanvasAgg from PIL import Image from .colormap import random_color from panopticapi.utils import rgb2id
17,020
soft_mask (ndarray): float array of shape (H, W), each value in [0, 1]. color: color of the mask. Refer to `matplotlib.colors` for a full list of formats that are accepted. If None, will pick a random color. text (str): if None, will be drawn on the object alpha (float): blending efficient. Smaller values lead to more transparent masks. Returns: output (VisImage): image object with mask drawn. """ if color is None: color = random_color(rgb=True, maximum=1) color = mplc.to_rgb(color) shape2d = (soft_mask.shape[0], soft_mask.shape[1]) rgba = np.zeros(shape2d + (4,), dtype="float32") rgba[:, :, :3] = color rgba[:, :, 3] = soft_mask * alpha self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0)) if text is not None: lighter_color = self._change_color_brightness(color, brightness_factor=0.7) binary_mask = (soft_mask > 0.5).astype("uint8") self._draw_text_in_mask(binary_mask, text, lighter_color) return self.output def draw_polygon(self, segment, color, edge_color=None, alpha=0.5): """ Args: segment: numpy array of shape Nx2, containing all the points in the polygon. color: color of the polygon. Refer to `matplotlib.colors` for a full list of formats that are accepted. edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a full list of formats that are accepted. If not provided, a darker shade of the polygon color will be used instead. alpha (float): blending efficient. Smaller values lead to more transparent masks. Returns: output (VisImage): image object with polygon drawn. """ if edge_color is None: # make edge color darker than the polygon color if alpha > 0.8: edge_color = self._change_color_brightness(color, brightness_factor=-0.7) else: edge_color = color edge_color = mplc.to_rgb(edge_color) + (1,) polygon = mpl.patches.Polygon( segment, fill=True, facecolor=mplc.to_rgb(color) + (alpha,), edgecolor=edge_color, linewidth=max(self._default_font_size // 15 * self.output.scale, 1), ) self.output.ax.add_patch(polygon) return self.output """ Internal methods: """ def _jitter(self, color): """ Randomly modifies given color to produce a slightly different color than the color given. Args: color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color picked. The values in the list are in the [0.0, 1.0] range. Returns: jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color after being jittered. The values in the list are in the [0.0, 1.0] range. """ color = mplc.to_rgb(color) vec = np.random.rand(3) # better to do it in another color space vec = vec / np.linalg.norm(vec) * 0.5 res = np.clip(vec + color, 0, 1) return tuple(res) def _create_grayscale_image(self, mask=None): """ Create a grayscale version of the original image. The colors in masked area, if given, will be kept. """ img_bw = self.img.astype("f4").mean(axis=2) img_bw = np.stack([img_bw] * 3, axis=2) if mask is not None: img_bw[mask] = self.img[mask] return img_bw def _change_color_brightness(self, color, brightness_factor): """ Depending on the brightness_factor, gives a lighter or darker color i.e. a color with less or more saturation than the original color. Args: color: color of the polygon. Refer to `matplotlib.colors` for a full list of formats that are accepted. brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of 0 will correspond to no change, a factor in [-1.0, 0) range will result in a darker color and a factor in (0, 1.0] range will result in a lighter color. Returns: modified_color (tuple[double]): a tuple containing the RGB values of the modified color. Each value in the tuple is in the [0.0, 1.0] range. """ assert brightness_factor >= -1.0 and brightness_factor <= 1.0 color = mplc.to_rgb(color) polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color)) modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1]) modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness modified_color = colorsys.hls_to_rgb(polygon_color[0], modified_lightness, polygon_color[2]) return modified_color def _convert_boxes(self, boxes): """ Convert different format of boxes to an NxB array, where B = 4 or 5 is the box dimension. """
# Copyright (c) Facebook, Inc. and its affiliates. logger = logging.getLogger(__name__) __all__ = ["ColorMode", "VisImage", "Visualizer"] _SMALL_OBJECT_AREA_THRESH = 1000 _LARGE_MASK_AREA_THRESH = 120000 _OFF_WHITE = (1.0, 1.0, 240.0 / 255) _BLACK = (0, 0, 0) _RED = (1.0, 0, 0) _KEYPOINT_THRESHOLD = 0.05 @unique class ColorMode(Enum): """ Enum of different color modes to use for instance visualizations. """ IMAGE = 0 """ Picks a random color for every instance and overlay segmentations with low opacity. """ SEGMENTATION = 1 """ Let instances of the same category have similar colors (from metadata.thing_colors), and overlay them with high opacity. This provides more attention on the quality of segmentation. """ IMAGE_BW = 2 """ Same as IMAGE, but convert all areas without masks to gray-scale. Only available for drawing per-instance mask predictions. """ class GenericMask: """ Attribute: polygons (list[ndarray]): list[ndarray]: polygons for this mask. Each ndarray has format [x, y, x, y, ...] mask (ndarray): a binary mask """ def __init__(self, mask_or_polygons, height, width): self._mask = self._polygons = self._has_holes = None self.height = height self.width = width m = mask_or_polygons if isinstance(m, dict): # RLEs assert "counts" in m and "size" in m if isinstance(m["counts"], list): # uncompressed RLEs h, w = m["size"] assert h == height and w == width m = mask_util.frPyObjects(m, h, w) self._mask = mask_util.decode(m)[:, :] return if isinstance(m, list): # list[ndarray] self._polygons = [np.asarray(x).reshape(-1) for x in m] return if isinstance(m, np.ndarray): # assumed to be a binary mask assert m.shape[1] != 2, m.shape assert m.shape == ( height, width, ), f"mask shape: {m.shape}, target dims: {height}, {width}" self._mask = m.astype("uint8") return raise ValueError("GenericMask cannot handle object {} of type '{}'".format(m, type(m))) @property def mask(self): if self._mask is None: self._mask = self.polygons_to_mask(self._polygons) return self._mask @property def polygons(self): if self._polygons is None: self._polygons, self._has_holes = self.mask_to_polygons(self._mask) return self._polygons @property def has_holes(self): if self._has_holes is None: if self._mask is not None: self._polygons, self._has_holes = self.mask_to_polygons(self._mask) else: self._has_holes = False # if original format is polygon, does not have holes return self._has_holes def mask_to_polygons(self, mask): # cv2.RETR_CCOMP flag retrieves all the contours and arranges them to a 2-level # hierarchy. External contours (boundary) of the object are placed in hierarchy-1. # Internal contours (holes) are placed in hierarchy-2. # cv2.CHAIN_APPROX_NONE flag gets vertices of polygons from contours. mask = np.ascontiguousarray(mask) # some versions of cv2 does not support incontiguous arr res = cv2.findContours(mask.astype("uint8"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) hierarchy = res[-1] if hierarchy is None: # empty mask return [], False has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0 res = res[-2] res = [x.flatten() for x in res] # These coordinates from OpenCV are integers in range [0, W-1 or H-1]. # We add 0.5 to turn them into real-value coordinate space. A better solution # would be to first +0.5 and then dilate the returned polygon by 0.5. res = [x + 0.5 for x in res if len(x) >= 6] return res, has_holes def polygons_to_mask(self, polygons): rle = mask_util.frPyObjects(polygons, self.height, self.width) rle = mask_util.merge(rle) return mask_util.decode(rle)[:, :] def area(self): return self.mask.sum() def bbox(self): p = mask_util.frPyObjects(self.polygons, self.height, self.width) p = mask_util.merge(p) bbox = mask_util.toBbox(p) bbox[2] += bbox[0] bbox[3] += bbox[1] return bbox class _PanopticPrediction: """ Unify different panoptic annotation/prediction formats """ def __init__(self, panoptic_seg, segments_info, metadata=None): if segments_info is None: assert metadata is not None # If "segments_info" is None, we assume "panoptic_img" is a # H*W int32 image storing the panoptic_id in the format of # category_id * label_divisor + instance_id. We reserve -1 for # VOID label. label_divisor = metadata.label_divisor segments_info = [] for panoptic_label in np.unique(panoptic_seg.numpy()): if panoptic_label == -1: # VOID region. continue pred_class = panoptic_label // label_divisor isthing = pred_class in metadata.thing_dataset_id_to_contiguous_id.values() segments_info.append( { "id": int(panoptic_label), "category_id": int(pred_class), "isthing": bool(isthing), } ) del metadata self._seg = panoptic_seg self._sinfo = {s["id"]: s for s in segments_info} # seg id -> seg info segment_ids, areas = torch.unique(panoptic_seg, sorted=True, return_counts=True) areas = areas.numpy() sorted_idxs = np.argsort(-areas) self._seg_ids, self._seg_areas = segment_ids[sorted_idxs], areas[sorted_idxs] self._seg_ids = self._seg_ids.tolist() for sid, area in zip(self._seg_ids, self._seg_areas): if sid in self._sinfo: self._sinfo[sid]["area"] = float(area) def non_empty_mask(self): """ Returns: (H, W) array, a mask for all pixels that have a prediction """ empty_ids = [] for id in self._seg_ids: if id not in self._sinfo: empty_ids.append(id) if len(empty_ids) == 0: return np.zeros(self._seg.shape, dtype=np.uint8) assert ( len(empty_ids) == 1 ), ">1 ids corresponds to no labels. This is currently not supported" return (self._seg != empty_ids[0]).numpy().astype(np.bool) def semantic_masks(self): for sid in self._seg_ids: sinfo = self._sinfo.get(sid) if sinfo is None or sinfo["isthing"]: # Some pixels (e.g. id 0 in PanopticFPN) have no instance or semantic predictions. continue yield (self._seg == sid).numpy().astype(np.bool), sinfo def instance_masks(self): for sid in self._seg_ids: sinfo = self._sinfo.get(sid) if sinfo is None or not sinfo["isthing"]: continue mask = (self._seg == sid).numpy().astype(np.bool) if mask.sum() > 0: yield mask, sinfo def _create_text_labels(classes, scores, class_names, is_crowd=None): """ Args: classes (list[int] or None): scores (list[float] or None): class_names (list[str] or None): is_crowd (list[bool] or None): Returns: list[str] or None """ labels = None if classes is not None: if class_names is not None and len(class_names) > 0: labels = [class_names[i] for i in classes] else: labels = [str(i) for i in classes] if scores is not None: if labels is None: labels = ["{:.0f}%".format(s * 100) for s in scores] else: labels = ["{} {:.0f}%".format(l, s * 100) for l, s in zip(labels, scores)] if labels is not None and is_crowd is not None: labels = [l + ("|crowd" if crowd else "") for l, crowd in zip(labels, is_crowd)] return labels class VisImage: def __init__(self, img, scale=1.0): """ Args: img (ndarray): an RGB image of shape (H, W, 3) in range [0, 255]. scale (float): scale the input image """ self.img = img self.scale = scale self.width, self.height = img.shape[1], img.shape[0] self._setup_figure(img) def _setup_figure(self, img): """ Args: Same as in :meth:`__init__()`. Returns: fig (matplotlib.pyplot.figure): top level container for all the image plot elements. ax (matplotlib.pyplot.Axes): contains figure elements and sets the coordinate system. """ fig = mplfigure.Figure(frameon=False) self.dpi = fig.get_dpi() # add a small 1e-2 to avoid precision lost due to matplotlib's truncation # (https://github.com/matplotlib/matplotlib/issues/15363) fig.set_size_inches( (self.width * self.scale + 1e-2) / self.dpi, (self.height * self.scale + 1e-2) / self.dpi, ) self.canvas = FigureCanvasAgg(fig) # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig) ax = fig.add_axes([0.0, 0.0, 1.0, 1.0]) ax.axis("off") self.fig = fig self.ax = ax self.reset_image(img) def reset_image(self, img): """ Args: img: same as in __init__ """ img = img.astype("uint8") self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest") def save(self, filepath): """ Args: filepath (str): a string that contains the absolute path, including the file name, where the visualized image will be saved. """ self.fig.savefig(filepath) def get_image(self): """ Returns: ndarray: the visualized image of shape (H, W, 3) (RGB) in uint8 type. The shape is scaled w.r.t the input image using the given `scale` argument. """ canvas = self.canvas s, (width, height) = canvas.print_to_buffer() # buf = io.BytesIO() # works for cairo backend # canvas.print_rgba(buf) # width, height = self.width, self.height # s = buf.getvalue() buffer = np.frombuffer(s, dtype="uint8") img_rgba = buffer.reshape(height, width, 4) rgb, alpha = np.split(img_rgba, [3], axis=2) return rgb.astype("uint8") class Visualizer: """ Visualizer that draws data about detection/segmentation on images. It contains methods like `draw_{text,box,circle,line,binary_mask,polygon}` that draw primitive objects to images, as well as high-level wrappers like `draw_{instance_predictions,sem_seg,panoptic_seg_predictions,dataset_dict}` that draw composite data in some pre-defined style. Note that the exact visualization style for the high-level wrappers are subject to change. Style such as color, opacity, label contents, visibility of labels, or even the visibility of objects themselves (e.g. when the object is too small) may change according to different heuristics, as long as the results still look visually reasonable. To obtain a consistent style, you can implement custom drawing functions with the abovementioned primitive methods instead. If you need more customized visualization styles, you can process the data yourself following their format documented in tutorials (:doc:`/tutorials/models`, :doc:`/tutorials/datasets`). This class does not intend to satisfy everyone's preference on drawing styles. This visualizer focuses on high rendering quality rather than performance. It is not designed to be used for real-time applications. """ # TODO implement a fast, rasterized version using OpenCV def __init__(self, img_rgb, metadata=None, scale=1.0, instance_mode=ColorMode.IMAGE): """ Args: img_rgb: a numpy array of shape (H, W, C), where H and W correspond to the height and width of the image respectively. C is the number of color channels. The image is required to be in RGB format since that is a requirement of the Matplotlib library. The image is also expected to be in the range [0, 255]. metadata (Metadata): dataset metadata (e.g. class names and colors) instance_mode (ColorMode): defines one of the pre-defined style for drawing instances on an image. """ self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8) if metadata is None: metadata = MetadataCatalog.get("__nonexist__") self.metadata = metadata self.output = VisImage(self.img, scale=scale) self.cpu_device = torch.device("cpu") # too small texts are useless, therefore clamp to 9 self._default_font_size = max( np.sqrt(self.output.height * self.output.width) // 90, 10 // scale ) self._instance_mode = instance_mode self.keypoint_threshold = _KEYPOINT_THRESHOLD def draw_instance_predictions(self, predictions): """ Draw instance-level prediction results on an image. Args: predictions (Instances): the output of an instance detection/segmentation model. Following fields will be used to draw: "pred_boxes", "pred_classes", "scores", "pred_masks" (or "pred_masks_rle"). Returns: output (VisImage): image object with visualizations. """ boxes = predictions.pred_boxes if predictions.has("pred_boxes") else None scores = predictions.scores if predictions.has("scores") else None classes = predictions.pred_classes.tolist() if predictions.has("pred_classes") else None labels = _create_text_labels(classes, scores, self.metadata.get("thing_classes", None)) keypoints = predictions.pred_keypoints if predictions.has("pred_keypoints") else None if predictions.has("pred_masks"): masks = np.asarray(predictions.pred_masks) masks = [GenericMask(x, self.output.height, self.output.width) for x in masks] else: masks = None if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get("thing_colors"): colors = [ self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in classes ] alpha = 0.8 else: colors = None alpha = 0.5 if self._instance_mode == ColorMode.IMAGE_BW: self.output.reset_image( self._create_grayscale_image( (predictions.pred_masks.any(dim=0) > 0).numpy() if predictions.has("pred_masks") else None ) ) alpha = 0.3 self.overlay_instances( masks=masks, boxes=boxes, labels=labels, keypoints=keypoints, assigned_colors=colors, alpha=alpha, ) return self.output def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.8): """ Draw semantic segmentation predictions/labels. Args: sem_seg (Tensor or ndarray): the segmentation of shape (H, W). Each value is the integer label of the pixel. area_threshold (int): segments with less than `area_threshold` are not drawn. alpha (float): the larger it is, the more opaque the segmentations are. Returns: output (VisImage): image object with visualizations. """ if isinstance(sem_seg, torch.Tensor): sem_seg = sem_seg.numpy() labels, areas = np.unique(sem_seg, return_counts=True) sorted_idxs = np.argsort(-areas).tolist() labels = labels[sorted_idxs] for label in filter(lambda l: l < len(self.metadata.stuff_classes), labels): try: mask_color = [x / 255 for x in self.metadata.stuff_colors[label]] except (AttributeError, IndexError): mask_color = None binary_mask = (sem_seg == label).astype(np.uint8) text = self.metadata.stuff_classes[label] self.draw_binary_mask( binary_mask, color=mask_color, edge_color=_OFF_WHITE, text=text, alpha=alpha, area_threshold=area_threshold, ) return self.output def draw_panoptic_seg(self, panoptic_seg, segments_info, area_threshold=None, alpha=0.7): """ Draw panoptic prediction annotations or results. Args: panoptic_seg (Tensor): of shape (height, width) where the values are ids for each segment. segments_info (list[dict] or None): Describe each segment in `panoptic_seg`. If it is a ``list[dict]``, each dict contains keys "id", "category_id". If None, category id of each pixel is computed by ``pixel // metadata.label_divisor``. area_threshold (int): stuff segments with less than `area_threshold` are not drawn. Returns: output (VisImage): image object with visualizations. """ pred = _PanopticPrediction(panoptic_seg, segments_info, self.metadata) if self._instance_mode == ColorMode.IMAGE_BW: self.output.reset_image(self._create_grayscale_image(pred.non_empty_mask())) # draw mask for all semantic segments first i.e. "stuff" for mask, sinfo in pred.semantic_masks(): category_idx = sinfo["category_id"] try: mask_color = [x / 255 for x in self.metadata.stuff_colors[category_idx]] except AttributeError: mask_color = None text = self.metadata.stuff_classes[category_idx] self.draw_binary_mask( mask, color=mask_color, edge_color=_OFF_WHITE, text=text, alpha=alpha, area_threshold=area_threshold, ) # draw mask for all instances second all_instances = list(pred.instance_masks()) if len(all_instances) == 0: return self.output masks, sinfo = list(zip(*all_instances)) category_ids = [x["category_id"] for x in sinfo] try: scores = [x["score"] for x in sinfo] except KeyError: scores = None labels = _create_text_labels( category_ids, scores, self.metadata.thing_classes, [x.get("iscrowd", 0) for x in sinfo] ) try: colors = [ self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in category_ids ] except AttributeError: colors = None self.overlay_instances(masks=masks, labels=labels, assigned_colors=colors, alpha=alpha) return self.output draw_panoptic_seg_predictions = draw_panoptic_seg # backward compatibility def draw_dataset_dict(self, dic): """ Draw annotations/segmentaions in Detectron2 Dataset format. Args: dic (dict): annotation/segmentation data of one image, in Detectron2 Dataset format. Returns: output (VisImage): image object with visualizations. """ annos = dic.get("annotations", None) if annos: if "segmentation" in annos[0]: masks = [x["segmentation"] for x in annos] else: masks = None if "keypoints" in annos[0]: keypts = [x["keypoints"] for x in annos] keypts = np.array(keypts).reshape(len(annos), -1, 3) else: keypts = None boxes = [ BoxMode.convert(x["bbox"], x["bbox_mode"], BoxMode.XYXY_ABS) if len(x["bbox"]) == 4 else x["bbox"] for x in annos ] colors = None category_ids = [x["category_id"] for x in annos] if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get("thing_colors"): colors = [ self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in category_ids ] names = self.metadata.get("thing_classes", None) labels = _create_text_labels( category_ids, scores=None, class_names=names, is_crowd=[x.get("iscrowd", 0) for x in annos], ) self.overlay_instances( labels=labels, boxes=boxes, masks=masks, keypoints=keypts, assigned_colors=colors ) sem_seg = dic.get("sem_seg", None) if sem_seg is None and "sem_seg_file_name" in dic: with PathManager.open(dic["sem_seg_file_name"], "rb") as f: sem_seg = Image.open(f) sem_seg = np.asarray(sem_seg, dtype="uint8") if sem_seg is not None: self.draw_sem_seg(sem_seg, area_threshold=0, alpha=0.5) pan_seg = dic.get("pan_seg", None) if pan_seg is None and "pan_seg_file_name" in dic: with PathManager.open(dic["pan_seg_file_name"], "rb") as f: pan_seg = Image.open(f) pan_seg = np.asarray(pan_seg) pan_seg = rgb2id(pan_seg) if pan_seg is not None: segments_info = dic["segments_info"] pan_seg = torch.tensor(pan_seg) self.draw_panoptic_seg(pan_seg, segments_info, area_threshold=0, alpha=0.5) return self.output def overlay_instances( self, *, boxes=None, labels=None, masks=None, keypoints=None, assigned_colors=None, alpha=0.5, ): """ Args: boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`, or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image, or a :class:`RotatedBoxes`, or an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format for the N objects in a single image, labels (list[str]): the text to be displayed for each instance. masks (masks-like object): Supported types are: * :class:`detectron2.structures.PolygonMasks`, :class:`detectron2.structures.BitMasks`. * list[list[ndarray]]: contains the segmentation masks for all objects in one image. The first level of the list corresponds to individual instances. The second level to all the polygon that compose the instance, and the third level to the polygon coordinates. The third level should have the format of [x0, y0, x1, y1, ..., xn, yn] (n >= 3). * list[ndarray]: each ndarray is a binary mask of shape (H, W). * list[dict]: each dict is a COCO-style RLE. keypoints (Keypoint or array like): an array-like object of shape (N, K, 3), where the N is the number of instances and K is the number of keypoints. The last dimension corresponds to (x, y, visibility or score). assigned_colors (list[matplotlib.colors]): a list of colors, where each color corresponds to each mask or box in the image. Refer to 'matplotlib.colors' for full list of formats that the colors are accepted in. Returns: output (VisImage): image object with visualizations. """ num_instances = 0 if boxes is not None: boxes = self._convert_boxes(boxes) num_instances = len(boxes) if masks is not None: masks = self._convert_masks(masks) if num_instances: assert len(masks) == num_instances else: num_instances = len(masks) if keypoints is not None: if num_instances: assert len(keypoints) == num_instances else: num_instances = len(keypoints) keypoints = self._convert_keypoints(keypoints) if labels is not None: assert len(labels) == num_instances if assigned_colors is None: assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)] if num_instances == 0: return self.output if boxes is not None and boxes.shape[1] == 5: return self.overlay_rotated_instances( boxes=boxes, labels=labels, assigned_colors=assigned_colors ) # Display in largest to smallest order to reduce occlusion. areas = None if boxes is not None: areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1) elif masks is not None: areas = np.asarray([x.area() for x in masks]) if areas is not None: sorted_idxs = np.argsort(-areas).tolist() # Re-order overlapped instances in descending order. boxes = boxes[sorted_idxs] if boxes is not None else None labels = [labels[k] for k in sorted_idxs] if labels is not None else None masks = [masks[idx] for idx in sorted_idxs] if masks is not None else None assigned_colors = [assigned_colors[idx] for idx in sorted_idxs] keypoints = keypoints[sorted_idxs] if keypoints is not None else None for i in range(num_instances): color = assigned_colors[i] if boxes is not None: self.draw_box(boxes[i], edge_color=color) if masks is not None: for segment in masks[i].polygons: self.draw_polygon(segment.reshape(-1, 2), color, alpha=alpha) if labels is not None: # first get a box if boxes is not None: x0, y0, x1, y1 = boxes[i] text_pos = (x0, y0) # if drawing boxes, put text on the box corner. horiz_align = "left" elif masks is not None: # skip small mask without polygon if len(masks[i].polygons) == 0: continue x0, y0, x1, y1 = masks[i].bbox() # draw text in the center (defined by median) when box is not drawn # median is less sensitive to outliers. text_pos = np.median(masks[i].mask.nonzero(), axis=1)[::-1] horiz_align = "center" else: continue # drawing the box confidence for keypoints isn't very useful. # for small objects, draw text at the side to avoid occlusion instance_area = (y1 - y0) * (x1 - x0) if ( instance_area < _SMALL_OBJECT_AREA_THRESH * self.output.scale or y1 - y0 < 40 * self.output.scale ): if y1 >= self.output.height - 5: text_pos = (x1, y0) else: text_pos = (x0, y1) height_ratio = (y1 - y0) / np.sqrt(self.output.height * self.output.width) lighter_color = self._change_color_brightness(color, brightness_factor=0.7) font_size = ( np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 * self._default_font_size ) self.draw_text( labels[i], text_pos, color=lighter_color, horizontal_alignment=horiz_align, font_size=font_size, ) # draw keypoints if keypoints is not None: for keypoints_per_instance in keypoints: self.draw_and_connect_keypoints(keypoints_per_instance) return self.output def overlay_rotated_instances(self, boxes=None, labels=None, assigned_colors=None): """ Args: boxes (ndarray): an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format for the N objects in a single image. labels (list[str]): the text to be displayed for each instance. assigned_colors (list[matplotlib.colors]): a list of colors, where each color corresponds to each mask or box in the image. Refer to 'matplotlib.colors' for full list of formats that the colors are accepted in. Returns: output (VisImage): image object with visualizations. """ num_instances = len(boxes) if assigned_colors is None: assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)] if num_instances == 0: return self.output # Display in largest to smallest order to reduce occlusion. if boxes is not None: areas = boxes[:, 2] * boxes[:, 3] sorted_idxs = np.argsort(-areas).tolist() # Re-order overlapped instances in descending order. boxes = boxes[sorted_idxs] labels = [labels[k] for k in sorted_idxs] if labels is not None else None colors = [assigned_colors[idx] for idx in sorted_idxs] for i in range(num_instances): self.draw_rotated_box_with_label( boxes[i], edge_color=colors[i], label=labels[i] if labels is not None else None ) return self.output def draw_and_connect_keypoints(self, keypoints): """ Draws keypoints of an instance and follows the rules for keypoint connections to draw lines between appropriate keypoints. This follows color heuristics for line color. Args: keypoints (Tensor): a tensor of shape (K, 3), where K is the number of keypoints and the last dimension corresponds to (x, y, probability). Returns: output (VisImage): image object with visualizations. """ visible = {} keypoint_names = self.metadata.get("keypoint_names") for idx, keypoint in enumerate(keypoints): # draw keypoint x, y, prob = keypoint if prob > self.keypoint_threshold: self.draw_circle((x, y), color=_RED) if keypoint_names: keypoint_name = keypoint_names[idx] visible[keypoint_name] = (x, y) if self.metadata.get("keypoint_connection_rules"): for kp0, kp1, color in self.metadata.keypoint_connection_rules: if kp0 in visible and kp1 in visible: x0, y0 = visible[kp0] x1, y1 = visible[kp1] color = tuple(x / 255.0 for x in color) self.draw_line([x0, x1], [y0, y1], color=color) # draw lines from nose to mid-shoulder and mid-shoulder to mid-hip # Note that this strategy is specific to person keypoints. # For other keypoints, it should just do nothing try: ls_x, ls_y = visible["left_shoulder"] rs_x, rs_y = visible["right_shoulder"] mid_shoulder_x, mid_shoulder_y = (ls_x + rs_x) / 2, (ls_y + rs_y) / 2 except KeyError: pass else: # draw line from nose to mid-shoulder nose_x, nose_y = visible.get("nose", (None, None)) if nose_x is not None: self.draw_line([nose_x, mid_shoulder_x], [nose_y, mid_shoulder_y], color=_RED) try: # draw line from mid-shoulder to mid-hip lh_x, lh_y = visible["left_hip"] rh_x, rh_y = visible["right_hip"] except KeyError: pass else: mid_hip_x, mid_hip_y = (lh_x + rh_x) / 2, (lh_y + rh_y) / 2 self.draw_line([mid_hip_x, mid_shoulder_x], [mid_hip_y, mid_shoulder_y], color=_RED) return self.output """ Primitive drawing functions: """ def draw_text( self, text, position, *, font_size=None, color="g", horizontal_alignment="center", rotation=0, ): """ Args: text (str): class label position (tuple): a tuple of the x and y coordinates to place text on image. font_size (int, optional): font of the text. If not provided, a font size proportional to the image width is calculated and used. color: color of the text. Refer to `matplotlib.colors` for full list of formats that are accepted. horizontal_alignment (str): see `matplotlib.text.Text` rotation: rotation angle in degrees CCW Returns: output (VisImage): image object with text drawn. """ if not font_size: font_size = self._default_font_size # since the text background is dark, we don't want the text to be dark color = np.maximum(list(mplc.to_rgb(color)), 0.2) color[np.argmax(color)] = max(0.8, np.max(color)) x, y = position self.output.ax.text( x, y, text, size=font_size * self.output.scale, family="sans-serif", bbox={"facecolor": "black", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"}, verticalalignment="top", horizontalalignment=horizontal_alignment, color=color, zorder=10, rotation=rotation, ) return self.output def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"): """ Args: box_coord (tuple): a tuple containing x0, y0, x1, y1 coordinates, where x0 and y0 are the coordinates of the image's top left corner. x1 and y1 are the coordinates of the image's bottom right corner. alpha (float): blending efficient. Smaller values lead to more transparent masks. edge_color: color of the outline of the box. Refer to `matplotlib.colors` for full list of formats that are accepted. line_style (string): the string to use to create the outline of the boxes. Returns: output (VisImage): image object with box drawn. """ x0, y0, x1, y1 = box_coord width = x1 - x0 height = y1 - y0 linewidth = max(self._default_font_size / 4, 1) self.output.ax.add_patch( mpl.patches.Rectangle( (x0, y0), width, height, fill=False, edgecolor=edge_color, linewidth=linewidth * self.output.scale, alpha=alpha, linestyle=line_style, ) ) return self.output def draw_rotated_box_with_label( self, rotated_box, alpha=0.5, edge_color="g", line_style="-", label=None ): """ Draw a rotated box with label on its top-left corner. Args: rotated_box (tuple): a tuple containing (cnt_x, cnt_y, w, h, angle), where cnt_x and cnt_y are the center coordinates of the box. w and h are the width and height of the box. angle represents how many degrees the box is rotated CCW with regard to the 0-degree box. alpha (float): blending efficient. Smaller values lead to more transparent masks. edge_color: color of the outline of the box. Refer to `matplotlib.colors` for full list of formats that are accepted. line_style (string): the string to use to create the outline of the boxes. label (string): label for rotated box. It will not be rendered when set to None. Returns: output (VisImage): image object with box drawn. """ cnt_x, cnt_y, w, h, angle = rotated_box area = w * h # use thinner lines when the box is small linewidth = self._default_font_size / ( 6 if area < _SMALL_OBJECT_AREA_THRESH * self.output.scale else 3 ) theta = angle * math.pi / 180.0 c = math.cos(theta) s = math.sin(theta) rect = [(-w / 2, h / 2), (-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2)] # x: left->right ; y: top->down rotated_rect = [(s * yy + c * xx + cnt_x, c * yy - s * xx + cnt_y) for (xx, yy) in rect] for k in range(4): j = (k + 1) % 4 self.draw_line( [rotated_rect[k][0], rotated_rect[j][0]], [rotated_rect[k][1], rotated_rect[j][1]], color=edge_color, linestyle="--" if k == 1 else line_style, linewidth=linewidth, ) if label is not None: text_pos = rotated_rect[1] # topleft corner height_ratio = h / np.sqrt(self.output.height * self.output.width) label_color = self._change_color_brightness(edge_color, brightness_factor=0.7) font_size = ( np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 * self._default_font_size ) self.draw_text(label, text_pos, color=label_color, font_size=font_size, rotation=angle) return self.output def draw_circle(self, circle_coord, color, radius=3): """ Args: circle_coord (list(int) or tuple(int)): contains the x and y coordinates of the center of the circle. color: color of the polygon. Refer to `matplotlib.colors` for a full list of formats that are accepted. radius (int): radius of the circle. Returns: output (VisImage): image object with box drawn. """ x, y = circle_coord self.output.ax.add_patch( mpl.patches.Circle(circle_coord, radius=radius, fill=True, color=color) ) return self.output def draw_line(self, x_data, y_data, color, linestyle="-", linewidth=None): """ Args: x_data (list[int]): a list containing x values of all the points being drawn. Length of list should match the length of y_data. y_data (list[int]): a list containing y values of all the points being drawn. Length of list should match the length of x_data. color: color of the line. Refer to `matplotlib.colors` for a full list of formats that are accepted. linestyle: style of the line. Refer to `matplotlib.lines.Line2D` for a full list of formats that are accepted. linewidth (float or None): width of the line. When it's None, a default value will be computed and used. Returns: output (VisImage): image object with line drawn. """ if linewidth is None: linewidth = self._default_font_size / 3 linewidth = max(linewidth, 1) self.output.ax.add_line( mpl.lines.Line2D( x_data, y_data, linewidth=linewidth * self.output.scale, color=color, linestyle=linestyle, ) ) return self.output def draw_binary_mask( self, binary_mask, color=None, *, edge_color=None, text=None, alpha=0.5, area_threshold=10 ): """ Args: binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and W is the image width. Each value in the array is either a 0 or 1 value of uint8 type. color: color of the mask. Refer to `matplotlib.colors` for a full list of formats that are accepted. If None, will pick a random color. edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a full list of formats that are accepted. text (str): if None, will be drawn on the object alpha (float): blending efficient. Smaller values lead to more transparent masks. area_threshold (float): a connected component smaller than this area will not be shown. Returns: output (VisImage): image object with mask drawn. """ if color is None: color = random_color(rgb=True, maximum=1) color = mplc.to_rgb(color) has_valid_segment = False binary_mask = binary_mask.astype("uint8") # opencv needs uint8 mask = GenericMask(binary_mask, self.output.height, self.output.width) shape2d = (binary_mask.shape[0], binary_mask.shape[1]) if not mask.has_holes: # draw polygons for regular masks for segment in mask.polygons: area = mask_util.area(mask_util.frPyObjects([segment], shape2d[0], shape2d[1])) if area < (area_threshold or 0): continue has_valid_segment = True segment = segment.reshape(-1, 2) self.draw_polygon(segment, color=color, edge_color=edge_color, alpha=alpha) else: # TODO: Use Path/PathPatch to draw vector graphics: # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon rgba = np.zeros(shape2d + (4,), dtype="float32") rgba[:, :, :3] = color rgba[:, :, 3] = (mask.mask == 1).astype("float32") * alpha has_valid_segment = True self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0)) if text is not None and has_valid_segment: lighter_color = self._change_color_brightness(color, brightness_factor=0.7) self._draw_text_in_mask(binary_mask, text, lighter_color) return self.output def draw_soft_mask(self, soft_mask, color=None, *, text=None, alpha=0.5): """ Args: soft_mask (ndarray): float array of shape (H, W), each value in [0, 1]. color: color of the mask. Refer to `matplotlib.colors` for a full list of formats that are accepted. If None, will pick a random color. text (str): if None, will be drawn on the object alpha (float): blending efficient. Smaller values lead to more transparent masks. Returns: output (VisImage): image object with mask drawn. """ if color is None: color = random_color(rgb=True, maximum=1) color = mplc.to_rgb(color) shape2d = (soft_mask.shape[0], soft_mask.shape[1]) rgba = np.zeros(shape2d + (4,), dtype="float32") rgba[:, :, :3] = color rgba[:, :, 3] = soft_mask * alpha self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0)) if text is not None: lighter_color = self._change_color_brightness(color, brightness_factor=0.7) binary_mask = (soft_mask > 0.5).astype("uint8") self._draw_text_in_mask(binary_mask, text, lighter_color) return self.output def draw_polygon(self, segment, color, edge_color=None, alpha=0.5): """ Args: segment: numpy array of shape Nx2, containing all the points in the polygon. color: color of the polygon. Refer to `matplotlib.colors` for a full list of formats that are accepted. edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a full list of formats that are accepted. If not provided, a darker shade of the polygon color will be used instead. alpha (float): blending efficient. Smaller values lead to more transparent masks. Returns: output (VisImage): image object with polygon drawn. """ if edge_color is None: # make edge color darker than the polygon color if alpha > 0.8: edge_color = self._change_color_brightness(color, brightness_factor=-0.7) else: edge_color = color edge_color = mplc.to_rgb(edge_color) + (1,) polygon = mpl.patches.Polygon( segment, fill=True, facecolor=mplc.to_rgb(color) + (alpha,), edgecolor=edge_color, linewidth=max(self._default_font_size // 15 * self.output.scale, 1), ) self.output.ax.add_patch(polygon) return self.output """ Internal methods: """ def _jitter(self, color): """ Randomly modifies given color to produce a slightly different color than the color given. Args: color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color picked. The values in the list are in the [0.0, 1.0] range. Returns: jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color after being jittered. The values in the list are in the [0.0, 1.0] range. """ color = mplc.to_rgb(color) vec = np.random.rand(3) # better to do it in another color space vec = vec / np.linalg.norm(vec) * 0.5 res = np.clip(vec + color, 0, 1) return tuple(res) def _create_grayscale_image(self, mask=None): """ Create a grayscale version of the original image. The colors in masked area, if given, will be kept. """ img_bw = self.img.astype("f4").mean(axis=2) img_bw = np.stack([img_bw] * 3, axis=2) if mask is not None: img_bw[mask] = self.img[mask] return img_bw def _change_color_brightness(self, color, brightness_factor): """ Depending on the brightness_factor, gives a lighter or darker color i.e. a color with less or more saturation than the original color. Args: color: color of the polygon. Refer to `matplotlib.colors` for a full list of formats that are accepted. brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of 0 will correspond to no change, a factor in [-1.0, 0) range will result in a darker color and a factor in (0, 1.0] range will result in a lighter color. Returns: modified_color (tuple[double]): a tuple containing the RGB values of the modified color. Each value in the tuple is in the [0.0, 1.0] range. """ assert brightness_factor >= -1.0 and brightness_factor <= 1.0 color = mplc.to_rgb(color) polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color)) modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1]) modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness modified_color = colorsys.hls_to_rgb(polygon_color[0], modified_lightness, polygon_color[2]) return modified_color def _convert_boxes(self, boxes): """ Convert different format of boxes to an NxB array, where B = 4 or 5 is the box dimension. """
if isinstance(boxes, Boxes) or isinstance(boxes, RotatedBoxes):
1
2023-12-22 13:31:33+00:00
24k
iKala/ievals
ievals/cli/ieval.py
[ { "identifier": "TGI_Evaluator", "path": "ievals/modules/qa_evaluators/tgi.py", "snippet": "class TGI_Evaluator(Evaluator):\n def __init__(\n self,\n choices,\n k,\n ip_addr,\n model_name,\n systemMessageToken=\"<|im_start|>system\\n\",\n messageEndToken=\"<|im_end|>\",\n assistantMessageToken=\"<|im_start|>assistant\\n\",\n userMessageToken=\"<|im_start|>user\\n\",\n switch_zh_hans=False,\n ):\n super(TGI_Evaluator, self).__init__(choices, model_name, k)\n self.ip_addr = ip_addr\n self.model_name = model_name\n self.userMessageToken = userMessageToken\n self.assistantMessageToken = assistantMessageToken\n self.messageEndToken = messageEndToken\n self.systemMessageToken = systemMessageToken\n self.converter = None\n if switch_zh_hans:\n self.converter = opencc.OpenCC(\"t2s.json\")\n\n def format_example(self, line, include_answer=True, cot=False):\n example = line[\"question\"]\n for choice in self.choices:\n example += f'\\n{choice}. {line[f\"{choice}\"]}'\n\n example += \"\\n答案:\"\n if include_answer:\n if cot:\n ans = line[\"answer\"]\n content = \"讓我們一步一步思考,\\n\" + line[\"explanation\"] + f\"\\n所以答案是{ans}。\"\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": content},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": line[\"answer\"]},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n ]\n\n def generate_few_shot_prompt(self, subject, dev_df, cot=False):\n prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject}考試單選題,請選出正確的答案。\",\n }\n ]\n k = self.k\n if self.k == -1:\n k = dev_df.shape[0]\n for i in range(k):\n tmp = self.format_example(dev_df.iloc[i, :], include_answer=True, cot=cot)\n if i == 0:\n tmp[0][\"content\"] = (\n f\"以下是關於{subject}考試單選題,請選出正確的答案。\\n\\n\" + tmp[0][\"content\"]\n )\n prompt += tmp\n return prompt\n\n def eval_subject(\n self,\n subject_name,\n test_df,\n dev_df=None,\n few_shot=False,\n save_result_dir=None,\n cot=False,\n ):\n correct_num = 0\n if save_result_dir:\n result = []\n score = []\n if few_shot:\n few_shot_prompt = self.generate_few_shot_prompt(\n subject_name, dev_df, cot=cot\n )\n else:\n few_shot_prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject_name}考試單選題,請選出正確的答案。\",\n }\n ]\n answers = list(test_df[\"answer\"])\n for row_index, row in tqdm(\n test_df.iterrows(), total=len(test_df), dynamic_ncols=True\n ):\n question = self.format_example(row, include_answer=False)\n full_prompt = few_shot_prompt + question\n if not few_shot:\n full_prompt[-1][\"content\"] = (\n f\"以下是關於{subject_name}考試單選題,請選出正確的答案。\\n\\n\"\n + full_prompt[-1][\"content\"]\n )\n response = None\n timeout_counter = 0\n text = \"\"\n for prompt in full_prompt:\n if prompt[\"role\"] == \"system\":\n text += (\n self.systemMessageToken\n + prompt[\"content\"]\n + self.messageEndToken\n )\n elif prompt[\"role\"] == \"user\":\n text += (\n self.userMessageToken + prompt[\"content\"] + self.messageEndToken\n )\n elif prompt[\"role\"] == \"assistant\":\n text += (\n self.assistantMessageToken\n + prompt[\"content\"]\n + self.messageEndToken\n )\n text += self.assistantMessageToken\n if self.converter:\n text = self.converter.convert(text)\n\n while response is None and timeout_counter <= 30:\n try:\n response = requests.post(\n f\"http://{self.ip_addr}/generate\",\n data=json.dumps(\n {\n \"inputs\": text,\n \"parameters\": {\n \"max_new_tokens\": 90,\n \"temperature\": 0.001,\n \"stop\": [self.messageEndToken],\n },\n }\n ),\n headers={\"Content-Type\": \"application/json\"},\n )\n r = response.json()\n if \"generated_text\" not in r:\n raise ValueError(\"not found: \" + str(r))\n except Exception as msg:\n if \"timeout=600\" in str(msg):\n timeout_counter += 1\n logging.error(msg)\n sleep(5)\n continue\n if response == None:\n response_str = \"\"\n else:\n response_str = response.json()[\"generated_text\"].split(\n self.messageEndToken\n )[0]\n if cot:\n ans_list = re.findall(r\"答案是(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案為(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"選項(.+?)是正確的。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案为(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"选项(.+?)是正确的。\", response_str)\n\n if len(ans_list) == 0:\n correct = 0\n else:\n if self.exact_match(ans_list[-1], row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n response_str = response_str.strip()\n if few_shot:\n if len(response_str) > 0:\n if self.exact_match(response_str, row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n else:\n if len(response_str) > 0:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n if save_result_dir:\n result.append(response_str)\n score.append(correct)\n correct_ratio = 100 * correct_num / len(answers)\n\n if save_result_dir:\n test_df[\"model_output\"] = result\n test_df[\"correctness\"] = score\n test_df.to_csv(\n os.path.join(save_result_dir, f\"{subject_name}_val.csv\"),\n encoding=\"utf-8\",\n index=False,\n )\n return correct_ratio\n\n def extract_ans(self, response_str):\n pattern = [\n r\"([A-D]).\",\n r\"答案:([A-D])\",\n r\"([A-D]). \",\n r\"^選([A-D])\",\n r\"^选([A-D])\",\n r\"^选项([A-D])\",\n r\"^選項([A-D])\",\n r\"答案是\\s?选?项?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案應該是:\\s?选?项?\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"正確答案是([A-D])\",\n r\"正確答案是 ([A-D])\",\n r\"正確的一項是\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n ]\n ans_list = []\n if response_str[0] in [\"A\", \"B\", \"C\", \"D\"]:\n ans_list.append(response_str[0])\n for p in pattern:\n if self.converter:\n p = self.converter.convert(p)\n\n if len(ans_list) == 0:\n ans_list = re.findall(p, response_str)\n else:\n break\n return ans_list" }, { "identifier": "Gemini_Evaluator", "path": "ievals/modules/qa_evaluators/gemini.py", "snippet": "class Gemini_Evaluator(Evaluator):\n def __init__(self, choices, k, api_key, model_name, switch_zh_hans=False):\n super(Gemini_Evaluator, self).__init__(choices, model_name, k)\n genai.configure(api_key=api_key)\n\n self.model = genai.GenerativeModel(\n model_name,\n safety_settings=[\n {\n \"category\": \"HARM_CATEGORY_HARASSMENT\",\n \"threshold\": \"BLOCK_ONLY_HIGH\",\n },\n {\n \"category\": \"HARM_CATEGORY_HATE_SPEECH\",\n \"threshold\": \"BLOCK_ONLY_HIGH\",\n },\n {\n \"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\n \"threshold\": \"BLOCK_ONLY_HIGH\",\n },\n {\n \"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\n \"threshold\": \"BLOCK_ONLY_HIGH\",\n },\n ],\n )\n\n self.model_name = model_name\n self.converter = None\n if switch_zh_hans:\n self.converter = opencc.OpenCC(\"t2s.json\")\n\n def format_example(self, line, include_answer=True, cot=False):\n example = line[\"question\"]\n for choice in self.choices:\n example += f'\\n{choice}. {line[f\"{choice}\"]}'\n\n example += \"\\n答案:\"\n if include_answer:\n if cot:\n ans = line[\"answer\"]\n content = \"讓我們一步一步思考,\\n\" + line[\"explanation\"] + f\"\\n所以答案是{ans}。\"\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": content},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": line[\"answer\"]},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n ]\n\n def generate_few_shot_prompt(self, subject, dev_df, cot=False):\n prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI主力,以下是關於{subject}考試單選題,請選出正確的答案。\",\n }\n ]\n k = self.k\n if self.k == -1:\n k = dev_df.shape[0]\n for i in range(k):\n tmp = self.format_example(dev_df.iloc[i, :], include_answer=True, cot=cot)\n if i == 0:\n tmp[0][\"content\"] = (\n f\"以下是關於{subject}考試單選題,請選出正確的答案。\\n\\n\" + tmp[0][\"content\"]\n )\n prompt += tmp\n return prompt\n\n def eval_subject(\n self,\n subject_name,\n test_df,\n dev_df=None,\n few_shot=False,\n save_result_dir=None,\n cot=False,\n ):\n correct_num = 0\n if save_result_dir:\n result = []\n score = []\n if few_shot:\n few_shot_prompt = self.generate_few_shot_prompt(\n subject_name, dev_df, cot=cot\n )\n else:\n few_shot_prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI主力,以下是關於{subject_name}考試單選題,請選出正確的答案。\",\n }\n ]\n answers = list(test_df[\"answer\"])\n for row_index, row in tqdm(\n test_df.iterrows(), total=len(test_df), dynamic_ncols=True\n ):\n question = self.format_example(row, include_answer=False)\n full_prompt = few_shot_prompt + question\n if not few_shot:\n full_prompt[-1][\"content\"] = (\n f\"以下是關於{subject_name}考試單選題,請選出正確的答案。\\n\\n\"\n + full_prompt[-1][\"content\"]\n )\n response = None\n timeout_counter = 0\n text = []\n prev_role = \"\"\n for prompt in full_prompt:\n if prompt[\"role\"] == \"system\":\n text.append(prompt[\"content\"] + \"\\n\")\n elif prompt[\"role\"] == \"user\":\n if prev_role == \"system\":\n text[-1] += \"問題: \" + prompt[\"content\"] + \"\\n\"\n else:\n text.append(\"問題: \" + prompt[\"content\"] + \"\\n\")\n elif prompt[\"role\"] == \"assistant\":\n text.append(prompt[\"content\"] + \"\\n\")\n prev_role = prompt[\"role\"]\n if self.converter:\n text = [self.converter.convert(seg) for seg in text]\n\n while response is None and timeout_counter <= 30:\n try:\n response = self.model.generate_content(text)\n except Exception as msg:\n if \"timeout=600\" in str(msg):\n timeout_counter += 1\n logging.error(msg)\n sleep(5)\n continue\n\n if response == None:\n response_str = \"\"\n else:\n try:\n response_str = response.text\n except (ValueError, IndexError):\n response_str = \"\"\n\n if cot:\n ans_list = re.findall(r\"答案是(.+?)。\", response_str)\n if self.converter:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案为(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"选项(.+?)是正确的。\", response_str)\n else:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案為(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"選項(.+?)是正確的。\", response_str)\n\n if len(ans_list) == 0:\n correct = 0\n else:\n if self.exact_match(ans_list[-1], row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n response_str = response_str.strip()\n if few_shot:\n if len(response_str) > 0:\n if self.exact_match(response_str, row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n else:\n if len(response_str) > 0:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n if save_result_dir:\n result.append(response_str)\n score.append(correct)\n correct_ratio = 100 * correct_num / len(answers)\n\n if save_result_dir:\n test_df[\"model_output\"] = result\n test_df[\"correctness\"] = score\n test_df.to_csv(\n os.path.join(save_result_dir, f\"{subject_name}_val.csv\"),\n encoding=\"utf-8\",\n index=False,\n )\n return correct_ratio\n\n def extract_ans(self, response_str):\n pattern = [\n r\"^选([A-D])\",\n r\"^选项([A-D])\",\n r\"答案是\\s?选?项?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"^選([A-D])\",\n r\"^選項([A-D])\",\n r\"答案是\\s?選?項?\\s?([A-D])\",\n r\"答案為\\s?選?項?\\s?([A-D])\",\n r\"答案應為\\s?選?項?\\s?([A-D])\",\n r\"答案選\\s?選?項?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"正確的一項是\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n ]\n ans_list = []\n if response_str[0] in [\"A\", \"B\", \"C\", \"D\"]:\n ans_list.append(response_str[0])\n for p in pattern:\n if self.converter:\n p = self.converter.convert(p)\n if len(ans_list) == 0:\n ans_list = re.findall(p, response_str)\n else:\n break\n return ans_list" }, { "identifier": "Claude_Evaluator", "path": "ievals/modules/qa_evaluators/claude.py", "snippet": "class Claude_Evaluator(Evaluator):\n def __init__(self, choices, k, api_key, model_name, switch_zh_hans=False):\n super(Claude_Evaluator, self).__init__(choices, model_name, k)\n self.client = anthropic.Anthropic(api_key=api_key)\n self.model_name\n self.converter = None\n if switch_zh_hans:\n self.converter = opencc.OpenCC(\"t2s.json\")\n\n def format_example(self, line, include_answer=True, cot=False):\n example = line[\"question\"]\n for choice in self.choices:\n example += f'\\n{choice}. {line[f\"{choice}\"]}'\n\n example += \"\\n答案:\"\n if include_answer:\n if cot:\n ans = line[\"answer\"]\n content = \"讓我們一步一步思考,\\n\" + line[\"explanation\"] + f\"\\n所以答案是{ans}。\"\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": content},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": line[\"answer\"]},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n ]\n\n def generate_few_shot_prompt(self, subject, dev_df, cot=False):\n prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject}考試單選題,請直接選出正確的答案。\",\n }\n ]\n k = self.k\n if self.k == -1:\n k = dev_df.shape[0]\n for i in range(k):\n tmp = self.format_example(dev_df.iloc[i, :], include_answer=True, cot=cot)\n if i == 0:\n tmp[0][\"content\"] = (\n f\"以下是關於{subject}考試單選題,請直接選出正確的答案。\\n\\n\" + tmp[0][\"content\"]\n )\n prompt += tmp\n return prompt\n\n def eval_subject(\n self,\n subject_name,\n test_df,\n dev_df=None,\n few_shot=False,\n save_result_dir=None,\n cot=False,\n ):\n correct_num = 0\n if save_result_dir:\n result = []\n score = []\n if few_shot:\n few_shot_prompt = self.generate_few_shot_prompt(\n subject_name, dev_df, cot=cot\n )\n else:\n few_shot_prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject_name}考試單選題,請直接選出正確的答案。\",\n }\n ]\n\n answers = list(test_df[\"answer\"])\n for row_index, row in tqdm(\n test_df.iterrows(), total=len(test_df), dynamic_ncols=True\n ):\n question = self.format_example(row, include_answer=False)\n full_prompt = few_shot_prompt + question\n if not few_shot:\n full_prompt[-1][\"content\"] = (\n f\"以下是關於{subject_name}考試單選題,請直接選出正確的答案。\\n\\n\"\n + full_prompt[-1][\"content\"]\n )\n response = None\n timeout_counter = 0\n text = \"\"\n for prompt in full_prompt:\n if prompt[\"role\"] == \"system\":\n text += anthropic.HUMAN_PROMPT + \" \" + prompt[\"content\"]\n elif prompt[\"role\"] == \"user\":\n text += anthropic.HUMAN_PROMPT + \" \" + prompt[\"content\"]\n elif prompt[\"role\"] == \"assistant\":\n text += anthropic.AI_PROMPT + \" \" + prompt[\"content\"]\n text += anthropic.AI_PROMPT\n if self.converter:\n text = self.converter.convert(text)\n\n while response is None and timeout_counter <= 30:\n try:\n response = self.client.completions.create(\n prompt=text,\n stop_sequences=[anthropic.HUMAN_PROMPT],\n model=self.model_name,\n temperature=0.1,\n max_tokens_to_sample=300,\n )\n except Exception as msg:\n if \"timeout=600\" in str(msg):\n timeout_counter += 1\n logging.error(msg)\n sleep(5)\n continue\n if response == None:\n response_str = \"\"\n else:\n response_str = response.completion\n\n if cot:\n ans_list = re.findall(r\"答案是(.+?)。\", response_str)\n\n if self.converter:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案为(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"选项(.+?)是正确的。\", response_str)\n else:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案為(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"選項(.+?)是正確的。\", response_str)\n\n if len(ans_list) == 0:\n correct = 0\n else:\n if self.exact_match(ans_list[-1], row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n response_str = response_str.strip()\n if few_shot:\n if len(response_str) > 0:\n if self.exact_match(response_str, row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n else:\n if len(response_str) > 0:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n if save_result_dir:\n result.append(response_str)\n score.append(correct)\n correct_ratio = 100 * correct_num / len(answers)\n\n if save_result_dir:\n test_df[\"model_output\"] = result\n test_df[\"correctness\"] = score\n test_df.to_csv(\n os.path.join(save_result_dir, f\"{subject_name}_val.csv\"),\n encoding=\"utf-8\",\n index=False,\n )\n return correct_ratio\n\n def extract_ans(self, response_str):\n pattern = [\n r\"正確的答案應該是:.*?\\b([A-D])\\b\",\n r\"正確的選項應為:.*?\\b([A-D])\\b\",\n r\"所以答案為([A-D])\",\n r\"答案為\\s?([A-D])\",\n r\"所以下列方程式的解是([A-D])\",\n r\"选([A-D])\",\n r\"选项([A-D])\",\n r\"^選([A-D])\",\n r\"^選項([A-D])\",\n r\"答案是\\s?選?項?\\s?([A-D])\",\n r\"答案為\\s?選?項?\\s?([A-D])\",\n r\"答案應為\\s?選?項?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案選\\s?選?項?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"正確的一項是\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案是\\s?选?项?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n ]\n ans_list = []\n if response_str[0] in [\"A\", \"B\", \"C\", \"D\"]:\n ans_list.append(response_str[0])\n for p in pattern:\n if self.converter:\n p = self.converter.convert(p)\n if len(ans_list) == 0:\n ans_list = re.findall(p, response_str, re.DOTALL)\n else:\n break\n return ans_list" }, { "identifier": "Azure_Evaluator", "path": "ievals/modules/qa_evaluators/azure.py", "snippet": "class Azure_Evaluator(Evaluator):\n def __init__(self, choices, k, api_key, model_name, switch_zh_hans=False):\n super(Azure_Evaluator, self).__init__(choices, model_name, k)\n self.client = AzureOpenAI(\n api_key=api_key,\n api_version=os.getenv(\"AZURE_OPENAI_VERSION\", \"2023-07-01-preview\"),\n azure_endpoint=os.getenv(\"AZURE_OPENAI_ENDPOINT\"),\n )\n self.converter = None\n if switch_zh_hans:\n self.converter = opencc.OpenCC(\"t2s.json\")\n\n def format_example(self, line, include_answer=True, cot=False):\n example = line[\"question\"]\n for choice in self.choices:\n example += f'\\n{choice}. {line[f\"{choice}\"]}'\n\n example += \"\\n答案:\"\n if include_answer:\n if cot:\n ans = line[\"answer\"]\n content = \"讓我們一步一步思考,\\n\" + line[\"explanation\"] + f\"\\n所以答案是{ans}。\"\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": content},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": line[\"answer\"]},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n ]\n\n def generate_few_shot_prompt(self, subject, dev_df, cot=False):\n prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject}考試單選題,請選出正確的答案。\",\n }\n ]\n k = self.k\n if self.k == -1:\n k = dev_df.shape[0]\n for i in range(k):\n tmp = self.format_example(dev_df.iloc[i, :], include_answer=True, cot=cot)\n if i == 0:\n tmp[0][\"content\"] = (\n f\"以下是關於{subject}考試單選題,請選出正確的答案。\\n\\n\" + tmp[0][\"content\"]\n )\n if self.converter:\n tmp[0][\"content\"] = self.converter.convert(tmp[0][\"content\"])\n\n prompt += tmp\n\n return prompt\n\n def eval_subject(\n self,\n subject_name,\n test_df,\n dev_df=None,\n few_shot=False,\n save_result_dir=None,\n cot=False,\n ):\n correct_num = 0\n if save_result_dir:\n result = []\n score = []\n if few_shot:\n few_shot_prompt = self.generate_few_shot_prompt(\n subject_name, dev_df, cot=cot\n )\n else:\n few_shot_prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject_name}考試單選題,請選出正確的答案。\",\n }\n ]\n answers = list(test_df[\"answer\"])\n for row_index, row in tqdm(\n test_df.iterrows(), total=len(test_df), dynamic_ncols=True\n ):\n question = self.format_example(row, include_answer=False)\n full_prompt = few_shot_prompt + question\n if not few_shot:\n full_prompt[-1][\"content\"] = (\n f\"以下是關於{subject_name}考試單選題,請選出正確的答案。\\n\\n\"\n + full_prompt[-1][\"content\"]\n )\n\n if self.converter:\n converted = []\n for p in full_prompt:\n p[\"content\"] = self.converter.convert(p[\"content\"])\n converted.append(p)\n full_prompt = converted\n\n response = None\n timeout_counter = 0\n\n while response is None and timeout_counter <= 30:\n try:\n response = self.client.chat.completions.create(\n model=self.model_name, messages=full_prompt, temperature=0.0\n )\n except Exception as msg:\n if \"timeout=600\" in str(msg):\n timeout_counter += 1\n logging.error(msg)\n sleep(5)\n continue\n\n response_str = \"\"\n if response != None:\n response_str = response.choices[0].message.content\n\n if cot:\n ans_list = re.findall(r\"答案是(.+?)。\", response_str)\n if self.converter:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案为(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"选项(.+?)是正确的。\", response_str)\n else:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案為(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"選項(.+?)是正確的。\", response_str)\n\n if len(ans_list) == 0:\n correct = 0\n else:\n if self.exact_match(ans_list[-1], row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n if response_str is None:\n response_str = \"\"\n else:\n response_str = response_str.strip()\n if few_shot:\n if len(response_str) > 0:\n if self.exact_match(response_str, row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n else:\n if len(response_str) > 0:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n if save_result_dir:\n result.append(response_str)\n score.append(correct)\n correct_ratio = 100 * correct_num / len(answers)\n\n if save_result_dir:\n test_df[\"model_output\"] = result\n test_df[\"correctness\"] = score\n test_df.to_csv(\n os.path.join(save_result_dir, f\"{subject_name}_val.csv\"),\n encoding=\"utf-8\",\n index=False,\n )\n return correct_ratio\n\n def extract_ans(self, response_str):\n pattern = [\n r\"([A-D]). \",\n r\"([A-D]).\",\n r\"^選([A-D])\",\n r\"^選項([A-D])\",\n r\"^选([A-D])\",\n r\"^选项([A-D])\",\n r\"答案是\\s?選?項?\\s?([A-D])\",\n r\"答案為\\s?選?項?\\s?([A-D])\",\n r\"答案應為\\s?選?項?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案選\\s?選?項?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"正確的一項是\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n ]\n ans_list = []\n if response_str[0] in [\"A\", \"B\", \"C\", \"D\"]:\n ans_list.append(response_str[0])\n for p in pattern:\n if self.converter:\n p = self.converter.convert(p)\n if len(ans_list) == 0:\n ans_list = re.findall(p, response_str)\n else:\n break\n return ans_list" }, { "identifier": "GPT_Evaluator", "path": "ievals/modules/qa_evaluators/oai_complete.py", "snippet": "class GPT_Evaluator(Evaluator):\n \"\"\"\n Completion endpoint for instruction based model\n davinci, gpt-3.5-instruct\n \"\"\"\n\n def __init__(self, choices, k, api_key, model_name, switch_zh_hans=False):\n super(GPT_Evaluator, self).__init__(choices, model_name, k)\n openai.api_key = api_key\n self.client = openai.OpenAI(api_key=api_key)\n self.converter = None\n if switch_zh_hans:\n self.converter = opencc.OpenCC(\"t2s.json\")\n\n def format_example(self, line, include_answer=True, cot=False):\n example = line[\"question\"]\n for choice in self.choices:\n example += f'\\n{choice}. {line[f\"{choice}\"]}'\n\n example += \"\\n答案:\"\n if include_answer:\n if cot:\n ans = line[\"answer\"]\n content = \"讓我們一步一步思考,\\n\" + line[\"explanation\"] + f\"\\n所以答案是{ans}。\"\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": content},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": line[\"answer\"]},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n ]\n\n def generate_few_shot_prompt(self, subject, dev_df, cot=False):\n prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject}考試單選題,請選出正確的答案。\",\n }\n ]\n k = self.k\n if self.k == -1:\n k = dev_df.shape[0]\n for i in range(k):\n tmp = self.format_example(dev_df.iloc[i, :], include_answer=True, cot=cot)\n if i == 0:\n tmp[0][\"content\"] = (\n f\"以下是關於{subject}考試單選題,請選出正確的答案。\\n\\n\" + tmp[0][\"content\"]\n )\n if self.converter:\n tmp[0][\"content\"] = self.converter.convert(tmp[0][\"content\"])\n prompt += tmp\n return prompt\n\n def eval_subject(\n self,\n subject_name,\n test_df,\n dev_df=None,\n few_shot=False,\n save_result_dir=None,\n cot=False,\n ):\n correct_num = 0\n if save_result_dir:\n result = []\n score = []\n if few_shot:\n few_shot_prompt = self.generate_few_shot_prompt(\n subject_name, dev_df, cot=cot\n )\n else:\n few_shot_prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject_name}考試單選題,請選出正確的答案。\",\n }\n ]\n answers = list(test_df[\"answer\"])\n for row_index, row in tqdm(\n test_df.iterrows(), total=len(test_df), dynamic_ncols=True\n ):\n question = self.format_example(row, include_answer=False)\n full_prompt = few_shot_prompt + question\n if not few_shot:\n full_prompt[-1][\"content\"] = (\n f\"以下是關於{subject_name}考試單選題,請選出正確的答案。\\n\\n\"\n + full_prompt[-1][\"content\"]\n )\n response = None\n timeout_counter = 0\n if self.converter:\n converted = []\n for p in full_prompt:\n p[\"content\"] = self.converter.convert(p[\"content\"])\n converted.append(p)\n full_prompt = converted\n\n text = \"\"\n for prompt in full_prompt:\n text += prompt[\"content\"] + \"\\n\"\n\n while response is None and timeout_counter <= 30:\n try:\n response = self.client.completions.create(\n model=self.model_name, prompt=text, temperature=0.0\n )\n except Exception as msg:\n if \"timeout=600\" in str(msg):\n timeout_counter += 1\n logging.error(msg)\n sleep(5)\n continue\n if response == None:\n response_str = \"\"\n else:\n response_str = response.choices[0].text\n\n if cot:\n ans_list = re.findall(r\"答案是(.+?)。\", response_str)\n if self.converter: # simplified chinese\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案为(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"选项(.+?)是正确的。\", response_str)\n else:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案為(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"選項(.+?)是正確的。\", response_str)\n\n if len(ans_list) == 0:\n correct = 0\n else:\n if self.exact_match(ans_list[-1], row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n response_str = response_str.strip()\n if few_shot:\n if len(response_str) > 0:\n if self.exact_match(response_str, row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n else:\n if len(response_str) > 0:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n if save_result_dir:\n result.append(response_str)\n score.append(correct)\n correct_ratio = 100 * correct_num / len(answers)\n\n if save_result_dir:\n test_df[\"model_output\"] = result\n test_df[\"correctness\"] = score\n test_df.to_csv(\n os.path.join(save_result_dir, f\"{subject_name}_val.csv\"),\n encoding=\"utf-8\",\n index=False,\n )\n return correct_ratio\n\n def extract_ans(self, response_str):\n pattern = [\n r\"([A-D]). \",\n r\"([A-D]).\",\n r\"^選([A-D])\",\n r\"^選項([A-D])\",\n r\"^选([A-D])\",\n r\"^选项([A-D])\",\n r\"答案是\\s?選?項?\\s?([A-D])\",\n r\"答案為\\s?選?項?\\s?([A-D])\",\n r\"答案應為\\s?選?項?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案選\\s?選?項?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"正確的一項是\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n ]\n ans_list = []\n if response_str[0] in [\"A\", \"B\", \"C\", \"D\"]:\n ans_list.append(response_str[0])\n for p in pattern:\n if self.converter:\n p = self.converter.convert(p)\n if len(ans_list) == 0:\n ans_list = re.findall(p, response_str)\n else:\n break\n return ans_list" }, { "identifier": "ChatGPT_Evaluator", "path": "ievals/modules/qa_evaluators/chatgpt.py", "snippet": "class ChatGPT_Evaluator(Evaluator):\n def __init__(self, choices, k, api_key, model_name, switch_zh_hans=False):\n super(ChatGPT_Evaluator, self).__init__(choices, model_name, k)\n openai.api_key = api_key\n self.client = openai.OpenAI(api_key=api_key)\n self.converter = None\n if switch_zh_hans:\n self.converter = opencc.OpenCC(\"t2s.json\")\n\n def format_example(self, line, include_answer=True, cot=False):\n example = line[\"question\"]\n for choice in self.choices:\n example += f'\\n{choice}. {line[f\"{choice}\"]}'\n\n example += \"\\n答案:\"\n if include_answer:\n if cot:\n ans = line[\"answer\"]\n content = \"讓我們一步一步思考,\\n\" + line[\"explanation\"] + f\"\\n所以答案是{ans}。\"\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": content},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": line[\"answer\"]},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n ]\n\n def generate_few_shot_prompt(self, subject, dev_df, cot=False):\n prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject}考試單選題,請選出正確的答案。\",\n }\n ]\n k = self.k\n if self.k == -1:\n k = dev_df.shape[0]\n for i in range(k):\n tmp = self.format_example(dev_df.iloc[i, :], include_answer=True, cot=cot)\n if i == 0:\n tmp[0][\"content\"] = (\n f\"以下是關於{subject}考試單選題,請選出正確的答案。\\n\\n\" + tmp[0][\"content\"]\n )\n if self.converter:\n tmp[0][\"content\"] = self.converter.convert(tmp[0][\"content\"])\n prompt += tmp\n\n return prompt\n\n def eval_subject(\n self,\n subject_name,\n test_df,\n dev_df=None,\n few_shot=False,\n save_result_dir=None,\n cot=False,\n ):\n correct_num = 0\n if save_result_dir:\n result = []\n score = []\n if few_shot:\n few_shot_prompt = self.generate_few_shot_prompt(\n subject_name, dev_df, cot=cot\n )\n else:\n few_shot_prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject_name}考試單選題,請選出正確的答案。\",\n }\n ]\n answers = list(test_df[\"answer\"])\n for row_index, row in tqdm(\n test_df.iterrows(), total=len(test_df), dynamic_ncols=True\n ):\n question = self.format_example(row, include_answer=False)\n full_prompt = few_shot_prompt + question\n if not few_shot:\n full_prompt[-1][\"content\"] = (\n f\"以下是關於{subject_name}考試單選題,請選出正確的答案。\\n\\n\"\n + full_prompt[-1][\"content\"]\n )\n response = None\n timeout_counter = 0\n if self.converter: # convert to simplified chinese\n for idx, prompt in enumerate(full_prompt):\n full_prompt[idx][\"content\"] = self.converter.convert(\n prompt[\"content\"]\n )\n\n while response is None and timeout_counter <= 30:\n try:\n response = self.client.chat.completions.create(\n model=self.model_name,\n messages=full_prompt,\n temperature=0.0,\n max_tokens=200,\n )\n except Exception as msg:\n if \"timeout=600\" in str(msg):\n timeout_counter += 1\n logging.error(msg)\n sleep(5)\n continue\n if response == None:\n response_str = \"\"\n else:\n response_str = response.choices[0].message.content\n if cot:\n ans_list = re.findall(r\"答案是(.+?)。\", response_str)\n if self.converter:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案为(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"选项(.+?)是正确的。\", response_str)\n else:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案為(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"選項(.+?)是正確的。\", response_str)\n\n if len(ans_list) == 0:\n correct = 0\n else:\n if self.exact_match(ans_list[-1], row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n response_str = response_str.strip()\n if few_shot:\n if len(response_str) > 0:\n if self.exact_match(response_str, row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n else:\n if len(response_str) > 0:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n if save_result_dir:\n result.append(response_str)\n score.append(correct)\n correct_ratio = 100 * correct_num / len(answers)\n\n if save_result_dir:\n test_df[\"model_output\"] = result\n test_df[\"correctness\"] = score\n test_df.to_csv(\n os.path.join(save_result_dir, f\"{subject_name}_val.csv\"),\n encoding=\"utf-8\",\n index=False,\n )\n return correct_ratio\n\n def extract_ans(self, response_str):\n # manually found regex which can be used to parse most of the response\n # text\n pattern = [\n r\"([A-D]). \",\n r\"([A-D]).\",\n r\"^選([A-D])\",\n r\"^選項([A-D])\",\n r\"^选([A-D])\",\n r\"^选项([A-D])\",\n r\"答案是\\s?選?項?\\s?([A-D])\",\n r\"答案為\\s?選?項?\\s?([A-D])\",\n r\"答案應為\\s?選?項?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案選\\s?選?項?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"正確的一項是\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n ]\n ans_list = []\n if response_str[0] in [\"A\", \"B\", \"C\", \"D\"]:\n ans_list.append(response_str[0])\n for p in pattern:\n if self.converter:\n p = self.converter.convert(p)\n\n if len(ans_list) == 0:\n ans_list = re.findall(p, response_str)\n else:\n break\n return ans_list" }, { "identifier": "DashScope_Evaluator", "path": "ievals/modules/qa_evaluators/ali_dashscope.py", "snippet": "class DashScope_Evaluator(Evaluator):\n \"\"\"\n Completion endpoint for instruction based model\n qwen models\n \"\"\"\n\n def __init__(self, choices, k, api_key, model_name, switch_zh_hans=False):\n super(DashScope_Evaluator, self).__init__(choices, model_name, k)\n dashscope.api_key = api_key\n assert model_name in set(Generation.Models.__dict__.values())\n self.model_name = model_name\n self.converter = None\n if switch_zh_hans:\n self.converter = opencc.OpenCC(\"t2s.json\")\n\n def format_example(self, line, include_answer=True, cot=False):\n example = line[\"question\"]\n for choice in self.choices:\n example += f'\\n{choice}. {line[f\"{choice}\"]}'\n\n example += \"\\n答案:\"\n if include_answer:\n if cot:\n ans = line[\"answer\"]\n content = \"讓我們一步一步思考,\\n\" + line[\"explanation\"] + f\"\\n所以答案是{ans}。\"\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": content},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n {\"role\": \"assistant\", \"content\": line[\"answer\"]},\n ]\n else:\n return [\n {\"role\": \"user\", \"content\": example},\n ]\n\n def generate_few_shot_prompt(self, subject, dev_df, cot=False):\n prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject}考試單選題,請選出正確的答案。\",\n }\n ]\n k = self.k\n if self.k == -1:\n k = dev_df.shape[0]\n for i in range(k):\n tmp = self.format_example(dev_df.iloc[i, :], include_answer=True, cot=cot)\n if i == 0:\n tmp[0][\"content\"] = (\n f\"以下是關於{subject}考試單選題,請選出正確的答案。\\n\\n\" + tmp[0][\"content\"]\n )\n if self.converter:\n tmp[0][\"content\"] = self.converter.convert(tmp[0][\"content\"])\n prompt += tmp\n return prompt\n\n def eval_subject(\n self,\n subject_name,\n test_df,\n dev_df=None,\n few_shot=False,\n save_result_dir=None,\n cot=False,\n ):\n correct_num = 0\n if save_result_dir:\n result = []\n score = []\n if few_shot:\n few_shot_prompt = self.generate_few_shot_prompt(\n subject_name, dev_df, cot=cot\n )\n else:\n few_shot_prompt = [\n {\n \"role\": \"system\",\n \"content\": f\"你是一位專業的中文AI助理,以下是關於{subject_name}考試單選題,請選出正確的答案。\",\n }\n ]\n answers = list(test_df[\"answer\"])\n for row_index, row in tqdm(\n test_df.iterrows(), total=len(test_df), dynamic_ncols=True\n ):\n question = self.format_example(row, include_answer=False)\n full_prompt = few_shot_prompt + question\n if not few_shot:\n full_prompt[-1][\"content\"] = (\n f\"以下是關於{subject_name}考試單選題,請選出正確的答案。\\n\\n\"\n + full_prompt[-1][\"content\"]\n )\n response = None\n timeout_counter = 0\n if self.converter:\n converted = []\n for p in full_prompt:\n p[\"content\"] = self.converter.convert(p[\"content\"])\n converted.append(p)\n full_prompt = converted\n\n text = \"\"\n for prompt in full_prompt:\n text += prompt[\"content\"] + \"\\n\"\n\n while response is None and timeout_counter <= 30:\n try:\n response = Generation.call(model=self.model_name, prompt=text)\n except Exception as msg:\n if \"timeout=600\" in str(msg):\n timeout_counter += 1\n logging.error(msg)\n sleep(5)\n continue\n\n if response.status_code == HTTPStatus.OK:\n response_str = response.output.text\n else:\n response_str = \"\"\n\n if cot:\n ans_list = re.findall(r\"答案是(.+?)。\", response_str)\n if self.converter: # simplified chinese\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案为(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"选项(.+?)是正确的。\", response_str)\n else:\n if len(ans_list) == 0:\n ans_list = re.findall(r\"答案為(.+?)。\", response_str)\n if len(ans_list) == 0:\n ans_list = re.findall(r\"選項(.+?)是正確的。\", response_str)\n\n if len(ans_list) == 0:\n correct = 0\n else:\n if self.exact_match(ans_list[-1], row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n response_str = response_str.strip()\n if few_shot:\n if len(response_str) > 0:\n if self.exact_match(response_str, row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n else:\n if len(response_str) > 0:\n ans_list = self.extract_ans(response_str)\n if len(ans_list) > 0 and (ans_list[-1] == row[\"answer\"]):\n correct_num += 1\n correct = 1\n else:\n correct = 0\n else:\n correct = 0\n if save_result_dir:\n result.append(response_str)\n score.append(correct)\n correct_ratio = 100 * correct_num / len(answers)\n\n if save_result_dir:\n test_df[\"model_output\"] = result\n test_df[\"correctness\"] = score\n test_df.to_csv(\n os.path.join(save_result_dir, f\"{subject_name}_val.csv\"),\n encoding=\"utf-8\",\n index=False,\n )\n return correct_ratio\n\n def extract_ans(self, response_str):\n pattern = [\n r\"([A-D]). \",\n r\"([A-D]).\",\n r\"^選([A-D])\",\n r\"^選項([A-D])\",\n r\"^选([A-D])\",\n r\"^选项([A-D])\",\n r\"答案是\\s?選?項?\\s?([A-D])\",\n r\"答案為\\s?選?項?\\s?([A-D])\",\n r\"答案應為\\s?選?項?\\s?([A-D])\",\n r\"答案为\\s?选?项?\\s?([A-D])\",\n r\"答案应为\\s?选?项?\\s?([A-D])\",\n r\"答案選\\s?選?項?\\s?([A-D])\",\n r\"答案选\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"正確的一項是\\s?([A-D])\",\n r\"正确的一项是\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案是:\\s?選?項?\\s?([A-D])\",\n r\"答案應該是:\\s?選?項?\\s?([A-D])\",\n r\"答案為:\\s?選?項?\\s?([A-D])\",\n r\"答案應為:\\s?選?項?\\s?([A-D])\",\n r\"答案:\\s?選?項?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n r\"答案是:\\s?选?项?\\s?([A-D])\",\n r\"答案应该是:\\s?选?项?\\s?([A-D])\",\n r\"答案为:\\s?选?项?\\s?([A-D])\",\n r\"答案应为:\\s?选?项?\\s?([A-D])\",\n r\"答案:\\s?选?项?\\s?([A-D])\",\n ]\n ans_list = []\n if response_str[0] in [\"A\", \"B\", \"C\", \"D\"]:\n ans_list.append(response_str[0])\n for p in pattern:\n if self.converter:\n p = self.converter.convert(p)\n if len(ans_list) == 0:\n ans_list = re.findall(p, response_str)\n else:\n break\n return ans_list" }, { "identifier": "run_exp", "path": "ievals/exp_executer.py", "snippet": "def run_exp(\n evaluator,\n model_name,\n dataset,\n postfix_name=\"tgi\",\n cache_path=\".cache\",\n split_name=\"test\",\n few_shot=False,\n):\n model_name_path = model_name.replace(\"/\", \"_\")\n save_result_dir = None\n\n if cache_path:\n os.makedirs(f\"{cache_path}\", exist_ok=True)\n os.makedirs(f\"{cache_path}/{model_name_path}\", exist_ok=True)\n save_result_dir = f\"{cache_path}/{model_name_path}\"\n\n task_list, subject2name, subject2category = get_exp_setting(dataset)\n postfix = model_name.split(\"/\")[-1]\n prefix_name = dataset.split(\"/\")[-1]\n result_cache = f\"{prefix_name}_{postfix_name}.tsv\"\n if os.path.exists(result_cache):\n logging.info(f\"Found previous cache {result_cache}, skipping executed subjects\")\n df = pd.read_csv(result_cache, delimiter=\"\\t\", header=None)\n df.columns = [\"model_name\", \"subject\", \"score\"]\n finished_subjects = df[\"subject\"].tolist()\n task_list = [t for t in task_list if t not in finished_subjects]\n\n output_filename = \"\"\n # TODO: absract out the dataset-task logic, as this is likely\n # limited under multi subject task only\n for task in task_list:\n zh_name = subject2name[task]\n test = load_dataset(dataset, task)[split_name]\n test_df = pd.DataFrame([dict(row) for row in test])\n dev = load_dataset(dataset, task)[\"train\"]\n dev_df = pd.DataFrame([dict(row) for row in dev])\n\n accuracy = evaluator.eval_subject(\n zh_name,\n test_df,\n dev_df=dev_df,\n few_shot=few_shot,\n save_result_dir=f\"{cache_path}/{model_name_path}\",\n )\n\n with open(result_cache, \"a\") as fout:\n fout.write(\"{}\\t{}\\t{:.5f}\\n\".format(model_name, task, accuracy))\n\n df = pd.read_csv(result_cache, delimiter=\"\\t\", header=None)\n df.columns = [\"model_name\", \"subject\", \"score\"]\n for model_name in df[\"model_name\"].unique():\n print(model_name)" } ]
import os import logging import argparse import pandas as pd from datasets import load_dataset from ievals.modules.qa_evaluators.tgi import TGI_Evaluator from ievals.modules.qa_evaluators.gemini import Gemini_Evaluator from ievals.modules.qa_evaluators.claude import Claude_Evaluator from ievals.modules.qa_evaluators.azure import Azure_Evaluator from ievals.modules.qa_evaluators.oai_complete import GPT_Evaluator from ievals.modules.qa_evaluators.chatgpt import ChatGPT_Evaluator from ievals.modules.qa_evaluators.hf_chat import HF_Chat_Evaluator from ievals.modules.qa_evaluators.hf_base import ( Qwen_Evaluator, ) # we only use this for qwen base model from ievals.modules.qa_evaluators.ali_dashscope import DashScope_Evaluator from ievals.exp_executer import run_exp
19,411
""" CLI for all models Support mode: if tgi service was used you must pass in IP and hostname if the service was found in model_config.csv you could skip providing the 4 tokens (user, assistant, system, eos) else you need to pass in the four token in args """ try: except ImportError as e: logging.error("huggingface and qwen models are not supported due to " + str(e)) def get_model_config(): current_dir = os.path.dirname(os.path.abspath(__file__)) up_dir = os.path.abspath(os.path.join(current_dir, os.pardir)) df = pd.read_csv(os.path.join(up_dir, "model_config.csv")) df.fillna("", inplace=True) valid_model_names = df["model_name"].tolist() return valid_model_names, df def get_tgi_prompt_config(model_name): valid_model_names, df = get_model_config() if model_name not in valid_model_names: return None, None prompt_config = df[df["model_name"] == model_name].iloc[0] prompt_config.pop("model_name") return prompt_config def get_evaluator(model_name, series=""): if len(series): if series == "azure":
""" CLI for all models Support mode: if tgi service was used you must pass in IP and hostname if the service was found in model_config.csv you could skip providing the 4 tokens (user, assistant, system, eos) else you need to pass in the four token in args """ try: except ImportError as e: logging.error("huggingface and qwen models are not supported due to " + str(e)) def get_model_config(): current_dir = os.path.dirname(os.path.abspath(__file__)) up_dir = os.path.abspath(os.path.join(current_dir, os.pardir)) df = pd.read_csv(os.path.join(up_dir, "model_config.csv")) df.fillna("", inplace=True) valid_model_names = df["model_name"].tolist() return valid_model_names, df def get_tgi_prompt_config(model_name): valid_model_names, df = get_model_config() if model_name not in valid_model_names: return None, None prompt_config = df[df["model_name"] == model_name].iloc[0] prompt_config.pop("model_name") return prompt_config def get_evaluator(model_name, series=""): if len(series): if series == "azure":
return Azure_Evaluator
3
2023-12-24 08:00:38+00:00
24k
kraina-ai/quackosm
tests/test_pbf_file_reader.py
[ { "identifier": "FEATURES_INDEX", "path": "quackosm/_constants.py", "snippet": "FEATURES_INDEX = \"feature_id\"" }, { "identifier": "OsmTagsFilter", "path": "quackosm/_osm_tags_filters.py", "snippet": "def merge_osm_tags_filter(osm_tags_filter: OsmTagsFilter) -> OsmTagsFilter: ...\ndef merge_osm_tags_filter(osm_tags_filter: GroupedOsmTagsFilter) -> OsmTagsFilter: ...\ndef merge_osm_tags_filter(osm_tags_filter: Iterable[OsmTagsFilter]) -> OsmTagsFilter: ...\ndef merge_osm_tags_filter(osm_tags_filter: Iterable[GroupedOsmTagsFilter]) -> OsmTagsFilter: ...\ndef merge_osm_tags_filter(\n osm_tags_filter: Union[\n OsmTagsFilter, GroupedOsmTagsFilter, Iterable[OsmTagsFilter], Iterable[GroupedOsmTagsFilter]\n ]\n) -> OsmTagsFilter:\ndef _merge_grouped_osm_tags_filter(grouped_filter: GroupedOsmTagsFilter) -> OsmTagsFilter:\ndef _merge_multiple_osm_tags_filters(osm_tags_filters: Iterable[OsmTagsFilter]) -> OsmTagsFilter:" }, { "identifier": "PbfFileReader", "path": "quackosm/pbf_file_reader.py", "snippet": "class PbfFileReader:\n \"\"\"\n PbfFileReader.\n\n PBF(Protocolbuffer Binary Format)[1] file reader is a dedicated `*.osm.pbf` files reader\n class based on DuckDB[2] and its spatial extension[3].\n\n Handler can filter out OSM features based on tags filter and geometry filter\n to limit the result.\n\n References:\n 1. https://wiki.openstreetmap.org/wiki/PBF_Format\n 2. https://duckdb.org/\n 3. https://github.com/duckdb/duckdb_spatial\n \"\"\"\n\n class ConvertedOSMParquetFiles(NamedTuple):\n \"\"\"List of parquet files read from the `*.osm.pbf` file.\"\"\"\n\n nodes_valid_with_tags: \"duckdb.DuckDBPyRelation\"\n nodes_filtered_ids: \"duckdb.DuckDBPyRelation\"\n\n ways_all_with_tags: \"duckdb.DuckDBPyRelation\"\n ways_with_unnested_nodes_refs: \"duckdb.DuckDBPyRelation\"\n ways_required_ids: \"duckdb.DuckDBPyRelation\"\n ways_filtered_ids: \"duckdb.DuckDBPyRelation\"\n\n relations_all_with_tags: \"duckdb.DuckDBPyRelation\"\n relations_with_unnested_way_refs: \"duckdb.DuckDBPyRelation\"\n relations_filtered_ids: \"duckdb.DuckDBPyRelation\"\n\n class ParsedOSMFeatures(NamedTuple):\n \"\"\"Final list of parsed features from the `*.osm.pbf` file.\"\"\"\n\n nodes: \"duckdb.DuckDBPyRelation\"\n ways: \"duckdb.DuckDBPyRelation\"\n relations: \"duckdb.DuckDBPyRelation\"\n\n def __init__(\n self,\n tags_filter: Optional[Union[OsmTagsFilter, GroupedOsmTagsFilter]] = None,\n geometry_filter: Optional[BaseGeometry] = None,\n working_directory: Union[str, Path] = \"files\",\n osm_way_polygon_features_config: Optional[\n Union[OsmWayPolygonConfig, dict[str, Any]]\n ] = None,\n ) -> None:\n \"\"\"\n Initialize PbfFileReader.\n\n Args:\n tags_filter (Union[OsmTagsFilter, GroupedOsmTagsFilter], optional): A dictionary\n specifying which tags to download.\n The keys should be OSM tags (e.g. `building`, `amenity`).\n The values should either be `True` for retrieving all objects with the tag,\n string for retrieving a single tag-value pair\n or list of strings for retrieving all values specified in the list.\n `tags={'leisure': 'park}` would return parks from the area.\n `tags={'leisure': 'park, 'amenity': True, 'shop': ['bakery', 'bicycle']}`\n would return parks, all amenity types, bakeries and bicycle shops.\n If `None`, handler will allow all of the tags to be parsed. Defaults to `None`.\n geometry_filter (BaseGeometry, optional): Region which can be used to filter only\n intersecting OSM objects. Defaults to `None`.\n working_directory (Union[str, Path], optional): Directory where to save\n the parsed `*.parquet` files. Defaults to \"files\".\n osm_way_polygon_features_config (Union[OsmWayPolygonConfig, dict[str, Any]], optional):\n Config used to determine which closed way features are polygons.\n Modifications to this config left are left for experienced OSM users.\n Defaults to predefined \"osm_way_polygon_features.json\".\n \"\"\"\n self.tags_filter = tags_filter\n self.merged_tags_filter = merge_osm_tags_filter(tags_filter) if tags_filter else None\n self.geometry_filter = geometry_filter\n self.working_directory = Path(working_directory)\n self.working_directory.mkdir(parents=True, exist_ok=True)\n self.connection: duckdb.DuckDBPyConnection = None\n\n self.rows_per_bucket = 1_000_000\n memory = psutil.virtual_memory()\n # If less than 8 / 16 GB total memory, reduce number of rows per group\n if memory.total < (8 * (1024**3)):\n self.rows_per_bucket = 100_000\n elif memory.total < (16 * (1024**3)):\n self.rows_per_bucket = 500_000\n\n if osm_way_polygon_features_config is None:\n # Config based on two sources + manual OSM wiki check\n # 1. https://github.com/tyrasd/osm-polygon-features/blob/v0.9.2/polygon-features.json\n # 2. https://github.com/ideditor/id-area-keys/blob/v5.0.1/areaKeys.json\n osm_way_polygon_features_config = json.loads(\n (Path(__file__).parent / \"osm_way_polygon_features.json\").read_text()\n )\n\n self.osm_way_polygon_features_config: OsmWayPolygonConfig = (\n osm_way_polygon_features_config\n if isinstance(osm_way_polygon_features_config, OsmWayPolygonConfig)\n else parse_dict_to_config_object(osm_way_polygon_features_config)\n )\n\n def get_features_gdf(\n self,\n file_paths: Union[str, Path, Iterable[Union[str, Path]]],\n explode_tags: Optional[bool] = None,\n ignore_cache: bool = False,\n filter_osm_ids: Optional[list[str]] = None,\n ) -> gpd.GeoDataFrame:\n \"\"\"\n Get features GeoDataFrame from a list of PBF files.\n\n Function parses multiple PBF files and returns a single GeoDataFrame with parsed\n OSM objects.\n\n Args:\n file_paths (Union[str, Path, Iterable[Union[str, Path]]]):\n Path or list of paths of `*.osm.pbf` files to be parsed.\n explode_tags (bool, optional): Whether to split tags into columns based on OSM tag keys.\n If `None`, will be set based on `tags_filter` parameter.\n If no tags filter is provided, then `explode_tags` will set to `False`,\n if there is tags filter it will set to `True`. Defaults to `None`.\n ignore_cache: (bool, optional): Whether to ignore precalculated geoparquet files or not.\n Defaults to False.\n filter_osm_ids: (list[str], optional): List of OSM features ids to read from the file.\n Have to be in the form of 'node/<id>', 'way/<id>' or 'relation/<id>'.\n Defaults to an empty list.\n\n Returns:\n gpd.GeoDataFrame: GeoDataFrame with OSM features.\n \"\"\"\n if isinstance(file_paths, (str, Path)):\n file_paths = [file_paths]\n\n if filter_osm_ids is None:\n filter_osm_ids = []\n\n if explode_tags is None:\n explode_tags = self.tags_filter is not None\n\n parsed_geoparquet_files = []\n for file_path in file_paths:\n parsed_geoparquet_file = self.convert_pbf_to_gpq(\n file_path,\n explode_tags=explode_tags,\n ignore_cache=ignore_cache,\n filter_osm_ids=filter_osm_ids,\n )\n parsed_geoparquet_files.append(parsed_geoparquet_file)\n\n parquet_tables = [\n io.read_geoparquet_table(parsed_parquet_file) # type: ignore\n for parsed_parquet_file in parsed_geoparquet_files\n ]\n joined_parquet_table: pa.Table = pa.concat_tables(parquet_tables)\n gdf_parquet = gpd.GeoDataFrame(\n data=joined_parquet_table.drop(GEOMETRY_COLUMN).to_pandas(maps_as_pydicts=\"strict\"),\n geometry=ga.to_geopandas(joined_parquet_table.column(GEOMETRY_COLUMN)),\n ).set_index(FEATURES_INDEX)\n\n return gdf_parquet\n\n def convert_pbf_to_gpq(\n self,\n pbf_path: Union[str, Path],\n result_file_path: Optional[Union[str, Path]] = None,\n explode_tags: Optional[bool] = None,\n ignore_cache: bool = False,\n filter_osm_ids: Optional[list[str]] = None,\n ) -> Path:\n \"\"\"\n Convert PBF file to GeoParquet file.\n\n Args:\n pbf_path (Union[str, Path]): Pbf file to be parsed to GeoParquet.\n result_file_path (Union[str, Path], optional): Where to save\n the geoparquet file. If not provided, will be generated based on hashes\n from provided tags filter and geometry filter. Defaults to `None`.\n explode_tags (bool, optional): Whether to split tags into columns based on OSM tag keys.\n If `None`, will be set based on `tags_filter` parameter.\n If no tags filter is provided, then `explode_tags` will set to `False`,\n if there is tags filter it will set to `True`. Defaults to `None`.\n ignore_cache (bool, optional): Whether to ignore precalculated geoparquet files or not.\n Defaults to False.\n filter_osm_ids: (list[str], optional): List of OSM features ids to read from the file.\n Have to be in the form of 'node/<id>', 'way/<id>' or 'relation/<id>'.\n Defaults to an empty list.\n\n Returns:\n Path: Path to the generated GeoParquet file.\n \"\"\"\n if filter_osm_ids is None:\n filter_osm_ids = []\n\n if explode_tags is None:\n explode_tags = self.tags_filter is not None\n\n with tempfile.TemporaryDirectory(dir=self.working_directory.resolve()) as tmp_dir_name:\n try:\n self._set_up_duckdb_connection(tmp_dir_name)\n result_file_path = result_file_path or self._generate_geoparquet_result_file_path(\n pbf_path,\n filter_osm_ids=filter_osm_ids,\n explode_tags=explode_tags,\n )\n parsed_geoparquet_file = self._parse_pbf_file(\n pbf_path=pbf_path,\n tmp_dir_name=tmp_dir_name,\n result_file_path=Path(result_file_path),\n filter_osm_ids=filter_osm_ids,\n explode_tags=explode_tags,\n ignore_cache=ignore_cache,\n )\n return parsed_geoparquet_file\n finally:\n if self.connection is not None:\n self.connection.close()\n self.connection = None\n\n def _set_up_duckdb_connection(self, tmp_dir_name: str) -> None:\n self.connection = duckdb.connect(\n database=str(Path(tmp_dir_name) / \"db.duckdb\"),\n config=dict(preserve_insertion_order=False),\n )\n for extension_name in (\"parquet\", \"spatial\"):\n self.connection.install_extension(extension_name)\n self.connection.load_extension(extension_name)\n\n self.connection.sql(\"\"\"\n CREATE OR REPLACE MACRO linestring_to_linestring_wkt(ls) AS\n 'LINESTRING (' || array_to_string([pt.x || ' ' || pt.y for pt in ls], ', ') || ')';\n \"\"\")\n self.connection.sql(\"\"\"\n CREATE OR REPLACE MACRO linestring_to_polygon_wkt(ls) AS\n 'POLYGON ((' || array_to_string([pt.x || ' ' || pt.y for pt in ls], ', ') || '))';\n \"\"\")\n\n def _parse_pbf_file(\n self,\n pbf_path: Union[str, Path],\n tmp_dir_name: str,\n result_file_path: Path,\n filter_osm_ids: list[str],\n explode_tags: bool = True,\n ignore_cache: bool = False,\n ) -> Path:\n if not result_file_path.exists() or ignore_cache:\n elements = self.connection.sql(f\"SELECT * FROM ST_READOSM('{Path(pbf_path)}');\")\n converted_osm_parquet_files = self._prefilter_elements_ids(\n elements, tmp_dir_name, filter_osm_ids\n )\n\n self._delete_directories(\n tmp_dir_name,\n [\n \"nodes_filtered_non_distinct_ids\",\n \"nodes_prepared_ids\",\n \"ways_valid_ids\",\n \"ways_filtered_non_distinct_ids\",\n \"relations_valid_ids\",\n \"relations_ids\",\n ],\n )\n\n filtered_nodes_with_geometry = self._get_filtered_nodes_with_geometry(\n converted_osm_parquet_files, tmp_dir_name\n )\n self._delete_directories(tmp_dir_name, \"nodes_filtered_ids\")\n\n ways_refs_with_nodes_structs = self._get_ways_refs_with_nodes_structs(\n converted_osm_parquet_files, tmp_dir_name\n )\n self._delete_directories(\n tmp_dir_name,\n [\n \"nodes_valid_with_tags\",\n ],\n )\n\n filtered_ways_with_linestrings = self._get_filtered_ways_with_linestrings(\n osm_parquet_files=converted_osm_parquet_files,\n ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,\n tmp_dir_name=tmp_dir_name,\n )\n required_ways_with_linestrings = self._get_required_ways_with_linestrings(\n osm_parquet_files=converted_osm_parquet_files,\n ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,\n tmp_dir_name=tmp_dir_name,\n )\n self._delete_directories(\n tmp_dir_name,\n [\n \"ways_required_grouped\",\n \"ways_required_ids\",\n \"ways_with_unnested_nodes_refs\",\n \"ways_refs_with_nodes_structs\",\n \"required_ways_ids_grouped\",\n \"required_ways_grouped\",\n \"required_ways_tmp\",\n \"filtered_ways_ids_grouped\",\n \"filtered_ways_grouped\",\n \"filtered_ways_tmp\",\n ],\n )\n\n filtered_ways_with_proper_geometry = self._get_filtered_ways_with_proper_geometry(\n converted_osm_parquet_files, filtered_ways_with_linestrings, tmp_dir_name\n )\n self._delete_directories(\n tmp_dir_name,\n [\n \"ways_prepared_ids\",\n \"ways_filtered_ids\",\n \"ways_all_with_tags\",\n \"filtered_ways_with_linestrings\",\n ],\n )\n\n filtered_relations_with_geometry = self._get_filtered_relations_with_geometry(\n converted_osm_parquet_files, required_ways_with_linestrings, tmp_dir_name\n )\n self._delete_directories(\n tmp_dir_name,\n [\n \"relations_all_with_tags\",\n \"relations_with_unnested_way_refs\",\n \"relations_filtered_ids\",\n \"required_ways_with_linestrings\",\n \"valid_relation_parts\",\n \"relation_inner_parts\",\n \"relation_outer_parts\",\n \"relation_outer_parts_with_holes\",\n \"relation_outer_parts_without_holes\",\n ],\n )\n\n self._concatenate_results_to_geoparquet(\n PbfFileReader.ParsedOSMFeatures(\n nodes=filtered_nodes_with_geometry,\n ways=filtered_ways_with_proper_geometry,\n relations=filtered_relations_with_geometry,\n ),\n tmp_dir_name=tmp_dir_name,\n save_file_path=result_file_path,\n explode_tags=explode_tags,\n )\n\n return result_file_path\n\n def _generate_geoparquet_result_file_path(\n self,\n pbf_file_path: Union[str, Path],\n explode_tags: bool,\n filter_osm_ids: list[str],\n ) -> Path:\n pbf_file_name = Path(pbf_file_path).name.removesuffix(\".osm.pbf\")\n\n osm_filter_tags_hash_part = \"nofilter\"\n if self.tags_filter is not None:\n h = hashlib.new(\"sha256\")\n h.update(json.dumps(self.tags_filter).encode())\n osm_filter_tags_hash_part = h.hexdigest()\n\n clipping_geometry_hash_part = \"noclip\"\n if self.geometry_filter is not None:\n h = hashlib.new(\"sha256\")\n h.update(wktlib.dumps(self.geometry_filter).encode())\n clipping_geometry_hash_part = h.hexdigest()\n\n exploded_tags_part = \"exploded\" if explode_tags else \"compact\"\n\n filter_osm_ids_hash_part = \"\"\n if filter_osm_ids:\n h = hashlib.new(\"sha256\")\n h.update(json.dumps(sorted(set(filter_osm_ids))).encode())\n filter_osm_ids_hash_part = f\"_{h.hexdigest()}\"\n\n result_file_name = (\n f\"{pbf_file_name}_{osm_filter_tags_hash_part}\"\n f\"_{clipping_geometry_hash_part}_{exploded_tags_part}{filter_osm_ids_hash_part}.geoparquet\"\n )\n return Path(self.working_directory) / result_file_name\n\n def _prefilter_elements_ids(\n self, elements: \"duckdb.DuckDBPyRelation\", tmp_dir_name: str, filter_osm_ids: list[str]\n ) -> ConvertedOSMParquetFiles:\n sql_filter = self._generate_osm_tags_sql_filter()\n filtered_tags_clause = self._generate_filtered_tags_clause()\n\n is_intersecting = self.geometry_filter is not None\n\n with TaskProgressSpinner(\"Reading nodes\", \"1\"):\n # NODES - VALID (NV)\n # - select all with kind = 'node'\n # - select all with lat and lon not empty\n nodes_valid_with_tags = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT\n id,\n {filtered_tags_clause},\n lon,\n lat\n FROM ({elements.sql_query()})\n WHERE kind = 'node'\n AND lat IS NOT NULL AND lon IS NOT NULL\n \"\"\",\n file_path=Path(tmp_dir_name) / \"nodes_valid_with_tags\",\n )\n # NODES - INTERSECTING (NI)\n # - select all from NV which intersect given geometry filter\n # NODES - FILTERED (NF)\n # - select all from NI with tags filter\n filter_osm_node_ids_filter = self._generate_elements_filter(filter_osm_ids, \"node\")\n if is_intersecting:\n wkt = cast(BaseGeometry, self.geometry_filter).wkt\n intersection_filter = f\"ST_Intersects(ST_Point(lon, lat), ST_GeomFromText('{wkt}'))\"\n with TaskProgressSpinner(\"Filtering nodes - intersection\", \"2\"):\n nodes_intersecting_ids = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT DISTINCT id FROM ({nodes_valid_with_tags.sql_query()}) n\n WHERE {intersection_filter} = true\n \"\"\",\n file_path=Path(tmp_dir_name) / \"nodes_intersecting_ids\",\n )\n with TaskProgressSpinner(\"Filtering nodes - tags\", \"3\"):\n self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT id FROM ({nodes_valid_with_tags.sql_query()}) n\n SEMI JOIN ({nodes_intersecting_ids.sql_query()}) ni ON n.id = ni.id\n WHERE tags IS NOT NULL AND cardinality(tags) > 0 AND ({sql_filter})\n AND ({filter_osm_node_ids_filter})\n \"\"\",\n file_path=Path(tmp_dir_name) / \"nodes_filtered_non_distinct_ids\",\n )\n else:\n with TaskProgressSpinner(\"Filtering nodes - intersection\", \"2\"):\n pass\n with TaskProgressSpinner(\"Filtering nodes - tags\", \"3\"):\n nodes_intersecting_ids = nodes_valid_with_tags\n self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT id FROM ({nodes_valid_with_tags.sql_query()}) n\n WHERE tags IS NOT NULL AND cardinality(tags) > 0 AND ({sql_filter})\n AND ({filter_osm_node_ids_filter})\n \"\"\",\n file_path=Path(tmp_dir_name) / \"nodes_filtered_non_distinct_ids\",\n )\n with TaskProgressSpinner(\"Calculating distinct filtered nodes ids\", \"4\"):\n nodes_filtered_ids = self._calculate_unique_ids_to_parquet(\n Path(tmp_dir_name) / \"nodes_filtered_non_distinct_ids\",\n Path(tmp_dir_name) / \"nodes_filtered_ids\",\n )\n\n with TaskProgressSpinner(\"Reading ways\", \"5\"):\n # WAYS - VALID (WV)\n # - select all with kind = 'way'\n # - select all with more then one ref\n # - join all NV to refs\n # - select all where all refs has been joined (total_refs == found_refs)\n self.connection.sql(f\"\"\"\n SELECT *\n FROM ({elements.sql_query()}) w\n WHERE kind = 'way' AND len(refs) >= 2\n \"\"\").to_view(\"ways\", replace=True)\n ways_all_with_tags = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n WITH filtered_tags AS (\n SELECT id, {filtered_tags_clause}, tags as raw_tags\n FROM ways w\n WHERE tags IS NOT NULL AND cardinality(tags) > 0\n )\n SELECT id, tags, raw_tags\n FROM filtered_tags\n WHERE tags IS NOT NULL AND cardinality(tags) > 0\n \"\"\",\n file_path=Path(tmp_dir_name) / \"ways_all_with_tags\",\n )\n with TaskProgressSpinner(\"Unnesting ways\", \"6\"):\n ways_with_unnested_nodes_refs = self._sql_to_parquet_file(\n sql_query=\"\"\"\n SELECT w.id, UNNEST(refs) as ref, UNNEST(range(length(refs))) as ref_idx\n FROM ways w\n \"\"\",\n file_path=Path(tmp_dir_name) / \"ways_with_unnested_nodes_refs\",\n )\n with TaskProgressSpinner(\"Filtering ways - valid refs\", \"7\"):\n ways_valid_ids = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n WITH total_ways_with_nodes_refs AS (\n SELECT id, ref\n FROM ({ways_with_unnested_nodes_refs.sql_query()})\n ),\n unmatched_ways_with_nodes_refs AS (\n SELECT id, ref\n FROM ({ways_with_unnested_nodes_refs.sql_query()}) w\n ANTI JOIN ({nodes_valid_with_tags.sql_query()}) nv ON nv.id = w.ref\n )\n SELECT DISTINCT id\n FROM total_ways_with_nodes_refs\n EXCEPT\n SELECT DISTINCT id\n FROM unmatched_ways_with_nodes_refs\n \"\"\",\n file_path=Path(tmp_dir_name) / \"ways_valid_ids\",\n )\n\n with TaskProgressSpinner(\"Filtering ways - intersection\", \"8\"):\n # WAYS - INTERSECTING (WI)\n # - select all from WV with joining any from NV on ref\n if is_intersecting:\n ways_intersecting_ids = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT DISTINCT uwr.id\n FROM ({ways_with_unnested_nodes_refs.sql_query()}) uwr\n SEMI JOIN ({ways_valid_ids.sql_query()}) wv ON uwr.id = wv.id\n SEMI JOIN ({nodes_intersecting_ids.sql_query()}) n ON n.id = uwr.ref\n \"\"\",\n file_path=Path(tmp_dir_name) / \"ways_intersecting_ids\",\n )\n else:\n ways_intersecting_ids = ways_valid_ids\n with TaskProgressSpinner(\"Filtering ways - tags\", \"9\"):\n # WAYS - FILTERED (WF)\n # - select all from WI with tags filter\n filter_osm_way_ids_filter = self._generate_elements_filter(filter_osm_ids, \"way\")\n self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT id FROM ({ways_all_with_tags.sql_query()}) w\n SEMI JOIN ({ways_intersecting_ids.sql_query()}) wi ON w.id = wi.id\n WHERE ({sql_filter}) AND ({filter_osm_way_ids_filter})\n \"\"\",\n file_path=Path(tmp_dir_name) / \"ways_filtered_non_distinct_ids\",\n )\n\n with TaskProgressSpinner(\"Calculating distinct filtered ways ids\", \"10\"):\n ways_filtered_ids = self._calculate_unique_ids_to_parquet(\n Path(tmp_dir_name) / \"ways_filtered_non_distinct_ids\",\n Path(tmp_dir_name) / \"ways_filtered_ids\",\n )\n\n with TaskProgressSpinner(\"Reading relations\", \"11\"):\n # RELATIONS - VALID (RV)\n # - select all with kind = 'relation'\n # - select all with more then one ref\n # - select all with type in ['boundary', 'multipolygon']\n # - join all WV to refs\n # - select all where all refs has been joined (total_refs == found_refs)\n self.connection.sql(f\"\"\"\n SELECT *\n FROM ({elements.sql_query()})\n WHERE kind = 'relation' AND len(refs) > 0\n AND list_contains(map_keys(tags), 'type')\n AND list_has_any(map_extract(tags, 'type'), ['boundary', 'multipolygon'])\n \"\"\").to_view(\"relations\", replace=True)\n relations_all_with_tags = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n WITH filtered_tags AS (\n SELECT id, {filtered_tags_clause}\n FROM relations r\n WHERE tags IS NOT NULL AND cardinality(tags) > 0\n )\n SELECT id, tags\n FROM filtered_tags\n WHERE tags IS NOT NULL AND cardinality(tags) > 0\n \"\"\",\n file_path=Path(tmp_dir_name) / \"relations_all_with_tags\",\n )\n\n with TaskProgressSpinner(\"Unnesting relations\", \"12\"):\n relations_with_unnested_way_refs = self._sql_to_parquet_file(\n sql_query=\"\"\"\n WITH unnested_relation_refs AS (\n SELECT\n r.id,\n UNNEST(refs) as ref,\n UNNEST(ref_types) as ref_type,\n UNNEST(ref_roles) as ref_role,\n UNNEST(range(length(refs))) as ref_idx\n FROM relations r\n )\n SELECT id, ref, ref_role, ref_idx\n FROM unnested_relation_refs\n WHERE ref_type = 'way'\n \"\"\",\n file_path=Path(tmp_dir_name) / \"relations_with_unnested_way_refs\",\n )\n\n with TaskProgressSpinner(\"Filtering relations - valid refs\", \"13\"):\n relations_valid_ids = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n WITH total_relation_refs AS (\n SELECT id, ref\n FROM ({relations_with_unnested_way_refs.sql_query()}) frr\n ),\n unmatched_relation_refs AS (\n SELECT id, ref\n FROM ({relations_with_unnested_way_refs.sql_query()}) r\n ANTI JOIN ({ways_valid_ids.sql_query()}) wv ON wv.id = r.ref\n )\n SELECT DISTINCT id\n FROM total_relation_refs\n EXCEPT\n SELECT DISTINCT id\n FROM unmatched_relation_refs\n \"\"\",\n file_path=Path(tmp_dir_name) / \"relations_valid_ids\",\n )\n\n with TaskProgressSpinner(\"Filtering relations - intersection\", \"14\"):\n # RELATIONS - INTERSECTING (RI)\n # - select all from RW with joining any from RV on ref\n if is_intersecting:\n relations_intersecting_ids = self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT frr.id\n FROM ({relations_with_unnested_way_refs.sql_query()}) frr\n SEMI JOIN ({relations_valid_ids.sql_query()}) rv ON frr.id = rv.id\n SEMI JOIN ({ways_intersecting_ids.sql_query()}) wi ON wi.id = frr.ref\n \"\"\",\n file_path=Path(tmp_dir_name) / \"relations_intersecting_ids\",\n )\n else:\n relations_intersecting_ids = relations_valid_ids\n\n with TaskProgressSpinner(\"Filtering relations - tags\", \"15\"):\n # RELATIONS - FILTERED (RF)\n # - select all from RI with tags filter\n filter_osm_relation_ids_filter = self._generate_elements_filter(\n filter_osm_ids, \"relation\"\n )\n\n relations_ids_path = Path(tmp_dir_name) / \"relations_ids\"\n relations_ids_path.mkdir(parents=True, exist_ok=True)\n self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT id FROM ({relations_all_with_tags.sql_query()}) r\n SEMI JOIN ({relations_intersecting_ids.sql_query()}) ri ON r.id = ri.id\n WHERE ({sql_filter}) AND ({filter_osm_relation_ids_filter})\n \"\"\",\n file_path=relations_ids_path / \"filtered\",\n )\n\n with TaskProgressSpinner(\"Calculating distinct filtered relations ids\", \"16\"):\n relations_filtered_ids = self._calculate_unique_ids_to_parquet(\n relations_ids_path / \"filtered\", Path(tmp_dir_name) / \"relations_filtered_ids\"\n )\n\n ways_prepared_ids_path = Path(tmp_dir_name) / \"ways_prepared_ids\"\n ways_prepared_ids_path.mkdir(parents=True, exist_ok=True)\n\n with TaskProgressSpinner(\"Loading required ways - by relations\", \"17\"):\n # WAYS - REQUIRED (WR)\n # - required - all IDs from WF\n # + all needed to construct relations from RF\n self._sql_to_parquet_file(\n sql_query=f\"\"\"\n SELECT ref as id\n FROM ({relations_with_unnested_way_refs.sql_query()}) frr\n SEMI JOIN ({relations_filtered_ids.sql_query()}) fri ON fri.id = frr.id\n \"\"\",\n file_path=ways_prepared_ids_path / \"required_by_relations\",\n )\n\n with TaskProgressSpinner(\"Calculating distinct required ways ids\", \"18\"):\n ways_required_ids = self._calculate_unique_ids_to_parquet(\n ways_prepared_ids_path, Path(tmp_dir_name) / \"ways_required_ids\"\n )\n\n return PbfFileReader.ConvertedOSMParquetFiles(\n nodes_valid_with_tags=nodes_valid_with_tags,\n nodes_filtered_ids=nodes_filtered_ids,\n ways_all_with_tags=ways_all_with_tags,\n ways_with_unnested_nodes_refs=ways_with_unnested_nodes_refs,\n ways_required_ids=ways_required_ids,\n ways_filtered_ids=ways_filtered_ids,\n relations_all_with_tags=relations_all_with_tags,\n relations_with_unnested_way_refs=relations_with_unnested_way_refs,\n relations_filtered_ids=relations_filtered_ids,\n )\n\n def _delete_directories(\n self, tmp_dir_name: Union[Path, str], directories: Union[str, list[str]]\n ) -> None:\n if isinstance(directories, str):\n directories = [directories]\n for directory in directories:\n directory_path = Path(tmp_dir_name) / directory\n if not directory_path.exists():\n continue\n shutil.rmtree(directory_path)\n\n def _generate_osm_tags_sql_filter(self) -> str:\n \"\"\"Prepare features filter clauses based on tags filter.\"\"\"\n filter_clauses = [\"(1=1)\"]\n\n if self.merged_tags_filter:\n filter_clauses.clear()\n\n for filter_tag_key, filter_tag_value in self.merged_tags_filter.items():\n if isinstance(filter_tag_value, bool) and filter_tag_value:\n filter_clauses.append(f\"(list_contains(map_keys(tags), '{filter_tag_key}'))\")\n elif isinstance(filter_tag_value, str):\n escaped_value = self._sql_escape(filter_tag_value)\n filter_clauses.append(\n f\"list_extract(map_extract(tags, '{filter_tag_key}'), 1) =\"\n f\" '{escaped_value}'\"\n )\n elif isinstance(filter_tag_value, list) and filter_tag_value:\n values_list = [f\"'{self._sql_escape(value)}'\" for value in filter_tag_value]\n filter_clauses.append(\n f\"list_extract(map_extract(tags, '{filter_tag_key}'), 1) IN\"\n f\" ({', '.join(values_list)})\"\n )\n\n return \" OR \".join(filter_clauses)\n\n def _generate_filtered_tags_clause(self) -> str:\n \"\"\"Prepare filtered tags clause by removing tags commonly ignored by OGR.\"\"\"\n tags_to_ignore = [\n \"area\",\n \"created_by\",\n \"converted_by\",\n \"source\",\n \"time\",\n \"ele\",\n \"note\",\n \"todo\",\n \"fixme\",\n \"FIXME\",\n \"openGeoDB:\",\n ]\n escaped_tags_to_ignore = [f\"'{tag}'\" for tag in tags_to_ignore]\n\n return f\"\"\"\n map_from_entries(\n [\n tag_entry\n for tag_entry in map_entries(tags)\n if not tag_entry.key in ({','.join(escaped_tags_to_ignore)})\n and not starts_with(tag_entry.key, 'openGeoDB:')\n ]\n ) as tags\n \"\"\"\n\n def _generate_elements_filter(\n self, filter_osm_ids: list[str], element_type: Literal[\"node\", \"way\", \"relation\"]\n ) -> str:\n filter_osm_relation_ids = [\n osm_id.replace(f\"{element_type}/\", \"\")\n for osm_id in filter_osm_ids\n if osm_id.startswith(f\"{element_type}/\")\n ]\n if not filter_osm_ids:\n filter_osm_ids_filter = \"1=1\"\n elif filter_osm_relation_ids:\n filter_osm_ids_filter = f\"id in ({','.join(filter_osm_relation_ids)})\"\n else:\n filter_osm_ids_filter = \"id IS NULL\"\n\n return filter_osm_ids_filter\n\n def _sql_escape(self, value: str) -> str:\n \"\"\"Escape value for SQL query.\"\"\"\n return value.replace(\"'\", \"''\")\n\n def _sql_to_parquet_file(self, sql_query: str, file_path: Path) -> \"duckdb.DuckDBPyRelation\":\n relation = self.connection.sql(sql_query)\n return self._save_parquet_file(relation, file_path)\n\n def _save_parquet_file(\n self, relation: \"duckdb.DuckDBPyRelation\", file_path: Path\n ) -> \"duckdb.DuckDBPyRelation\":\n self.connection.sql(f\"\"\"\n COPY (\n SELECT * FROM ({relation.sql_query()})\n ) TO '{file_path}' (FORMAT 'parquet', PER_THREAD_OUTPUT true, ROW_GROUP_SIZE 25000)\n \"\"\")\n return self.connection.sql(f\"\"\"\n SELECT * FROM read_parquet('{file_path}/**')\n \"\"\")\n\n def _calculate_unique_ids_to_parquet(\n self, file_path: Path, result_path: Optional[Path] = None\n ) -> \"duckdb.DuckDBPyRelation\":\n if result_path is None:\n result_path = file_path / \"distinct\"\n\n self.connection.sql(f\"\"\"\n COPY (\n SELECT id FROM read_parquet('{file_path}/**') GROUP BY id\n ) TO '{result_path}' (FORMAT 'parquet', PER_THREAD_OUTPUT true, ROW_GROUP_SIZE 25000)\n \"\"\")\n\n return self.connection.sql(f\"\"\"\n SELECT * FROM read_parquet('{result_path}/**')\n \"\"\")\n\n def _get_filtered_nodes_with_geometry(\n self,\n osm_parquet_files: ConvertedOSMParquetFiles,\n tmp_dir_name: str,\n ) -> \"duckdb.DuckDBPyRelation\":\n nodes_with_geometry = self.connection.sql(f\"\"\"\n SELECT\n n.id,\n n.tags,\n ST_Point(round(n.lon, 7), round(n.lat, 7)) geometry\n FROM ({osm_parquet_files.nodes_valid_with_tags.sql_query()}) n\n SEMI JOIN ({osm_parquet_files.nodes_filtered_ids.sql_query()}) fn ON n.id = fn.id\n \"\"\")\n nodes_parquet = self._save_parquet_file_with_geometry(\n relation=nodes_with_geometry,\n file_path=Path(tmp_dir_name) / \"filtered_nodes_with_geometry\",\n step_name=\"Saving filtered nodes with geometries\",\n step_number=\"19\",\n )\n return nodes_parquet\n\n def _get_ways_refs_with_nodes_structs(\n self,\n osm_parquet_files: ConvertedOSMParquetFiles,\n tmp_dir_name: str,\n ) -> \"duckdb.DuckDBPyRelation\":\n ways_refs_with_nodes_structs = self.connection.sql(f\"\"\"\n SELECT\n w.id,\n w.ref,\n w.ref_idx,\n struct_pack(x := round(n.lon, 7), y := round(n.lat, 7))::POINT_2D point\n FROM ({osm_parquet_files.nodes_valid_with_tags.sql_query()}) n\n JOIN ({osm_parquet_files.ways_with_unnested_nodes_refs.sql_query()}) w ON w.ref = n.id\n \"\"\")\n with TaskProgressSpinner(\"Saving required nodes with structs\", \"20\"):\n ways_refs_parquet = self._save_parquet_file(\n relation=ways_refs_with_nodes_structs,\n file_path=Path(tmp_dir_name) / \"ways_refs_with_nodes_structs\",\n )\n return ways_refs_parquet\n\n def _get_filtered_ways_with_linestrings(\n self,\n osm_parquet_files: ConvertedOSMParquetFiles,\n ways_refs_with_nodes_structs: \"duckdb.DuckDBPyRelation\",\n tmp_dir_name: str,\n ) -> \"duckdb.DuckDBPyRelation\":\n grouped_ways_path = Path(tmp_dir_name) / \"filtered_ways_grouped\"\n grouped_ways_tmp_path = Path(tmp_dir_name) / \"filtered_ways_tmp\"\n destination_dir_path = Path(tmp_dir_name) / \"filtered_ways_with_linestrings\"\n\n with TaskProgressSpinner(\"Grouping filtered ways\", \"21\"):\n groups = self._group_ways(\n ways_ids=osm_parquet_files.ways_filtered_ids,\n destination_dir_path=destination_dir_path,\n grouped_ways_tmp_path=grouped_ways_tmp_path,\n grouped_ways_path=grouped_ways_path,\n ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,\n )\n\n with TaskProgressBar(\"Saving filtered ways with linestrings\", \"22\") as bar:\n self._construct_ways_linestrings(\n bar=bar,\n groups=groups,\n destination_dir_path=destination_dir_path,\n grouped_ways_path=grouped_ways_path,\n )\n\n ways_parquet = self.connection.sql(f\"\"\"\n SELECT * FROM read_parquet('{destination_dir_path}/**')\n \"\"\")\n return ways_parquet\n\n def _get_required_ways_with_linestrings(\n self,\n osm_parquet_files: ConvertedOSMParquetFiles,\n ways_refs_with_nodes_structs: \"duckdb.DuckDBPyRelation\",\n tmp_dir_name: str,\n ) -> \"duckdb.DuckDBPyRelation\":\n grouped_ways_path = Path(tmp_dir_name) / \"required_ways_grouped\"\n grouped_ways_tmp_path = Path(tmp_dir_name) / \"required_ways_tmp\"\n destination_dir_path = Path(tmp_dir_name) / \"required_ways_with_linestrings\"\n\n with TaskProgressSpinner(\"Grouping required ways\", \"23\"):\n groups = self._group_ways(\n ways_ids=osm_parquet_files.ways_required_ids,\n destination_dir_path=destination_dir_path,\n grouped_ways_tmp_path=grouped_ways_tmp_path,\n grouped_ways_path=grouped_ways_path,\n ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,\n )\n\n with TaskProgressBar(\"Saving required ways with linestrings\", \"24\") as bar:\n self._construct_ways_linestrings(\n bar=bar,\n groups=groups,\n destination_dir_path=destination_dir_path,\n grouped_ways_path=grouped_ways_path,\n )\n\n ways_parquet = self.connection.sql(f\"\"\"\n SELECT * FROM read_parquet('{destination_dir_path}/**')\n \"\"\")\n return ways_parquet\n\n def _group_ways(\n self,\n ways_ids: \"duckdb.DuckDBPyRelation\",\n ways_refs_with_nodes_structs: \"duckdb.DuckDBPyRelation\",\n destination_dir_path: Path,\n grouped_ways_tmp_path: Path,\n grouped_ways_path: Path,\n ) -> int:\n total_required_ways = ways_ids.count(\"id\").fetchone()[0]\n\n destination_dir_path.mkdir(parents=True, exist_ok=True)\n grouped_ways_tmp_path.mkdir(parents=True, exist_ok=True)\n\n if total_required_ways == 0:\n empty_file_path = str(destination_dir_path / \"empty.parquet\")\n self.connection.sql(\"CREATE OR REPLACE TABLE x(id STRING, linestring LINESTRING_2D);\")\n self.connection.table(\"x\").to_parquet(empty_file_path)\n return -1\n\n groups = int(floor(total_required_ways / self.rows_per_bucket))\n\n ways_ids_grouped_relation = self.connection.sql(f\"\"\"\n SELECT id,\n floor(\n row_number() OVER () / {self.rows_per_bucket}\n )::INTEGER as \"group\",\n FROM ({ways_ids.sql_query()})\n \"\"\")\n grouped_ways_ids_with_group_path = grouped_ways_tmp_path / \"ids_with_group\"\n ways_ids_grouped_relation_parquet = self._save_parquet_file(\n relation=ways_ids_grouped_relation, file_path=grouped_ways_ids_with_group_path\n )\n\n ways_with_nodes_points_relation = self.connection.sql(f\"\"\"\n SELECT\n w.id, w.point, w.ref_idx, rw.\"group\"\n FROM ({ways_ids_grouped_relation_parquet.sql_query()}) rw\n JOIN ({ways_refs_with_nodes_structs.sql_query()}) w\n ON rw.id = w.id\n \"\"\")\n\n grouped_ways_ids_with_points_path = grouped_ways_tmp_path / \"ids_with_points\"\n ways_with_nodes_points_relation_parquet = self._save_parquet_file(\n relation=ways_with_nodes_points_relation, file_path=grouped_ways_ids_with_points_path\n )\n\n self.connection.sql(f\"\"\"\n COPY (\n SELECT\n id, point, ref_idx, \"group\"\n FROM ({ways_with_nodes_points_relation_parquet.sql_query()}) w\n ) TO '{grouped_ways_path}'\n (FORMAT 'parquet', PARTITION_BY (\"group\"), ROW_GROUP_SIZE 25000)\n \"\"\")\n\n return groups\n\n def _construct_ways_linestrings(\n self,\n bar: TaskProgressBar,\n groups: int,\n destination_dir_path: Path,\n grouped_ways_path: Path,\n ) -> None:\n grouped_ways_path.mkdir(parents=True, exist_ok=True)\n\n for group in bar.track(range(groups + 1)):\n current_ways_group_path = grouped_ways_path / f\"group={group}\"\n current_ways_group_relation = self.connection.sql(f\"\"\"\n SELECT * FROM read_parquet('{current_ways_group_path}/**')\n \"\"\")\n\n ways_with_linestrings = self.connection.sql(f\"\"\"\n SELECT id, list(point ORDER BY ref_idx ASC)::LINESTRING_2D linestring\n FROM ({current_ways_group_relation.sql_query()})\n GROUP BY id\n \"\"\")\n self._save_parquet_file(\n relation=ways_with_linestrings,\n file_path=destination_dir_path / f\"group={group}\",\n )\n\n def _get_filtered_ways_with_proper_geometry(\n self,\n osm_parquet_files: ConvertedOSMParquetFiles,\n required_ways_with_linestrings: \"duckdb.DuckDBPyRelation\",\n tmp_dir_name: str,\n ) -> \"duckdb.DuckDBPyRelation\":\n osm_way_polygon_features_filter_clauses = [\n \"list_contains(map_keys(raw_tags), 'area') AND \"\n \"list_extract(map_extract(raw_tags, 'area'), 1) = 'yes'\"\n ]\n\n for osm_tag_key in self.osm_way_polygon_features_config.all:\n osm_way_polygon_features_filter_clauses.append(\n f\"list_contains(map_keys(raw_tags), '{osm_tag_key}')\"\n )\n\n for osm_tag_key, osm_tag_values in self.osm_way_polygon_features_config.allowlist.items():\n escaped_values = \",\".join(\n [f\"'{self._sql_escape(osm_tag_value)}'\" for osm_tag_value in osm_tag_values]\n )\n osm_way_polygon_features_filter_clauses.append(\n f\"list_contains(map_keys(raw_tags), '{osm_tag_key}') AND\"\n f\" list_has_any(map_extract(raw_tags, '{osm_tag_key}'), [{escaped_values}])\"\n )\n\n for osm_tag_key, osm_tag_values in self.osm_way_polygon_features_config.denylist.items():\n escaped_values = \",\".join(\n [f\"'{self._sql_escape(osm_tag_value)}'\" for osm_tag_value in osm_tag_values]\n )\n osm_way_polygon_features_filter_clauses.append(\n f\"list_contains(map_keys(raw_tags), '{osm_tag_key}') AND NOT\"\n f\" list_has_any(map_extract(raw_tags, '{osm_tag_key}'), [{escaped_values}])\"\n )\n\n ways_with_proper_geometry = self.connection.sql(f\"\"\"\n WITH required_ways_with_linestrings AS (\n SELECT\n w.id,\n w.tags,\n w_l.linestring,\n -- Filter below is based on `_is_closed_way_a_polygon` function from OSMnx\n -- Filter values are built dynamically from a config.\n (\n -- if first and last nodes are the same\n ST_Equals(linestring[1]::POINT_2D, linestring[-1]::POINT_2D)\n -- if the element doesn't have any tags leave it as a Linestring\n AND raw_tags IS NOT NULL\n -- if the element is specifically tagged 'area':'no' -> LineString\n AND NOT (\n list_contains(map_keys(raw_tags), 'area')\n AND list_extract(map_extract(raw_tags, 'area'), 1) = 'no'\n )\n AND ({' OR '.join(osm_way_polygon_features_filter_clauses)})\n ) AS is_polygon\n FROM ({required_ways_with_linestrings.sql_query()}) w_l\n SEMI JOIN ({osm_parquet_files.ways_filtered_ids.sql_query()}) fw ON w_l.id = fw.id\n JOIN ({osm_parquet_files.ways_all_with_tags.sql_query()}) w ON w.id = w_l.id\n ),\n proper_geometries AS (\n SELECT\n id,\n tags,\n (CASE\n WHEN is_polygon\n THEN linestring_to_polygon_wkt(linestring)\n ELSE linestring_to_linestring_wkt(linestring)\n END)::GEOMETRY AS geometry\n FROM\n required_ways_with_linestrings w\n )\n SELECT id, tags, geometry FROM proper_geometries\n \"\"\")\n ways_parquet = self._save_parquet_file_with_geometry(\n relation=ways_with_proper_geometry,\n file_path=Path(tmp_dir_name) / \"filtered_ways_with_geometry\",\n step_name=\"Saving filtered ways with geometries\",\n step_number=\"25\",\n )\n return ways_parquet\n\n def _get_filtered_relations_with_geometry(\n self,\n osm_parquet_files: ConvertedOSMParquetFiles,\n required_ways_with_linestrings: \"duckdb.DuckDBPyRelation\",\n tmp_dir_name: str,\n ) -> \"duckdb.DuckDBPyRelation\":\n valid_relation_parts = self.connection.sql(f\"\"\"\n WITH unnested_relations AS (\n SELECT\n r.id,\n COALESCE(r.ref_role, 'outer') as ref_role,\n r.ref,\n linestring_to_linestring_wkt(w.linestring)::GEOMETRY as geometry\n FROM ({osm_parquet_files.relations_with_unnested_way_refs.sql_query()}) r\n SEMI JOIN ({osm_parquet_files.relations_filtered_ids.sql_query()}) fr\n ON r.id = fr.id\n JOIN ({required_ways_with_linestrings.sql_query()}) w\n ON w.id = r.ref\n ORDER BY r.id, r.ref_idx\n ),\n any_outer_refs AS (\n SELECT id, bool_or(ref_role == 'outer') any_outer_refs\n FROM unnested_relations\n GROUP BY id\n ),\n relations_with_geometries AS (\n SELECT\n x.id,\n CASE WHEN aor.any_outer_refs\n THEN x.ref_role ELSE 'outer'\n END as ref_role,\n x.geom geometry,\n row_number() OVER (PARTITION BY x.id) as geometry_id\n FROM (\n SELECT\n id,\n ref_role,\n UNNEST(\n ST_Dump(ST_LineMerge(ST_Collect(list(geometry)))), recursive := true\n ),\n FROM unnested_relations\n GROUP BY id, ref_role\n ) x\n JOIN any_outer_refs aor ON aor.id = x.id\n WHERE ST_NPoints(geom) >= 4\n ),\n valid_relations AS (\n SELECT id, is_valid\n FROM (\n SELECT\n id,\n bool_and(\n ST_Equals(ST_StartPoint(geometry), ST_EndPoint(geometry))\n ) is_valid\n FROM relations_with_geometries\n GROUP BY id\n )\n WHERE is_valid = true\n )\n SELECT * FROM relations_with_geometries\n SEMI JOIN valid_relations ON relations_with_geometries.id = valid_relations.id\n \"\"\")\n valid_relation_parts_parquet = self._save_parquet_file_with_geometry(\n relation=valid_relation_parts,\n file_path=Path(tmp_dir_name) / \"valid_relation_parts\",\n step_name=\"Saving valid relations parts\",\n step_number=\"26\",\n )\n relation_inner_parts = self.connection.sql(f\"\"\"\n SELECT id, geometry_id, ST_MakePolygon(geometry) geometry\n FROM ({valid_relation_parts_parquet.sql_query()})\n WHERE ref_role = 'inner'\n \"\"\")\n relation_inner_parts_parquet = self._save_parquet_file_with_geometry(\n relation=relation_inner_parts,\n file_path=Path(tmp_dir_name) / \"relation_inner_parts\",\n fix_geometries=True,\n step_name=\"Saving relations inner parts\",\n step_number=\"27\",\n )\n relation_outer_parts = self.connection.sql(f\"\"\"\n SELECT id, geometry_id, ST_MakePolygon(geometry) geometry\n FROM ({valid_relation_parts_parquet.sql_query()})\n WHERE ref_role = 'outer'\n \"\"\")\n relation_outer_parts_parquet = self._save_parquet_file_with_geometry(\n relation=relation_outer_parts,\n file_path=Path(tmp_dir_name) / \"relation_outer_parts\",\n fix_geometries=True,\n step_name=\"Saving relations outer parts\",\n step_number=\"28\",\n )\n relation_outer_parts_with_holes = self.connection.sql(f\"\"\"\n SELECT\n og.id,\n og.geometry_id,\n ST_Difference(any_value(og.geometry), ST_Union_Agg(ig.geometry)) geometry\n FROM ({relation_outer_parts_parquet.sql_query()}) og\n JOIN ({relation_inner_parts_parquet.sql_query()}) ig\n ON og.id = ig.id AND ST_WITHIN(ig.geometry, og.geometry)\n GROUP BY og.id, og.geometry_id\n \"\"\")\n relation_outer_parts_with_holes_parquet = self._save_parquet_file_with_geometry(\n relation=relation_outer_parts_with_holes,\n file_path=Path(tmp_dir_name) / \"relation_outer_parts_with_holes\",\n step_name=\"Saving relations outer parts with holes\",\n step_number=\"29\",\n )\n relation_outer_parts_without_holes = self.connection.sql(f\"\"\"\n SELECT\n og.id,\n og.geometry_id,\n og.geometry\n FROM ({relation_outer_parts_parquet.sql_query()}) og\n ANTI JOIN ({relation_outer_parts_with_holes_parquet.sql_query()}) ogwh\n ON og.id = ogwh.id AND og.geometry_id = ogwh.geometry_id\n \"\"\")\n relation_outer_parts_without_holes_parquet = self._save_parquet_file_with_geometry(\n relation=relation_outer_parts_without_holes,\n file_path=Path(tmp_dir_name) / \"relation_outer_parts_without_holes\",\n step_name=\"Saving relations outer parts without holes\",\n step_number=\"30\",\n )\n relations_with_geometry = self.connection.sql(f\"\"\"\n WITH unioned_outer_geometries AS (\n SELECT id, geometry\n FROM ({relation_outer_parts_with_holes_parquet.sql_query()})\n UNION ALL\n SELECT id, geometry\n FROM ({relation_outer_parts_without_holes_parquet.sql_query()})\n ),\n final_geometries AS (\n SELECT id, ST_Union_Agg(geometry) geometry\n FROM unioned_outer_geometries\n GROUP BY id\n )\n SELECT r_g.id, r.tags, r_g.geometry\n FROM final_geometries r_g\n JOIN ({osm_parquet_files.relations_all_with_tags.sql_query()}) r\n ON r.id = r_g.id\n \"\"\")\n relations_parquet = self._save_parquet_file_with_geometry(\n relation=relations_with_geometry,\n file_path=Path(tmp_dir_name) / \"filtered_relations_with_geometry\",\n step_name=\"Saving filtered relations with geometries\",\n step_number=\"31\",\n )\n return relations_parquet\n\n def _save_parquet_file_with_geometry(\n self,\n relation: \"duckdb.DuckDBPyRelation\",\n file_path: Path,\n step_name: str,\n step_number: str,\n fix_geometries: bool = False,\n ) -> \"duckdb.DuckDBPyRelation\":\n if not fix_geometries:\n with TaskProgressSpinner(step_name, step_number):\n self.connection.sql(f\"\"\"\n COPY (\n SELECT\n * EXCLUDE (geometry), ST_AsWKB(geometry) geometry_wkb\n FROM ({relation.sql_query()})\n ) TO '{file_path}' (\n FORMAT 'parquet',\n PER_THREAD_OUTPUT true,\n ROW_GROUP_SIZE 25000\n )\n \"\"\")\n else:\n valid_path = file_path / \"valid\"\n invalid_path = file_path / \"invalid\"\n fixed_path = file_path / \"fixed\"\n\n valid_path.mkdir(parents=True, exist_ok=True)\n invalid_path.mkdir(parents=True, exist_ok=True)\n fixed_path.mkdir(parents=True, exist_ok=True)\n\n # Save valid features\n with TaskProgressSpinner(f\"{step_name} - valid geometries\", f\"{step_number}.1\"):\n self.connection.sql(f\"\"\"\n COPY (\n SELECT\n * EXCLUDE (geometry), ST_AsWKB(geometry) geometry_wkb\n FROM ({relation.sql_query()})\n WHERE ST_IsValid(geometry)\n ) TO '{valid_path}' (\n FORMAT 'parquet',\n PER_THREAD_OUTPUT true,\n ROW_GROUP_SIZE 25000\n )\n \"\"\")\n\n # Save invalid features\n with TaskProgressSpinner(f\"{step_name} - invalid geometries\", f\"{step_number}.2\"):\n self.connection.sql(f\"\"\"\n COPY (\n SELECT\n * EXCLUDE (geometry), ST_AsWKB(geometry) geometry_wkb,\n floor(\n row_number() OVER () / {self.rows_per_bucket}\n )::INTEGER as \"group\",\n FROM ({relation.sql_query()})\n WHERE NOT ST_IsValid(geometry)\n ) TO '{invalid_path}' (\n FORMAT 'parquet', PARTITION_BY (\"group\"), ROW_GROUP_SIZE 25000\n )\n \"\"\")\n\n # Fix invalid features\n total_groups = 0\n while (invalid_path / f\"group={total_groups}\").exists():\n total_groups += 1\n\n if total_groups > 0:\n with TaskProgressBar(\n f\"{step_name} - fixing invalid geometries\", f\"{step_number}.3\"\n ) as bar:\n for group_id in bar.track(range(total_groups)):\n current_invalid_features_group_path = invalid_path / f\"group={group_id}\"\n current_invalid_features_group_table = pq.read_table(\n current_invalid_features_group_path\n ).drop(\"group\")\n valid_geometry_column = ga.as_wkb(\n ga.to_geopandas(\n ga.with_crs(\n current_invalid_features_group_table.column(\"geometry_wkb\"),\n WGS84_CRS,\n )\n ).make_valid(),\n )\n current_invalid_features_group_table = (\n current_invalid_features_group_table.drop(\"geometry_wkb\")\n )\n\n current_invalid_features_group_table = (\n current_invalid_features_group_table.append_column(\n \"geometry_wkb\", valid_geometry_column\n )\n )\n pq.write_table(\n current_invalid_features_group_table,\n fixed_path / f\"data_{group_id}.parquet\",\n )\n\n self._delete_directories(invalid_path.parent, [\"invalid\"])\n\n return self.connection.sql(f\"\"\"\n SELECT * EXCLUDE (geometry_wkb), ST_GeomFromWKB(geometry_wkb) geometry\n FROM read_parquet('{file_path}/**')\n \"\"\")\n\n def _concatenate_results_to_geoparquet(\n self,\n parsed_data: ParsedOSMFeatures,\n tmp_dir_name: str,\n save_file_path: Path,\n explode_tags: bool,\n ) -> None:\n select_clauses = [\n *self._generate_osm_tags_sql_select(parsed_data, explode_tags),\n \"geometry\",\n ]\n\n node_select_clauses = [\"'node/' || id as feature_id\", *select_clauses]\n way_select_clauses = [\"'way/' || id as feature_id\", *select_clauses]\n relation_select_clauses = [\"'relation/' || id as feature_id\", *select_clauses]\n\n unioned_features = self.connection.sql(f\"\"\"\n SELECT {', '.join(node_select_clauses)}\n FROM ({parsed_data.nodes.sql_query()}) n\n UNION ALL\n SELECT {', '.join(way_select_clauses)}\n FROM ({parsed_data.ways.sql_query()}) w\n UNION ALL\n SELECT {', '.join(relation_select_clauses)}\n FROM ({parsed_data.relations.sql_query()}) r\n \"\"\")\n\n grouped_features = self._parse_features_relation_to_groups(unioned_features, explode_tags)\n\n valid_features_full_relation = self.connection.sql(f\"\"\"\n SELECT * FROM ({grouped_features.sql_query()})\n WHERE ST_IsValid(geometry)\n \"\"\")\n\n valid_features_parquet_path = Path(tmp_dir_name) / \"osm_valid_elements\"\n valid_features_parquet_relation = self._save_parquet_file_with_geometry(\n valid_features_full_relation,\n valid_features_parquet_path,\n step_name=\"Saving valid features\",\n step_number=\"32.1\",\n )\n\n valid_features_parquet_table = pq.read_table(valid_features_parquet_path)\n\n is_empty = valid_features_parquet_table.num_rows == 0\n\n if not is_empty:\n geometry_column = ga.as_wkb(\n ga.with_crs(valid_features_parquet_table.column(\"geometry_wkb\"), WGS84_CRS)\n )\n else:\n geometry_column = ga.as_wkb(gpd.GeoSeries([], crs=WGS84_CRS))\n\n valid_features_parquet_table = valid_features_parquet_table.append_column(\n GEOMETRY_COLUMN, geometry_column\n ).drop(\"geometry_wkb\")\n\n parquet_tables = [valid_features_parquet_table]\n\n invalid_features_full_relation = self.connection.sql(f\"\"\"\n SELECT * FROM ({grouped_features.sql_query()}) a\n ANTI JOIN ({valid_features_parquet_relation.sql_query()}) b\n ON a.feature_id = b.feature_id\n \"\"\")\n\n total_nodes = parsed_data.nodes.count(\"id\").fetchone()[0]\n total_ways = parsed_data.ways.count(\"id\").fetchone()[0]\n total_relations = parsed_data.relations.count(\"id\").fetchone()[0]\n total_features = total_nodes + total_ways + total_relations\n\n valid_features = valid_features_parquet_relation.count(\"feature_id\").fetchone()[0]\n\n invalid_features = total_features - valid_features\n\n if invalid_features > 0:\n with TaskProgressSpinner(\"Grouping invalid features\", \"32.2\"):\n groups = floor(invalid_features / self.rows_per_bucket)\n grouped_invalid_features_result_parquet = (\n Path(tmp_dir_name) / \"osm_invalid_elements_grouped\"\n )\n self.connection.sql(f\"\"\"\n COPY (\n SELECT\n * EXCLUDE (geometry), ST_AsWKB(geometry) geometry_wkb,\n floor(\n row_number() OVER () / {self.rows_per_bucket}\n )::INTEGER as \"group\",\n FROM ({invalid_features_full_relation.sql_query()})\n ) TO '{grouped_invalid_features_result_parquet}'\n (FORMAT 'parquet', PARTITION_BY (\"group\"), ROW_GROUP_SIZE 25000)\n \"\"\")\n\n with TaskProgressBar(\"Fixing invalid features\", \"32.3\") as bar:\n for group in bar.track(range(groups + 1)):\n current_invalid_features_group_path = (\n grouped_invalid_features_result_parquet / f\"group={group}\"\n )\n current_invalid_features_group_table = pq.read_table(\n current_invalid_features_group_path\n ).drop(\"group\")\n valid_geometry_column = ga.as_wkb(\n ga.to_geopandas(\n ga.with_crs(\n current_invalid_features_group_table.column(\"geometry_wkb\"),\n WGS84_CRS,\n )\n ).make_valid()\n )\n\n current_invalid_features_group_table = (\n current_invalid_features_group_table.append_column(\n GEOMETRY_COLUMN, valid_geometry_column\n )\n )\n current_invalid_features_group_table = (\n current_invalid_features_group_table.drop(\"geometry_wkb\")\n )\n parquet_tables.append(current_invalid_features_group_table)\n\n joined_parquet_table: pa.Table = pa.concat_tables(parquet_tables)\n\n is_empty = joined_parquet_table.num_rows == 0\n\n empty_columns = []\n for column_name in joined_parquet_table.column_names:\n if column_name in (FEATURES_INDEX, GEOMETRY_COLUMN):\n continue\n if (\n is_empty\n or pa.compute.all(\n pa.compute.is_null(joined_parquet_table.column(column_name))\n ).as_py()\n ):\n empty_columns.append(column_name)\n\n if empty_columns:\n joined_parquet_table = joined_parquet_table.drop(empty_columns)\n\n with TaskProgressSpinner(\"Saving final geoparquet file\", \"33\"):\n io.write_geoparquet_table( # type: ignore\n joined_parquet_table, save_file_path, primary_geometry_column=GEOMETRY_COLUMN\n )\n\n def _generate_osm_tags_sql_select(\n self, parsed_data: ParsedOSMFeatures, explode_tags: bool\n ) -> list[str]:\n \"\"\"Prepare features filter clauses based on tags filter.\"\"\"\n osm_tag_keys_select_clauses = []\n\n # TODO: elif keep other tags\n if not self.merged_tags_filter and not explode_tags:\n osm_tag_keys_select_clauses = [\"tags\"]\n elif not self.merged_tags_filter and explode_tags:\n osm_tag_keys = set()\n for elements in (\n parsed_data.nodes,\n parsed_data.ways,\n parsed_data.relations,\n ):\n found_tag_keys = [row[0] for row in self.connection.sql(f\"\"\"\n SELECT DISTINCT UNNEST(map_keys(tags)) tag_key\n FROM ({elements.sql_query()})\n \"\"\").fetchall()]\n osm_tag_keys.update(found_tag_keys)\n osm_tag_keys_select_clauses = [\n f\"list_extract(map_extract(tags, '{osm_tag_key}'), 1) as \\\"{osm_tag_key}\\\"\"\n for osm_tag_key in sorted(list(osm_tag_keys))\n ]\n elif self.merged_tags_filter and not explode_tags:\n filter_tag_clauses = []\n for filter_tag_key, filter_tag_value in self.merged_tags_filter.items():\n if isinstance(filter_tag_value, bool) and filter_tag_value:\n filter_tag_clauses.append(f\"tag_entry.key = '{filter_tag_key}'\")\n elif isinstance(filter_tag_value, str):\n escaped_value = self._sql_escape(filter_tag_value)\n filter_tag_clauses.append(\n f\"(tag_entry.key = '{filter_tag_key}' AND tag_entry.value =\"\n f\" '{escaped_value}')\"\n )\n elif isinstance(filter_tag_value, list) and filter_tag_value:\n values_list = [f\"'{self._sql_escape(value)}'\" for value in filter_tag_value]\n filter_tag_clauses.append(\n f\"(tag_entry.key = '{filter_tag_key}' AND tag_entry.value IN\"\n f\" ({', '.join(values_list)}))\"\n )\n osm_tag_keys_select_clauses = [f\"\"\"\n map_from_entries(\n [\n tag_entry\n for tag_entry in map_entries(tags)\n if {\" OR \".join(filter_tag_clauses)}\n ]\n ) as tags\n \"\"\"]\n elif self.merged_tags_filter and explode_tags:\n for filter_tag_key, filter_tag_value in self.merged_tags_filter.items():\n if isinstance(filter_tag_value, bool) and filter_tag_value:\n osm_tag_keys_select_clauses.append(\n f\"list_extract(map_extract(tags, '{filter_tag_key}'), 1) as\"\n f' \"{filter_tag_key}\"'\n )\n elif isinstance(filter_tag_value, str):\n escaped_value = self._sql_escape(filter_tag_value)\n osm_tag_keys_select_clauses.append(f\"\"\"\n CASE WHEN list_extract(\n map_extract(tags, '{filter_tag_key}'), 1\n ) = '{escaped_value}'\n THEN '{escaped_value}'\n ELSE NULL\n END as \"{filter_tag_key}\"\n \"\"\")\n elif isinstance(filter_tag_value, list) and filter_tag_value:\n values_list = [f\"'{self._sql_escape(value)}'\" for value in filter_tag_value]\n osm_tag_keys_select_clauses.append(f\"\"\"\n CASE WHEN list_extract(\n map_extract(tags, '{filter_tag_key}'), 1\n ) IN ({', '.join(values_list)})\n THEN list_extract(map_extract(tags, '{filter_tag_key}'), 1)\n ELSE NULL\n END as \"{filter_tag_key}\"\n \"\"\")\n\n if len(osm_tag_keys_select_clauses) > 100:\n warnings.warn(\n \"Select clause contains more than 100 columns\"\n f\" (found {len(osm_tag_keys_select_clauses)} columns).\"\n \" Query might fail with insufficient memory resources.\"\n \" Consider applying more restrictive OsmTagsFilter for parsing.\",\n stacklevel=1,\n )\n\n return osm_tag_keys_select_clauses\n\n def _parse_features_relation_to_groups(\n self,\n features_relation: \"duckdb.DuckDBPyRelation\",\n explode_tags: bool,\n ) -> \"duckdb.DuckDBPyRelation\":\n \"\"\"\n Optionally group raw OSM features into groups defined in `GroupedOsmTagsFilter`.\n\n Creates new features based on definition from `GroupedOsmTagsFilter`.\n Returns transformed DuckDB relation with columns based on group names from the filter.\n Values are built by concatenation of matching tag key and value with\n an equal sign (eg. amenity=parking). Since many tags can match a definition\n of a single group, a first match is used as a feature value.\n\n Args:\n features_relation (duckdb.DuckDBPyRelation): Generated features from the loader.\n explode_tags (bool): Whether to split tags into columns based on OSM tag keys.\n\n Returns:\n duckdb.DuckDBPyRelation: Parsed features_relation.\n \"\"\"\n if not self.tags_filter or not is_expected_type(self.tags_filter, GroupedOsmTagsFilter):\n return features_relation\n\n grouped_features_relation: \"duckdb.DuckDBPyRelation\"\n grouped_tags_filter = cast(GroupedOsmTagsFilter, self.tags_filter)\n\n if explode_tags:\n case_clauses = []\n for group_name in sorted(grouped_tags_filter.keys()):\n osm_filter = grouped_tags_filter[group_name]\n case_when_clauses = []\n for osm_tag_key, osm_tag_value in osm_filter.items():\n if isinstance(osm_tag_value, bool) and osm_tag_value:\n case_when_clauses.append(\n f\"WHEN \\\"{osm_tag_key}\\\" IS NOT NULL THEN '{osm_tag_key}=' ||\"\n f' \"{osm_tag_key}\"'\n )\n elif isinstance(osm_tag_value, str):\n escaped_value = self._sql_escape(osm_tag_value)\n case_when_clauses.append(\n f\"WHEN \\\"{osm_tag_key}\\\" = '{escaped_value}' THEN '{osm_tag_key}=' ||\"\n f' \"{osm_tag_key}\"'\n )\n elif isinstance(osm_tag_value, list) and osm_tag_value:\n values_list = [f\"'{self._sql_escape(value)}'\" for value in osm_tag_value]\n case_when_clauses.append(\n f\"WHEN \\\"{osm_tag_key}\\\" IN ({', '.join(values_list)}) THEN\"\n f\" '{osm_tag_key}=' || \\\"{osm_tag_key}\\\"\"\n )\n case_clause = f'CASE {\" \".join(case_when_clauses)} END AS \"{group_name}\"'\n case_clauses.append(case_clause)\n\n joined_case_clauses = \", \".join(case_clauses)\n grouped_features_relation = self.connection.sql(f\"\"\"\n SELECT feature_id, {joined_case_clauses}, geometry\n FROM ({features_relation.sql_query()})\n \"\"\")\n else:\n case_clauses = []\n group_names = sorted(grouped_tags_filter.keys())\n for group_name in group_names:\n osm_filter = grouped_tags_filter[group_name]\n case_when_clauses = []\n for osm_tag_key, osm_tag_value in osm_filter.items():\n element_clause = f\"element_at(tags, '{osm_tag_key}')[1]\"\n if isinstance(osm_tag_value, bool) and osm_tag_value:\n case_when_clauses.append(\n f\"WHEN {element_clause} IS NOT NULL THEN '{osm_tag_key}=' ||\"\n f\" {element_clause}\"\n )\n elif isinstance(osm_tag_value, str):\n escaped_value = self._sql_escape(osm_tag_value)\n case_when_clauses.append(\n f\"WHEN {element_clause} = '{escaped_value}' THEN '{osm_tag_key}=' ||\"\n f\" {element_clause}\"\n )\n elif isinstance(osm_tag_value, list) and osm_tag_value:\n values_list = [f\"'{self._sql_escape(value)}'\" for value in osm_tag_value]\n case_when_clauses.append(\n f\"WHEN {element_clause} IN ({', '.join(values_list)}) THEN\"\n f\" '{osm_tag_key}=' || {element_clause}\"\n )\n case_clause = f'CASE {\" \".join(case_when_clauses)} END'\n case_clauses.append(case_clause)\n\n group_names_as_sql_strings = [f\"'{group_name}'\" for group_name in group_names]\n groups_map = (\n f\"map([{', '.join(group_names_as_sql_strings)}], [{', '.join(case_clauses)}])\"\n )\n non_null_groups_map = f\"\"\"map_from_entries(\n [\n tag_entry\n for tag_entry in map_entries({groups_map})\n if tag_entry.value IS NOT NULL\n ]\n ) as tags\"\"\"\n\n grouped_features_relation = self.connection.sql(f\"\"\"\n SELECT feature_id, {non_null_groups_map}, geometry\n FROM ({features_relation.sql_query()})\n \"\"\")\n\n return grouped_features_relation" } ]
import platform import re import subprocess import warnings import duckdb import geopandas as gpd import pandas as pd import pyogrio import pytest import six from collections.abc import Iterable from pathlib import Path from typing import Optional, Union, cast from unittest import TestCase from parametrization import Parametrization as P from shapely import hausdorff_distance from shapely.geometry import MultiPolygon, Polygon from shapely.geometry.base import BaseGeometry from shapely.ops import unary_union from srai.geometry import remove_interiors from srai.loaders.download import download_file from srai.loaders.osm_loaders.filters import GEOFABRIK_LAYERS, HEX2VEC_FILTER from quackosm._constants import FEATURES_INDEX from quackosm._osm_tags_filters import OsmTagsFilter from quackosm.pbf_file_reader import PbfFileReader
17,811
"""Tests for PbfFileReader.""" ut = TestCase() LFS_DIRECTORY_URL = "https://github.com/kraina-ai/srai-test-files/raw/main/files/" @pytest.mark.parametrize( # type: ignore "test_file_name,query,expected_result_length,expected_features_columns_length", [ ( "d17f922ed15e9609013a6b895e1e7af2d49158f03586f2c675d17b760af3452e.osm.pbf", None, 678, 271, ), ( "eb2848d259345ce7dfe8af34fd1ab24503bb0b952e04e872c87c55550fa50fbf.osm.pbf", None, 1, 22, ), ("529cdcbb7a3cc103658ef31b39bed24984e421127d319c867edf2f86ff3bb098.osm.pbf", None, 0, 0), ( "d17f922ed15e9609013a6b895e1e7af2d49158f03586f2c675d17b760af3452e.osm.pbf", HEX2VEC_FILTER, 97, 10, ), ( "eb2848d259345ce7dfe8af34fd1ab24503bb0b952e04e872c87c55550fa50fbf.osm.pbf", HEX2VEC_FILTER, 0, 0, ), ( "d17f922ed15e9609013a6b895e1e7af2d49158f03586f2c675d17b760af3452e.osm.pbf", GEOFABRIK_LAYERS, 433, 22, ), ( "eb2848d259345ce7dfe8af34fd1ab24503bb0b952e04e872c87c55550fa50fbf.osm.pbf", GEOFABRIK_LAYERS, 0, 0, ), ], ) def test_pbf_reader( test_file_name: str,
"""Tests for PbfFileReader.""" ut = TestCase() LFS_DIRECTORY_URL = "https://github.com/kraina-ai/srai-test-files/raw/main/files/" @pytest.mark.parametrize( # type: ignore "test_file_name,query,expected_result_length,expected_features_columns_length", [ ( "d17f922ed15e9609013a6b895e1e7af2d49158f03586f2c675d17b760af3452e.osm.pbf", None, 678, 271, ), ( "eb2848d259345ce7dfe8af34fd1ab24503bb0b952e04e872c87c55550fa50fbf.osm.pbf", None, 1, 22, ), ("529cdcbb7a3cc103658ef31b39bed24984e421127d319c867edf2f86ff3bb098.osm.pbf", None, 0, 0), ( "d17f922ed15e9609013a6b895e1e7af2d49158f03586f2c675d17b760af3452e.osm.pbf", HEX2VEC_FILTER, 97, 10, ), ( "eb2848d259345ce7dfe8af34fd1ab24503bb0b952e04e872c87c55550fa50fbf.osm.pbf", HEX2VEC_FILTER, 0, 0, ), ( "d17f922ed15e9609013a6b895e1e7af2d49158f03586f2c675d17b760af3452e.osm.pbf", GEOFABRIK_LAYERS, 433, 22, ), ( "eb2848d259345ce7dfe8af34fd1ab24503bb0b952e04e872c87c55550fa50fbf.osm.pbf", GEOFABRIK_LAYERS, 0, 0, ), ], ) def test_pbf_reader( test_file_name: str,
query: OsmTagsFilter,
1
2023-12-28 11:26:41+00:00
24k
KyanChen/TTP
tests/test_datasets/test_dataset.py
[ { "identifier": "ADE20KDataset", "path": "mmseg/datasets/ade.py", "snippet": "class ADE20KDataset(BaseSegDataset):\n \"\"\"ADE20K dataset.\n\n In segmentation map annotation for ADE20K, 0 stands for background, which\n is not included in 150 categories. ``reduce_zero_label`` is fixed to True.\n The ``img_suffix`` is fixed to '.jpg' and ``seg_map_suffix`` is fixed to\n '.png'.\n \"\"\"\n METAINFO = dict(\n classes=('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road',\n 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk',\n 'person', 'earth', 'door', 'table', 'mountain', 'plant',\n 'curtain', 'chair', 'car', 'water', 'painting', 'sofa',\n 'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchair',\n 'seat', 'fence', 'desk', 'rock', 'wardrobe', 'lamp',\n 'bathtub', 'railing', 'cushion', 'base', 'box', 'column',\n 'signboard', 'chest of drawers', 'counter', 'sand', 'sink',\n 'skyscraper', 'fireplace', 'refrigerator', 'grandstand',\n 'path', 'stairs', 'runway', 'case', 'pool table', 'pillow',\n 'screen door', 'stairway', 'river', 'bridge', 'bookcase',\n 'blind', 'coffee table', 'toilet', 'flower', 'book', 'hill',\n 'bench', 'countertop', 'stove', 'palm', 'kitchen island',\n 'computer', 'swivel chair', 'boat', 'bar', 'arcade machine',\n 'hovel', 'bus', 'towel', 'light', 'truck', 'tower',\n 'chandelier', 'awning', 'streetlight', 'booth',\n 'television receiver', 'airplane', 'dirt track', 'apparel',\n 'pole', 'land', 'bannister', 'escalator', 'ottoman', 'bottle',\n 'buffet', 'poster', 'stage', 'van', 'ship', 'fountain',\n 'conveyer belt', 'canopy', 'washer', 'plaything',\n 'swimming pool', 'stool', 'barrel', 'basket', 'waterfall',\n 'tent', 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food',\n 'step', 'tank', 'trade name', 'microwave', 'pot', 'animal',\n 'bicycle', 'lake', 'dishwasher', 'screen', 'blanket',\n 'sculpture', 'hood', 'sconce', 'vase', 'traffic light',\n 'tray', 'ashcan', 'fan', 'pier', 'crt screen', 'plate',\n 'monitor', 'bulletin board', 'shower', 'radiator', 'glass',\n 'clock', 'flag'),\n palette=[[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],\n [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],\n [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],\n [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],\n [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],\n [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],\n [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],\n [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],\n [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],\n [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],\n [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],\n [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],\n [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],\n [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],\n [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],\n [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],\n [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],\n [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],\n [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],\n [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],\n [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],\n [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],\n [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],\n [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],\n [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],\n [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],\n [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],\n [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],\n [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],\n [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],\n [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],\n [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],\n [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],\n [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],\n [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],\n [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],\n [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],\n [102, 255, 0], [92, 0, 255]])\n\n def __init__(self,\n img_suffix='.jpg',\n seg_map_suffix='.png',\n reduce_zero_label=True,\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix,\n seg_map_suffix=seg_map_suffix,\n reduce_zero_label=reduce_zero_label,\n **kwargs)" }, { "identifier": "BaseSegDataset", "path": "mmseg/datasets/basesegdataset.py", "snippet": "class BaseSegDataset(BaseDataset):\n \"\"\"Custom dataset for semantic segmentation. An example of file structure\n is as followed.\n\n .. code-block:: none\n\n ├── data\n │ ├── my_dataset\n │ │ ├── img_dir\n │ │ │ ├── train\n │ │ │ │ ├── xxx{img_suffix}\n │ │ │ │ ├── yyy{img_suffix}\n │ │ │ │ ├── zzz{img_suffix}\n │ │ │ ├── val\n │ │ ├── ann_dir\n │ │ │ ├── train\n │ │ │ │ ├── xxx{seg_map_suffix}\n │ │ │ │ ├── yyy{seg_map_suffix}\n │ │ │ │ ├── zzz{seg_map_suffix}\n │ │ │ ├── val\n\n The img/gt_semantic_seg pair of BaseSegDataset should be of the same\n except suffix. A valid img/gt_semantic_seg filename pair should be like\n ``xxx{img_suffix}`` and ``xxx{seg_map_suffix}`` (extension is also included\n in the suffix). If split is given, then ``xxx`` is specified in txt file.\n Otherwise, all files in ``img_dir/``and ``ann_dir`` will be loaded.\n Please refer to ``docs/en/tutorials/new_dataset.md`` for more details.\n\n\n Args:\n ann_file (str): Annotation file path. Defaults to ''.\n metainfo (dict, optional): Meta information for dataset, such as\n specify classes to load. Defaults to None.\n data_root (str, optional): The root directory for ``data_prefix`` and\n ``ann_file``. Defaults to None.\n data_prefix (dict, optional): Prefix for training data. Defaults to\n dict(img_path=None, seg_map_path=None).\n img_suffix (str): Suffix of images. Default: '.jpg'\n seg_map_suffix (str): Suffix of segmentation maps. Default: '.png'\n filter_cfg (dict, optional): Config for filter data. Defaults to None.\n indices (int or Sequence[int], optional): Support using first few\n data in annotation file to facilitate training/testing on a smaller\n dataset. Defaults to None which means using all ``data_infos``.\n serialize_data (bool, optional): Whether to hold memory using\n serialized objects, when enabled, data loader workers can use\n shared RAM from master process instead of making a copy. Defaults\n to True.\n pipeline (list, optional): Processing pipeline. Defaults to [].\n test_mode (bool, optional): ``test_mode=True`` means in test phase.\n Defaults to False.\n lazy_init (bool, optional): Whether to load annotation during\n instantiation. In some cases, such as visualization, only the meta\n information of the dataset is needed, which is not necessary to\n load annotation file. ``Basedataset`` can skip load annotations to\n save time by set ``lazy_init=True``. Defaults to False.\n max_refetch (int, optional): If ``Basedataset.prepare_data`` get a\n None img. The maximum extra number of cycles to get a valid\n image. Defaults to 1000.\n ignore_index (int): The label index to be ignored. Default: 255\n reduce_zero_label (bool): Whether to mark label zero as ignored.\n Default to False.\n backend_args (dict, Optional): Arguments to instantiate a file backend.\n See https://mmengine.readthedocs.io/en/latest/api/fileio.htm\n for details. Defaults to None.\n Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.\n \"\"\"\n METAINFO: dict = dict()\n\n def __init__(self,\n ann_file: str = '',\n img_suffix='.jpg',\n seg_map_suffix='.png',\n metainfo: Optional[dict] = None,\n data_root: Optional[str] = None,\n data_prefix: dict = dict(img_path='', seg_map_path=''),\n filter_cfg: Optional[dict] = None,\n indices: Optional[Union[int, Sequence[int]]] = None,\n serialize_data: bool = True,\n pipeline: List[Union[dict, Callable]] = [],\n test_mode: bool = False,\n lazy_init: bool = False,\n max_refetch: int = 1000,\n ignore_index: int = 255,\n reduce_zero_label: bool = False,\n backend_args: Optional[dict] = None) -> None:\n\n self.img_suffix = img_suffix\n self.seg_map_suffix = seg_map_suffix\n self.ignore_index = ignore_index\n self.reduce_zero_label = reduce_zero_label\n self.backend_args = backend_args.copy() if backend_args else None\n\n self.data_root = data_root\n self.data_prefix = copy.copy(data_prefix)\n self.ann_file = ann_file\n self.filter_cfg = copy.deepcopy(filter_cfg)\n self._indices = indices\n self.serialize_data = serialize_data\n self.test_mode = test_mode\n self.max_refetch = max_refetch\n self.data_list: List[dict] = []\n self.data_bytes: np.ndarray\n\n # Set meta information.\n self._metainfo = self._load_metainfo(copy.deepcopy(metainfo))\n\n # Get label map for custom classes\n new_classes = self._metainfo.get('classes', None)\n self.label_map = self.get_label_map(new_classes)\n self._metainfo.update(\n dict(\n label_map=self.label_map,\n reduce_zero_label=self.reduce_zero_label))\n\n # Update palette based on label map or generate palette\n # if it is not defined\n updated_palette = self._update_palette()\n self._metainfo.update(dict(palette=updated_palette))\n\n # Join paths.\n if self.data_root is not None:\n self._join_prefix()\n\n # Build pipeline.\n self.pipeline = Compose(pipeline)\n # Full initialize the dataset.\n if not lazy_init:\n self.full_init()\n\n if test_mode:\n assert self._metainfo.get('classes') is not None, \\\n 'dataset metainfo `classes` should be specified when testing'\n\n @classmethod\n def get_label_map(cls,\n new_classes: Optional[Sequence] = None\n ) -> Union[Dict, None]:\n \"\"\"Require label mapping.\n\n The ``label_map`` is a dictionary, its keys are the old label ids and\n its values are the new label ids, and is used for changing pixel\n labels in load_annotations. If and only if old classes in cls.METAINFO\n is not equal to new classes in self._metainfo and nether of them is not\n None, `label_map` is not None.\n\n Args:\n new_classes (list, tuple, optional): The new classes name from\n metainfo. Default to None.\n\n\n Returns:\n dict, optional: The mapping from old classes in cls.METAINFO to\n new classes in self._metainfo\n \"\"\"\n old_classes = cls.METAINFO.get('classes', None)\n if (new_classes is not None and old_classes is not None\n and list(new_classes) != list(old_classes)):\n\n label_map = {}\n if not set(new_classes).issubset(cls.METAINFO['classes']):\n raise ValueError(\n f'new classes {new_classes} is not a '\n f'subset of classes {old_classes} in METAINFO.')\n for i, c in enumerate(old_classes):\n if c not in new_classes:\n label_map[i] = 255\n else:\n label_map[i] = new_classes.index(c)\n return label_map\n else:\n return None\n\n def _update_palette(self) -> list:\n \"\"\"Update palette after loading metainfo.\n\n If length of palette is equal to classes, just return the palette.\n If palette is not defined, it will randomly generate a palette.\n If classes is updated by customer, it will return the subset of\n palette.\n\n Returns:\n Sequence: Palette for current dataset.\n \"\"\"\n palette = self._metainfo.get('palette', [])\n classes = self._metainfo.get('classes', [])\n # palette does match classes\n if len(palette) == len(classes):\n return palette\n\n if len(palette) == 0:\n # Get random state before set seed, and restore\n # random state later.\n # It will prevent loss of randomness, as the palette\n # may be different in each iteration if not specified.\n # See: https://github.com/open-mmlab/mmdetection/issues/5844\n state = np.random.get_state()\n np.random.seed(42)\n # random palette\n new_palette = np.random.randint(\n 0, 255, size=(len(classes), 3)).tolist()\n np.random.set_state(state)\n elif len(palette) >= len(classes) and self.label_map is not None:\n new_palette = []\n # return subset of palette\n for old_id, new_id in sorted(\n self.label_map.items(), key=lambda x: x[1]):\n if new_id != 255:\n new_palette.append(palette[old_id])\n new_palette = type(palette)(new_palette)\n else:\n raise ValueError('palette does not match classes '\n f'as metainfo is {self._metainfo}.')\n return new_palette\n\n def load_data_list(self) -> List[dict]:\n \"\"\"Load annotation from directory or annotation file.\n\n Returns:\n list[dict]: All data info of dataset.\n \"\"\"\n data_list = []\n img_dir = self.data_prefix.get('img_path', None)\n ann_dir = self.data_prefix.get('seg_map_path', None)\n if not osp.isdir(self.ann_file) and self.ann_file:\n assert osp.isfile(self.ann_file), \\\n f'Failed to load `ann_file` {self.ann_file}'\n lines = mmengine.list_from_file(\n self.ann_file, backend_args=self.backend_args)\n for line in lines:\n img_name = line.strip()\n data_info = dict(\n img_path=osp.join(img_dir, img_name + self.img_suffix))\n if ann_dir is not None:\n seg_map = img_name + self.seg_map_suffix\n data_info['seg_map_path'] = osp.join(ann_dir, seg_map)\n data_info['label_map'] = self.label_map\n data_info['reduce_zero_label'] = self.reduce_zero_label\n data_info['seg_fields'] = []\n data_list.append(data_info)\n else:\n _suffix_len = len(self.img_suffix)\n for img in fileio.list_dir_or_file(\n dir_path=img_dir,\n list_dir=False,\n suffix=self.img_suffix,\n recursive=True,\n backend_args=self.backend_args):\n data_info = dict(img_path=osp.join(img_dir, img))\n if ann_dir is not None:\n seg_map = img[:-_suffix_len] + self.seg_map_suffix\n data_info['seg_map_path'] = osp.join(ann_dir, seg_map)\n data_info['label_map'] = self.label_map\n data_info['reduce_zero_label'] = self.reduce_zero_label\n data_info['seg_fields'] = []\n data_list.append(data_info)\n data_list = sorted(data_list, key=lambda x: x['img_path'])\n return data_list" }, { "identifier": "BDD100KDataset", "path": "mmseg/datasets/bdd100k.py", "snippet": "class BDD100KDataset(BaseSegDataset):\n METAINFO = dict(\n classes=('road', 'sidewalk', 'building', 'wall', 'fence', 'pole',\n 'traffic light', 'traffic sign', 'vegetation', 'terrain',\n 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train',\n 'motorcycle', 'bicycle'),\n palette=[[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156],\n [190, 153, 153], [153, 153, 153], [250, 170,\n 30], [220, 220, 0],\n [107, 142, 35], [152, 251, 152], [70, 130, 180],\n [220, 20, 60], [255, 0, 0], [0, 0, 142], [0, 0, 70],\n [0, 60, 100], [0, 80, 100], [0, 0, 230], [119, 11, 32]])\n\n def __init__(self,\n img_suffix='.jpg',\n seg_map_suffix='.png',\n reduce_zero_label=False,\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix,\n seg_map_suffix=seg_map_suffix,\n reduce_zero_label=reduce_zero_label,\n **kwargs)" }, { "identifier": "CityscapesDataset", "path": "mmseg/datasets/cityscapes.py", "snippet": "class CityscapesDataset(BaseSegDataset):\n \"\"\"Cityscapes dataset.\n\n The ``img_suffix`` is fixed to '_leftImg8bit.png' and ``seg_map_suffix`` is\n fixed to '_gtFine_labelTrainIds.png' for Cityscapes dataset.\n \"\"\"\n METAINFO = dict(\n classes=('road', 'sidewalk', 'building', 'wall', 'fence', 'pole',\n 'traffic light', 'traffic sign', 'vegetation', 'terrain',\n 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train',\n 'motorcycle', 'bicycle'),\n palette=[[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156],\n [190, 153, 153], [153, 153, 153], [250, 170,\n 30], [220, 220, 0],\n [107, 142, 35], [152, 251, 152], [70, 130, 180],\n [220, 20, 60], [255, 0, 0], [0, 0, 142], [0, 0, 70],\n [0, 60, 100], [0, 80, 100], [0, 0, 230], [119, 11, 32]])\n\n def __init__(self,\n img_suffix='_leftImg8bit.png',\n seg_map_suffix='_gtFine_labelTrainIds.png',\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs)" }, { "identifier": "COCOStuffDataset", "path": "mmseg/datasets/coco_stuff.py", "snippet": "class COCOStuffDataset(BaseSegDataset):\n \"\"\"COCO-Stuff dataset.\n\n In segmentation map annotation for COCO-Stuff, Train-IDs of the 10k version\n are from 1 to 171, where 0 is the ignore index, and Train-ID of COCO Stuff\n 164k is from 0 to 170, where 255 is the ignore index. So, they are all 171\n semantic categories. ``reduce_zero_label`` is set to True and False for the\n 10k and 164k versions, respectively. The ``img_suffix`` is fixed to '.jpg',\n and ``seg_map_suffix`` is fixed to '.png'.\n \"\"\"\n METAINFO = dict(\n classes=(\n 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',\n 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',\n 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',\n 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',\n 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',\n 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',\n 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',\n 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',\n 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',\n 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',\n 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',\n 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',\n 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',\n 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner',\n 'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet',\n 'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile',\n 'cloth', 'clothes', 'clouds', 'counter', 'cupboard', 'curtain',\n 'desk-stuff', 'dirt', 'door-stuff', 'fence', 'floor-marble',\n 'floor-other', 'floor-stone', 'floor-tile', 'floor-wood', 'flower',\n 'fog', 'food-other', 'fruit', 'furniture-other', 'grass', 'gravel',\n 'ground-other', 'hill', 'house', 'leaves', 'light', 'mat', 'metal',\n 'mirror-stuff', 'moss', 'mountain', 'mud', 'napkin', 'net',\n 'paper', 'pavement', 'pillow', 'plant-other', 'plastic',\n 'platform', 'playingfield', 'railing', 'railroad', 'river', 'road',\n 'rock', 'roof', 'rug', 'salad', 'sand', 'sea', 'shelf',\n 'sky-other', 'skyscraper', 'snow', 'solid-other', 'stairs',\n 'stone', 'straw', 'structural-other', 'table', 'tent',\n 'textile-other', 'towel', 'tree', 'vegetable', 'wall-brick',\n 'wall-concrete', 'wall-other', 'wall-panel', 'wall-stone',\n 'wall-tile', 'wall-wood', 'water-other', 'waterdrops',\n 'window-blind', 'window-other', 'wood'),\n palette=[[0, 192, 64], [0, 192, 64], [0, 64, 96], [128, 192, 192],\n [0, 64, 64], [0, 192, 224], [0, 192, 192], [128, 192, 64],\n [0, 192, 96], [128, 192, 64], [128, 32, 192], [0, 0, 224],\n [0, 0, 64], [0, 160, 192], [128, 0, 96], [128, 0, 192],\n [0, 32, 192], [128, 128, 224], [0, 0, 192], [128, 160, 192],\n [128, 128, 0], [128, 0, 32], [128, 32, 0], [128, 0, 128],\n [64, 128, 32], [0, 160, 0], [0, 0, 0], [192, 128, 160],\n [0, 32, 0], [0, 128, 128], [64, 128, 160], [128, 160, 0],\n [0, 128, 0], [192, 128, 32], [128, 96, 128], [0, 0, 128],\n [64, 0, 32], [0, 224, 128], [128, 0, 0], [192, 0, 160],\n [0, 96, 128], [128, 128, 128], [64, 0, 160], [128, 224, 128],\n [128, 128, 64], [192, 0, 32], [128, 96, 0], [128, 0, 192],\n [0, 128, 32], [64, 224, 0], [0, 0, 64], [128, 128, 160],\n [64, 96, 0], [0, 128, 192], [0, 128, 160], [192, 224, 0],\n [0, 128, 64], [128, 128, 32], [192, 32, 128], [0, 64, 192],\n [0, 0, 32], [64, 160, 128], [128, 64, 64], [128, 0, 160],\n [64, 32, 128], [128, 192, 192], [0, 0, 160], [192, 160, 128],\n [128, 192, 0], [128, 0, 96], [192, 32, 0], [128, 64, 128],\n [64, 128, 96], [64, 160, 0], [0, 64, 0], [192, 128, 224],\n [64, 32, 0], [0, 192, 128], [64, 128, 224], [192, 160, 0],\n [0, 192, 0], [192, 128, 96], [192, 96, 128], [0, 64, 128],\n [64, 0, 96], [64, 224, 128], [128, 64, 0], [192, 0, 224],\n [64, 96, 128], [128, 192, 128], [64, 0, 224], [192, 224, 128],\n [128, 192, 64], [192, 0, 96], [192, 96, 0], [128, 64, 192],\n [0, 128, 96], [0, 224, 0], [64, 64, 64], [128, 128, 224],\n [0, 96, 0], [64, 192, 192], [0, 128, 224], [128, 224, 0],\n [64, 192, 64], [128, 128, 96], [128, 32, 128], [64, 0, 192],\n [0, 64, 96], [0, 160, 128], [192, 0, 64], [128, 64, 224],\n [0, 32, 128], [192, 128, 192], [0, 64, 224], [128, 160, 128],\n [192, 128, 0], [128, 64, 32], [128, 32, 64], [192, 0, 128],\n [64, 192, 32], [0, 160, 64], [64, 0, 0], [192, 192, 160],\n [0, 32, 64], [64, 128, 128], [64, 192, 160], [128, 160, 64],\n [64, 128, 0], [192, 192, 32], [128, 96, 192], [64, 0, 128],\n [64, 64, 32], [0, 224, 192], [192, 0, 0], [192, 64, 160],\n [0, 96, 192], [192, 128, 128], [64, 64, 160], [128, 224, 192],\n [192, 128, 64], [192, 64, 32], [128, 96, 64], [192, 0, 192],\n [0, 192, 32], [64, 224, 64], [64, 0, 64], [128, 192, 160],\n [64, 96, 64], [64, 128, 192], [0, 192, 160], [192, 224, 64],\n [64, 128, 64], [128, 192, 32], [192, 32, 192], [64, 64, 192],\n [0, 64, 32], [64, 160, 192], [192, 64, 64], [128, 64, 160],\n [64, 32, 192], [192, 192, 192], [0, 64, 160], [192, 160, 192],\n [192, 192, 0], [128, 64, 96], [192, 32, 64], [192, 64, 128],\n [64, 192, 96], [64, 160, 64], [64, 64, 0]])\n\n def __init__(self,\n img_suffix='.jpg',\n seg_map_suffix='_labelTrainIds.png',\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs)" }, { "identifier": "DecathlonDataset", "path": "mmseg/datasets/decathlon.py", "snippet": "class DecathlonDataset(BaseSegDataset):\n \"\"\"Dataset for Dacathlon dataset.\n\n The dataset.json format is shown as follows\n\n .. code-block:: none\n\n {\n \"name\": \"BRATS\",\n \"tensorImageSize\": \"4D\",\n \"modality\":\n {\n \"0\": \"FLAIR\",\n \"1\": \"T1w\",\n \"2\": \"t1gd\",\n \"3\": \"T2w\"\n },\n \"labels\": {\n \"0\": \"background\",\n \"1\": \"edema\",\n \"2\": \"non-enhancing tumor\",\n \"3\": \"enhancing tumour\"\n },\n \"numTraining\": 484,\n \"numTest\": 266,\n \"training\":\n [\n {\n \"image\": \"./imagesTr/BRATS_306.nii.gz\"\n \"label\": \"./labelsTr/BRATS_306.nii.gz\"\n ...\n }\n ]\n \"test\":\n [\n \"./imagesTs/BRATS_557.nii.gz\"\n ...\n ]\n }\n \"\"\"\n\n def load_data_list(self) -> List[dict]:\n \"\"\"Load annotation from directory or annotation file.\n\n Returns:\n list[dict]: All data info of dataset.\n \"\"\"\n # `self.ann_file` denotes the absolute annotation file path if\n # `self.root=None` or relative path if `self.root=/path/to/data/`.\n annotations = load(self.ann_file)\n if not isinstance(annotations, dict):\n raise TypeError(f'The annotations loaded from annotation file '\n f'should be a dict, but got {type(annotations)}!')\n raw_data_list = annotations[\n 'training'] if not self.test_mode else annotations['test']\n data_list = []\n for raw_data_info in raw_data_list:\n # `2:` works for removing './' in file path, which will break\n # loading from cloud storage.\n if isinstance(raw_data_info, dict):\n data_info = dict(\n img_path=osp.join(self.data_root, raw_data_info['image']\n [2:]))\n data_info['seg_map_path'] = osp.join(\n self.data_root, raw_data_info['label'][2:])\n else:\n data_info = dict(\n img_path=osp.join(self.data_root, raw_data_info)[2:])\n data_info['label_map'] = self.label_map\n data_info['reduce_zero_label'] = self.reduce_zero_label\n data_info['seg_fields'] = []\n data_list.append(data_info)\n annotations.pop('training')\n annotations.pop('test')\n\n metainfo = copy.deepcopy(annotations)\n metainfo['classes'] = [*metainfo['labels'].values()]\n # Meta information load from annotation file will not influence the\n # existed meta information load from `BaseDataset.METAINFO` and\n # `metainfo` arguments defined in constructor.\n for k, v in metainfo.items():\n self._metainfo.setdefault(k, v)\n\n return data_list" }, { "identifier": "DSDLSegDataset", "path": "mmseg/datasets/dsdl.py", "snippet": "class DSDLSegDataset(BaseSegDataset):\n \"\"\"Dataset for dsdl segmentation.\n\n Args:\n specific_key_path(dict): Path of specific key which can not\n be loaded by it's field name.\n pre_transform(dict): pre-transform functions before loading.\n used_labels(sequence): list of actual used classes in train steps,\n this must be subset of class domain.\n \"\"\"\n\n METAINFO = {}\n\n def __init__(self,\n specific_key_path: Dict = {},\n pre_transform: Dict = {},\n used_labels: Optional[Sequence] = None,\n **kwargs) -> None:\n\n if DSDLDataset is None:\n raise RuntimeError(\n 'Package dsdl is not installed. Please run \"pip install dsdl\".'\n )\n self.used_labels = used_labels\n\n loc_config = dict(type='LocalFileReader', working_dir='')\n if kwargs.get('data_root'):\n kwargs['ann_file'] = os.path.join(kwargs['data_root'],\n kwargs['ann_file'])\n required_fields = ['Image', 'LabelMap']\n\n self.dsdldataset = DSDLDataset(\n dsdl_yaml=kwargs['ann_file'],\n location_config=loc_config,\n required_fields=required_fields,\n specific_key_path=specific_key_path,\n transform=pre_transform,\n )\n BaseSegDataset.__init__(self, **kwargs)\n\n def load_data_list(self) -> List[Dict]:\n \"\"\"Load data info from a dsdl yaml file named as ``self.ann_file``\n\n Returns:\n List[dict]: A list of data list.\n \"\"\"\n\n if self.used_labels:\n self._metainfo['classes'] = tuple(self.used_labels)\n self.label_map = self.get_label_map(self.used_labels)\n else:\n self._metainfo['classes'] = tuple(['background'] +\n self.dsdldataset.class_names)\n data_list = []\n\n for i, data in enumerate(self.dsdldataset):\n datainfo = dict(\n img_path=os.path.join(self.data_prefix['img_path'],\n data['Image'][0].location),\n seg_map_path=os.path.join(self.data_prefix['seg_map_path'],\n data['LabelMap'][0].location),\n label_map=self.label_map,\n reduce_zero_label=self.reduce_zero_label,\n seg_fields=[],\n )\n data_list.append(datainfo)\n\n return data_list\n\n def get_label_map(self,\n new_classes: Optional[Sequence] = None\n ) -> Union[Dict, None]:\n \"\"\"Require label mapping.\n\n The ``label_map`` is a dictionary, its keys are the old label ids and\n its values are the new label ids, and is used for changing pixel\n labels in load_annotations. If and only if old classes in class_dom\n is not equal to new classes in args and nether of them is not\n None, `label_map` is not None.\n Args:\n new_classes (list, tuple, optional): The new classes name from\n metainfo. Default to None.\n Returns:\n dict, optional: The mapping from old classes to new classes.\n \"\"\"\n old_classes = ['background'] + self.dsdldataset.class_names\n if (new_classes is not None and old_classes is not None\n and list(new_classes) != list(old_classes)):\n\n label_map = {}\n if not set(new_classes).issubset(old_classes):\n raise ValueError(\n f'new classes {new_classes} is not a '\n f'subset of classes {old_classes} in class_dom.')\n for i, c in enumerate(old_classes):\n if c not in new_classes:\n label_map[i] = 255\n else:\n label_map[i] = new_classes.index(c)\n return label_map\n else:\n return None" }, { "identifier": "iSAIDDataset", "path": "mmseg/datasets/isaid.py", "snippet": "class iSAIDDataset(BaseSegDataset):\n \"\"\" iSAID: A Large-scale Dataset for Instance Segmentation in Aerial Images\n In segmentation map annotation for iSAID dataset, which is included\n in 16 categories. ``reduce_zero_label`` is fixed to False. The\n ``img_suffix`` is fixed to '.png' and ``seg_map_suffix`` is fixed to\n '_manual1.png'.\n \"\"\"\n\n METAINFO = dict(\n classes=('background', 'ship', 'store_tank', 'baseball_diamond',\n 'tennis_court', 'basketball_court', 'Ground_Track_Field',\n 'Bridge', 'Large_Vehicle', 'Small_Vehicle', 'Helicopter',\n 'Swimming_pool', 'Roundabout', 'Soccer_ball_field', 'plane',\n 'Harbor'),\n palette=[[0, 0, 0], [0, 0, 63], [0, 63, 63], [0, 63, 0], [0, 63, 127],\n [0, 63, 191], [0, 63, 255], [0, 127, 63], [0, 127, 127],\n [0, 0, 127], [0, 0, 191], [0, 0, 255], [0, 191, 127],\n [0, 127, 191], [0, 127, 255], [0, 100, 155]])\n\n def __init__(self,\n img_suffix='.png',\n seg_map_suffix='_instance_color_RGB.png',\n ignore_index=255,\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix,\n seg_map_suffix=seg_map_suffix,\n ignore_index=ignore_index,\n **kwargs)\n assert fileio.exists(\n self.data_prefix['img_path'], backend_args=self.backend_args)" }, { "identifier": "ISPRSDataset", "path": "mmseg/datasets/isprs.py", "snippet": "class ISPRSDataset(BaseSegDataset):\n \"\"\"ISPRS dataset.\n\n In segmentation map annotation for ISPRS, 0 is the ignore index.\n ``reduce_zero_label`` should be set to True. The ``img_suffix`` and\n ``seg_map_suffix`` are both fixed to '.png'.\n \"\"\"\n METAINFO = dict(\n classes=('impervious_surface', 'building', 'low_vegetation', 'tree',\n 'car', 'clutter'),\n palette=[[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0],\n [255, 255, 0], [255, 0, 0]])\n\n def __init__(self,\n img_suffix='.png',\n seg_map_suffix='.png',\n reduce_zero_label=True,\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix,\n seg_map_suffix=seg_map_suffix,\n reduce_zero_label=reduce_zero_label,\n **kwargs)" }, { "identifier": "LIPDataset", "path": "mmseg/datasets/lip.py", "snippet": "class LIPDataset(BaseSegDataset):\n \"\"\"LIP dataset.\n\n The ``img_suffix`` is fixed to '.jpg' and ``seg_map_suffix`` is fixed to\n '.png'.\n \"\"\"\n METAINFO = dict(\n classes=('Background', 'Hat', 'Hair', 'Glove', 'Sunglasses',\n 'UpperClothes', 'Dress', 'Coat', 'Socks', 'Pants',\n 'Jumpsuits', 'Scarf', 'Skirt', 'Face', 'Left-arm',\n 'Right-arm', 'Left-leg', 'Right-leg', 'Left-shoe',\n 'Right-shoe'),\n palette=(\n [0, 0, 0],\n [128, 0, 0],\n [255, 0, 0],\n [0, 85, 0],\n [170, 0, 51],\n [255, 85, 0],\n [0, 0, 85],\n [0, 119, 221],\n [85, 85, 0],\n [0, 85, 85],\n [85, 51, 0],\n [52, 86, 128],\n [0, 128, 0],\n [0, 0, 255],\n [51, 170, 221],\n [0, 255, 255],\n [85, 255, 170],\n [170, 255, 85],\n [255, 255, 0],\n [255, 170, 0],\n ))\n\n def __init__(self,\n img_suffix='.jpg',\n seg_map_suffix='.png',\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs)" }, { "identifier": "LoveDADataset", "path": "mmseg/datasets/loveda.py", "snippet": "class LoveDADataset(BaseSegDataset):\n \"\"\"LoveDA dataset.\n\n In segmentation map annotation for LoveDA, 0 is the ignore index.\n ``reduce_zero_label`` should be set to True. The ``img_suffix`` and\n ``seg_map_suffix`` are both fixed to '.png'.\n \"\"\"\n METAINFO = dict(\n classes=('background', 'building', 'road', 'water', 'barren', 'forest',\n 'agricultural'),\n palette=[[255, 255, 255], [255, 0, 0], [255, 255, 0], [0, 0, 255],\n [159, 129, 183], [0, 255, 0], [255, 195, 128]])\n\n def __init__(self,\n img_suffix='.png',\n seg_map_suffix='.png',\n reduce_zero_label=True,\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix,\n seg_map_suffix=seg_map_suffix,\n reduce_zero_label=reduce_zero_label,\n **kwargs)" }, { "identifier": "MapillaryDataset_v1", "path": "mmseg/datasets/mapillary.py", "snippet": "class MapillaryDataset_v1(BaseSegDataset):\n \"\"\"Mapillary Vistas Dataset.\n\n Dataset paper link:\n http://ieeexplore.ieee.org/document/8237796/\n\n v1.2 contain 66 object classes.\n (37 instance-specific)\n\n v2.0 contain 124 object classes.\n (70 instance-specific, 46 stuff, 8 void or crowd).\n\n The ``img_suffix`` is fixed to '.jpg' and ``seg_map_suffix`` is\n fixed to '.png' for Mapillary Vistas Dataset.\n \"\"\"\n METAINFO = dict(\n classes=('Bird', 'Ground Animal', 'Curb', 'Fence', 'Guard Rail',\n 'Barrier', 'Wall', 'Bike Lane', 'Crosswalk - Plain',\n 'Curb Cut', 'Parking', 'Pedestrian Area', 'Rail Track',\n 'Road', 'Service Lane', 'Sidewalk', 'Bridge', 'Building',\n 'Tunnel', 'Person', 'Bicyclist', 'Motorcyclist',\n 'Other Rider', 'Lane Marking - Crosswalk',\n 'Lane Marking - General', 'Mountain', 'Sand', 'Sky', 'Snow',\n 'Terrain', 'Vegetation', 'Water', 'Banner', 'Bench',\n 'Bike Rack', 'Billboard', 'Catch Basin', 'CCTV Camera',\n 'Fire Hydrant', 'Junction Box', 'Mailbox', 'Manhole',\n 'Phone Booth', 'Pothole', 'Street Light', 'Pole',\n 'Traffic Sign Frame', 'Utility Pole', 'Traffic Light',\n 'Traffic Sign (Back)', 'Traffic Sign (Front)', 'Trash Can',\n 'Bicycle', 'Boat', 'Bus', 'Car', 'Caravan', 'Motorcycle',\n 'On Rails', 'Other Vehicle', 'Trailer', 'Truck',\n 'Wheeled Slow', 'Car Mount', 'Ego Vehicle', 'Unlabeled'),\n palette=[[165, 42, 42], [0, 192, 0], [196, 196, 196], [190, 153, 153],\n [180, 165, 180], [90, 120, 150], [102, 102, 156],\n [128, 64, 255], [140, 140, 200], [170, 170, 170],\n [250, 170, 160], [96, 96, 96],\n [230, 150, 140], [128, 64, 128], [110, 110, 110],\n [244, 35, 232], [150, 100, 100], [70, 70, 70], [150, 120, 90],\n [220, 20, 60], [255, 0, 0], [255, 0, 100], [255, 0, 200],\n [200, 128, 128], [255, 255, 255], [64, 170,\n 64], [230, 160, 50],\n [70, 130, 180], [190, 255, 255], [152, 251, 152],\n [107, 142, 35], [0, 170, 30], [255, 255, 128], [250, 0, 30],\n [100, 140, 180], [220, 220, 220], [220, 128, 128],\n [222, 40, 40], [100, 170, 30], [40, 40, 40], [33, 33, 33],\n [100, 128, 160], [142, 0, 0], [70, 100, 150], [210, 170, 100],\n [153, 153, 153], [128, 128, 128], [0, 0, 80], [250, 170, 30],\n [192, 192, 192], [220, 220, 0], [140, 140, 20], [119, 11, 32],\n [150, 0, 255], [0, 60, 100], [0, 0, 142], [0, 0, 90],\n [0, 0, 230], [0, 80, 100], [128, 64, 64], [0, 0, 110],\n [0, 0, 70], [0, 0, 192], [32, 32, 32], [120, 10,\n 10], [0, 0, 0]])\n\n def __init__(self,\n img_suffix='.jpg',\n seg_map_suffix='.png',\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs)" }, { "identifier": "MapillaryDataset_v2", "path": "mmseg/datasets/mapillary.py", "snippet": "class MapillaryDataset_v2(BaseSegDataset):\n \"\"\"Mapillary Vistas Dataset.\n\n Dataset paper link:\n http://ieeexplore.ieee.org/document/8237796/\n\n v1.2 contain 66 object classes.\n (37 instance-specific)\n\n v2.0 contain 124 object classes.\n (70 instance-specific, 46 stuff, 8 void or crowd).\n\n The ``img_suffix`` is fixed to '.jpg' and ``seg_map_suffix`` is\n fixed to '.png' for Mapillary Vistas Dataset.\n \"\"\"\n METAINFO = dict(\n classes=(\n 'Bird', 'Ground Animal', 'Ambiguous Barrier', 'Concrete Block',\n 'Curb', 'Fence', 'Guard Rail', 'Barrier', 'Road Median',\n 'Road Side', 'Lane Separator', 'Temporary Barrier', 'Wall',\n 'Bike Lane', 'Crosswalk - Plain', 'Curb Cut', 'Driveway',\n 'Parking', 'Parking Aisle', 'Pedestrian Area', 'Rail Track',\n 'Road', 'Road Shoulder', 'Service Lane', 'Sidewalk',\n 'Traffic Island', 'Bridge', 'Building', 'Garage', 'Tunnel',\n 'Person', 'Person Group', 'Bicyclist', 'Motorcyclist',\n 'Other Rider', 'Lane Marking - Dashed Line',\n 'Lane Marking - Straight Line', 'Lane Marking - Zigzag Line',\n 'Lane Marking - Ambiguous', 'Lane Marking - Arrow (Left)',\n 'Lane Marking - Arrow (Other)', 'Lane Marking - Arrow (Right)',\n 'Lane Marking - Arrow (Split Left or Straight)',\n 'Lane Marking - Arrow (Split Right or Straight)',\n 'Lane Marking - Arrow (Straight)', 'Lane Marking - Crosswalk',\n 'Lane Marking - Give Way (Row)',\n 'Lane Marking - Give Way (Single)',\n 'Lane Marking - Hatched (Chevron)',\n 'Lane Marking - Hatched (Diagonal)', 'Lane Marking - Other',\n 'Lane Marking - Stop Line', 'Lane Marking - Symbol (Bicycle)',\n 'Lane Marking - Symbol (Other)', 'Lane Marking - Text',\n 'Lane Marking (only) - Dashed Line',\n 'Lane Marking (only) - Crosswalk', 'Lane Marking (only) - Other',\n 'Lane Marking (only) - Test', 'Mountain', 'Sand', 'Sky', 'Snow',\n 'Terrain', 'Vegetation', 'Water', 'Banner', 'Bench', 'Bike Rack',\n 'Catch Basin', 'CCTV Camera', 'Fire Hydrant', 'Junction Box',\n 'Mailbox', 'Manhole', 'Parking Meter', 'Phone Booth', 'Pothole',\n 'Signage - Advertisement', 'Signage - Ambiguous', 'Signage - Back',\n 'Signage - Information', 'Signage - Other', 'Signage - Store',\n 'Street Light', 'Pole', 'Pole Group', 'Traffic Sign Frame',\n 'Utility Pole', 'Traffic Cone', 'Traffic Light - General (Single)',\n 'Traffic Light - Pedestrians', 'Traffic Light - General (Upright)',\n 'Traffic Light - General (Horizontal)', 'Traffic Light - Cyclists',\n 'Traffic Light - Other', 'Traffic Sign - Ambiguous',\n 'Traffic Sign (Back)', 'Traffic Sign - Direction (Back)',\n 'Traffic Sign - Direction (Front)', 'Traffic Sign (Front)',\n 'Traffic Sign - Parking', 'Traffic Sign - Temporary (Back)',\n 'Traffic Sign - Temporary (Front)', 'Trash Can', 'Bicycle', 'Boat',\n 'Bus', 'Car', 'Caravan', 'Motorcycle', 'On Rails', 'Other Vehicle',\n 'Trailer', 'Truck', 'Vehicle Group', 'Wheeled Slow', 'Water Valve',\n 'Car Mount', 'Dynamic', 'Ego Vehicle', 'Ground', 'Static',\n 'Unlabeled'),\n palette=[[165, 42, 42], [0, 192, 0], [250, 170, 31], [250, 170, 32],\n [196, 196, 196], [190, 153, 153], [180, 165, 180],\n [90, 120, 150], [250, 170, 33], [250, 170, 34],\n [128, 128, 128], [250, 170, 35], [102, 102, 156],\n [128, 64, 255], [140, 140, 200], [170, 170, 170],\n [250, 170, 36], [250, 170, 160], [250, 170, 37], [96, 96, 96],\n [230, 150, 140], [128, 64, 128], [110, 110, 110],\n [110, 110, 110], [244, 35, 232], [128, 196,\n 128], [150, 100, 100],\n [70, 70, 70], [150, 150, 150], [150, 120, 90], [220, 20, 60],\n [220, 20, 60], [255, 0, 0], [255, 0, 100], [255, 0, 200],\n [255, 255, 255], [255, 255, 255], [250, 170, 29],\n [250, 170, 28], [250, 170, 26], [250, 170,\n 25], [250, 170, 24],\n [250, 170, 22], [250, 170, 21], [250, 170,\n 20], [255, 255, 255],\n [250, 170, 19], [250, 170, 18], [250, 170,\n 12], [250, 170, 11],\n [255, 255, 255], [255, 255, 255], [250, 170, 16],\n [250, 170, 15], [250, 170, 15], [255, 255, 255],\n [255, 255, 255], [255, 255, 255], [255, 255, 255],\n [64, 170, 64], [230, 160, 50],\n [70, 130, 180], [190, 255, 255], [152, 251, 152],\n [107, 142, 35], [0, 170, 30], [255, 255, 128], [250, 0, 30],\n [100, 140, 180], [220, 128, 128], [222, 40,\n 40], [100, 170, 30],\n [40, 40, 40], [33, 33, 33], [100, 128, 160], [20, 20, 255],\n [142, 0, 0], [70, 100, 150], [250, 171, 30], [250, 172, 30],\n [250, 173, 30], [250, 174, 30], [250, 175,\n 30], [250, 176, 30],\n [210, 170, 100], [153, 153, 153], [153, 153, 153],\n [128, 128, 128], [0, 0, 80], [210, 60, 60], [250, 170, 30],\n [250, 170, 30], [250, 170, 30], [250, 170,\n 30], [250, 170, 30],\n [250, 170, 30], [192, 192, 192], [192, 192, 192],\n [192, 192, 192], [220, 220, 0], [220, 220, 0], [0, 0, 196],\n [192, 192, 192], [220, 220, 0], [140, 140, 20], [119, 11, 32],\n [150, 0, 255], [0, 60, 100], [0, 0, 142], [0, 0, 90],\n [0, 0, 230], [0, 80, 100], [128, 64, 64], [0, 0, 110],\n [0, 0, 70], [0, 0, 142], [0, 0, 192], [170, 170, 170],\n [32, 32, 32], [111, 74, 0], [120, 10, 10], [81, 0, 81],\n [111, 111, 0], [0, 0, 0]])\n\n def __init__(self,\n img_suffix='.jpg',\n seg_map_suffix='.png',\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs)" }, { "identifier": "NYUDataset", "path": "mmseg/datasets/nyu.py", "snippet": "class NYUDataset(BaseSegDataset):\n \"\"\"NYU depth estimation dataset. The file structure should be.\n\n .. code-block:: none\n\n ├── data\n │ ├── nyu\n │ │ ├── images\n │ │ │ ├── train\n │ │ │ │ ├── scene_xxx.jpg\n │ │ │ │ ├── ...\n │ │ │ ├── test\n │ │ ├── annotations\n │ │ │ ├── train\n │ │ │ │ ├── scene_xxx.png\n │ │ │ │ ├── ...\n │ │ │ ├── test\n\n Args:\n ann_file (str): Annotation file path. Defaults to ''.\n metainfo (dict, optional): Meta information for dataset, such as\n specify classes to load. Defaults to None.\n data_root (str, optional): The root directory for ``data_prefix`` and\n ``ann_file``. Defaults to None.\n data_prefix (dict, optional): Prefix for training data. Defaults to\n dict(img_path='images', depth_map_path='annotations').\n img_suffix (str): Suffix of images. Default: '.jpg'\n seg_map_suffix (str): Suffix of segmentation maps. Default: '.png'\n filter_cfg (dict, optional): Config for filter data. Defaults to None.\n indices (int or Sequence[int], optional): Support using first few\n data in annotation file to facilitate training/testing on a smaller\n dataset. Defaults to None which means using all ``data_infos``.\n serialize_data (bool, optional): Whether to hold memory using\n serialized objects, when enabled, data loader workers can use\n shared RAM from master process instead of making a copy. Defaults\n to True.\n pipeline (list, optional): Processing pipeline. Defaults to [].\n test_mode (bool, optional): ``test_mode=True`` means in test phase.\n Defaults to False.\n lazy_init (bool, optional): Whether to load annotation during\n instantiation. In some cases, such as visualization, only the meta\n information of the dataset is needed, which is not necessary to\n load annotation file. ``Basedataset`` can skip load annotations to\n save time by set ``lazy_init=True``. Defaults to False.\n max_refetch (int, optional): If ``Basedataset.prepare_data`` get a\n None img. The maximum extra number of cycles to get a valid\n image. Defaults to 1000.\n ignore_index (int): The label index to be ignored. Default: 255\n reduce_zero_label (bool): Whether to mark label zero as ignored.\n Default to False.\n backend_args (dict, Optional): Arguments to instantiate a file backend.\n See https://mmengine.readthedocs.io/en/latest/api/fileio.htm\n for details. Defaults to None.\n Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.\n \"\"\"\n METAINFO = dict(\n classes=('printer_room', 'bathroom', 'living_room', 'study',\n 'conference_room', 'study_room', 'kitchen', 'home_office',\n 'bedroom', 'dinette', 'playroom', 'indoor_balcony',\n 'laundry_room', 'basement', 'excercise_room', 'foyer',\n 'home_storage', 'cafe', 'furniture_store', 'office_kitchen',\n 'student_lounge', 'dining_room', 'reception_room',\n 'computer_lab', 'classroom', 'office', 'bookstore'))\n\n def __init__(self,\n data_prefix=dict(\n img_path='images', depth_map_path='annotations'),\n img_suffix='.jpg',\n depth_map_suffix='.png',\n **kwargs) -> None:\n super().__init__(\n data_prefix=data_prefix,\n img_suffix=img_suffix,\n seg_map_suffix=depth_map_suffix,\n **kwargs)\n\n def _get_category_id_from_filename(self, image_fname: str) -> int:\n \"\"\"Retrieve the category ID from the given image filename.\"\"\"\n image_fname = osp.basename(image_fname)\n position = image_fname.find(next(filter(str.isdigit, image_fname)), 0)\n categoty_name = image_fname[:position - 1]\n if categoty_name not in self._metainfo['classes']:\n return -1\n else:\n return self._metainfo['classes'].index(categoty_name)\n\n def load_data_list(self) -> List[dict]:\n \"\"\"Load annotation from directory or annotation file.\n\n Returns:\n list[dict]: All data info of dataset.\n \"\"\"\n data_list = []\n img_dir = self.data_prefix.get('img_path', None)\n ann_dir = self.data_prefix.get('depth_map_path', None)\n\n _suffix_len = len(self.img_suffix)\n for img in fileio.list_dir_or_file(\n dir_path=img_dir,\n list_dir=False,\n suffix=self.img_suffix,\n recursive=True,\n backend_args=self.backend_args):\n data_info = dict(img_path=osp.join(img_dir, img))\n if ann_dir is not None:\n depth_map = img[:-_suffix_len] + self.seg_map_suffix\n data_info['depth_map_path'] = osp.join(ann_dir, depth_map)\n data_info['seg_fields'] = []\n data_info['category_id'] = self._get_category_id_from_filename(img)\n data_list.append(data_info)\n data_list = sorted(data_list, key=lambda x: x['img_path'])\n return data_list" }, { "identifier": "PotsdamDataset", "path": "mmseg/datasets/potsdam.py", "snippet": "class PotsdamDataset(BaseSegDataset):\n \"\"\"ISPRS Potsdam dataset.\n\n In segmentation map annotation for Potsdam dataset, 0 is the ignore index.\n ``reduce_zero_label`` should be set to True. The ``img_suffix`` and\n ``seg_map_suffix`` are both fixed to '.png'.\n \"\"\"\n METAINFO = dict(\n classes=('impervious_surface', 'building', 'low_vegetation', 'tree',\n 'car', 'clutter'),\n palette=[[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0],\n [255, 255, 0], [255, 0, 0]])\n\n def __init__(self,\n img_suffix='.png',\n seg_map_suffix='.png',\n reduce_zero_label=True,\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix,\n seg_map_suffix=seg_map_suffix,\n reduce_zero_label=reduce_zero_label,\n **kwargs)" }, { "identifier": "REFUGEDataset", "path": "mmseg/datasets/refuge.py", "snippet": "class REFUGEDataset(BaseSegDataset):\n \"\"\"REFUGE dataset.\n\n In segmentation map annotation for REFUGE, 0 stands for background, which\n is not included in 2 categories. ``reduce_zero_label`` is fixed to True.\n The ``img_suffix`` is fixed to '.png' and ``seg_map_suffix`` is fixed to\n '.png'.\n \"\"\"\n METAINFO = dict(\n classes=('background', ' Optic Cup', 'Optic Disc'),\n palette=[[120, 120, 120], [6, 230, 230], [56, 59, 120]])\n\n def __init__(self, **kwargs) -> None:\n super().__init__(\n img_suffix='.png',\n seg_map_suffix='.png',\n reduce_zero_label=False,\n **kwargs)\n assert fileio.exists(\n self.data_prefix['img_path'], backend_args=self.backend_args)" }, { "identifier": "SynapseDataset", "path": "mmseg/datasets/synapse.py", "snippet": "class SynapseDataset(BaseSegDataset):\n \"\"\"Synapse dataset.\n\n Before dataset preprocess of Synapse, there are total 13 categories of\n foreground which does not include background. After preprocessing, 8\n foreground categories are kept while the other 5 foreground categories are\n handled as background. The ``img_suffix`` is fixed to '.jpg' and\n ``seg_map_suffix`` is fixed to '.png'.\n \"\"\"\n METAINFO = dict(\n classes=('background', 'aorta', 'gallbladder', 'left_kidney',\n 'right_kidney', 'liver', 'pancreas', 'spleen', 'stomach'),\n palette=[[0, 0, 0], [0, 0, 255], [0, 255, 0], [255, 0, 0],\n [0, 255, 255], [255, 0, 255], [255, 255, 0], [60, 255, 255],\n [240, 240, 240]])\n\n def __init__(self,\n img_suffix='.jpg',\n seg_map_suffix='.png',\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs)" }, { "identifier": "PascalVOCDataset", "path": "mmseg/datasets/voc.py", "snippet": "class PascalVOCDataset(BaseSegDataset):\n \"\"\"Pascal VOC dataset.\n\n Args:\n split (str): Split txt file for Pascal VOC.\n \"\"\"\n METAINFO = dict(\n classes=('background', 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',\n 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep',\n 'sofa', 'train', 'tvmonitor'),\n palette=[[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],\n [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],\n [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],\n [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],\n [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],\n [0, 64, 128]])\n\n def __init__(self,\n ann_file,\n img_suffix='.jpg',\n seg_map_suffix='.png',\n **kwargs) -> None:\n super().__init__(\n img_suffix=img_suffix,\n seg_map_suffix=seg_map_suffix,\n ann_file=ann_file,\n **kwargs)\n assert fileio.exists(self.data_prefix['img_path'],\n self.backend_args) and osp.isfile(self.ann_file)" }, { "identifier": "DATASETS", "path": "mmseg/registry/registry.py", "snippet": "DATASETS = Registry(\n 'dataset', parent=MMENGINE_DATASETS, locations=['mmseg.datasets'])" }, { "identifier": "get_classes", "path": "mmseg/utils/class_names.py", "snippet": "def get_classes(dataset):\n \"\"\"Get class names of a dataset.\"\"\"\n alias2name = {}\n for name, aliases in dataset_aliases.items():\n for alias in aliases:\n alias2name[alias] = name\n\n if is_str(dataset):\n if dataset in alias2name:\n labels = eval(alias2name[dataset] + '_classes()')\n else:\n raise ValueError(f'Unrecognized dataset: {dataset}')\n else:\n raise TypeError(f'dataset must a str, but got {type(dataset)}')\n return labels" }, { "identifier": "get_palette", "path": "mmseg/utils/class_names.py", "snippet": "def get_palette(dataset):\n \"\"\"Get class palette (RGB) of a dataset.\"\"\"\n alias2name = {}\n for name, aliases in dataset_aliases.items():\n for alias in aliases:\n alias2name[alias] = name\n\n if is_str(dataset):\n if dataset in alias2name:\n labels = eval(alias2name[dataset] + '_palette()')\n else:\n raise ValueError(f'Unrecognized dataset: {dataset}')\n else:\n raise TypeError(f'dataset must a str, but got {type(dataset)}')\n return labels" } ]
import os import os.path as osp import tempfile import pytest from mmseg.datasets import (ADE20KDataset, BaseSegDataset, BDD100KDataset, CityscapesDataset, COCOStuffDataset, DecathlonDataset, DSDLSegDataset, ISPRSDataset, LIPDataset, LoveDADataset, MapillaryDataset_v1, MapillaryDataset_v2, NYUDataset, PascalVOCDataset, PotsdamDataset, REFUGEDataset, SynapseDataset, iSAIDDataset) from mmseg.registry import DATASETS from mmseg.utils import get_classes, get_palette from dsdl.dataset import DSDLDataset
18,062
# Copyright (c) OpenMMLab. All rights reserved. try: except ImportError: DSDLDataset = None def test_classes(): assert list( CityscapesDataset.METAINFO['classes']) == get_classes('cityscapes') assert list(PascalVOCDataset.METAINFO['classes']) == get_classes( 'voc') == get_classes('pascal_voc') assert list(ADE20KDataset.METAINFO['classes']) == get_classes( 'ade') == get_classes('ade20k') assert list( COCOStuffDataset.METAINFO['classes']) == get_classes('cocostuff') assert list(LoveDADataset.METAINFO['classes']) == get_classes('loveda') assert list(PotsdamDataset.METAINFO['classes']) == get_classes('potsdam') assert list(ISPRSDataset.METAINFO['classes']) == get_classes('vaihingen')
# Copyright (c) OpenMMLab. All rights reserved. try: except ImportError: DSDLDataset = None def test_classes(): assert list( CityscapesDataset.METAINFO['classes']) == get_classes('cityscapes') assert list(PascalVOCDataset.METAINFO['classes']) == get_classes( 'voc') == get_classes('pascal_voc') assert list(ADE20KDataset.METAINFO['classes']) == get_classes( 'ade') == get_classes('ade20k') assert list( COCOStuffDataset.METAINFO['classes']) == get_classes('cocostuff') assert list(LoveDADataset.METAINFO['classes']) == get_classes('loveda') assert list(PotsdamDataset.METAINFO['classes']) == get_classes('potsdam') assert list(ISPRSDataset.METAINFO['classes']) == get_classes('vaihingen')
assert list(iSAIDDataset.METAINFO['classes']) == get_classes('isaid')
7
2023-12-23 08:36:47+00:00
24k
see2023/Bert-VITS2-ext
train_ms.py
[ { "identifier": "config", "path": "config.py", "snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, out_dir: str, sampling_rate: int = 44100):\n def from_dict(cls, dataset_path: str, data: Dict[str, any]):\n def __init__(\n self,\n transcription_path: str,\n cleaned_path: str,\n train_path: str,\n val_path: str,\n config_path: str,\n val_per_lang: int = 5,\n max_val_total: int = 10000,\n clean: bool = True,\n ):\n def from_dict(cls, dataset_path: str, data: Dict[str, any]):\n def __init__(\n self,\n config_path: str,\n num_processes: int = 2,\n device: str = \"cuda\",\n use_multi_device: bool = False,\n ):\n def from_dict(cls, dataset_path: str, data: Dict[str, any]):\n def __init__(\n self,\n config_path: str,\n num_processes: int = 2,\n device: str = \"cuda\",\n use_multi_device: bool = False,\n ):\n def from_dict(cls, dataset_path: str, data: Dict[str, any]):\n def __init__(\n self,\n config_path: str,\n env: Dict[str, any],\n base: Dict[str, any],\n model: str,\n num_workers: int,\n spec_cache: bool,\n keep_ckpts: int,\n ):\n def from_dict(cls, dataset_path: str, data: Dict[str, any]):\n def __init__(\n self,\n device: str,\n model: str,\n v_model: str,\n config_path: str,\n language_identification_library: str,\n port: int = 7860,\n share: bool = False,\n debug: bool = False,\n ):\n def from_dict(cls, dataset_path: str, data: Dict[str, any]):\n def __init__(\n self, models: List[Dict[str, any]], port: int = 5000, device: str = \"cuda\"\n ):\n def from_dict(cls, data: Dict[str, any]):\n def __init__(self, app_key: str, secret_key: str):\n def from_dict(cls, data: Dict[str, any]):\n def __init__(self, config_path: str):" }, { "identifier": "TextAudioSpeakerLoader", "path": "data_utils.py", "snippet": "class TextAudioSpeakerLoader(torch.utils.data.Dataset):\n \"\"\"\n 1) loads audio, speaker_id, text pairs\n 2) normalizes text and converts them to sequences of integers\n 3) computes spectrograms from audio files.\n \"\"\"\n\n def __init__(self, audiopaths_sid_text, hparams):\n self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)\n self.max_wav_value = hparams.max_wav_value\n self.sampling_rate = hparams.sampling_rate\n self.filter_length = hparams.filter_length\n self.hop_length = hparams.hop_length\n self.win_length = hparams.win_length\n self.sampling_rate = hparams.sampling_rate\n self.spk_map = hparams.spk2id\n self.hparams = hparams\n\n self.use_mel_spec_posterior = getattr(\n hparams, \"use_mel_posterior_encoder\", False\n )\n if self.use_mel_spec_posterior:\n self.n_mel_channels = getattr(hparams, \"n_mel_channels\", 80)\n\n self.cleaned_text = getattr(hparams, \"cleaned_text\", False)\n\n self.add_blank = hparams.add_blank\n self.min_text_len = getattr(hparams, \"min_text_len\", 1)\n self.max_text_len = getattr(hparams, \"max_text_len\", 384)\n\n random.seed(1234)\n random.shuffle(self.audiopaths_sid_text)\n self._filter()\n\n def _filter(self):\n \"\"\"\n Filter text & store spec lengths\n \"\"\"\n # Store spectrogram lengths for Bucketing\n # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)\n # spec_length = wav_length // hop_length\n\n audiopaths_sid_text_new = []\n lengths = []\n skipped = 0\n logger.info(\"Init dataset...\")\n for _id, spk, language, text, phones, tone, word2ph in tqdm(\n self.audiopaths_sid_text\n ):\n audiopath = f\"{_id}\"\n if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:\n phones = phones.split(\" \")\n tone = [int(i) for i in tone.split(\" \")]\n word2ph = [int(i) for i in word2ph.split(\" \")]\n audiopaths_sid_text_new.append(\n [audiopath, spk, language, text, phones, tone, word2ph]\n )\n lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))\n else:\n skipped += 1\n logger.info(\n \"skipped: \"\n + str(skipped)\n + \", total: \"\n + str(len(self.audiopaths_sid_text))\n )\n self.audiopaths_sid_text = audiopaths_sid_text_new\n self.lengths = lengths\n\n def get_audio_text_speaker_pair(self, audiopath_sid_text):\n # separate filename, speaker_id and text\n audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text\n\n bert, ja_bert, en_bert, phones, tone, language = self.get_text(\n text, word2ph, phones, tone, language, audiopath\n )\n\n spec, wav = self.get_audio(audiopath)\n sid = torch.LongTensor([int(self.spk_map[sid])])\n\n return (phones, spec, wav, sid, tone, language, bert, ja_bert, en_bert)\n\n def get_audio(self, filename):\n audio_norm, sampling_rate = torchaudio.load(filename, frame_offset=0, num_frames=-1, normalize=True, channels_first=True)\n '''\n # from https://github.com/YYuX-1145/Bert-VITS2-Integration-package\n audio, sampling_rate = load_wav_to_torch(filename)\n if sampling_rate != self.sampling_rate:\n raise ValueError(\n \"{} {} SR doesn't match target {} SR\".format(\n filename, sampling_rate, self.sampling_rate\n )\n )\n audio_norm = audio / self.max_wav_value\n audio_norm = audio_norm.unsqueeze(0)\n '''\n spec_filename = filename.replace(\".wav\", \".spec.pt\")\n if self.use_mel_spec_posterior:\n spec_filename = spec_filename.replace(\".spec.pt\", \".mel.pt\")\n try:\n spec = torch.load(spec_filename)\n except:\n if self.use_mel_spec_posterior:\n spec = mel_spectrogram_torch(\n audio_norm,\n self.filter_length,\n self.n_mel_channels,\n self.sampling_rate,\n self.hop_length,\n self.win_length,\n self.hparams.mel_fmin,\n self.hparams.mel_fmax,\n center=False,\n )\n else:\n spec = spectrogram_torch(\n audio_norm,\n self.filter_length,\n self.sampling_rate,\n self.hop_length,\n self.win_length,\n center=False,\n )\n spec = torch.squeeze(spec, 0)\n if config.train_ms_config.spec_cache:\n torch.save(spec, spec_filename)\n return spec, audio_norm\n\n def get_text(self, text, word2ph, phone, tone, language_str, wav_path):\n phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)\n if self.add_blank:\n phone = commons.intersperse(phone, 0)\n tone = commons.intersperse(tone, 0)\n language = commons.intersperse(language, 0)\n for i in range(len(word2ph)):\n word2ph[i] = word2ph[i] * 2\n word2ph[0] += 1\n bert_path = wav_path.replace(\".wav\", \".bert.pt\")\n try:\n bert_ori = torch.load(bert_path)\n assert bert_ori.shape[-1] == len(phone)\n except Exception as e:\n logger.warning(\"Bert load Failed\")\n logger.warning(e)\n\n if language_str == \"ZH\":\n bert = bert_ori\n ja_bert = torch.randn(1024, len(phone))\n en_bert = torch.randn(1024, len(phone))\n elif language_str == \"JP\":\n bert = torch.randn(1024, len(phone))\n ja_bert = bert_ori\n en_bert = torch.randn(1024, len(phone))\n elif language_str == \"EN\":\n bert = torch.randn(1024, len(phone))\n ja_bert = torch.randn(1024, len(phone))\n en_bert = bert_ori\n phone = torch.LongTensor(phone)\n tone = torch.LongTensor(tone)\n language = torch.LongTensor(language)\n return bert, ja_bert, en_bert, phone, tone, language\n\n def get_sid(self, sid):\n sid = torch.LongTensor([int(sid)])\n return sid\n\n def __getitem__(self, index):\n return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])\n\n def __len__(self):\n return len(self.audiopaths_sid_text)" }, { "identifier": "TextAudioSpeakerCollate", "path": "data_utils.py", "snippet": "class TextAudioSpeakerCollate:\n \"\"\"Zero-pads model inputs and targets\"\"\"\n\n def __init__(self, return_ids=False):\n self.return_ids = return_ids\n\n def __call__(self, batch):\n \"\"\"Collate's training batch from normalized text, audio and speaker identities\n PARAMS\n ------\n batch: [text_normalized, spec_normalized, wav_normalized, sid]\n \"\"\"\n # Right zero-pad all one-hot text sequences to max input length\n _, ids_sorted_decreasing = torch.sort(\n torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True\n )\n\n max_text_len = max([len(x[0]) for x in batch])\n max_spec_len = max([x[1].size(1) for x in batch])\n max_wav_len = max([x[2].size(1) for x in batch])\n\n text_lengths = torch.LongTensor(len(batch))\n spec_lengths = torch.LongTensor(len(batch))\n wav_lengths = torch.LongTensor(len(batch))\n sid = torch.LongTensor(len(batch))\n\n text_padded = torch.LongTensor(len(batch), max_text_len)\n tone_padded = torch.LongTensor(len(batch), max_text_len)\n language_padded = torch.LongTensor(len(batch), max_text_len)\n bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)\n ja_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)\n en_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)\n\n spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)\n wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)\n text_padded.zero_()\n tone_padded.zero_()\n language_padded.zero_()\n spec_padded.zero_()\n wav_padded.zero_()\n bert_padded.zero_()\n ja_bert_padded.zero_()\n en_bert_padded.zero_()\n\n for i in range(len(ids_sorted_decreasing)):\n row = batch[ids_sorted_decreasing[i]]\n\n text = row[0]\n text_padded[i, : text.size(0)] = text\n text_lengths[i] = text.size(0)\n\n spec = row[1]\n spec_padded[i, :, : spec.size(1)] = spec\n spec_lengths[i] = spec.size(1)\n\n wav = row[2]\n wav_padded[i, :, : wav.size(1)] = wav\n wav_lengths[i] = wav.size(1)\n\n sid[i] = row[3]\n\n tone = row[4]\n tone_padded[i, : tone.size(0)] = tone\n\n language = row[5]\n language_padded[i, : language.size(0)] = language\n\n bert = row[6]\n bert_padded[i, :, : bert.size(1)] = bert\n\n ja_bert = row[7]\n ja_bert_padded[i, :, : ja_bert.size(1)] = ja_bert\n\n en_bert = row[8]\n en_bert_padded[i, :, : en_bert.size(1)] = en_bert\n\n return (\n text_padded,\n text_lengths,\n spec_padded,\n spec_lengths,\n wav_padded,\n wav_lengths,\n sid,\n tone_padded,\n language_padded,\n bert_padded,\n ja_bert_padded,\n en_bert_padded,\n )" }, { "identifier": "DistributedBucketSampler", "path": "data_utils.py", "snippet": "class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):\n \"\"\"\n Maintain similar input lengths in a batch.\n Length groups are specified by boundaries.\n Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.\n\n It removes samples which are not included in the boundaries.\n Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.\n \"\"\"\n\n def __init__(\n self,\n dataset,\n batch_size,\n boundaries,\n num_replicas=None,\n rank=None,\n shuffle=True,\n ):\n super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)\n self.lengths = dataset.lengths\n self.batch_size = batch_size\n self.boundaries = boundaries\n\n self.buckets, self.num_samples_per_bucket = self._create_buckets()\n self.total_size = sum(self.num_samples_per_bucket)\n self.num_samples = self.total_size // self.num_replicas\n\n def _create_buckets(self):\n buckets = [[] for _ in range(len(self.boundaries) - 1)]\n for i in range(len(self.lengths)):\n length = self.lengths[i]\n idx_bucket = self._bisect(length)\n if idx_bucket != -1:\n buckets[idx_bucket].append(i)\n\n try:\n for i in range(len(buckets) - 1, 0, -1):\n if len(buckets[i]) == 0:\n buckets.pop(i)\n self.boundaries.pop(i + 1)\n assert all(len(bucket) > 0 for bucket in buckets)\n # When one bucket is not traversed\n except Exception as e:\n print(\"Bucket warning \", e)\n for i in range(len(buckets) - 1, -1, -1):\n if len(buckets[i]) == 0:\n buckets.pop(i)\n self.boundaries.pop(i + 1)\n\n num_samples_per_bucket = []\n for i in range(len(buckets)):\n len_bucket = len(buckets[i])\n total_batch_size = self.num_replicas * self.batch_size\n rem = (\n total_batch_size - (len_bucket % total_batch_size)\n ) % total_batch_size\n num_samples_per_bucket.append(len_bucket + rem)\n return buckets, num_samples_per_bucket\n\n def __iter__(self):\n # deterministically shuffle based on epoch\n g = torch.Generator()\n g.manual_seed(self.epoch)\n\n indices = []\n if self.shuffle:\n for bucket in self.buckets:\n indices.append(torch.randperm(len(bucket), generator=g).tolist())\n else:\n for bucket in self.buckets:\n indices.append(list(range(len(bucket))))\n\n batches = []\n for i in range(len(self.buckets)):\n bucket = self.buckets[i]\n len_bucket = len(bucket)\n if len_bucket == 0:\n continue\n ids_bucket = indices[i]\n num_samples_bucket = self.num_samples_per_bucket[i]\n\n # add extra samples to make it evenly divisible\n rem = num_samples_bucket - len_bucket\n ids_bucket = (\n ids_bucket\n + ids_bucket * (rem // len_bucket)\n + ids_bucket[: (rem % len_bucket)]\n )\n\n # subsample\n ids_bucket = ids_bucket[self.rank :: self.num_replicas]\n\n # batching\n for j in range(len(ids_bucket) // self.batch_size):\n batch = [\n bucket[idx]\n for idx in ids_bucket[\n j * self.batch_size : (j + 1) * self.batch_size\n ]\n ]\n batches.append(batch)\n\n if self.shuffle:\n batch_ids = torch.randperm(len(batches), generator=g).tolist()\n batches = [batches[i] for i in batch_ids]\n self.batches = batches\n\n assert len(self.batches) * self.batch_size == self.num_samples\n return iter(self.batches)\n\n def _bisect(self, x, lo=0, hi=None):\n if hi is None:\n hi = len(self.boundaries) - 1\n\n if hi > lo:\n mid = (hi + lo) // 2\n if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:\n return mid\n elif x <= self.boundaries[mid]:\n return self._bisect(x, lo, mid)\n else:\n return self._bisect(x, mid + 1, hi)\n else:\n return -1\n\n def __len__(self):\n return self.num_samples // self.batch_size" }, { "identifier": "AudioVisemesLoader", "path": "data_utils.py", "snippet": "class AudioVisemesLoader(torch.utils.data.Dataset):\n \"\"\"\n loads audio, visemes torch variable pairs from visemes list file .\n file is like: \n ./records/date_time.z.npy|./records/date_time.npy\n \"\"\"\n \n def __init__(self, audio_visemes_list_file, hparams):\n self.audio_visemes_list_items = load_filepaths_and_text(audio_visemes_list_file)\n print('audio_visemes_list_items: ', len(self.audio_visemes_list_items))\n random.seed(1234)\n random.shuffle(self.audio_visemes_list_items)\n self.max_visemes_len = 1210\n self.min_visemes_len = 1190\n self._filter()\n\n\n def _filter(self):\n # check if the file exists, and can parse as torch tensor\n audio_visemes_list_items_new = []\n for audio_file, visemes_file in self.audio_visemes_list_items:\n if os.path.exists(audio_file) and os.path.exists(visemes_file):\n # check using torch.load\n try:\n audio = torch.load(audio_file)\n visemes = np.load(visemes_file)\n if visemes.shape[0] < self.min_visemes_len:\n print('drop this data: --------- visemes.shape[0] < self.min_visemes_len: ', visemes.shape[0], visemes_file)\n continue\n audio_visemes_list_items_new.append([audio_file, visemes_file])\n except Exception as e:\n print('error: ', audio_file, visemes_file)\n print(e)\n self.audio_visemes_list_items = audio_visemes_list_items_new\n print('audio_visemes_list_items after filter: ', len(self.audio_visemes_list_items))\n\n def __getitem__(self, index):\n # read these two torch.tensor\n audio_file, visemes_file = self.audio_visemes_list_items[index]\n audio_z = torch.load(audio_file).squeeze(0).detach()\n # [192, seq_len(1722)]\n\n visemes = np.load(visemes_file)\n visemes = torch.from_numpy(visemes)\n #[seq_len(1194), 61]\n visemes = visemes.transpose(0, 1)\n #[61, seq_len(1194)]\n if visemes.shape[1] > self.max_visemes_len:\n # cut the extra part\n # print('__getitem__ 1 cut visemes from ', visemes.shape[0], ' to ', self.max_visemes_len, 'file: ', visemes_file)\n visemes = visemes[:, :self.max_visemes_len]\n elif visemes.shape[1] < self.max_visemes_len:\n # padding to max_visemes_len with last frame\n # print('__getitem__ 2 padding visemes from ', visemes.shape[0], ' to ', self.max_visemes_len, 'file: ', visemes_file)\n # last_frame = visemes[-1]\n # visemes = np.concatenate([visemes, np.tile(last_frame, (self.max_visemes_len - visemes.shape[0], 1))], axis=0)\n # visemes = torch.from_numpy(visemes)\n pass\n\n visemes_offset = 0.08 # 将visemes延迟n s\n visemes_offset_frames = int(visemes_offset * const_map.ARKIT_FPS)\n visemes = visemes[:, visemes_offset_frames:]\n\n audio_z_offset = 0.0\n audio_z_offset_frames = int(audio_z_offset * const_map.Z_FPS)\n audio_z = audio_z[:, audio_z_offset_frames:]\n\n # 获取二者的时长,将过长的一方多的部分丢弃\n visemes_duration = visemes.shape[1] / const_map.ARKIT_FPS\n audio_z_duration = audio_z.shape[1] / const_map.Z_FPS\n if visemes_duration > audio_z_duration:\n visemes = visemes[:, :int(audio_z_duration * const_map.ARKIT_FPS)]\n elif visemes_duration < audio_z_duration:\n audio_z = audio_z[:, :int(visemes_duration * const_map.Z_FPS)]\n\n\n # print('__getitem__ 3 audio.shape: ', audio.shape, 'visemes.shape: ', visemes.shape,'file: ', visemes_file)\n return audio_z, visemes\n\n def __len__(self):\n return len(self.audio_visemes_list_items)" }, { "identifier": "SynthesizerTrn", "path": "models.py", "snippet": "class SynthesizerTrn(nn.Module):\n \"\"\"\n Synthesizer for Training\n \"\"\"\n\n def __init__(\n self,\n n_vocab,\n spec_channels,\n segment_size,\n inter_channels,\n hidden_channels,\n filter_channels,\n n_heads,\n n_layers,\n kernel_size,\n p_dropout,\n resblock,\n resblock_kernel_sizes,\n resblock_dilation_sizes,\n upsample_rates,\n upsample_initial_channel,\n upsample_kernel_sizes,\n n_speakers=256,\n gin_channels=256,\n use_sdp=True,\n n_flow_layer=4,\n n_layers_trans_flow=4,\n flow_share_parameter=False,\n use_transformer_flow=True,\n **kwargs\n ):\n super().__init__()\n self.n_vocab = n_vocab\n self.spec_channels = spec_channels\n self.inter_channels = inter_channels\n self.hidden_channels = hidden_channels\n self.filter_channels = filter_channels\n self.n_heads = n_heads\n self.n_layers = n_layers\n self.kernel_size = kernel_size\n self.p_dropout = p_dropout\n self.resblock = resblock\n self.resblock_kernel_sizes = resblock_kernel_sizes\n self.resblock_dilation_sizes = resblock_dilation_sizes\n self.upsample_rates = upsample_rates\n self.upsample_initial_channel = upsample_initial_channel\n self.upsample_kernel_sizes = upsample_kernel_sizes\n self.segment_size = segment_size\n self.n_speakers = n_speakers\n self.gin_channels = gin_channels\n self.n_layers_trans_flow = n_layers_trans_flow\n self.use_spk_conditioned_encoder = kwargs.get(\n \"use_spk_conditioned_encoder\", True\n )\n self.use_sdp = use_sdp\n self.use_noise_scaled_mas = kwargs.get(\"use_noise_scaled_mas\", False)\n self.mas_noise_scale_initial = kwargs.get(\"mas_noise_scale_initial\", 0.01)\n self.noise_scale_delta = kwargs.get(\"noise_scale_delta\", 2e-6)\n self.current_mas_noise_scale = self.mas_noise_scale_initial\n if self.use_spk_conditioned_encoder and gin_channels > 0:\n self.enc_gin_channels = gin_channels\n self.enc_p = TextEncoder(\n n_vocab,\n inter_channels,\n hidden_channels,\n filter_channels,\n n_heads,\n n_layers,\n kernel_size,\n p_dropout,\n gin_channels=self.enc_gin_channels,\n )\n self.dec = Generator(\n inter_channels,\n resblock,\n resblock_kernel_sizes,\n resblock_dilation_sizes,\n upsample_rates,\n upsample_initial_channel,\n upsample_kernel_sizes,\n gin_channels=gin_channels,\n )\n self.enc_q = PosteriorEncoder(\n spec_channels,\n inter_channels,\n hidden_channels,\n 5,\n 1,\n 16,\n gin_channels=gin_channels,\n )\n if use_transformer_flow:\n self.flow = TransformerCouplingBlock(\n inter_channels,\n hidden_channels,\n filter_channels,\n n_heads,\n n_layers_trans_flow,\n 5,\n p_dropout,\n n_flow_layer,\n gin_channels=gin_channels,\n share_parameter=flow_share_parameter,\n )\n else:\n self.flow = ResidualCouplingBlock(\n inter_channels,\n hidden_channels,\n 5,\n 1,\n n_flow_layer,\n gin_channels=gin_channels,\n )\n self.sdp = StochasticDurationPredictor(\n hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels\n )\n self.dp = DurationPredictor(\n hidden_channels, 256, 3, 0.5, gin_channels=gin_channels\n )\n\n if n_speakers >= 1:\n self.emb_g = nn.Embedding(n_speakers, gin_channels)\n else:\n self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)\n\n def forward(\n self,\n x,\n x_lengths,\n y,\n y_lengths,\n sid,\n tone,\n language,\n bert,\n ja_bert,\n en_bert,\n ):\n if self.n_speakers > 0:\n g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]\n else:\n g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)\n x, m_p, logs_p, x_mask = self.enc_p(\n x, x_lengths, tone, language, bert, ja_bert, en_bert, g=g\n )\n z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)\n z_p = self.flow(z, y_mask, g=g)\n\n with torch.no_grad():\n # negative cross-entropy\n s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]\n neg_cent1 = torch.sum(\n -0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True\n ) # [b, 1, t_s]\n neg_cent2 = torch.matmul(\n -0.5 * (z_p**2).transpose(1, 2), s_p_sq_r\n ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]\n neg_cent3 = torch.matmul(\n z_p.transpose(1, 2), (m_p * s_p_sq_r)\n ) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]\n neg_cent4 = torch.sum(\n -0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True\n ) # [b, 1, t_s]\n neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4\n if self.use_noise_scaled_mas:\n epsilon = (\n torch.std(neg_cent)\n * torch.randn_like(neg_cent)\n * self.current_mas_noise_scale\n )\n neg_cent = neg_cent + epsilon\n\n attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)\n attn = (\n monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1))\n .unsqueeze(1)\n .detach()\n )\n\n w = attn.sum(2)\n\n l_length_sdp = self.sdp(x, x_mask, w, g=g)\n l_length_sdp = l_length_sdp / torch.sum(x_mask)\n\n logw_ = torch.log(w + 1e-6) * x_mask\n logw = self.dp(x, x_mask, g=g)\n logw_sdp = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=1.0)\n l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(\n x_mask\n ) # for averaging\n l_length_sdp += torch.sum((logw_sdp - logw_) ** 2, [1, 2]) / torch.sum(x_mask)\n\n l_length = l_length_dp + l_length_sdp\n\n # expand prior\n m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)\n logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)\n\n z_slice, ids_slice = commons.rand_slice_segments(\n z, y_lengths, self.segment_size\n )\n o = self.dec(z_slice, g=g)\n return (\n o,\n l_length,\n attn,\n ids_slice,\n x_mask,\n y_mask,\n (z, z_p, m_p, logs_p, m_q, logs_q),\n (x, logw, logw_, logw_sdp),\n g,\n )\n\n def infer(\n self,\n x,\n x_lengths,\n sid,\n tone,\n language,\n bert,\n ja_bert,\n en_bert,\n noise_scale=0.667,\n length_scale=1,\n noise_scale_w=0.8,\n max_len=None,\n sdp_ratio=0,\n y=None,\n ):\n # x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)\n # g = self.gst(y)\n if self.n_speakers > 0:\n g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]\n else:\n g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)\n x, m_p, logs_p, x_mask = self.enc_p(\n x, x_lengths, tone, language, bert, ja_bert, en_bert, g=g\n )\n logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (\n sdp_ratio\n ) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)\n w = torch.exp(logw) * x_mask * length_scale\n w_ceil = torch.ceil(w)\n y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()\n y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(\n x_mask.dtype\n )\n attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)\n attn = commons.generate_path(w_ceil, attn_mask)\n\n m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(\n 1, 2\n ) # [b, t', t], [b, t, d] -> [b, d, t']\n logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(\n 1, 2\n ) # [b, t', t], [b, t, d] -> [b, d, t']\n\n z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale\n z = self.flow(z_p, y_mask, g=g, reverse=True)\n o = self.dec((z * y_mask)[:, :, :max_len], g=g)\n return o, attn, y_mask, (z, z_p, m_p, logs_p)\n\n def get_post_enc_dec(self):\n return self.enc_q, self.dec" }, { "identifier": "MultiPeriodDiscriminator", "path": "models.py", "snippet": "class MultiPeriodDiscriminator(torch.nn.Module):\n def __init__(self, use_spectral_norm=False):\n super(MultiPeriodDiscriminator, self).__init__()\n periods = [2, 3, 5, 7, 11]\n\n discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]\n discs = discs + [\n DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods\n ]\n self.discriminators = nn.ModuleList(discs)\n\n def forward(self, y, y_hat):\n y_d_rs = []\n y_d_gs = []\n fmap_rs = []\n fmap_gs = []\n for i, d in enumerate(self.discriminators):\n y_d_r, fmap_r = d(y)\n y_d_g, fmap_g = d(y_hat)\n y_d_rs.append(y_d_r)\n y_d_gs.append(y_d_g)\n fmap_rs.append(fmap_r)\n fmap_gs.append(fmap_g)\n\n return y_d_rs, y_d_gs, fmap_rs, fmap_gs" }, { "identifier": "DurationDiscriminator", "path": "models.py", "snippet": "class DurationDiscriminator(nn.Module): # vits2\n def __init__(\n self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0\n ):\n super().__init__()\n\n self.in_channels = in_channels\n self.filter_channels = filter_channels\n self.kernel_size = kernel_size\n self.p_dropout = p_dropout\n self.gin_channels = gin_channels\n\n self.drop = nn.Dropout(p_dropout)\n self.conv_1 = nn.Conv1d(\n in_channels, filter_channels, kernel_size, padding=kernel_size // 2\n )\n self.norm_1 = modules.LayerNorm(filter_channels)\n self.conv_2 = nn.Conv1d(\n filter_channels, filter_channels, kernel_size, padding=kernel_size // 2\n )\n self.norm_2 = modules.LayerNorm(filter_channels)\n self.dur_proj = nn.Conv1d(1, filter_channels, 1)\n\n self.LSTM = nn.LSTM(\n 2 * filter_channels, filter_channels, batch_first=True, bidirectional=True\n )\n\n if gin_channels != 0:\n self.cond = nn.Conv1d(gin_channels, in_channels, 1)\n\n self.output_layer = nn.Sequential(\n nn.Linear(2 * filter_channels, 1), nn.Sigmoid()\n )\n\n def forward_probability(self, x, dur):\n dur = self.dur_proj(dur)\n x = torch.cat([x, dur], dim=1)\n x = x.transpose(1, 2)\n x, _ = self.LSTM(x)\n output_prob = self.output_layer(x)\n return output_prob\n\n def forward(self, x, x_mask, dur_r, dur_hat, g=None):\n x = torch.detach(x)\n if g is not None:\n g = torch.detach(g)\n x = x + self.cond(g)\n x = self.conv_1(x * x_mask)\n x = torch.relu(x)\n x = self.norm_1(x)\n x = self.drop(x)\n x = self.conv_2(x * x_mask)\n x = torch.relu(x)\n x = self.norm_2(x)\n x = self.drop(x)\n\n output_probs = []\n for dur in [dur_r, dur_hat]:\n output_prob = self.forward_probability(x, dur)\n output_probs.append(output_prob)\n\n return output_probs" }, { "identifier": "WavLMDiscriminator", "path": "models.py", "snippet": "class WavLMDiscriminator(nn.Module):\n \"\"\"docstring for Discriminator.\"\"\"\n\n def __init__(\n self, slm_hidden=768, slm_layers=13, initial_channel=64, use_spectral_norm=False\n ):\n super(WavLMDiscriminator, self).__init__()\n norm_f = weight_norm if use_spectral_norm == False else spectral_norm\n self.pre = norm_f(\n Conv1d(slm_hidden * slm_layers, initial_channel, 1, 1, padding=0)\n )\n\n self.convs = nn.ModuleList(\n [\n norm_f(\n nn.Conv1d(\n initial_channel, initial_channel * 2, kernel_size=5, padding=2\n )\n ),\n norm_f(\n nn.Conv1d(\n initial_channel * 2,\n initial_channel * 4,\n kernel_size=5,\n padding=2,\n )\n ),\n norm_f(\n nn.Conv1d(initial_channel * 4, initial_channel * 4, 5, 1, padding=2)\n ),\n ]\n )\n\n self.conv_post = norm_f(Conv1d(initial_channel * 4, 1, 3, 1, padding=1))\n\n def forward(self, x):\n x = self.pre(x)\n\n fmap = []\n for l in self.convs:\n x = l(x)\n x = F.leaky_relu(x, modules.LRELU_SLOPE)\n fmap.append(x)\n x = self.conv_post(x)\n x = torch.flatten(x, 1, -1)\n\n return x" }, { "identifier": "VisemesNet", "path": "models.py", "snippet": "class VisemesNet(nn.Module):\n def active(self, x):\n # active_fun: 0: null, 1: tanh, 2: relu, 3: LeakyReLU\n if self.active_fun == 1:\n return torch.tanh(x)\n elif self.active_fun == 2:\n return torch.relu(x)\n elif self.active_fun == 3:\n return self.leakyReLU(x)\n else:\n return x\n\n def __init__(self, hidden_channels, lstm_bidirectional=True, active_fun = 3, enable_conv=True, \n use_transformer = False, enable_dropout=True):\n super(VisemesNet, self).__init__()\n self.lstm_bidirectional = lstm_bidirectional\n self.lstm_directions = 2 if lstm_bidirectional else 1\n self.use_transformer = use_transformer\n self.enable_dropout = enable_dropout\n if active_fun == 3:\n self.leakyReLU = nn.LeakyReLU(negative_slope=0.01)\n if use_transformer:\n num_heads=8\n num_layers=3\n dim_feedforward=512\n dropout=0.1\n activation=\"relu\"\n self.transformer_encoder_layer = nn.TransformerEncoderLayer(\n d_model=hidden_channels, \n nhead=num_heads,\n dim_feedforward=dim_feedforward,\n dropout=dropout,\n activation=activation,\n batch_first=True\n )\n self.transformer_encoder = nn.TransformerEncoder(self.transformer_encoder_layer, num_layers=num_layers)\n else:\n self.lstm = nn.LSTM(input_size=hidden_channels, hidden_size=128, num_layers=3, batch_first=True, bidirectional=lstm_bidirectional)\n if use_transformer:\n self.fc1 = nn.Linear(hidden_channels, 96)\n else:\n self.fc1 = nn.Linear(128 * self.lstm_directions, 96)\n self.fc2 = nn.Linear(96, 61)\n dropout_rate = 0.5\n if self.enable_dropout:\n self.dropout = nn.Dropout(dropout_rate)\n conv_kernel_pre = 15\n conv_kernel_post = 11\n self.conv1d_pre = nn.Conv1d(in_channels=hidden_channels, out_channels=hidden_channels, kernel_size=conv_kernel_pre, stride=1, padding=conv_kernel_pre//2)\n self.conv1d_post = nn.Conv1d(in_channels=61, out_channels=61, kernel_size=conv_kernel_post, stride=1, padding=conv_kernel_post//2)\n self.enable_conv = enable_conv\n self.active_fun = active_fun\n\n def forward(self, x, y=None):\n # x [batch_size, hidden_channels, seq_len]\n if self.use_transformer:\n return self.forward_transformer(x, y)\n else:\n return self.forward_lstm(x, y)\n\n def forward_transformer(self, x, y=None):\n # x [batch_size, hidden_channels, seq_len]\n if self.enable_conv:\n x = self.conv1d_pre(x)\n # batch_first: True (batch, seq, feature); False (seq, batch, feature).\n x = x.transpose(1, 2)\n\n expressions = self.transformer_encoder(x)\n \n if self.enable_dropout:\n expressions = self.dropout(expressions)\n expressions = self.fc1(expressions)\n # expressions = self.active(expressions)\n if self.enable_dropout:\n expressions = self.dropout(expressions)\n expressions = self.fc2(expressions)\n\n expressions = expressions.transpose(1, 2)\n if self.enable_conv:\n expressions = self.conv1d_post(expressions)\n\n return expressions \n\n def forward_lstm(self, x, y=None):\n # x [batch_size, hidden_channels, seq_len]\n if self.enable_conv:\n x = self.conv1d_pre(x)\n x = x.transpose(1, 2)\n # x [batch_size, seq_len, hidden_channels]\n expressions = None\n expressions, _ = self.lstm(x)\n if self.enable_dropout:\n expressions = self.dropout(expressions)\n expressions = self.fc1(expressions)\n expressions = self.active(expressions)\n if self.enable_dropout:\n expressions = self.dropout(expressions)\n expressions = self.fc2(expressions)\n\n expressions = expressions.transpose(1, 2)\n if self.enable_conv:\n expressions = self.conv1d_post(expressions)\n return expressions\n \n def init_weights(self):\n # 初始化权重\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n nn.init.constant_(m.bias.data, 0)\n elif isinstance(m, nn.LSTM):\n for name, param in m.named_parameters():\n if 'weight_ih' in name:\n nn.init.xavier_uniform_(param.data)\n elif 'weight_hh' in name:\n nn.init.orthogonal_(param.data)\n elif 'bias' in name:\n nn.init.constant_(param.data, 0)\n elif isinstance(m, nn.BatchNorm1d):\n nn.init.constant_(m.weight.data, 1)\n nn.init.constant_(m.bias.data, 0)\n elif isinstance(m, nn.Conv1d):\n nn.init.xavier_uniform_(m.weight.data)\n nn.init.constant_(m.bias.data, 0)\n elif isinstance(m, nn.TransformerEncoderLayer):\n for name, param in m.named_parameters():\n if 'weight' in name:\n if param.dim() == 1:\n nn.init.normal_(param.data)\n else:\n nn.init.xavier_uniform_(param.data)\n elif 'bias' in name:\n nn.init.constant_(param.data, 0)\n elif isinstance(m, nn.TransformerEncoder):\n for param in m.parameters():\n if param.dim() > 1:\n nn.init.xavier_uniform_(param.data)\n else:\n nn.init.constant_(param.data, 0)" }, { "identifier": "generator_loss", "path": "losses.py", "snippet": "def generator_loss(disc_outputs):\n loss = 0\n gen_losses = []\n for dg in disc_outputs:\n dg = dg.float()\n l = torch.mean((1 - dg) ** 2)\n gen_losses.append(l)\n loss += l\n\n return loss, gen_losses" }, { "identifier": "discriminator_loss", "path": "losses.py", "snippet": "def discriminator_loss(disc_real_outputs, disc_generated_outputs):\n loss = 0\n r_losses = []\n g_losses = []\n for dr, dg in zip(disc_real_outputs, disc_generated_outputs):\n dr = dr.float()\n dg = dg.float()\n r_loss = torch.mean((1 - dr) ** 2)\n g_loss = torch.mean(dg**2)\n loss += r_loss + g_loss\n r_losses.append(r_loss.item())\n g_losses.append(g_loss.item())\n\n return loss, r_losses, g_losses" }, { "identifier": "feature_loss", "path": "losses.py", "snippet": "def feature_loss(fmap_r, fmap_g):\n loss = 0\n for dr, dg in zip(fmap_r, fmap_g):\n for rl, gl in zip(dr, dg):\n rl = rl.float().detach()\n gl = gl.float()\n loss += torch.mean(torch.abs(rl - gl))\n\n return loss * 2" }, { "identifier": "kl_loss", "path": "losses.py", "snippet": "def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):\n \"\"\"\n z_p, logs_q: [b, h, t_t]\n m_p, logs_p: [b, h, t_t]\n \"\"\"\n z_p = z_p.float()\n logs_q = logs_q.float()\n m_p = m_p.float()\n logs_p = logs_p.float()\n z_mask = z_mask.float()\n\n kl = logs_p - logs_q - 0.5\n kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2.0 * logs_p)\n kl = torch.sum(kl * z_mask)\n l = kl / torch.sum(z_mask)\n return l" }, { "identifier": "WavLMLoss", "path": "losses.py", "snippet": "class WavLMLoss(torch.nn.Module):\n def __init__(self, model, wd, model_sr, slm_sr=16000):\n super(WavLMLoss, self).__init__()\n self.wavlm = AutoModel.from_pretrained(model)\n self.wd = wd\n self.resample = torchaudio.transforms.Resample(model_sr, slm_sr)\n self.wavlm.eval()\n for param in self.wavlm.parameters():\n param.requires_grad = False\n\n def forward(self, wav, y_rec):\n with torch.no_grad():\n wav_16 = self.resample(wav)\n wav_embeddings = self.wavlm(\n input_values=wav_16, output_hidden_states=True\n ).hidden_states\n y_rec_16 = self.resample(y_rec)\n y_rec_embeddings = self.wavlm(\n input_values=y_rec_16.squeeze(), output_hidden_states=True\n ).hidden_states\n\n floss = 0\n for er, eg in zip(wav_embeddings, y_rec_embeddings):\n floss += torch.mean(torch.abs(er - eg))\n\n return floss.mean()\n\n def generator(self, y_rec):\n y_rec_16 = self.resample(y_rec)\n y_rec_embeddings = self.wavlm(\n input_values=y_rec_16, output_hidden_states=True\n ).hidden_states\n y_rec_embeddings = (\n torch.stack(y_rec_embeddings, dim=1)\n .transpose(-1, -2)\n .flatten(start_dim=1, end_dim=2)\n )\n y_df_hat_g = self.wd(y_rec_embeddings)\n loss_gen = torch.mean((1 - y_df_hat_g) ** 2)\n\n return loss_gen\n\n def discriminator(self, wav, y_rec):\n with torch.no_grad():\n wav_16 = self.resample(wav)\n wav_embeddings = self.wavlm(\n input_values=wav_16, output_hidden_states=True\n ).hidden_states\n y_rec_16 = self.resample(y_rec)\n y_rec_embeddings = self.wavlm(\n input_values=y_rec_16, output_hidden_states=True\n ).hidden_states\n\n y_embeddings = (\n torch.stack(wav_embeddings, dim=1)\n .transpose(-1, -2)\n .flatten(start_dim=1, end_dim=2)\n )\n y_rec_embeddings = (\n torch.stack(y_rec_embeddings, dim=1)\n .transpose(-1, -2)\n .flatten(start_dim=1, end_dim=2)\n )\n\n y_d_rs = self.wd(y_embeddings)\n y_d_gs = self.wd(y_rec_embeddings)\n\n y_df_hat_r, y_df_hat_g = y_d_rs, y_d_gs\n\n r_loss = torch.mean((1 - y_df_hat_r) ** 2)\n g_loss = torch.mean((y_df_hat_g) ** 2)\n\n loss_disc_f = r_loss + g_loss\n\n return loss_disc_f.mean()\n\n def discriminator_forward(self, wav):\n with torch.no_grad():\n wav_16 = self.resample(wav)\n wav_embeddings = self.wavlm(\n input_values=wav_16, output_hidden_states=True\n ).hidden_states\n y_embeddings = (\n torch.stack(wav_embeddings, dim=1)\n .transpose(-1, -2)\n .flatten(start_dim=1, end_dim=2)\n )\n\n y_d_rs = self.wd(y_embeddings)\n\n return y_d_rs" }, { "identifier": "mel_spectrogram_torch", "path": "mel_processing.py", "snippet": "def mel_spectrogram_torch(\n y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False\n):\n if torch.min(y) < -1.0:\n print(\"min value is \", torch.min(y))\n if torch.max(y) > 1.0:\n print(\"max value is \", torch.max(y))\n\n global mel_basis, hann_window\n dtype_device = str(y.dtype) + \"_\" + str(y.device)\n fmax_dtype_device = str(fmax) + \"_\" + dtype_device\n wnsize_dtype_device = str(win_size) + \"_\" + dtype_device\n if fmax_dtype_device not in mel_basis:\n mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)\n mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(\n dtype=y.dtype, device=y.device\n )\n if wnsize_dtype_device not in hann_window:\n hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(\n dtype=y.dtype, device=y.device\n )\n\n y = torch.nn.functional.pad(\n y.unsqueeze(1),\n (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),\n mode=\"reflect\",\n )\n y = y.squeeze(1)\n\n spec = torch.stft(\n y,\n n_fft,\n hop_length=hop_size,\n win_length=win_size,\n window=hann_window[wnsize_dtype_device],\n center=center,\n pad_mode=\"reflect\",\n normalized=False,\n onesided=True,\n return_complex=False,\n )\n\n spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)\n\n spec = torch.matmul(mel_basis[fmax_dtype_device], spec)\n spec = spectral_normalize_torch(spec)\n\n return spec" }, { "identifier": "spec_to_mel_torch", "path": "mel_processing.py", "snippet": "def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):\n global mel_basis\n dtype_device = str(spec.dtype) + \"_\" + str(spec.device)\n fmax_dtype_device = str(fmax) + \"_\" + dtype_device\n if fmax_dtype_device not in mel_basis:\n mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)\n mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(\n dtype=spec.dtype, device=spec.device\n )\n spec = torch.matmul(mel_basis[fmax_dtype_device], spec)\n spec = spectral_normalize_torch(spec)\n return spec" }, { "identifier": "symbols", "path": "text/symbols.py", "snippet": "" } ]
import platform import os import torch import torch.distributed as dist import logging import argparse import datetime import gc import commons import utils from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from config import config from data_utils import ( TextAudioSpeakerLoader, TextAudioSpeakerCollate, DistributedBucketSampler, AudioVisemesLoader, ) from models import ( SynthesizerTrn, MultiPeriodDiscriminator, DurationDiscriminator, WavLMDiscriminator, VisemesNet, ) from losses import ( generator_loss, discriminator_loss, feature_loss, kl_loss, WavLMLoss, ) from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols
14,949
global_visemes_step += 1 if batch_idx % hps.train.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tvisemes_hat_mse: {:.6f}\tgrad_norm_v: {:.6f}'.format( epoch, batch_idx * len(spec), len(train_loader.dataset), 100. * batch_idx / len(train_loader), visemes_hat_mse.item(), grad_norm_v)) def get_visemes_mse(visemes, visemes_hat): if visemes.shape[-1] != visemes_hat.shape[-1]: # 如果y和x的最低维度不一样 visemes_hat = F.interpolate(visemes_hat, size=visemes.shape[-1], mode='linear', align_corners=True) # 对x进行线性插值,使其形状与y一致 visemes_hat_mse = torch.mean(torch.pow(visemes_hat - visemes, 2)) return visemes_hat_mse def eval_visemes_only(epoch, hps, net_v, eval_loader): net_v.eval() with torch.no_grad(): visemes_hat_mse_sum = 0.0 for batch_idx, (spec, visemes) in tqdm(enumerate(eval_loader)): spec, visemes = spec.cuda(), visemes.cuda() # 通过VisemesFCNet从z生成visemes_hat,和均方差 visemes_hat = net_v(spec) visemes_hat_mse = get_visemes_mse(visemes, visemes_hat) visemes_hat_mse_sum += visemes_hat_mse # print('visemes_hat_mse', visemes_hat_mse) break visemes_hat_mse_avg = visemes_hat_mse_sum / (batch_idx + 1) log_str = '------------------ eval epoch: {} visemes_hat_mse_avg: {:.6f}'.format(epoch, visemes_hat_mse_avg) print(log_str) logger.warning(log_str) net_v.train() def run(): # 环境变量解析 envs = config.train_ms_config.env for env_name, env_value in envs.items(): if env_name not in os.environ.keys(): print("加载config中的配置{}".format(str(env_value))) os.environ[env_name] = str(env_value) print( "加载环境变量 \nMASTER_ADDR: {},\nMASTER_PORT: {},\nWORLD_SIZE: {},\nRANK: {},\nLOCAL_RANK: {}".format( os.environ["MASTER_ADDR"], os.environ["MASTER_PORT"], os.environ["WORLD_SIZE"], os.environ["RANK"], os.environ["LOCAL_RANK"], ) ) backend = "nccl" if platform.system() == "Windows": backend = "gloo" # If Windows,switch to gloo backend. dist.init_process_group( backend=backend, init_method="env://", timeout=datetime.timedelta(seconds=300), ) # Use torchrun instead of mp.spawn rank = dist.get_rank() local_rank = int(os.environ["LOCAL_RANK"]) n_gpus = dist.get_world_size() # 命令行/config.yml配置解析 # hps = utils.get_hparams() parser = argparse.ArgumentParser() # 非必要不建议使用命令行配置,请使用config.yml文件 parser.add_argument( "-c", "--config", type=str, default=config.train_ms_config.config_path, help="JSON file for configuration", ) parser.add_argument( "-m", "--model", type=str, help="数据集文件夹路径,请注意,数据不再默认放在/logs文件夹下。如果需要用命令行配置,请声明相对于根目录的路径", default=config.dataset_path, ) parser.add_argument('--visemes', dest='visemes', action="store_true", default=False, help="train visemes only, lock the encoder and decoder") args = parser.parse_args() model_dir = os.path.join(args.model, config.train_ms_config.model) if not os.path.exists(model_dir): os.makedirs(model_dir) hps = utils.get_hparams_from_file(args.config) hps.model_dir = model_dir set_logger(hps) if args.visemes: run_only_visemes(hps) # 比较路径是否相同 if os.path.realpath(args.config) != os.path.realpath( config.train_ms_config.config_path ): with open(args.config, "r", encoding="utf-8") as f: data = f.read() with open(config.train_ms_config.config_path, "w", encoding="utf-8") as f: f.write(data) torch.manual_seed(hps.train.seed) torch.cuda.set_device(local_rank) global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) writer = SummaryWriter(log_dir=hps.model_dir) writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, )
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) logger = logging.getLogger(__name__) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 global_step = 0 global_visemes_step = 0 def run_only_visemes(hps): # 使用最简单的单机模式,仅训练隐变量z到表情(visemes)的全连接 VisemesFCNet 的参数 global global_visemes_step torch.manual_seed(hps.train.seed) torch.cuda.set_device(0) train_dataset = AudioVisemesLoader(hps.data.training_visemes_files, hps.data) train_loader = DataLoader(train_dataset, num_workers=0, shuffle=False, pin_memory=True, batch_size=1, drop_last=True) eval_dataset = AudioVisemesLoader(hps.data.validation_visemes_files, hps.data) eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False) net_v = VisemesNet(hps.model.hidden_channels).cuda() latest_model_path = utils.latest_checkpoint_path(hps.model_dir, "V_*.pth") if latest_model_path is not None: _, optim_d, _, epoch_str = utils.load_checkpoint(latest_model_path, net_v, None, skip_optimizer=False) else : epoch_str = 1 global_visemes_step = 0 net_v.init_weights() optim_v = torch.optim.AdamW( net_v.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps) optim_v.param_groups[0]['initial_lr'] = hps.train.learning_rate scheduler_v = torch.optim.lr_scheduler.ExponentialLR(optim_v, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2, ) scaler = GradScaler(enabled=hps.train.bf16_run) for epoch in range(epoch_str, hps.train.epochs + 1): train_visemes_only(epoch, hps, net_v, train_loader, optim_v, scaler) scheduler_v.step() if epoch % hps.train.eval_interval == 0: eval_visemes_only(epoch, hps, net_v, eval_loader) utils.save_checkpoint(net_v, optim_v,hps.train.learning_rate , epoch, os.path.join(hps.model_dir, "V_{}.pth".format(epoch))) def train_visemes_only(epoch, hps, net_v, train_loader, optim_v, scaler): for batch_idx, (spec, visemes) in tqdm(enumerate(train_loader)): spec, visemes = spec.cuda(), visemes.cuda() with autocast(enabled=hps.train.bf16_run): # 通过VisemesNet从z生成visemes_hat,和均方差 visemes_hat = net_v(spec) visemes_hat_mse = get_visemes_mse(visemes, visemes_hat) optim_v.zero_grad() scaler.scale(visemes_hat_mse).backward() scaler.unscale_(optim_v) grad_norm_v = commons.clip_grad_value_(net_v.parameters(), None) scaler.step(optim_v) global global_visemes_step global_visemes_step += 1 if batch_idx % hps.train.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tvisemes_hat_mse: {:.6f}\tgrad_norm_v: {:.6f}'.format( epoch, batch_idx * len(spec), len(train_loader.dataset), 100. * batch_idx / len(train_loader), visemes_hat_mse.item(), grad_norm_v)) def get_visemes_mse(visemes, visemes_hat): if visemes.shape[-1] != visemes_hat.shape[-1]: # 如果y和x的最低维度不一样 visemes_hat = F.interpolate(visemes_hat, size=visemes.shape[-1], mode='linear', align_corners=True) # 对x进行线性插值,使其形状与y一致 visemes_hat_mse = torch.mean(torch.pow(visemes_hat - visemes, 2)) return visemes_hat_mse def eval_visemes_only(epoch, hps, net_v, eval_loader): net_v.eval() with torch.no_grad(): visemes_hat_mse_sum = 0.0 for batch_idx, (spec, visemes) in tqdm(enumerate(eval_loader)): spec, visemes = spec.cuda(), visemes.cuda() # 通过VisemesFCNet从z生成visemes_hat,和均方差 visemes_hat = net_v(spec) visemes_hat_mse = get_visemes_mse(visemes, visemes_hat) visemes_hat_mse_sum += visemes_hat_mse # print('visemes_hat_mse', visemes_hat_mse) break visemes_hat_mse_avg = visemes_hat_mse_sum / (batch_idx + 1) log_str = '------------------ eval epoch: {} visemes_hat_mse_avg: {:.6f}'.format(epoch, visemes_hat_mse_avg) print(log_str) logger.warning(log_str) net_v.train() def run(): # 环境变量解析 envs = config.train_ms_config.env for env_name, env_value in envs.items(): if env_name not in os.environ.keys(): print("加载config中的配置{}".format(str(env_value))) os.environ[env_name] = str(env_value) print( "加载环境变量 \nMASTER_ADDR: {},\nMASTER_PORT: {},\nWORLD_SIZE: {},\nRANK: {},\nLOCAL_RANK: {}".format( os.environ["MASTER_ADDR"], os.environ["MASTER_PORT"], os.environ["WORLD_SIZE"], os.environ["RANK"], os.environ["LOCAL_RANK"], ) ) backend = "nccl" if platform.system() == "Windows": backend = "gloo" # If Windows,switch to gloo backend. dist.init_process_group( backend=backend, init_method="env://", timeout=datetime.timedelta(seconds=300), ) # Use torchrun instead of mp.spawn rank = dist.get_rank() local_rank = int(os.environ["LOCAL_RANK"]) n_gpus = dist.get_world_size() # 命令行/config.yml配置解析 # hps = utils.get_hparams() parser = argparse.ArgumentParser() # 非必要不建议使用命令行配置,请使用config.yml文件 parser.add_argument( "-c", "--config", type=str, default=config.train_ms_config.config_path, help="JSON file for configuration", ) parser.add_argument( "-m", "--model", type=str, help="数据集文件夹路径,请注意,数据不再默认放在/logs文件夹下。如果需要用命令行配置,请声明相对于根目录的路径", default=config.dataset_path, ) parser.add_argument('--visemes', dest='visemes', action="store_true", default=False, help="train visemes only, lock the encoder and decoder") args = parser.parse_args() model_dir = os.path.join(args.model, config.train_ms_config.model) if not os.path.exists(model_dir): os.makedirs(model_dir) hps = utils.get_hparams_from_file(args.config) hps.model_dir = model_dir set_logger(hps) if args.visemes: run_only_visemes(hps) # 比较路径是否相同 if os.path.realpath(args.config) != os.path.realpath( config.train_ms_config.config_path ): with open(args.config, "r", encoding="utf-8") as f: data = f.read() with open(config.train_ms_config.config_path, "w", encoding="utf-8") as f: f.write(data) torch.manual_seed(hps.train.seed) torch.cuda.set_device(local_rank) global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) writer = SummaryWriter(log_dir=hps.model_dir) writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, )
collate_fn = TextAudioSpeakerCollate()
2
2023-12-27 03:09:11+00:00
24k
open-mmlab/Amphion
models/tts/naturalspeech2/ns2_trainer.py
[ { "identifier": "Logger", "path": "utils/util.py", "snippet": "class Logger(object):\n def __init__(\n self,\n filename,\n level=\"info\",\n when=\"D\",\n backCount=10,\n fmt=\"%(asctime)s : %(message)s\",\n ):\n self.level_relations = {\n \"debug\": logging.DEBUG,\n \"info\": logging.INFO,\n \"warning\": logging.WARNING,\n \"error\": logging.ERROR,\n \"crit\": logging.CRITICAL,\n }\n if level == \"debug\":\n fmt = \"%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s\"\n self.logger = logging.getLogger(filename)\n format_str = logging.Formatter(fmt)\n self.logger.setLevel(self.level_relations.get(level))\n sh = logging.StreamHandler()\n sh.setFormatter(format_str)\n th = handlers.TimedRotatingFileHandler(\n filename=filename, when=when, backupCount=backCount, encoding=\"utf-8\"\n )\n th.setFormatter(format_str)\n self.logger.addHandler(sh)\n self.logger.addHandler(th)\n self.logger.info(\n \"==========================New Starting Here==============================\"\n )" }, { "identifier": "ValueWindow", "path": "utils/util.py", "snippet": "class ValueWindow:\n def __init__(self, window_size=100):\n self._window_size = window_size\n self._values = []\n\n def append(self, x):\n self._values = self._values[-(self._window_size - 1) :] + [x]\n\n @property\n def sum(self):\n return sum(self._values)\n\n @property\n def count(self):\n return len(self._values)\n\n @property\n def average(self):\n return self.sum / max(1, self.count)\n\n def reset(self):\n self._values = []" }, { "identifier": "TTSTrainer", "path": "models/tts/base/tts_trainer.py", "snippet": "class TTSTrainer(BaseTrainer):\n r\"\"\"The base trainer for all TTS models. It inherits from BaseTrainer and implements\n ``build_criterion``, ``_build_dataset`` and ``_build_singer_lut`` methods. You can inherit from this\n class, and implement ``_build_model``, ``_forward_step``.\n \"\"\"\n\n def __init__(self, args=None, cfg=None):\n self.args = args\n self.cfg = cfg\n\n cfg.exp_name = args.exp_name\n\n # init with accelerate\n self._init_accelerator()\n self.accelerator.wait_for_everyone()\n\n with self.accelerator.main_process_first():\n self.logger = get_logger(args.exp_name, log_level=\"INFO\")\n\n # Log some info\n self.logger.info(\"=\" * 56)\n self.logger.info(\"||\\t\\t\" + \"New training process started.\" + \"\\t\\t||\")\n self.logger.info(\"=\" * 56)\n self.logger.info(\"\\n\")\n self.logger.debug(f\"Using {args.log_level.upper()} logging level.\")\n self.logger.info(f\"Experiment name: {args.exp_name}\")\n self.logger.info(f\"Experiment directory: {self.exp_dir}\")\n self.checkpoint_dir = os.path.join(self.exp_dir, \"checkpoint\")\n if self.accelerator.is_main_process:\n os.makedirs(self.checkpoint_dir, exist_ok=True)\n self.logger.debug(f\"Checkpoint directory: {self.checkpoint_dir}\")\n\n # init counts\n self.batch_count: int = 0\n self.step: int = 0\n self.epoch: int = 0\n self.max_epoch = (\n self.cfg.train.max_epoch if self.cfg.train.max_epoch > 0 else float(\"inf\")\n )\n self.logger.info(\n \"Max epoch: {}\".format(\n self.max_epoch if self.max_epoch < float(\"inf\") else \"Unlimited\"\n )\n )\n\n # Check values\n if self.accelerator.is_main_process:\n self.__check_basic_configs()\n # Set runtime configs\n self.save_checkpoint_stride = self.cfg.train.save_checkpoint_stride\n self.checkpoints_path = [\n [] for _ in range(len(self.save_checkpoint_stride))\n ]\n self.keep_last = [\n i if i > 0 else float(\"inf\") for i in self.cfg.train.keep_last\n ]\n self.run_eval = self.cfg.train.run_eval\n\n # set random seed\n with self.accelerator.main_process_first():\n start = time.monotonic_ns()\n self._set_random_seed(self.cfg.train.random_seed)\n end = time.monotonic_ns()\n self.logger.debug(\n f\"Setting random seed done in {(end - start) / 1e6:.2f}ms\"\n )\n self.logger.debug(f\"Random seed: {self.cfg.train.random_seed}\")\n\n # setup data_loader\n with self.accelerator.main_process_first():\n self.logger.info(\"Building dataset...\")\n start = time.monotonic_ns()\n self.train_dataloader, self.valid_dataloader = self._build_dataloader()\n end = time.monotonic_ns()\n self.logger.info(f\"Building dataset done in {(end - start) / 1e6:.2f}ms\")\n\n # save phone table to exp dir. Should be done before building model due to loading phone table in model\n if cfg.preprocess.use_phone and cfg.preprocess.phone_extractor != \"lexicon\":\n self._save_phone_symbols_file_to_exp_path()\n\n # setup model\n with self.accelerator.main_process_first():\n self.logger.info(\"Building model...\")\n start = time.monotonic_ns()\n self.model = self._build_model()\n end = time.monotonic_ns()\n self.logger.debug(self.model)\n self.logger.info(f\"Building model done in {(end - start) / 1e6:.2f}ms\")\n self.logger.info(\n f\"Model parameters: {self.__count_parameters(self.model)/1e6:.2f}M\"\n )\n\n # optimizer & scheduler\n with self.accelerator.main_process_first():\n self.logger.info(\"Building optimizer and scheduler...\")\n start = time.monotonic_ns()\n self.optimizer = self._build_optimizer()\n self.scheduler = self._build_scheduler()\n end = time.monotonic_ns()\n self.logger.info(\n f\"Building optimizer and scheduler done in {(end - start) / 1e6:.2f}ms\"\n )\n\n # create criterion\n with self.accelerator.main_process_first():\n self.logger.info(\"Building criterion...\")\n start = time.monotonic_ns()\n self.criterion = self._build_criterion()\n end = time.monotonic_ns()\n self.logger.info(f\"Building criterion done in {(end - start) / 1e6:.2f}ms\")\n\n # Resume or Finetune\n with self.accelerator.main_process_first():\n self._check_resume()\n\n # accelerate prepare\n self.logger.info(\"Initializing accelerate...\")\n start = time.monotonic_ns()\n self._accelerator_prepare()\n end = time.monotonic_ns()\n self.logger.info(f\"Initializing accelerate done in {(end - start) / 1e6:.2f}ms\")\n\n # save config file path\n self.config_save_path = os.path.join(self.exp_dir, \"args.json\")\n self.device = self.accelerator.device\n\n if cfg.preprocess.use_spkid and cfg.train.multi_speaker_training:\n self.speakers = self._build_speaker_lut()\n self.utt2spk_dict = self._build_utt2spk_dict()\n\n # Only for TTS tasks\n self.task_type = \"TTS\"\n self.logger.info(\"Task type: {}\".format(self.task_type))\n\n def _check_resume(self):\n # if args.resume:\n if self.args.resume or (\n self.cfg.model_type == \"VALLE\" and self.args.train_stage == 2\n ):\n if self.cfg.model_type == \"VALLE\" and self.args.train_stage == 2:\n self.args.resume_type = \"finetune\"\n\n self.logger.info(\"Resuming from checkpoint...\")\n start = time.monotonic_ns()\n self.ckpt_path = self._load_model(\n self.checkpoint_dir, self.args.checkpoint_path, self.args.resume_type\n )\n end = time.monotonic_ns()\n self.logger.info(\n f\"Resuming from checkpoint done in {(end - start) / 1e6:.2f}ms\"\n )\n self.checkpoints_path = json.load(\n open(os.path.join(self.ckpt_path, \"ckpts.json\"), \"r\")\n )\n\n self.checkpoint_dir = os.path.join(self.exp_dir, \"checkpoint\")\n if self.accelerator.is_main_process:\n os.makedirs(self.checkpoint_dir, exist_ok=True)\n self.logger.debug(f\"Checkpoint directory: {self.checkpoint_dir}\")\n\n def _init_accelerator(self):\n self.exp_dir = os.path.join(\n os.path.abspath(self.cfg.log_dir), self.args.exp_name\n )\n project_config = ProjectConfiguration(\n project_dir=self.exp_dir,\n logging_dir=os.path.join(self.exp_dir, \"log\"),\n )\n kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)\n self.accelerator = accelerate.Accelerator(\n gradient_accumulation_steps=self.cfg.train.gradient_accumulation_step,\n log_with=self.cfg.train.tracker,\n project_config=project_config,\n kwargs_handlers=[kwargs],\n )\n if self.accelerator.is_main_process:\n os.makedirs(project_config.project_dir, exist_ok=True)\n os.makedirs(project_config.logging_dir, exist_ok=True)\n with self.accelerator.main_process_first():\n self.accelerator.init_trackers(self.args.exp_name)\n\n def _accelerator_prepare(self):\n (\n self.train_dataloader,\n self.valid_dataloader,\n ) = self.accelerator.prepare(\n self.train_dataloader,\n self.valid_dataloader,\n )\n\n if isinstance(self.model, dict):\n for key in self.model.keys():\n self.model[key] = self.accelerator.prepare(self.model[key])\n else:\n self.model = self.accelerator.prepare(self.model)\n\n if isinstance(self.optimizer, dict):\n for key in self.optimizer.keys():\n self.optimizer[key] = self.accelerator.prepare(self.optimizer[key])\n else:\n self.optimizer = self.accelerator.prepare(self.optimizer)\n\n if isinstance(self.scheduler, dict):\n for key in self.scheduler.keys():\n self.scheduler[key] = self.accelerator.prepare(self.scheduler[key])\n else:\n self.scheduler = self.accelerator.prepare(self.scheduler)\n\n ### Following are methods only for TTS tasks ###\n def _build_dataset(self):\n pass\n\n def _build_criterion(self):\n pass\n\n def _build_model(self):\n pass\n\n def _build_dataloader(self):\n \"\"\"Build dataloader which merges a series of datasets.\"\"\"\n # Build dataset instance for each dataset and combine them by ConcatDataset\n Dataset, Collator = self._build_dataset()\n\n # Build train set\n datasets_list = []\n for dataset in self.cfg.dataset:\n subdataset = Dataset(self.cfg, dataset, is_valid=False)\n datasets_list.append(subdataset)\n train_dataset = ConcatDataset(datasets_list)\n train_collate = Collator(self.cfg)\n _, batch_sampler = build_samplers(train_dataset, self.cfg, self.logger, \"train\")\n train_loader = DataLoader(\n train_dataset,\n collate_fn=train_collate,\n batch_sampler=batch_sampler,\n num_workers=self.cfg.train.dataloader.num_worker,\n pin_memory=self.cfg.train.dataloader.pin_memory,\n )\n\n # Build test set\n datasets_list = []\n for dataset in self.cfg.dataset:\n subdataset = Dataset(self.cfg, dataset, is_valid=True)\n datasets_list.append(subdataset)\n valid_dataset = ConcatDataset(datasets_list)\n valid_collate = Collator(self.cfg)\n _, batch_sampler = build_samplers(valid_dataset, self.cfg, self.logger, \"valid\")\n valid_loader = DataLoader(\n valid_dataset,\n collate_fn=valid_collate,\n batch_sampler=batch_sampler,\n num_workers=self.cfg.train.dataloader.num_worker,\n pin_memory=self.cfg.train.dataloader.pin_memory,\n )\n return train_loader, valid_loader\n\n def _build_optimizer(self):\n pass\n\n def _build_scheduler(self):\n pass\n\n def _load_model(self, checkpoint_dir, checkpoint_path=None, resume_type=\"resume\"):\n \"\"\"Load model from checkpoint. If a folder is given, it will\n load the latest checkpoint in checkpoint_dir. If a path is given\n it will load the checkpoint specified by checkpoint_path.\n **Only use this method after** ``accelerator.prepare()``.\n \"\"\"\n if checkpoint_path is None:\n ls = [str(i) for i in Path(checkpoint_dir).glob(\"*\")]\n ls.sort(key=lambda x: int(x.split(\"_\")[-3].split(\"-\")[-1]), reverse=True)\n checkpoint_path = ls[0]\n self.logger.info(\"Load model from {}\".format(checkpoint_path))\n print(\"Load model from {}\".format(checkpoint_path))\n if resume_type == \"resume\":\n self.accelerator.load_state(checkpoint_path)\n self.epoch = int(checkpoint_path.split(\"_\")[-3].split(\"-\")[-1]) + 1\n self.step = int(checkpoint_path.split(\"_\")[-2].split(\"-\")[-1]) + 1\n elif resume_type == \"finetune\":\n self.model.load_state_dict(\n torch.load(os.path.join(checkpoint_path, \"pytorch_model.bin\"))\n )\n self.model.cuda(self.accelerator.device)\n self.logger.info(\"Load model weights for finetune SUCCESS!\")\n else:\n raise ValueError(\"Unsupported resume type: {}\".format(resume_type))\n\n return checkpoint_path\n\n ### THIS IS MAIN ENTRY ###\n def train_loop(self):\n r\"\"\"Training loop. The public entry of training process.\"\"\"\n # Wait everyone to prepare before we move on\n self.accelerator.wait_for_everyone()\n # dump config file\n if self.accelerator.is_main_process:\n self.__dump_cfg(self.config_save_path)\n\n # self.optimizer.zero_grad()\n # Wait to ensure good to go\n\n self.accelerator.wait_for_everyone()\n while self.epoch < self.max_epoch:\n self.logger.info(\"\\n\")\n self.logger.info(\"-\" * 32)\n self.logger.info(\"Epoch {}: \".format(self.epoch))\n\n # Do training & validating epoch\n train_total_loss, train_losses = self._train_epoch()\n if isinstance(train_losses, dict):\n for key, loss in train_losses.items():\n self.logger.info(\" |- Train/{} Loss: {:.6f}\".format(key, loss))\n self.accelerator.log(\n {\"Epoch/Train {} Loss\".format(key): loss},\n step=self.epoch,\n )\n\n valid_total_loss, valid_losses = self._valid_epoch()\n if isinstance(valid_losses, dict):\n for key, loss in valid_losses.items():\n self.logger.info(\" |- Valid/{} Loss: {:.6f}\".format(key, loss))\n self.accelerator.log(\n {\"Epoch/Train {} Loss\".format(key): loss},\n step=self.epoch,\n )\n\n self.logger.info(\" |- Train/Loss: {:.6f}\".format(train_total_loss))\n self.logger.info(\" |- Valid/Loss: {:.6f}\".format(valid_total_loss))\n self.accelerator.log(\n {\n \"Epoch/Train Loss\": train_total_loss,\n \"Epoch/Valid Loss\": valid_total_loss,\n },\n step=self.epoch,\n )\n\n self.accelerator.wait_for_everyone()\n\n # Check if hit save_checkpoint_stride and run_eval\n run_eval = False\n if self.accelerator.is_main_process:\n save_checkpoint = False\n hit_dix = []\n for i, num in enumerate(self.save_checkpoint_stride):\n if self.epoch % num == 0:\n save_checkpoint = True\n hit_dix.append(i)\n run_eval |= self.run_eval[i]\n\n self.accelerator.wait_for_everyone()\n if self.accelerator.is_main_process and save_checkpoint:\n path = os.path.join(\n self.checkpoint_dir,\n \"epoch-{:04d}_step-{:07d}_loss-{:.6f}\".format(\n self.epoch, self.step, train_total_loss\n ),\n )\n self.accelerator.save_state(path)\n\n json.dump(\n self.checkpoints_path,\n open(os.path.join(path, \"ckpts.json\"), \"w\"),\n ensure_ascii=False,\n indent=4,\n )\n\n # Remove old checkpoints\n to_remove = []\n for idx in hit_dix:\n self.checkpoints_path[idx].append(path)\n while len(self.checkpoints_path[idx]) > self.keep_last[idx]:\n to_remove.append((idx, self.checkpoints_path[idx].pop(0)))\n\n # Search conflicts\n total = set()\n for i in self.checkpoints_path:\n total |= set(i)\n do_remove = set()\n for idx, path in to_remove[::-1]:\n if path in total:\n self.checkpoints_path[idx].insert(0, path)\n else:\n do_remove.add(path)\n\n # Remove old checkpoints\n for path in do_remove:\n shutil.rmtree(path, ignore_errors=True)\n self.logger.debug(f\"Remove old checkpoint: {path}\")\n\n self.accelerator.wait_for_everyone()\n if run_eval:\n # TODO: run evaluation\n pass\n\n # Update info for each epoch\n self.epoch += 1\n\n # Finish training and save final checkpoint\n self.accelerator.wait_for_everyone()\n if self.accelerator.is_main_process:\n path = os.path.join(\n self.checkpoint_dir,\n \"final_epoch-{:04d}_step-{:07d}_loss-{:.6f}\".format(\n self.epoch, self.step, valid_total_loss\n ),\n )\n self.accelerator.save_state(\n os.path.join(\n self.checkpoint_dir,\n \"final_epoch-{:04d}_step-{:07d}_loss-{:.6f}\".format(\n self.epoch, self.step, valid_total_loss\n ),\n )\n )\n\n json.dump(\n self.checkpoints_path,\n open(os.path.join(path, \"ckpts.json\"), \"w\"),\n ensure_ascii=False,\n indent=4,\n )\n\n self.accelerator.end_training()\n\n ### Following are methods that can be used directly in child classes ###\n def _train_epoch(self):\n r\"\"\"Training epoch. Should return average loss of a batch (sample) over\n one epoch. See ``train_loop`` for usage.\n \"\"\"\n if isinstance(self.model, dict):\n for key in self.model.keys():\n self.model[key].train()\n else:\n self.model.train()\n\n epoch_sum_loss: float = 0.0\n epoch_losses: dict = {}\n epoch_step: int = 0\n for batch in tqdm(\n self.train_dataloader,\n desc=f\"Training Epoch {self.epoch}\",\n unit=\"batch\",\n colour=\"GREEN\",\n leave=False,\n dynamic_ncols=True,\n smoothing=0.04,\n disable=not self.accelerator.is_main_process,\n ):\n # Do training step and BP\n with self.accelerator.accumulate(self.model):\n total_loss, train_losses, _ = self._train_step(batch)\n self.batch_count += 1\n\n # Update info for each step\n # TODO: step means BP counts or batch counts?\n if self.batch_count % self.cfg.train.gradient_accumulation_step == 0:\n if isinstance(self.scheduler, dict):\n for key in self.scheduler.keys():\n self.scheduler[key].step()\n else:\n if isinstance(self.scheduler, Eden):\n self.scheduler.step_batch(self.step)\n else:\n self.scheduler.step()\n\n epoch_sum_loss += total_loss\n\n if isinstance(train_losses, dict):\n for key, value in train_losses.items():\n epoch_losses[key] += value\n\n if isinstance(train_losses, dict):\n for key, loss in train_losses.items():\n self.accelerator.log(\n {\"Epoch/Train {} Loss\".format(key): loss},\n step=self.step,\n )\n\n self.step += 1\n epoch_step += 1\n\n self.accelerator.wait_for_everyone()\n\n epoch_sum_loss = (\n epoch_sum_loss\n / len(self.train_dataloader)\n * self.cfg.train.gradient_accumulation_step\n )\n\n for key in epoch_losses.keys():\n epoch_losses[key] = (\n epoch_losses[key]\n / len(self.train_dataloader)\n * self.cfg.train.gradient_accumulation_step\n )\n\n return epoch_sum_loss, epoch_losses\n\n @torch.inference_mode()\n def _valid_epoch(self):\n r\"\"\"Testing epoch. Should return average loss of a batch (sample) over\n one epoch. See ``train_loop`` for usage.\n \"\"\"\n if isinstance(self.model, dict):\n for key in self.model.keys():\n self.model[key].eval()\n else:\n self.model.eval()\n\n epoch_sum_loss = 0.0\n epoch_losses = dict()\n for batch in tqdm(\n self.valid_dataloader,\n desc=f\"Validating Epoch {self.epoch}\",\n unit=\"batch\",\n colour=\"GREEN\",\n leave=False,\n dynamic_ncols=True,\n smoothing=0.04,\n disable=not self.accelerator.is_main_process,\n ):\n total_loss, valid_losses, valid_stats = self._valid_step(batch)\n epoch_sum_loss += total_loss\n if isinstance(valid_losses, dict):\n for key, value in valid_losses.items():\n if key not in epoch_losses.keys():\n epoch_losses[key] = value\n else:\n epoch_losses[key] += value\n\n epoch_sum_loss = epoch_sum_loss / len(self.valid_dataloader)\n for key in epoch_losses.keys():\n epoch_losses[key] = epoch_losses[key] / len(self.valid_dataloader)\n\n self.accelerator.wait_for_everyone()\n\n return epoch_sum_loss, epoch_losses\n\n def _train_step(self):\n pass\n\n def _valid_step(self, batch):\n pass\n\n def _inference(self):\n pass\n\n def _is_valid_pattern(self, directory_name):\n directory_name = str(directory_name)\n pattern = r\"^epoch-\\d{4}_step-\\d{7}_loss-\\d{1}\\.\\d{6}\"\n return re.match(pattern, directory_name) is not None\n\n def _check_basic_configs(self):\n if self.cfg.train.gradient_accumulation_step <= 0:\n self.logger.fatal(\"Invalid gradient_accumulation_step value!\")\n self.logger.error(\n f\"Invalid gradient_accumulation_step value: {self.cfg.train.gradient_accumulation_step}. It should be positive.\"\n )\n self.accelerator.end_training()\n raise ValueError(\n f\"Invalid gradient_accumulation_step value: {self.cfg.train.gradient_accumulation_step}. It should be positive.\"\n )\n\n def __dump_cfg(self, path):\n os.makedirs(os.path.dirname(path), exist_ok=True)\n json5.dump(\n self.cfg,\n open(path, \"w\"),\n indent=4,\n sort_keys=True,\n ensure_ascii=False,\n quote_keys=True,\n )\n\n def __check_basic_configs(self):\n if self.cfg.train.gradient_accumulation_step <= 0:\n self.logger.fatal(\"Invalid gradient_accumulation_step value!\")\n self.logger.error(\n f\"Invalid gradient_accumulation_step value: {self.cfg.train.gradient_accumulation_step}. It should be positive.\"\n )\n self.accelerator.end_training()\n raise ValueError(\n f\"Invalid gradient_accumulation_step value: {self.cfg.train.gradient_accumulation_step}. It should be positive.\"\n )\n # TODO: check other values\n\n @staticmethod\n def __count_parameters(model):\n model_param = 0.0\n if isinstance(model, dict):\n for key, value in model.items():\n model_param += sum(p.numel() for p in model[key].parameters())\n else:\n model_param = sum(p.numel() for p in model.parameters())\n return model_param\n\n def _build_speaker_lut(self):\n # combine speakers\n if not os.path.exists(os.path.join(self.exp_dir, self.cfg.preprocess.spk2id)):\n speakers = {}\n else:\n with open(\n os.path.join(self.exp_dir, self.cfg.preprocess.spk2id), \"r\"\n ) as speaker_file:\n speakers = json.load(speaker_file)\n for dataset in self.cfg.dataset:\n speaker_lut_path = os.path.join(\n self.cfg.preprocess.processed_dir, dataset, self.cfg.preprocess.spk2id\n )\n with open(speaker_lut_path, \"r\") as speaker_lut_path:\n singer_lut = json.load(speaker_lut_path)\n for singer in singer_lut.keys():\n if singer not in speakers:\n speakers[singer] = len(speakers)\n with open(\n os.path.join(self.exp_dir, self.cfg.preprocess.spk2id), \"w\"\n ) as speaker_file:\n json.dump(speakers, speaker_file, indent=4, ensure_ascii=False)\n print(\n \"speakers have been dumped to {}\".format(\n os.path.join(self.exp_dir, self.cfg.preprocess.spk2id)\n )\n )\n return speakers\n\n def _build_utt2spk_dict(self):\n # combine speakers\n utt2spk = {}\n if not os.path.exists(os.path.join(self.exp_dir, self.cfg.preprocess.utt2spk)):\n utt2spk = {}\n else:\n with open(\n os.path.join(self.exp_dir, self.cfg.preprocess.utt2spk), \"r\"\n ) as utt2spk_file:\n for line in utt2spk_file.readlines():\n utt, spk = line.strip().split(\"\\t\")\n utt2spk[utt] = spk\n for dataset in self.cfg.dataset:\n utt2spk_dict_path = os.path.join(\n self.cfg.preprocess.processed_dir, dataset, self.cfg.preprocess.utt2spk\n )\n with open(utt2spk_dict_path, \"r\") as utt2spk_dict:\n for line in utt2spk_dict.readlines():\n utt, spk = line.strip().split(\"\\t\")\n if utt not in utt2spk.keys():\n utt2spk[utt] = spk\n with open(\n os.path.join(self.exp_dir, self.cfg.preprocess.utt2spk), \"w\"\n ) as utt2spk_file:\n for utt, spk in utt2spk.items():\n utt2spk_file.write(utt + \"\\t\" + spk + \"\\n\")\n print(\n \"utterance and speaker mapper have been dumped to {}\".format(\n os.path.join(self.exp_dir, self.cfg.preprocess.utt2spk)\n )\n )\n return utt2spk\n\n def _save_phone_symbols_file_to_exp_path(self):\n phone_symbols_file = os.path.join(\n self.cfg.preprocess.processed_dir,\n self.cfg.dataset[0],\n self.cfg.preprocess.symbols_dict,\n )\n phone_symbols_file_to_exp_path = os.path.join(\n self.exp_dir, self.cfg.preprocess.symbols_dict\n )\n shutil.copy(phone_symbols_file, phone_symbols_file_to_exp_path)\n print(\n \"phone symbols been dumped to {}\".format(\n os.path.join(self.exp_dir, self.cfg.preprocess.symbols_dict)\n )\n )" }, { "identifier": "BaseTrainer", "path": "models/base/base_trainer.py", "snippet": "class BaseTrainer(object):\n def __init__(self, args, cfg):\n self.args = args\n self.log_dir = args.log_dir\n self.cfg = cfg\n\n self.checkpoint_dir = os.path.join(args.log_dir, \"checkpoints\")\n os.makedirs(self.checkpoint_dir, exist_ok=True)\n if not cfg.train.ddp or args.local_rank == 0:\n self.sw = SummaryWriter(os.path.join(args.log_dir, \"events\"))\n self.logger = self.build_logger()\n self.time_window = ValueWindow(50)\n\n self.step = 0\n self.epoch = -1\n self.max_epochs = self.cfg.train.epochs\n self.max_steps = self.cfg.train.max_steps\n\n # set random seed & init distributed training\n set_all_random_seed(self.cfg.train.random_seed)\n if cfg.train.ddp:\n dist.init_process_group(backend=\"nccl\")\n\n if cfg.model_type not in [\"AutoencoderKL\", \"AudioLDM\"]:\n self.singers = self.build_singers_lut()\n\n # setup data_loader\n self.data_loader = self.build_data_loader()\n\n # setup model & enable distributed training\n self.model = self.build_model()\n print(self.model)\n\n if isinstance(self.model, dict):\n for key, value in self.model.items():\n value.cuda(self.args.local_rank)\n if key == \"PQMF\":\n continue\n if cfg.train.ddp:\n self.model[key] = DistributedDataParallel(\n value, device_ids=[self.args.local_rank]\n )\n else:\n self.model.cuda(self.args.local_rank)\n if cfg.train.ddp:\n self.model = DistributedDataParallel(\n self.model, device_ids=[self.args.local_rank]\n )\n\n # create criterion\n self.criterion = self.build_criterion()\n if isinstance(self.criterion, dict):\n for key, value in self.criterion.items():\n self.criterion[key].cuda(args.local_rank)\n else:\n self.criterion.cuda(self.args.local_rank)\n\n # optimizer\n self.optimizer = self.build_optimizer()\n self.scheduler = self.build_scheduler()\n\n # save config file\n self.config_save_path = os.path.join(self.checkpoint_dir, \"args.json\")\n\n def build_logger(self):\n log_file = os.path.join(self.checkpoint_dir, \"train.log\")\n logger = Logger(log_file, level=self.args.log_level).logger\n\n return logger\n\n def build_dataset(self):\n raise NotImplementedError\n\n def build_data_loader(self):\n Dataset, Collator = self.build_dataset()\n # build dataset instance for each dataset and combine them by ConcatDataset\n datasets_list = []\n for dataset in self.cfg.dataset:\n subdataset = Dataset(self.cfg, dataset, is_valid=False)\n datasets_list.append(subdataset)\n train_dataset = ConcatDataset(datasets_list)\n\n train_collate = Collator(self.cfg)\n # TODO: multi-GPU training\n if self.cfg.train.ddp:\n raise NotImplementedError(\"DDP is not supported yet.\")\n\n # sampler will provide indices to batch_sampler, which will perform batching and yield batch indices\n batch_sampler = BatchSampler(\n cfg=self.cfg, concat_dataset=train_dataset, dataset_list=datasets_list\n )\n\n # use batch_sampler argument instead of (sampler, shuffle, drop_last, batch_size)\n train_loader = DataLoader(\n train_dataset,\n collate_fn=train_collate,\n num_workers=self.args.num_workers,\n batch_sampler=batch_sampler,\n pin_memory=False,\n )\n if not self.cfg.train.ddp or self.args.local_rank == 0:\n datasets_list = []\n for dataset in self.cfg.dataset:\n subdataset = Dataset(self.cfg, dataset, is_valid=True)\n datasets_list.append(subdataset)\n valid_dataset = ConcatDataset(datasets_list)\n valid_collate = Collator(self.cfg)\n batch_sampler = BatchSampler(\n cfg=self.cfg, concat_dataset=valid_dataset, dataset_list=datasets_list\n )\n valid_loader = DataLoader(\n valid_dataset,\n collate_fn=valid_collate,\n num_workers=1,\n batch_sampler=batch_sampler,\n )\n else:\n raise NotImplementedError(\"DDP is not supported yet.\")\n # valid_loader = None\n data_loader = {\"train\": train_loader, \"valid\": valid_loader}\n return data_loader\n\n def build_singers_lut(self):\n # combine singers\n if not os.path.exists(os.path.join(self.log_dir, self.cfg.preprocess.spk2id)):\n singers = collections.OrderedDict()\n else:\n with open(\n os.path.join(self.log_dir, self.cfg.preprocess.spk2id), \"r\"\n ) as singer_file:\n singers = json.load(singer_file)\n singer_count = len(singers)\n for dataset in self.cfg.dataset:\n singer_lut_path = os.path.join(\n self.cfg.preprocess.processed_dir, dataset, self.cfg.preprocess.spk2id\n )\n with open(singer_lut_path, \"r\") as singer_lut_path:\n singer_lut = json.load(singer_lut_path)\n for singer in singer_lut.keys():\n if singer not in singers:\n singers[singer] = singer_count\n singer_count += 1\n with open(\n os.path.join(self.log_dir, self.cfg.preprocess.spk2id), \"w\"\n ) as singer_file:\n json.dump(singers, singer_file, indent=4, ensure_ascii=False)\n print(\n \"singers have been dumped to {}\".format(\n os.path.join(self.log_dir, self.cfg.preprocess.spk2id)\n )\n )\n return singers\n\n def build_model(self):\n raise NotImplementedError()\n\n def build_optimizer(self):\n raise NotImplementedError\n\n def build_scheduler(self):\n raise NotImplementedError()\n\n def build_criterion(self):\n raise NotImplementedError\n\n def get_state_dict(self):\n raise NotImplementedError\n\n def save_config_file(self):\n save_config(self.config_save_path, self.cfg)\n\n # TODO, save without module.\n def save_checkpoint(self, state_dict, saved_model_path):\n torch.save(state_dict, saved_model_path)\n\n def load_checkpoint(self):\n checkpoint_path = os.path.join(self.checkpoint_dir, \"checkpoint\")\n assert os.path.exists(checkpoint_path)\n checkpoint_filename = open(checkpoint_path).readlines()[-1].strip()\n model_path = os.path.join(self.checkpoint_dir, checkpoint_filename)\n assert os.path.exists(model_path)\n if not self.cfg.train.ddp or self.args.local_rank == 0:\n self.logger.info(f\"Re(store) from {model_path}\")\n checkpoint = torch.load(model_path, map_location=\"cpu\")\n return checkpoint\n\n def load_model(self, checkpoint):\n raise NotImplementedError\n\n def restore(self):\n checkpoint = self.load_checkpoint()\n self.load_model(checkpoint)\n\n def train_step(self, data):\n raise NotImplementedError(\n f\"Need to implement function {sys._getframe().f_code.co_name} in \"\n f\"your sub-class of {self.__class__.__name__}. \"\n )\n\n @torch.no_grad()\n def eval_step(self):\n raise NotImplementedError(\n f\"Need to implement function {sys._getframe().f_code.co_name} in \"\n f\"your sub-class of {self.__class__.__name__}. \"\n )\n\n def write_summary(self, losses, stats):\n raise NotImplementedError(\n f\"Need to implement function {sys._getframe().f_code.co_name} in \"\n f\"your sub-class of {self.__class__.__name__}. \"\n )\n\n def write_valid_summary(self, losses, stats):\n raise NotImplementedError(\n f\"Need to implement function {sys._getframe().f_code.co_name} in \"\n f\"your sub-class of {self.__class__.__name__}. \"\n )\n\n def echo_log(self, losses, mode=\"Training\"):\n message = [\n \"{} - Epoch {} Step {}: [{:.3f} s/step]\".format(\n mode, self.epoch + 1, self.step, self.time_window.average\n )\n ]\n\n for key in sorted(losses.keys()):\n if isinstance(losses[key], dict):\n for k, v in losses[key].items():\n message.append(\n str(k).split(\"/\")[-1] + \"=\" + str(round(float(v), 5))\n )\n else:\n message.append(\n str(key).split(\"/\")[-1] + \"=\" + str(round(float(losses[key]), 5))\n )\n self.logger.info(\", \".join(message))\n\n def eval_epoch(self):\n self.logger.info(\"Validation...\")\n valid_losses = {}\n for i, batch_data in enumerate(self.data_loader[\"valid\"]):\n for k, v in batch_data.items():\n if isinstance(v, torch.Tensor):\n batch_data[k] = v.cuda()\n valid_loss, valid_stats, total_valid_loss = self.eval_step(batch_data, i)\n for key in valid_loss:\n if key not in valid_losses:\n valid_losses[key] = 0\n valid_losses[key] += valid_loss[key]\n\n # Add mel and audio to the Tensorboard\n # Average loss\n for key in valid_losses:\n valid_losses[key] /= i + 1\n self.echo_log(valid_losses, \"Valid\")\n return valid_losses, valid_stats\n\n def train_epoch(self):\n for i, batch_data in enumerate(self.data_loader[\"train\"]):\n start_time = time.time()\n # Put the data to cuda device\n for k, v in batch_data.items():\n if isinstance(v, torch.Tensor):\n batch_data[k] = v.cuda(self.args.local_rank)\n\n # Training step\n train_losses, train_stats, total_loss = self.train_step(batch_data)\n self.time_window.append(time.time() - start_time)\n\n if self.args.local_rank == 0 or not self.cfg.train.ddp:\n if self.step % self.args.stdout_interval == 0:\n self.echo_log(train_losses, \"Training\")\n\n if self.step % self.cfg.train.save_summary_steps == 0:\n self.logger.info(f\"Save summary as step {self.step}\")\n self.write_summary(train_losses, train_stats)\n\n if (\n self.step % self.cfg.train.save_checkpoints_steps == 0\n and self.step != 0\n ):\n saved_model_name = \"step-{:07d}_loss-{:.4f}.pt\".format(\n self.step, total_loss\n )\n saved_model_path = os.path.join(\n self.checkpoint_dir, saved_model_name\n )\n saved_state_dict = self.get_state_dict()\n self.save_checkpoint(saved_state_dict, saved_model_path)\n self.save_config_file()\n # keep max n models\n remove_older_ckpt(\n saved_model_name,\n self.checkpoint_dir,\n max_to_keep=self.cfg.train.keep_checkpoint_max,\n )\n\n if self.step != 0 and self.step % self.cfg.train.valid_interval == 0:\n if isinstance(self.model, dict):\n for key in self.model.keys():\n self.model[key].eval()\n else:\n self.model.eval()\n # Evaluate one epoch and get average loss\n valid_losses, valid_stats = self.eval_epoch()\n if isinstance(self.model, dict):\n for key in self.model.keys():\n self.model[key].train()\n else:\n self.model.train()\n # Write validation losses to summary.\n self.write_valid_summary(valid_losses, valid_stats)\n self.step += 1\n\n def train(self):\n for epoch in range(max(0, self.epoch), self.max_epochs):\n self.train_epoch()\n self.epoch += 1\n if self.step > self.max_steps:\n self.logger.info(\"Training finished!\")\n break" }, { "identifier": "VariableSampler", "path": "models/base/base_sampler.py", "snippet": "class VariableSampler(BatchSampler):\n def __init__(self, sampler, drop_last: bool, use_random_sampler=False):\n self.data_list = sampler\n if use_random_sampler:\n self.sampler = RandomSampler(sampler)\n else:\n self.sampler = SequentialSampler(sampler)\n\n super().__init__(self.sampler, 1, drop_last)\n\n def __iter__(self):\n for batch_ids in self.data_list:\n yield batch_ids\n\n def __len__(self):\n if self.drop_last:\n return len(self.sampler) // self.batch_size\n else:\n return (len(self.sampler) + self.batch_size - 1) // self.batch_size" }, { "identifier": "NS2Dataset", "path": "models/tts/naturalspeech2/ns2_dataset.py", "snippet": "class NS2Dataset(torch.utils.data.Dataset):\n def __init__(self, cfg, dataset, is_valid=False):\n assert isinstance(dataset, str)\n\n processed_data_dir = os.path.join(cfg.preprocess.processed_dir, dataset)\n\n meta_file = cfg.preprocess.valid_file if is_valid else cfg.preprocess.train_file\n # train.json\n\n self.metafile_path = os.path.join(processed_data_dir, meta_file)\n\n self.metadata = self.get_metadata()\n\n self.cfg = cfg\n\n assert cfg.preprocess.use_mel == False\n if cfg.preprocess.use_mel:\n self.utt2melspec_path = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n self.utt2melspec_path[utt] = os.path.join(\n cfg.preprocess.processed_dir,\n dataset,\n cfg.preprocess.melspec_dir, # mel\n utt_info[\"speaker\"],\n uid + \".npy\",\n )\n\n assert cfg.preprocess.use_code == True\n if cfg.preprocess.use_code:\n self.utt2code_path = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n self.utt2code_path[utt] = os.path.join(\n cfg.preprocess.processed_dir,\n dataset,\n cfg.preprocess.code_dir, # code\n utt_info[\"speaker\"],\n uid + \".npy\",\n )\n\n assert cfg.preprocess.use_spkid == True\n if cfg.preprocess.use_spkid:\n self.utt2spkid = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n self.utt2spkid[utt] = utt_info[\"speaker\"]\n\n assert cfg.preprocess.use_pitch == True\n if cfg.preprocess.use_pitch:\n self.utt2pitch_path = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n self.utt2pitch_path[utt] = os.path.join(\n cfg.preprocess.processed_dir,\n dataset,\n cfg.preprocess.pitch_dir, # pitch\n utt_info[\"speaker\"],\n uid + \".npy\",\n )\n\n assert cfg.preprocess.use_duration == True\n if cfg.preprocess.use_duration:\n self.utt2duration_path = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n self.utt2duration_path[utt] = os.path.join(\n cfg.preprocess.processed_dir,\n dataset,\n cfg.preprocess.duration_dir, # duration\n utt_info[\"speaker\"],\n uid + \".npy\",\n )\n\n assert cfg.preprocess.use_phone == True\n if cfg.preprocess.use_phone:\n self.utt2phone = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n self.utt2phone[utt] = utt_info[\"phones\"]\n\n assert cfg.preprocess.use_len == True\n if cfg.preprocess.use_len:\n self.utt2len = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n self.utt2len[utt] = utt_info[\"num_frames\"]\n\n # for cross reference\n if cfg.preprocess.use_cross_reference:\n self.spkid2utt = {}\n for utt_info in self.metadata:\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n spkid = utt_info[\"speaker\"]\n if spkid not in self.spkid2utt:\n self.spkid2utt[spkid] = []\n self.spkid2utt[spkid].append(utt)\n\n # get phone to id / id to phone map\n self.phone2id, self.id2phone = self.get_phone_map()\n\n self.all_num_frames = []\n for i in range(len(self.metadata)):\n self.all_num_frames.append(self.metadata[i][\"num_frames\"])\n self.num_frame_sorted = np.array(sorted(self.all_num_frames))\n self.num_frame_indices = np.array(\n sorted(\n range(len(self.all_num_frames)), key=lambda k: self.all_num_frames[k]\n )\n )\n\n def __len__(self):\n return len(self.metadata)\n\n def get_dataset_name(self):\n return self.metadata[0][\"Dataset\"]\n\n def get_metadata(self):\n with open(self.metafile_path, \"r\", encoding=\"utf-8\") as f:\n metadata = json.load(f)\n\n print(\"metadata len: \", len(metadata))\n\n return metadata\n\n def get_phone_map(self):\n symbols = valid_symbols + [\"sp\", \"spn\", \"sil\"] + [\"<s>\", \"</s>\"]\n phone2id = {s: i for i, s in enumerate(symbols)}\n id2phone = {i: s for s, i in phone2id.items()}\n return phone2id, id2phone\n\n def __getitem__(self, index):\n utt_info = self.metadata[index]\n\n dataset = utt_info[\"Dataset\"]\n uid = utt_info[\"Uid\"]\n utt = \"{}_{}\".format(dataset, uid)\n\n single_feature = dict()\n\n if self.cfg.preprocess.read_metadata:\n metadata_uid_path = os.path.join(\n self.cfg.preprocess.processed_dir,\n self.cfg.preprocess.metadata_dir,\n dataset,\n # utt_info[\"speaker\"],\n uid + \".pkl\",\n )\n with open(metadata_uid_path, \"rb\") as f:\n metadata_uid = pickle.load(f)\n # code\n code = metadata_uid[\"code\"]\n # frame_nums\n frame_nums = code.shape[1]\n # pitch\n pitch = metadata_uid[\"pitch\"]\n # duration\n duration = metadata_uid[\"duration\"]\n # phone_id\n phone_id = np.array(\n [\n *map(\n self.phone2id.get,\n self.utt2phone[utt].replace(\"{\", \"\").replace(\"}\", \"\").split(),\n )\n ]\n )\n\n else:\n # code\n code = np.load(self.utt2code_path[utt])\n # frame_nums\n frame_nums = code.shape[1]\n # pitch\n pitch = np.load(self.utt2pitch_path[utt])\n # duration\n duration = np.load(self.utt2duration_path[utt])\n # phone_id\n phone_id = np.array(\n [\n *map(\n self.phone2id.get,\n self.utt2phone[utt].replace(\"{\", \"\").replace(\"}\", \"\").split(),\n )\n ]\n )\n\n # align length\n code, pitch, duration, phone_id, frame_nums = self.align_length(\n code, pitch, duration, phone_id, frame_nums\n )\n\n # spkid\n spkid = self.utt2spkid[utt]\n\n # get target and reference\n out = self.get_target_and_reference(code, pitch, duration, phone_id, frame_nums)\n code, ref_code = out[\"code\"], out[\"ref_code\"]\n pitch, ref_pitch = out[\"pitch\"], out[\"ref_pitch\"]\n duration, ref_duration = out[\"duration\"], out[\"ref_duration\"]\n phone_id, ref_phone_id = out[\"phone_id\"], out[\"ref_phone_id\"]\n frame_nums, ref_frame_nums = out[\"frame_nums\"], out[\"ref_frame_nums\"]\n\n # phone_id_frame\n assert len(phone_id) == len(duration)\n phone_id_frame = []\n for i in range(len(phone_id)):\n phone_id_frame.extend([phone_id[i] for _ in range(duration[i])])\n phone_id_frame = np.array(phone_id_frame)\n\n # ref_phone_id_frame\n assert len(ref_phone_id) == len(ref_duration)\n ref_phone_id_frame = []\n for i in range(len(ref_phone_id)):\n ref_phone_id_frame.extend([ref_phone_id[i] for _ in range(ref_duration[i])])\n ref_phone_id_frame = np.array(ref_phone_id_frame)\n\n single_feature.update(\n {\n \"code\": code,\n \"frame_nums\": frame_nums,\n \"pitch\": pitch,\n \"duration\": duration,\n \"phone_id\": phone_id,\n \"phone_id_frame\": phone_id_frame,\n \"ref_code\": ref_code,\n \"ref_frame_nums\": ref_frame_nums,\n \"ref_pitch\": ref_pitch,\n \"ref_duration\": ref_duration,\n \"ref_phone_id\": ref_phone_id,\n \"ref_phone_id_frame\": ref_phone_id_frame,\n \"spkid\": spkid,\n }\n )\n\n return single_feature\n\n def get_num_frames(self, index):\n utt_info = self.metadata[index]\n return utt_info[\"num_frames\"]\n\n def align_length(self, code, pitch, duration, phone_id, frame_nums):\n # aligh lenght of code, pitch, duration, phone_id, and frame nums\n code_len = code.shape[1]\n pitch_len = len(pitch)\n dur_sum = sum(duration)\n min_len = min(code_len, dur_sum)\n code = code[:, :min_len]\n if pitch_len >= min_len:\n pitch = pitch[:min_len]\n else:\n pitch = np.pad(pitch, (0, min_len - pitch_len), mode=\"edge\")\n frame_nums = min_len\n if dur_sum > min_len:\n assert (duration[-1] - (dur_sum - min_len)) >= 0\n duration[-1] = duration[-1] - (dur_sum - min_len)\n assert duration[-1] >= 0\n\n return code, pitch, duration, phone_id, frame_nums\n\n def get_target_and_reference(self, code, pitch, duration, phone_id, frame_nums):\n phone_nums = len(phone_id)\n clip_phone_nums = np.random.randint(\n int(phone_nums * 0.1), int(phone_nums * 0.5) + 1\n )\n clip_phone_nums = max(clip_phone_nums, 1)\n assert clip_phone_nums < phone_nums and clip_phone_nums >= 1\n if self.cfg.preprocess.clip_mode == \"mid\":\n start_idx = np.random.randint(0, phone_nums - clip_phone_nums)\n elif self.cfg.preprocess.clip_mode == \"start\":\n if duration[0] == 0 and clip_phone_nums == 1:\n start_idx = 1\n else:\n start_idx = 0\n else:\n assert self.cfg.preprocess.clip_mode in [\"mid\", \"start\"]\n end_idx = start_idx + clip_phone_nums\n start_frames = sum(duration[:start_idx])\n end_frames = sum(duration[:end_idx])\n\n new_code = np.concatenate(\n (code[:, :start_frames], code[:, end_frames:]), axis=1\n )\n ref_code = code[:, start_frames:end_frames]\n\n new_pitch = np.append(pitch[:start_frames], pitch[end_frames:])\n ref_pitch = pitch[start_frames:end_frames]\n\n new_duration = np.append(duration[:start_idx], duration[end_idx:])\n ref_duration = duration[start_idx:end_idx]\n\n new_phone_id = np.append(phone_id[:start_idx], phone_id[end_idx:])\n ref_phone_id = phone_id[start_idx:end_idx]\n\n new_frame_nums = frame_nums - (end_frames - start_frames)\n ref_frame_nums = end_frames - start_frames\n\n return {\n \"code\": new_code,\n \"ref_code\": ref_code,\n \"pitch\": new_pitch,\n \"ref_pitch\": ref_pitch,\n \"duration\": new_duration,\n \"ref_duration\": ref_duration,\n \"phone_id\": new_phone_id,\n \"ref_phone_id\": ref_phone_id,\n \"frame_nums\": new_frame_nums,\n \"ref_frame_nums\": ref_frame_nums,\n }" }, { "identifier": "NS2Collator", "path": "models/tts/naturalspeech2/ns2_dataset.py", "snippet": "class NS2Collator(BaseCollator):\n def __init__(self, cfg):\n BaseCollator.__init__(self, cfg)\n\n def __call__(self, batch):\n packed_batch_features = dict()\n\n # code: (B, 16, T)\n # frame_nums: (B,) not used\n # pitch: (B, T)\n # duration: (B, N)\n # phone_id: (B, N)\n # phone_id_frame: (B, T)\n # ref_code: (B, 16, T')\n # ref_frame_nums: (B,) not used\n # ref_pitch: (B, T) not used\n # ref_duration: (B, N') not used\n # ref_phone_id: (B, N') not used\n # ref_phone_frame: (B, T') not used\n # spkid: (B,) not used\n # phone_mask: (B, N)\n # mask: (B, T)\n # ref_mask: (B, T')\n\n for key in batch[0].keys():\n if key == \"phone_id\":\n phone_ids = [torch.LongTensor(b[\"phone_id\"]) for b in batch]\n phone_masks = [torch.ones(len(b[\"phone_id\"])) for b in batch]\n packed_batch_features[\"phone_id\"] = pad_sequence(\n phone_ids,\n batch_first=True,\n padding_value=0,\n )\n packed_batch_features[\"phone_mask\"] = pad_sequence(\n phone_masks,\n batch_first=True,\n padding_value=0,\n )\n elif key == \"phone_id_frame\":\n phone_id_frames = [torch.LongTensor(b[\"phone_id_frame\"]) for b in batch]\n masks = [torch.ones(len(b[\"phone_id_frame\"])) for b in batch]\n packed_batch_features[\"phone_id_frame\"] = pad_sequence(\n phone_id_frames,\n batch_first=True,\n padding_value=0,\n )\n packed_batch_features[\"mask\"] = pad_sequence(\n masks,\n batch_first=True,\n padding_value=0,\n )\n elif key == \"ref_code\":\n ref_codes = [\n torch.from_numpy(b[\"ref_code\"]).transpose(0, 1) for b in batch\n ]\n ref_masks = [torch.ones(max(b[\"ref_code\"].shape[1], 1)) for b in batch]\n packed_batch_features[\"ref_code\"] = pad_sequence(\n ref_codes,\n batch_first=True,\n padding_value=0,\n ).transpose(1, 2)\n packed_batch_features[\"ref_mask\"] = pad_sequence(\n ref_masks,\n batch_first=True,\n padding_value=0,\n )\n elif key == \"code\":\n codes = [torch.from_numpy(b[\"code\"]).transpose(0, 1) for b in batch]\n masks = [torch.ones(max(b[\"code\"].shape[1], 1)) for b in batch]\n packed_batch_features[\"code\"] = pad_sequence(\n codes,\n batch_first=True,\n padding_value=0,\n ).transpose(1, 2)\n packed_batch_features[\"mask\"] = pad_sequence(\n masks,\n batch_first=True,\n padding_value=0,\n )\n elif key == \"pitch\":\n values = [torch.from_numpy(b[key]) for b in batch]\n packed_batch_features[key] = pad_sequence(\n values, batch_first=True, padding_value=50.0\n )\n elif key == \"duration\":\n values = [torch.from_numpy(b[key]) for b in batch]\n packed_batch_features[key] = pad_sequence(\n values, batch_first=True, padding_value=0\n )\n elif key == \"frame_nums\":\n packed_batch_features[\"frame_nums\"] = torch.LongTensor(\n [b[\"frame_nums\"] for b in batch]\n )\n elif key == \"ref_frame_nums\":\n packed_batch_features[\"ref_frame_nums\"] = torch.LongTensor(\n [b[\"ref_frame_nums\"] for b in batch]\n )\n else:\n pass\n\n return packed_batch_features" }, { "identifier": "batch_by_size", "path": "models/tts/naturalspeech2/ns2_dataset.py", "snippet": "def batch_by_size(\n indices,\n num_tokens_fn,\n max_tokens=None,\n max_sentences=None,\n required_batch_size_multiple=1,\n):\n \"\"\"\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n num_tokens_fn (callable): function that returns the number of tokens at\n a given index\n max_tokens (int, optional): max number of tokens in each batch\n (default: None).\n max_sentences (int, optional): max number of sentences in each\n batch (default: None).\n required_batch_size_multiple (int, optional): require batch size to\n be a multiple of N (default: 1).\n \"\"\"\n bsz_mult = required_batch_size_multiple\n\n sample_len = 0\n sample_lens = []\n batch = []\n batches = []\n for i in range(len(indices)):\n idx = indices[i]\n num_tokens = num_tokens_fn(idx)\n sample_lens.append(num_tokens)\n sample_len = max(sample_len, num_tokens)\n\n assert (\n sample_len <= max_tokens\n ), \"sentence at index {} of size {} exceeds max_tokens \" \"limit of {}!\".format(\n idx, sample_len, max_tokens\n )\n num_tokens = (len(batch) + 1) * sample_len\n\n if _is_batch_full(batch, num_tokens, max_tokens, max_sentences):\n mod_len = max(\n bsz_mult * (len(batch) // bsz_mult),\n len(batch) % bsz_mult,\n )\n batches.append(batch[:mod_len])\n batch = batch[mod_len:]\n sample_lens = sample_lens[mod_len:]\n sample_len = max(sample_lens) if len(sample_lens) > 0 else 0\n batch.append(idx)\n if len(batch) > 0:\n batches.append(batch)\n return batches" }, { "identifier": "log_pitch_loss", "path": "models/tts/naturalspeech2/ns2_loss.py", "snippet": "def log_pitch_loss(pitch_pred_log, pitch_target, mask, loss_type=\"l1\"):\n pitch_target_log = torch.log(pitch_target)\n if loss_type == \"l1\":\n loss = F.l1_loss(\n pitch_pred_log, pitch_target_log, reduction=\"none\"\n ).float() * mask.to(pitch_target.dtype)\n elif loss_type == \"l2\":\n loss = F.mse_loss(\n pitch_pred_log, pitch_target_log, reduction=\"none\"\n ).float() * mask.to(pitch_target.dtype)\n else:\n raise NotImplementedError()\n loss = loss.sum() / (mask.to(pitch_target.dtype).sum() + 1e-8)\n return loss" }, { "identifier": "log_dur_loss", "path": "models/tts/naturalspeech2/ns2_loss.py", "snippet": "def log_dur_loss(dur_pred_log, dur_target, mask, loss_type=\"l1\"):\n # dur_pred_log: (B, N)\n # dur_target: (B, N)\n # mask: (B, N) mask is 0\n dur_target_log = torch.log(1 + dur_target)\n if loss_type == \"l1\":\n loss = F.l1_loss(\n dur_pred_log, dur_target_log, reduction=\"none\"\n ).float() * mask.to(dur_target.dtype)\n elif loss_type == \"l2\":\n loss = F.mse_loss(\n dur_pred_log, dur_target_log, reduction=\"none\"\n ).float() * mask.to(dur_target.dtype)\n else:\n raise NotImplementedError()\n loss = loss.sum() / (mask.to(dur_target.dtype).sum())\n return loss" }, { "identifier": "diff_loss", "path": "models/tts/naturalspeech2/ns2_loss.py", "snippet": "def diff_loss(pred, target, mask, loss_type=\"l1\"):\n # pred: (B, d, T)\n # target: (B, d, T)\n # mask: (B, T)\n if loss_type == \"l1\":\n loss = F.l1_loss(pred, target, reduction=\"none\").float() * (\n mask.to(pred.dtype).unsqueeze(1)\n )\n elif loss_type == \"l2\":\n loss = F.mse_loss(pred, target, reduction=\"none\").float() * (\n mask.to(pred.dtype).unsqueeze(1)\n )\n else:\n raise NotImplementedError()\n loss = (torch.mean(loss, dim=1)).sum() / (mask.to(pred.dtype).sum())\n return loss" }, { "identifier": "diff_ce_loss", "path": "models/tts/naturalspeech2/ns2_loss.py", "snippet": "def diff_ce_loss(pred_dist, gt_indices, mask):\n # pred_dist: (nq, B, T, 1024)\n # gt_indices: (nq, B, T)\n pred_dist = pred_dist.permute(1, 3, 0, 2) # (B, 1024, nq, T)\n gt_indices = gt_indices.permute(1, 0, 2).long() # (B, nq, T)\n loss = F.cross_entropy(\n pred_dist, gt_indices, reduction=\"none\"\n ).float() # (B, nq, T)\n loss = loss * mask.to(loss.dtype).unsqueeze(1)\n loss = (torch.mean(loss, dim=1)).sum() / (mask.to(loss.dtype).sum())\n return loss" }, { "identifier": "NaturalSpeech2", "path": "models/tts/naturalspeech2/ns2.py", "snippet": "class NaturalSpeech2(nn.Module):\n def __init__(self, cfg):\n super().__init__()\n self.cfg = cfg\n\n self.latent_dim = cfg.latent_dim\n self.query_emb_num = cfg.query_emb.query_token_num\n\n self.prior_encoder = PriorEncoder(cfg.prior_encoder)\n if cfg.diffusion.diffusion_type == \"diffusion\":\n self.diffusion = Diffusion(cfg.diffusion)\n elif cfg.diffusion.diffusion_type == \"flow\":\n self.diffusion = DiffusionFlow(cfg.diffusion)\n\n self.prompt_encoder = TransformerEncoder(cfg=cfg.prompt_encoder)\n if self.latent_dim != cfg.prompt_encoder.encoder_hidden:\n self.prompt_lin = nn.Linear(\n self.latent_dim, cfg.prompt_encoder.encoder_hidden\n )\n self.prompt_lin.weight.data.normal_(0.0, 0.02)\n else:\n self.prompt_lin = None\n\n self.query_emb = nn.Embedding(self.query_emb_num, cfg.query_emb.hidden_size)\n self.query_attn = nn.MultiheadAttention(\n cfg.query_emb.hidden_size, cfg.query_emb.head_num, batch_first=True\n )\n\n codec_model = EncodecModel.encodec_model_24khz()\n codec_model.set_target_bandwidth(12.0)\n codec_model.requires_grad_(False)\n self.quantizer = codec_model.quantizer\n\n @torch.no_grad()\n def code_to_latent(self, code):\n latent = self.quantizer.decode(code.transpose(0, 1))\n return latent\n\n def latent_to_code(self, latent, nq=16):\n residual = latent\n all_indices = []\n all_dist = []\n for i in range(nq):\n layer = self.quantizer.vq.layers[i]\n x = rearrange(residual, \"b d n -> b n d\")\n x = layer.project_in(x)\n shape = x.shape\n x = layer._codebook.preprocess(x)\n embed = layer._codebook.embed.t()\n dist = -(\n x.pow(2).sum(1, keepdim=True)\n - 2 * x @ embed\n + embed.pow(2).sum(0, keepdim=True)\n )\n indices = dist.max(dim=-1).indices\n indices = layer._codebook.postprocess_emb(indices, shape)\n dist = dist.reshape(*shape[:-1], dist.shape[-1])\n quantized = layer.decode(indices)\n residual = residual - quantized\n all_indices.append(indices)\n all_dist.append(dist)\n\n out_indices = torch.stack(all_indices)\n out_dist = torch.stack(all_dist)\n\n return out_indices, out_dist # (nq, B, T); (nq, B, T, 1024)\n\n @torch.no_grad()\n def latent_to_latent(self, latent, nq=16):\n codes, _ = self.latent_to_code(latent, nq)\n latent = self.quantizer.vq.decode(codes)\n return latent\n\n def forward(\n self,\n code=None,\n pitch=None,\n duration=None,\n phone_id=None,\n phone_id_frame=None,\n frame_nums=None,\n ref_code=None,\n ref_frame_nums=None,\n phone_mask=None,\n mask=None,\n ref_mask=None,\n ):\n ref_latent = self.code_to_latent(ref_code)\n latent = self.code_to_latent(code)\n\n if self.latent_dim is not None:\n ref_latent = self.prompt_lin(ref_latent.transpose(1, 2))\n\n ref_latent = self.prompt_encoder(ref_latent, ref_mask, condition=None)\n spk_emb = ref_latent.transpose(1, 2) # (B, d, T')\n\n spk_query_emb = self.query_emb(\n torch.arange(self.query_emb_num).to(latent.device)\n ).repeat(\n latent.shape[0], 1, 1\n ) # (B, query_emb_num, d)\n spk_query_emb, _ = self.query_attn(\n spk_query_emb,\n spk_emb.transpose(1, 2),\n spk_emb.transpose(1, 2),\n key_padding_mask=~(ref_mask.bool()),\n ) # (B, query_emb_num, d)\n\n prior_out = self.prior_encoder(\n phone_id=phone_id,\n duration=duration,\n pitch=pitch,\n phone_mask=phone_mask,\n mask=mask,\n ref_emb=spk_emb,\n ref_mask=ref_mask,\n is_inference=False,\n )\n prior_condition = prior_out[\"prior_out\"] # (B, T, d)\n\n diff_out = self.diffusion(latent, mask, prior_condition, spk_query_emb)\n\n return diff_out, prior_out\n\n @torch.no_grad()\n def inference(\n self, ref_code=None, phone_id=None, ref_mask=None, inference_steps=1000\n ):\n ref_latent = self.code_to_latent(ref_code)\n\n if self.latent_dim is not None:\n ref_latent = self.prompt_lin(ref_latent.transpose(1, 2))\n\n ref_latent = self.prompt_encoder(ref_latent, ref_mask, condition=None)\n spk_emb = ref_latent.transpose(1, 2) # (B, d, T')\n\n spk_query_emb = self.query_emb(\n torch.arange(self.query_emb_num).to(ref_latent.device)\n ).repeat(\n ref_latent.shape[0], 1, 1\n ) # (B, query_emb_num, d)\n spk_query_emb, _ = self.query_attn(\n spk_query_emb,\n spk_emb.transpose(1, 2),\n spk_emb.transpose(1, 2),\n key_padding_mask=~(ref_mask.bool()),\n ) # (B, query_emb_num, d)\n\n prior_out = self.prior_encoder(\n phone_id=phone_id,\n duration=None,\n pitch=None,\n phone_mask=None,\n mask=None,\n ref_emb=spk_emb,\n ref_mask=ref_mask,\n is_inference=True,\n )\n prior_condition = prior_out[\"prior_out\"] # (B, T, d)\n\n z = torch.randn(\n prior_condition.shape[0], self.latent_dim, prior_condition.shape[1]\n ).to(ref_latent.device) / (1.20)\n x0 = self.diffusion.reverse_diffusion(\n z, None, prior_condition, inference_steps, spk_query_emb\n )\n\n return x0, prior_out\n\n @torch.no_grad()\n def reverse_diffusion_from_t(\n self,\n code=None,\n pitch=None,\n duration=None,\n phone_id=None,\n ref_code=None,\n phone_mask=None,\n mask=None,\n ref_mask=None,\n n_timesteps=None,\n t=None,\n ):\n # o Only for debug\n\n ref_latent = self.code_to_latent(ref_code)\n latent = self.code_to_latent(code)\n\n if self.latent_dim is not None:\n ref_latent = self.prompt_lin(ref_latent.transpose(1, 2))\n\n ref_latent = self.prompt_encoder(ref_latent, ref_mask, condition=None)\n spk_emb = ref_latent.transpose(1, 2) # (B, d, T')\n\n spk_query_emb = self.query_emb(\n torch.arange(self.query_emb_num).to(latent.device)\n ).repeat(\n latent.shape[0], 1, 1\n ) # (B, query_emb_num, d)\n spk_query_emb, _ = self.query_attn(\n spk_query_emb,\n spk_emb.transpose(1, 2),\n spk_emb.transpose(1, 2),\n key_padding_mask=~(ref_mask.bool()),\n ) # (B, query_emb_num, d)\n\n prior_out = self.prior_encoder(\n phone_id=phone_id,\n duration=duration,\n pitch=pitch,\n phone_mask=phone_mask,\n mask=mask,\n ref_emb=spk_emb,\n ref_mask=ref_mask,\n is_inference=False,\n )\n prior_condition = prior_out[\"prior_out\"] # (B, T, d)\n\n diffusion_step = (\n torch.ones(\n latent.shape[0],\n dtype=latent.dtype,\n device=latent.device,\n requires_grad=False,\n )\n * t\n )\n diffusion_step = torch.clamp(diffusion_step, 1e-5, 1.0 - 1e-5)\n xt, _ = self.diffusion.forward_diffusion(\n x0=latent, diffusion_step=diffusion_step\n )\n # print(torch.abs(xt-latent).max(), torch.abs(xt-latent).mean(), torch.abs(xt-latent).std())\n\n x0 = self.diffusion.reverse_diffusion_from_t(\n xt, mask, prior_condition, n_timesteps, spk_query_emb, t_start=t\n )\n\n return x0, prior_out, xt" } ]
import os import shutil import json import time import torch import numpy as np import torch.nn.functional as F import accelerate from utils.util import Logger, ValueWindow from torch.utils.data import ConcatDataset, DataLoader from models.tts.base.tts_trainer import TTSTrainer from models.base.base_trainer import BaseTrainer from models.base.base_sampler import VariableSampler from models.tts.naturalspeech2.ns2_dataset import NS2Dataset, NS2Collator, batch_by_size from models.tts.naturalspeech2.ns2_loss import ( log_pitch_loss, log_dur_loss, diff_loss, diff_ce_loss, ) from torch.utils.data.sampler import BatchSampler, SequentialSampler from models.tts.naturalspeech2.ns2 import NaturalSpeech2 from torch.optim import Adam, AdamW from torch.nn import MSELoss, L1Loss from diffusers import get_scheduler from accelerate.logging import get_logger from accelerate.utils import ProjectConfiguration
19,710
for x in batch_sampler if len(x) % self.accelerator.num_processes == 0 ] valid_loader = DataLoader( valid_dataset, collate_fn=valid_collate, num_workers=self.cfg.train.dataloader.num_worker, batch_sampler=VariableSampler(batches, drop_last=False), pin_memory=self.cfg.train.dataloader.pin_memory, ) self.accelerator.wait_for_everyone() else: print("Use Normal Batchsize......") Dataset, Collator = self._build_dataset() train_dataset = Dataset(self.cfg, self.cfg.dataset[0], is_valid=False) train_collate = Collator(self.cfg) train_loader = DataLoader( train_dataset, shuffle=True, collate_fn=train_collate, batch_size=self.cfg.train.batch_size, num_workers=self.cfg.train.dataloader.num_worker, pin_memory=self.cfg.train.dataloader.pin_memory, ) valid_dataset = Dataset(self.cfg, self.cfg.dataset[0], is_valid=True) valid_collate = Collator(self.cfg) valid_loader = DataLoader( valid_dataset, shuffle=True, collate_fn=valid_collate, batch_size=self.cfg.train.batch_size, num_workers=self.cfg.train.dataloader.num_worker, pin_memory=self.cfg.train.dataloader.pin_memory, ) self.accelerator.wait_for_everyone() return train_loader, valid_loader def _build_optimizer(self): optimizer = torch.optim.AdamW( filter(lambda p: p.requires_grad, self.model.parameters()), **self.cfg.train.adam, ) return optimizer def _build_scheduler(self): lr_scheduler = get_scheduler( self.cfg.train.lr_scheduler, optimizer=self.optimizer, num_warmup_steps=self.cfg.train.lr_warmup_steps, num_training_steps=self.cfg.train.num_train_steps, ) return lr_scheduler def _build_criterion(self): criterion = torch.nn.L1Loss(reduction="mean") return criterion def write_summary(self, losses, stats): for key, value in losses.items(): self.sw.add_scalar(key, value, self.step) def write_valid_summary(self, losses, stats): for key, value in losses.items(): self.sw.add_scalar(key, value, self.step) def get_state_dict(self): state_dict = { "model": self.model.state_dict(), "optimizer": self.optimizer.state_dict(), "scheduler": self.scheduler.state_dict(), "step": self.step, "epoch": self.epoch, "batch_size": self.cfg.train.batch_size, } return state_dict def load_model(self, checkpoint): self.step = checkpoint["step"] self.epoch = checkpoint["epoch"] self.model.load_state_dict(checkpoint["model"]) self.optimizer.load_state_dict(checkpoint["optimizer"]) self.scheduler.load_state_dict(checkpoint["scheduler"]) def _train_step(self, batch): train_losses = {} total_loss = 0 train_stats = {} code = batch["code"] # (B, 16, T) pitch = batch["pitch"] # (B, T) duration = batch["duration"] # (B, N) phone_id = batch["phone_id"] # (B, N) ref_code = batch["ref_code"] # (B, 16, T') phone_mask = batch["phone_mask"] # (B, N) mask = batch["mask"] # (B, T) ref_mask = batch["ref_mask"] # (B, T') diff_out, prior_out = self.model( code=code, pitch=pitch, duration=duration, phone_id=phone_id, ref_code=ref_code, phone_mask=phone_mask, mask=mask, ref_mask=ref_mask, ) # pitch loss pitch_loss = log_pitch_loss(prior_out["pitch_pred_log"], pitch, mask=mask) total_loss += pitch_loss train_losses["pitch_loss"] = pitch_loss # duration loss
# Copyright (c) 2023 Amphion. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class NS2Trainer(TTSTrainer): def __init__(self, args, cfg): self.args = args self.cfg = cfg cfg.exp_name = args.exp_name self._init_accelerator() self.accelerator.wait_for_everyone() # Init logger with self.accelerator.main_process_first(): if self.accelerator.is_main_process: os.makedirs(os.path.join(self.exp_dir, "checkpoint"), exist_ok=True) self.log_file = os.path.join( os.path.join(self.exp_dir, "checkpoint"), "train.log" ) self.logger = Logger(self.log_file, level=self.args.log_level).logger self.time_window = ValueWindow(50) if self.accelerator.is_main_process: # Log some info self.logger.info("=" * 56) self.logger.info("||\t\t" + "New training process started." + "\t\t||") self.logger.info("=" * 56) self.logger.info("\n") self.logger.debug(f"Using {args.log_level.upper()} logging level.") self.logger.info(f"Experiment name: {args.exp_name}") self.logger.info(f"Experiment directory: {self.exp_dir}") self.checkpoint_dir = os.path.join(self.exp_dir, "checkpoint") if self.accelerator.is_main_process: os.makedirs(self.checkpoint_dir, exist_ok=True) if self.accelerator.is_main_process: self.logger.debug(f"Checkpoint directory: {self.checkpoint_dir}") # init counts self.batch_count: int = 0 self.step: int = 0 self.epoch: int = 0 self.max_epoch = ( self.cfg.train.max_epoch if self.cfg.train.max_epoch > 0 else float("inf") ) if self.accelerator.is_main_process: self.logger.info( "Max epoch: {}".format( self.max_epoch if self.max_epoch < float("inf") else "Unlimited" ) ) # Check values if self.accelerator.is_main_process: self._check_basic_configs() # Set runtime configs self.save_checkpoint_stride = self.cfg.train.save_checkpoint_stride self.checkpoints_path = [ [] for _ in range(len(self.save_checkpoint_stride)) ] self.keep_last = [ i if i > 0 else float("inf") for i in self.cfg.train.keep_last ] self.run_eval = self.cfg.train.run_eval # set random seed with self.accelerator.main_process_first(): start = time.monotonic_ns() self._set_random_seed(self.cfg.train.random_seed) end = time.monotonic_ns() if self.accelerator.is_main_process: self.logger.debug( f"Setting random seed done in {(end - start) / 1e6:.2f}ms" ) self.logger.debug(f"Random seed: {self.cfg.train.random_seed}") # setup data_loader with self.accelerator.main_process_first(): if self.accelerator.is_main_process: self.logger.info("Building dataset...") start = time.monotonic_ns() self.train_dataloader, self.valid_dataloader = self._build_dataloader() end = time.monotonic_ns() if self.accelerator.is_main_process: self.logger.info( f"Building dataset done in {(end - start) / 1e6:.2f}ms" ) # setup model with self.accelerator.main_process_first(): if self.accelerator.is_main_process: self.logger.info("Building model...") start = time.monotonic_ns() self.model = self._build_model() end = time.monotonic_ns() if self.accelerator.is_main_process: self.logger.debug(self.model) self.logger.info(f"Building model done in {(end - start) / 1e6:.2f}ms") self.logger.info( f"Model parameters: {self._count_parameters(self.model)/1e6:.2f}M" ) # optimizer & scheduler with self.accelerator.main_process_first(): if self.accelerator.is_main_process: self.logger.info("Building optimizer and scheduler...") start = time.monotonic_ns() self.optimizer = self._build_optimizer() self.scheduler = self._build_scheduler() end = time.monotonic_ns() if self.accelerator.is_main_process: self.logger.info( f"Building optimizer and scheduler done in {(end - start) / 1e6:.2f}ms" ) # accelerate prepare if not self.cfg.train.use_dynamic_batchsize: if self.accelerator.is_main_process: self.logger.info("Initializing accelerate...") start = time.monotonic_ns() ( self.train_dataloader, self.valid_dataloader, ) = self.accelerator.prepare( self.train_dataloader, self.valid_dataloader, ) if isinstance(self.model, dict): for key in self.model.keys(): self.model[key] = self.accelerator.prepare(self.model[key]) else: self.model = self.accelerator.prepare(self.model) if isinstance(self.optimizer, dict): for key in self.optimizer.keys(): self.optimizer[key] = self.accelerator.prepare(self.optimizer[key]) else: self.optimizer = self.accelerator.prepare(self.optimizer) if isinstance(self.scheduler, dict): for key in self.scheduler.keys(): self.scheduler[key] = self.accelerator.prepare(self.scheduler[key]) else: self.scheduler = self.accelerator.prepare(self.scheduler) end = time.monotonic_ns() if self.accelerator.is_main_process: self.logger.info( f"Initializing accelerate done in {(end - start) / 1e6:.2f}ms" ) # create criterion with self.accelerator.main_process_first(): if self.accelerator.is_main_process: self.logger.info("Building criterion...") start = time.monotonic_ns() self.criterion = self._build_criterion() end = time.monotonic_ns() if self.accelerator.is_main_process: self.logger.info( f"Building criterion done in {(end - start) / 1e6:.2f}ms" ) # TODO: Resume from ckpt need test/debug with self.accelerator.main_process_first(): if args.resume: if self.accelerator.is_main_process: self.logger.info("Resuming from checkpoint...") start = time.monotonic_ns() ckpt_path = self._load_model( self.checkpoint_dir, args.checkpoint_path, resume_type=args.resume_type, ) end = time.monotonic_ns() if self.accelerator.is_main_process: self.logger.info( f"Resuming from checkpoint done in {(end - start) / 1e6:.2f}ms" ) self.checkpoints_path = json.load( open(os.path.join(ckpt_path, "ckpts.json"), "r") ) self.checkpoint_dir = os.path.join(self.exp_dir, "checkpoint") if self.accelerator.is_main_process: os.makedirs(self.checkpoint_dir, exist_ok=True) if self.accelerator.is_main_process: self.logger.debug(f"Checkpoint directory: {self.checkpoint_dir}") # save config file path self.config_save_path = os.path.join(self.exp_dir, "args.json") # Only for TTS tasks self.task_type = "TTS" if self.accelerator.is_main_process: self.logger.info("Task type: {}".format(self.task_type)) def _init_accelerator(self): self.exp_dir = os.path.join( os.path.abspath(self.cfg.log_dir), self.args.exp_name ) project_config = ProjectConfiguration( project_dir=self.exp_dir, logging_dir=os.path.join(self.exp_dir, "log"), ) # ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=True) self.accelerator = accelerate.Accelerator( gradient_accumulation_steps=self.cfg.train.gradient_accumulation_step, log_with=self.cfg.train.tracker, project_config=project_config, # kwargs_handlers=[ddp_kwargs] ) if self.accelerator.is_main_process: os.makedirs(project_config.project_dir, exist_ok=True) os.makedirs(project_config.logging_dir, exist_ok=True) with self.accelerator.main_process_first(): self.accelerator.init_trackers(self.args.exp_name) def _build_model(self): model = NaturalSpeech2(cfg=self.cfg.model) return model def _build_dataset(self): return NS2Dataset, NS2Collator def _build_dataloader(self): if self.cfg.train.use_dynamic_batchsize: print("Use Dynamic Batchsize......") Dataset, Collator = self._build_dataset() train_dataset = Dataset(self.cfg, self.cfg.dataset[0], is_valid=False) train_collate = Collator(self.cfg) batch_sampler = batch_by_size( train_dataset.num_frame_indices, train_dataset.get_num_frames, max_tokens=self.cfg.train.max_tokens * self.accelerator.num_processes, max_sentences=self.cfg.train.max_sentences * self.accelerator.num_processes, required_batch_size_multiple=self.accelerator.num_processes, ) np.random.seed(980205) np.random.shuffle(batch_sampler) print(batch_sampler[:1]) batches = [ x[ self.accelerator.local_process_index :: self.accelerator.num_processes ] for x in batch_sampler if len(x) % self.accelerator.num_processes == 0 ] train_loader = DataLoader( train_dataset, collate_fn=train_collate, num_workers=self.cfg.train.dataloader.num_worker, batch_sampler=VariableSampler( batches, drop_last=False, use_random_sampler=True ), pin_memory=self.cfg.train.dataloader.pin_memory, ) self.accelerator.wait_for_everyone() valid_dataset = Dataset(self.cfg, self.cfg.dataset[0], is_valid=True) valid_collate = Collator(self.cfg) batch_sampler = batch_by_size( valid_dataset.num_frame_indices, valid_dataset.get_num_frames, max_tokens=self.cfg.train.max_tokens * self.accelerator.num_processes, max_sentences=self.cfg.train.max_sentences * self.accelerator.num_processes, required_batch_size_multiple=self.accelerator.num_processes, ) batches = [ x[ self.accelerator.local_process_index :: self.accelerator.num_processes ] for x in batch_sampler if len(x) % self.accelerator.num_processes == 0 ] valid_loader = DataLoader( valid_dataset, collate_fn=valid_collate, num_workers=self.cfg.train.dataloader.num_worker, batch_sampler=VariableSampler(batches, drop_last=False), pin_memory=self.cfg.train.dataloader.pin_memory, ) self.accelerator.wait_for_everyone() else: print("Use Normal Batchsize......") Dataset, Collator = self._build_dataset() train_dataset = Dataset(self.cfg, self.cfg.dataset[0], is_valid=False) train_collate = Collator(self.cfg) train_loader = DataLoader( train_dataset, shuffle=True, collate_fn=train_collate, batch_size=self.cfg.train.batch_size, num_workers=self.cfg.train.dataloader.num_worker, pin_memory=self.cfg.train.dataloader.pin_memory, ) valid_dataset = Dataset(self.cfg, self.cfg.dataset[0], is_valid=True) valid_collate = Collator(self.cfg) valid_loader = DataLoader( valid_dataset, shuffle=True, collate_fn=valid_collate, batch_size=self.cfg.train.batch_size, num_workers=self.cfg.train.dataloader.num_worker, pin_memory=self.cfg.train.dataloader.pin_memory, ) self.accelerator.wait_for_everyone() return train_loader, valid_loader def _build_optimizer(self): optimizer = torch.optim.AdamW( filter(lambda p: p.requires_grad, self.model.parameters()), **self.cfg.train.adam, ) return optimizer def _build_scheduler(self): lr_scheduler = get_scheduler( self.cfg.train.lr_scheduler, optimizer=self.optimizer, num_warmup_steps=self.cfg.train.lr_warmup_steps, num_training_steps=self.cfg.train.num_train_steps, ) return lr_scheduler def _build_criterion(self): criterion = torch.nn.L1Loss(reduction="mean") return criterion def write_summary(self, losses, stats): for key, value in losses.items(): self.sw.add_scalar(key, value, self.step) def write_valid_summary(self, losses, stats): for key, value in losses.items(): self.sw.add_scalar(key, value, self.step) def get_state_dict(self): state_dict = { "model": self.model.state_dict(), "optimizer": self.optimizer.state_dict(), "scheduler": self.scheduler.state_dict(), "step": self.step, "epoch": self.epoch, "batch_size": self.cfg.train.batch_size, } return state_dict def load_model(self, checkpoint): self.step = checkpoint["step"] self.epoch = checkpoint["epoch"] self.model.load_state_dict(checkpoint["model"]) self.optimizer.load_state_dict(checkpoint["optimizer"]) self.scheduler.load_state_dict(checkpoint["scheduler"]) def _train_step(self, batch): train_losses = {} total_loss = 0 train_stats = {} code = batch["code"] # (B, 16, T) pitch = batch["pitch"] # (B, T) duration = batch["duration"] # (B, N) phone_id = batch["phone_id"] # (B, N) ref_code = batch["ref_code"] # (B, 16, T') phone_mask = batch["phone_mask"] # (B, N) mask = batch["mask"] # (B, T) ref_mask = batch["ref_mask"] # (B, T') diff_out, prior_out = self.model( code=code, pitch=pitch, duration=duration, phone_id=phone_id, ref_code=ref_code, phone_mask=phone_mask, mask=mask, ref_mask=ref_mask, ) # pitch loss pitch_loss = log_pitch_loss(prior_out["pitch_pred_log"], pitch, mask=mask) total_loss += pitch_loss train_losses["pitch_loss"] = pitch_loss # duration loss
dur_loss = log_dur_loss(prior_out["dur_pred_log"], duration, mask=phone_mask)
9
2023-11-15 09:19:27+00:00
24k
BobaZooba/xllm
tests/unit/core/test_dependencies.py
[ { "identifier": "LMCollator", "path": "src/xllm/collators/lm.py", "snippet": "class LMCollator(BaseCollator):\n \"\"\"\n `LMCollator` is a data collator class specifically designed to prepare batches of data for language modeling tasks.\n Extending the `BaseCollator`, it adapts the general data collation procedure to suit the sequential nature of\n language models, where each token in an input sequence is used to predict the next token.\n\n The `LMCollator` provides a streamlined approach to handle the conversion of raw text data into the tokenized and\n tensor-formatted inputs required by language models during training. Its primary functionality is implemented in\n the `parse_batch` method, which oversees this conversion process.\n\n This collator is needed for simple language modeling. It compiles the lists of texts from each example into a\n single text by concatenating them using a separator.\n\n Key functionalities provided by `LMCollator`:\n\n - `parse_batch`: A method that processes a batch of `RawSample` objects, creating the tensors needed for training.\n It generates input token IDs (`input_ids`), an attention mask to differentiate between real tokens and padding\n (`attention_mask`), and the labels for training the language model (`labels`).\n\n Attributes (inherited from `BaseCollator`):\n\n - `tokenizer`: The tokenizer used to convert raw text into token IDs.\n - `max_length`: The maximum length allowed for tokenized sequences. Longer sequences will be truncated\n to this length.\n - `separator`: A string used to join text pieces within each raw sample, if necessary.\n\n The `LMCollator` is particularly useful when training Transformer-based language models like GPT on\n next-token prediction tasks. Since it already applies common preprocessing steps such as tokenization, padding,\n truncation, and sequence shifting, it makes setting up training pipelines simpler and more efficient.\n\n Usage of the `LMCollator` facilitates the generation of data in the precise format required by language models,\n enabling practitioners to focus on model architecture and performance rather than boilerplate data preparation code.\n \"\"\"\n\n def parse_batch(self, raw_batch: List[RawSample]) -> Batch:\n \"\"\"\n Processes a batch of raw text samples and converts them into a suitable format for language model training,\n specifically for tasks involving language modeling (LM) such as next-token prediction.\n\n Args:\n raw_batch (`List[RawSample]`):\n A list of dictionaries, where each `RawSample` dictionary contains a key-value pair.\n The key is defined by `enums.General.text_parts` and the value is expected to be either a string,\n a numeric value, or a list of these types representing segments of text to include in the batch.\n\n Returns:\n `Batch`: A dictionary containing the following keys, each associated with its corresponding tensor:\n - `enums.Transformers.input_ids`: The input tokens, with the last token removed from each sequence,\n as input to the model.\n - `enums.Transformers.attention_mask`: The attention mask, indicating valid tokens (as 1) and padding\n tokens (as 0) for the model, also with the last token removed from each sequence.\n - `enums.Transformers.labels`: The labels used for training the language model, obtained by shifting\n the input IDs by one token to the right to predict the next token.\n\n The `parse_batch` method operates in the following steps:\n\n - Joins the text segments for each sample in the batch using the specified separator.\n - Tokenizes the combined texts using the provided tokenizer, with padding to the longest sequence in the batch\n and truncation to the specified maximum length.\n - Constructs the input IDs and attention mask for the model input, ensuring to remove the last token from each,\n as it has no subsequent token to predict.\n - Prepares the labels by shifting the input sequence by one token position, facilitating the LM's task of\n predicting the next token in the sequence.\n\n This collator is tailored for language modeling, where the inputs and labels are often closely related\n sequences, with labels simply being the input sequence offset by one token. It integrates smoothly with\n training routines that utilize PyTorch's DataLoader and other training utilities.\n \"\"\"\n\n texts = list()\n\n for sample in raw_batch:\n item = sample[enums.General.text_parts]\n if isinstance(item, (str, int, float)):\n texts.append(self.separator.join(str(item)))\n else:\n texts.append(self.separator.join(str(i) for i in item))\n\n tokenized = self.tokenizer(\n texts,\n return_tensors=\"pt\",\n padding=True,\n truncation=True,\n max_length=self.max_length,\n )\n\n batch = {\n enums.Transformers.input_ids: tokenized.input_ids[:, :-1],\n enums.Transformers.attention_mask: tokenized.attention_mask[:, :-1],\n enums.Transformers.labels: tokenized.input_ids[:, 1:],\n }\n\n return batch" }, { "identifier": "collators_registry", "path": "src/xllm/collators/registry.py", "snippet": "" }, { "identifier": "Config", "path": "src/xllm/core/config.py", "snippet": "class Config:\n \"\"\"\n The `Config` class serves as a comprehensive configuration schema for managing various parameters required during\n the setup and execution of experiments relating to language models, such as training, quantization, and\n optimization.\n\n Write more here:\n - https://github.com/BobaZooba/xllm/blob/main/DOCS.md#config\n - https://github.com/BobaZooba/xllm/blob/main/DOCS.md#detailed-config-explanation\n\n This dataclass is used to encapsulate and standardize the configuration for a diverse range of tasks including\n dataset preparation, tokenizer and model initialization, training, evaluation, and interactions with remote services\n like the Hugging Face Model Hub.\n\n Attributes in this class cover aspects like model name and path, tokenizer settings, dataset paths, training\n strategies, quantization methods, hardware acceleration, logging, output directories, and more. The class provides\n properties with custom logic to resolve specific configurations and validation checks to ensure the environment is\n appropriately set up before proceeding with the workflow.\n\n Customization and flexibility are core to this class, as it provides reasonable defaults while also allowing for\n detailed and scalable configurations catered to advanced tasks such as leveraging LoRA, FSDP, deepspeed stage\n setups, and applying incremental quantization techniques like GPTQ and bits-and-bytes.\n\n Methods within the class include:\n - `check`: Performs checks across various attributes for compatibility and correctness.\n - Property getters such as `correct_tokenizer_name_or_path`, `lora_target_modules`, `dtype`, `deepspeed`, `fsdp`,\n and `lora_model_name_or_path_for_fusing` to fetch calculated or defaulted values based on attribute settings.\n\n Subclassing can be done to extend or modify the functionality of the `Config` class to address specific experimental\n scenarios or customized workflows. It is the central piece for orchestrating experimental setups and is intimately\n integrated with the rest of the codebase that operates on top of these configurations.\n\n Attributes:\n\n General Settings:\n - `experiment_key`: An enumeration key to specify the experiment type.\n - `save_safetensors`: A boolean value to indicate whether to use safe serialization for tensors.\n - `max_shard_size`: The maximum shard size when pushing the model to the HuggingFace Hub.\n - `local_rank`: Local rank for distributed training, used for logging and saving.\n - `use_gradient_checkpointing`: If set to `True`, enables gradient checkpointing to reduce memory usage at\n the cost of a slower backward pass.\n - `trainer_key`: An enumeration key to select the trainer using the trainers_registry.\n - `force_fp32`: Forces loading the model in fp32 precision, if set to `True`.\n - `force_fp16`: Forces loading the model in fp16 precision, if set to `True`.\n - `from_gptq`: Indicates if a GPTQ quantized model is being loaded.\n - `huggingface_hub_token`: Token for uploading models to HuggingFace Hub.\n - `deepspeed_stage`: Predefined DeepSpeed stage for optimization.\n - `deepspeed_config_path`: Path to the DeepSpeed config file.\n - `fsdp_strategy`: The strategy to be used for Fully Sharded Data Parallelism (FSDP).\n - `fsdp_offload`: If set to `True`, offloads weights to CPU when using FSDP to save memory.\n - `seed`: Seed for random number generators to ensure reproducibility.\n - `stabilize`: Converts some model weights to fp32 and others to bf16 for stabilization.\n - `path_to_env_file`: Custom path to the .env file for reading environment variables.\n\n Data Preparation:\n - `prepare_dataset`: Flags whether to prepare the dataset during the \"prepare\" stage.\n\n LoRA Fusing:\n - `lora_hub_model_id`: Name of the LoRA model on the hub for fusion.\n - `lora_model_local_path`: Local path to LoRA model to be fused.\n - `fused_model_local_path`: Local path to save the fused model.\n - `fuse_after_training`: If `True`, will fuse the model post-training.\n\n GPTQ Quantization:\n - `quantization_dataset_id`: Dataset ID for GPTQ quantization.\n - `quantization_max_samples`: Maximum number of samples to use during GPTQ quantization.\n - `quantized_model_path`: Path to save the GPTQ quantized model.\n - `quantized_hub_model_id`: Name of the model at the hub post-GPTQ quantization.\n - `quantized_hub_private_repo`: If set to `True`, creates a private repository for the quantized model.\n\n Dataset Related:\n - `dataset_key`: Key to select the dataset from the datasets_registry.\n - `train_local_path_to_data`: Local path to the training data file.\n - `eval_local_path_to_data`: Local path to the evaluation data file.\n - `shuffle`: If `True`, shuffles the training data.\n - `max_eval_samples`: Maximum number of examples to use for evaluation.\n - `add_eval_to_train_if_no_path`: If `True`, adds evaluation data to training if there's no separate eval path.\n\n Tokenizer Settings:\n - `tokenizer_name_or_path`: Name or path to the tokenizer.\n - `tokenizer_use_fast`: If `True`, uses the fast version of the tokenizer.\n - `tokenizer_padding_side`: Sets padding side to 'right' or 'left'.\n\n Data Collator Settings:\n - `collator_key`: Key to select the collator from the collators_registry.\n - `max_length`: Maximum sequence length for the model.\n\n Model Configuration:\n - `model_name_or_path`: Name or path to the model to be used.\n - `push_to_hub_bos_add_bos_token`: Adds BOS token when uploading tokenization configuration to the hub.\n - `use_flash_attention_2`: Flags the use of flash attention 2.\n - `trust_remote_code`: If `True`, trusts remote code from the HuggingFace Hub.\n - `device_map`: Device map for placing model layers on specific devices.\n - `prepare_model_for_kbit_training`: If `True`, prepares the model for k-bit training.\n\n BitsAndBytes Integration:\n - `load_in_8bit`: Load the model in 8-bit mode using bitsandbytes.\n - `load_in_4bit`: Load the model in 4-bit mode using bitsandbytes.\n - `llm_int8_threshold`: Threshold for detecting outliers in the model weights.\n - `llm_int8_has_fp16_weight`: If `True`, the model will have fp16 weights.\n - `bnb_4bit_use_double_quant`: If `True`, a second quantization step is used for 4-bit weights.\n - `bnb_4bit_quant_type`: Specifies the quantization type used for 4-bit weights.\n - `bnb_quantize_after_model_init`: Determines when the quantization should occur.\n\n GPTQ Specific Parameters:\n - `gptq_bits`: Number of bits for GPTQ quantization.\n - `gptq_group_size`: Group size for GPTQ quantization.\n - `gptq_disable_exllama`: If `True`, disables ExLlama kernels during GPTQ quantization.\n\n LoRA Specific Parameters:\n - `apply_lora`: If `True`, applies LoRA to the model.\n - `lora_rank`: LoRA rank to define the size of the LoRA matrices.\n - `lora_alpha`: Multiplication factor for the resulting LoRA matrix.\n - `lora_dropout`: Dropout rate for LoRA.\n - `raw_lora_target_modules`: Comma-separated string of module names to apply LoRA, or 'all' to apply broadly.\n\n Training Arguments:\n - `output_dir`: Path to save training outputs.\n - `per_device_train_batch_size`: Batch size per device for training.\n - `do_eval`: If `True`, performs evaluation.\n - `per_device_eval_batch_size`: Batch size per device for evaluation.\n - `gradient_accumulation_steps`: Number of steps to accumulate gradients for larger effective batch size.\n - `eval_accumulation_steps`: Number of steps to accumulate gradients during evaluation.\n - `eval_delay`: Delay before the first evaluation.\n - `eval_steps`: Number of update steps between evaluations.\n - `warmup_steps`: Number of steps for learning rate warmup.\n - `max_steps`: Maximum number of training steps.\n - `num_train_epochs`: Number of epochs for training.\n - `learning_rate`: Learning rate for the optimizer.\n - `max_grad_norm`: Gradient clipping threshold.\n - `weight_decay`: Coefficient for weight decay regularization.\n - `label_smoothing_factor`: Label smoothing factor.\n - `logging_steps`: Number of steps between logging intermediate results.\n - `save_steps`: Number of training steps between checkpoints and model upload.\n - `save_total_limit`: Maximum number of checkpoints to keep.\n - `optim`: Optimizer name, overwritten by DeepSpeed if used.\n - `push_to_hub`: If `True`, model checkpoints are uploaded to HuggingFace Hub.\n - `hub_model_id`: Name of the model on the HuggingFace Hub.\n - `hub_private_repo`: If `True`, creates a private repository on the HuggingFace Hub.\n\n Weights & Biases Integration:\n - `report_to_wandb`: If `True`, logs metrics to Weights & Biases.\n - `wandb_api_key`: API key for Weights & Biases.\n - `wandb_project`: Project name on Weights & Biases.\n - `wandb_entity`: Entity name (user or organization) on Weights & Biases.\n\n Example of creating a `Config` object:\n ```python\n config = Config(\n model_name_or_path='gpt2',\n dataset_key='my_dataset',\n gradient_accumulation_steps=8,\n max_length=512,\n deepspeed_stage=\"3\",\n )\n ```\n\n Note:\n - Throughout the codebase, `Config` instances are passed around to provide a unified source of configurations\n for various components.\n - It is crucial to ensure all required settings are properly set in a `Config` object before it is utilized,\n particularly when overriding defaults or specifying custom configurations.\n \"\"\"\n\n # general\n experiment_key: str = field(\n default=enums.Experiments.base,\n metadata={\"help\": \"Experiment class key\"},\n )\n save_safetensors: bool = field(\n default=True,\n metadata={\n \"help\": \"Use safe serialization (safe tensors) or not\",\n },\n )\n max_shard_size: str = field(\n default=\"10GB\", metadata={\"help\": \"max_shard_size for the model pushing to the HuggingFace Hub\"}\n )\n local_rank: int = field(\n default=0,\n metadata={\n \"help\": \"Local rank for logging and saving. Works only in distributed training\",\n },\n )\n use_gradient_checkpointing: bool = field(\n default=False,\n metadata={\n \"help\": \"If True, use gradient checkpointing to save memory at the expense of slower backward pass\",\n },\n )\n trainer_key: str = field(\n default=enums.Trainers.lm,\n metadata={\n \"help\": \"Key of the trainer for loading from trainers_registry\",\n },\n )\n force_fp32: bool = field(\n default=False,\n metadata={\n \"help\": \"Force using fp32 when model loading\",\n },\n )\n force_fp16: bool = field(\n default=False,\n metadata={\n \"help\": \"Force using fp16 when model loading\",\n },\n )\n from_gptq: bool = field(\n default=False,\n metadata={\n \"help\": \"If you loadining GPTQ quantized model\",\n },\n )\n huggingface_hub_token: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"HuggingFace Hub token. You can also set this key using .env file\",\n },\n )\n single_gpu: Optional[bool] = field(\n default=None,\n metadata={\n \"help\": \"Indicates that you are learning on the same GPU. It is necessary to use DeepSpeed on a single GPU\",\n },\n )\n master_port: int = field(\n default=9994,\n metadata={\n \"help\": \"Master port for running DeepSpeed on a single GPU. Modify if RuntimeError: Address already in use\",\n },\n )\n deepspeed_stage: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Predifined DeepSpeed stage\",\n },\n )\n deepspeed_config_path: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"Path to DeepSpeed config\",\n },\n )\n fsdp_strategy: str = field(\n default=\"\",\n metadata={\n \"help\": \"FSDP strategy\",\n },\n )\n fsdp_offload: bool = field(\n default=True,\n metadata={\n \"help\": \"Offload weights when using FSDP\",\n },\n )\n seed: int = field(\n default=42,\n metadata={\n \"help\": \"Seed value for random operations\",\n },\n )\n stabilize: bool = field(\n default=False,\n metadata={\n \"help\": \"Stabilize the model. Convert some weights (e.g. LoRA) to bf16\",\n },\n )\n norm_fp32: bool = field(\n default=False,\n metadata={\n \"help\": \"Convert norm to fp32\",\n },\n )\n path_to_env_file: Optional[str] = field(\n default=\"./.env\",\n metadata={\"help\": \"Custom path to .env file\"},\n )\n\n # prepare\n prepare_dataset: bool = field(\n default=True,\n metadata={\n \"help\": 'Prepare the dataset. Works only at \"prepare\" stage',\n },\n )\n\n # fuse\n lora_hub_model_id: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Fusing LoRA. The name of the LoRA model at the hub for fusing. Example: BobaZooba/Shurale\",\n },\n )\n lora_model_local_path: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Fusing LoRA. Local path to the LoRA model\",\n },\n )\n fused_model_local_path: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Local path to fused model. Useful if you want to quantize model after fusing on the same machine\",\n },\n )\n fuse_after_training: bool = field(\n default=False,\n metadata={\n \"help\": \"Fuse or not model after training\",\n },\n )\n\n # gptq quantization\n quantization_dataset_id: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Dataset id for GPTQ quantization. You can install either the idi dataset, or use any dataset\",\n },\n )\n quantization_max_samples: int = field(\n default=1024,\n metadata={\n \"help\": \"Max samples for GPTQ quantization if you use custom dataset\",\n },\n )\n quantized_model_path: str = field(\n default=\"./quantized_model/\",\n metadata={\n \"help\": \"Path to GPTQ quantized model\",\n },\n )\n quantized_hub_model_id: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"The name of the model at the hub for GPTQ quantization. Example: BobaZooba/Shurale-GPTQ\",\n },\n )\n quantized_hub_private_repo: bool = field(\n default=True,\n metadata={\n \"help\": \"Private repository for GPTQ quantization model or not\",\n },\n )\n\n # dataset\n dataset_key: str = field(\n default=enums.Datasets.soda,\n metadata={\n \"help\": \"Key of the dataset for loading from datasets_registry\",\n },\n )\n train_local_path_to_data: str = field(\n default=\"./train.jsonl\",\n metadata={\n \"help\": \"The path to the local training data file\",\n },\n )\n eval_local_path_to_data: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"The path to the local eval data file\",\n },\n )\n shuffle: bool = field(\n default=True,\n metadata={\n \"help\": \"Shuffle training data\",\n },\n )\n max_eval_samples: int = field(\n default=1_000,\n metadata={\n \"help\": \"Maximum number of examples for evaluation\",\n },\n )\n add_eval_to_train_if_no_path: bool = field(\n default=False,\n metadata={\n \"help\": \"Add evaluation data to training data if their number is greater than max_eval_samples\",\n },\n )\n\n # tokenizer\n tokenizer_name_or_path: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Tokenizer name or path. If the value is not set, \"\n \"then it will be taken from the model_name_or_path\",\n },\n )\n tokenizer_use_fast: Optional[bool] = field(\n default=None,\n metadata={\n \"help\": \"Use fast flag for the tokenizer\",\n },\n )\n tokenizer_padding_side: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Padding side of the collator: None, right or left\",\n },\n )\n\n # collator\n collator_key: str = field(\n default=enums.Collators.lm,\n metadata={\n \"help\": \"Key of the collator for loading from collators_registry\",\n },\n )\n max_length: int = field(\n default=2048,\n metadata={\n \"help\": \"Max sequence length of the model\",\n },\n )\n\n # model\n model_name_or_path: str = field(\n default=\"mistralai/Mistral-7B-v0.1\",\n metadata={\n \"help\": \"Model name or path. It could be from HuggingFace or locally\",\n },\n )\n push_to_hub_bos_add_bos_token: bool = field(\n default=False,\n metadata={\n \"help\": \"Upload to the hub tokenization config with add_bos_token equals to True. Might be helpful for TGI\"\n },\n )\n use_flash_attention_2: bool = field(\n default=False,\n metadata={\n \"help\": \"Use or not flash attention 2. Requires 1) CUDA >= 11.6; 2) install flash-attn 3) compatible model\",\n },\n )\n trust_remote_code: bool = field(\n default=False,\n metadata={\n \"help\": \"Trust remote code from HuggingFace\",\n },\n )\n device_map: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Device map for loading the model\",\n },\n )\n prepare_model_for_kbit_training: Optional[bool] = field(\n default=None,\n metadata={\n \"help\": \"Prepare or not for kbit training\",\n },\n )\n offload_folder: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Offloading folder. Helps for fusing in colab\",\n },\n )\n\n # bitsandbytes\n load_in_8bit: bool = field(\n default=False,\n metadata={\n \"help\": \"Load the model in 8 bit using bitsandbytes\",\n },\n )\n load_in_4bit: bool = field(\n default=False,\n metadata={\n \"help\": \"Load the model in 4 bit using bitsandbytes\",\n },\n )\n llm_int8_threshold: float = field(\n default=6.0,\n metadata={\n \"help\": \"Threshold for outlier detection\",\n },\n )\n llm_int8_has_fp16_weight: bool = field(\n default=True,\n metadata={\n \"help\": \"LLM has weights in fp16\",\n },\n )\n bnb_4bit_use_double_quant: bool = field(\n default=True,\n metadata={\n \"help\": \"Double quantization. \"\n \"This will enable a second quantization after the first \"\n \"one to save an additional 0.4 bits per parameter\",\n },\n )\n bnb_4bit_quant_type: str = field(\n default=\"nf4\",\n metadata={\n \"help\": \"Quantization type for 4 bit\",\n },\n )\n bnb_quantize_after_model_init: bool = field(\n default=False, metadata={\"help\": \"If False, quantization will be at model init\"}\n )\n\n # gptq\n gptq_bits: int = field(\n default=4,\n metadata={\n \"help\": \"Bits for GPTQ quantization\",\n },\n )\n gptq_group_size: int = field(\n default=128,\n metadata={\n \"help\": \"Group size for GPTQ quantization\",\n },\n )\n gptq_disable_exllama: bool = field(\n default=True,\n metadata={\n \"help\": \"Disable ExLlama kernels for GPTQ quantization\",\n },\n )\n\n # lora\n apply_lora: bool = field(\n default=False,\n metadata={\n \"help\": \"Apply LoRA to the model or not\",\n },\n )\n lora_rank: int = field(\n default=8,\n metadata={\n \"help\": \"LoRA rank value. LoRA matrices W_A x R and R x W_B, where R is LoRA rank\",\n },\n )\n lora_alpha: int = field(\n default=32,\n metadata={\n \"help\": \"LoRA alpha value. The resulting LoRA matrix will be multiplied by this value\",\n },\n )\n lora_dropout: float = field(\n default=0.1,\n metadata={\n \"help\": \"LoRA dropout value\",\n },\n )\n raw_lora_target_modules: str = field(\n default=\"all\",\n metadata={\n \"help\": 'Names of modules to apply LoRA. A comma-separated string, for example: \"k,q,v\". '\n 'When setting the value \"all\", LoRA will be applied to all linear layers, except for the '\n \"input embeddings and the lm_head.\",\n },\n )\n\n # training arguments\n output_dir: str = field(\n default=\"./outputs/\",\n metadata={\n \"help\": \"The path to the directory where the artifacts will be saved\",\n },\n )\n per_device_train_batch_size: int = field(\n default=2,\n metadata={\n \"help\": \"Batch size on each GPU\",\n },\n )\n do_eval: bool = field(\n default=False,\n metadata={\n \"help\": \"Run eval or not\",\n },\n )\n per_device_eval_batch_size: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"Batch size on each GPU for evaluation. \"\n \"If None per_device_eval_batch_size equals to per_device_train_batch_size\",\n },\n )\n gradient_accumulation_steps: int = field(\n default=1,\n metadata={\n \"help\": \"Number of steps to accumulate gradients\",\n },\n )\n eval_accumulation_steps: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"Number of steps to accumulate gradients at evaluation.\"\n \"If None eval_accumulation_steps equals to gradient_accumulation_steps\",\n },\n )\n eval_delay: int = field(\n default=0,\n metadata={\n \"help\": \"Number of epochs or steps to wait for before the first \"\n \"evaluation can be performed, depending on the evaluation_strategy\"\n },\n )\n eval_steps: Optional[int] = field(\n default=1_000, metadata={\"help\": \"Number of update steps between two evaluations\"}\n )\n warmup_steps: int = field(\n default=1_000,\n metadata={\n \"help\": \"Number of steps to warm up\",\n },\n )\n max_steps: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"Maximum number of training steps\",\n },\n )\n num_train_epochs: int = field(\n default=1,\n metadata={\n \"help\": \"Number of training epochs\",\n },\n )\n learning_rate: float = field(\n default=2e-4,\n metadata={\n \"help\": \"Learning rate value\",\n },\n )\n max_grad_norm: float = field(\n default=1.0,\n metadata={\n \"help\": \"Clip grad value\",\n },\n )\n weight_decay: float = field(\n default=0.001,\n metadata={\n \"help\": \"Weight decay value\",\n },\n )\n label_smoothing_factor: float = field(\n default=0.0,\n metadata={\n \"help\": \"Label smoothing value\",\n },\n )\n logging_steps: int = field(\n default=10,\n metadata={\n \"help\": \"Number of steps between logging\",\n },\n )\n save_steps: int = field(\n default=100,\n metadata={\n \"help\": \"The number of training steps between saving the checkpoint and uploading to the hub\",\n },\n )\n save_total_limit: int = field(\n default=1,\n metadata={\n \"help\": \"The number of checkpoints that are saved locally\",\n },\n )\n optim: Optional[str] = field(\n default=\"paged_adamw_8bit\",\n metadata={\n \"help\": \"Optimizer name. It will be overwritten if you use deepspeed\",\n },\n )\n push_to_hub: bool = field(\n default=False,\n metadata={\n \"help\": \"Upload the model to the hub. \"\n \"The model will be uploaded to the hub every save_steps. \"\n \"If LoRA is used, then LoRA's weights will be loaded onto the hub\",\n },\n )\n hub_model_id: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"The name of the model at the hub. Example: BobaZooba/Shurale\",\n },\n )\n hub_private_repo: bool = field(\n default=True,\n metadata={\n \"help\": \"Private repository or not\",\n },\n )\n neftune_noise_alpha: Optional[float] = field(\n default=None,\n metadata={\n \"help\": \"If not None, this will activate NEFTune noise embeddings. \"\n \"This can drastically improve model performance for instruction fine-tuning\",\n },\n )\n\n # training traction\n project_name: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Project name for training traction services like W&B\",\n },\n )\n report_to_wandb: bool = field(\n default=False,\n metadata={\n \"help\": \"Report or not to Weight & Biases\",\n },\n )\n wandb_api_key: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Weight & Biases API key. You can also set this key using .env file\",\n },\n )\n wandb_project: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Depreacted, use project_name. Weight & Biases project name\",\n },\n )\n wandb_entity: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"Weight & Biases entity name (user or company)\",\n },\n )\n\n def __post_init__(self):\n if self.huggingface_hub_token is not None:\n os.environ[enums.EnvironmentVariables.huggingface_hub_token] = self.huggingface_hub_token\n dist_logger(message=f\"Environment variable {enums.EnvironmentVariables.huggingface_hub_token} set\")\n\n if self.report_to_wandb:\n for key, value in zip(\n [\n enums.EnvironmentVariables.wandb_api_key,\n enums.EnvironmentVariables.wandb_project,\n enums.EnvironmentVariables.wandb_entity,\n ],\n [\n self.wandb_api_key,\n self.correct_project_name,\n self.wandb_entity,\n ],\n ):\n if value is not None:\n os.environ[key] = value\n dist_logger(message=f\"Environment variable {key} set\")\n else:\n os.environ[enums.EnvironmentVariables.wandb_disabled] = \"true\"\n\n @property\n def correct_project_name(self) -> Optional[str]:\n if self.project_name is not None and self.wandb_project is not None:\n dist_logger.warning(\n message=\"You set both project_name and wandb_project.\"\n \"Priority set to project_name for experiment tracking\"\n )\n return self.project_name\n elif self.project_name is not None:\n return self.project_name\n elif self.wandb_project is not None:\n dist_logger.warning(message=\"wandb_project is depreacted, please use project_name instead\")\n return self.wandb_project\n else:\n return None\n\n def check_hub(self) -> None:\n if self.push_to_hub and self.hub_model_id is None:\n raise ValueError(\"You want to push to HF hub, but hub_model_id is None\")\n elif self.hub_model_id is not None and not self.push_to_hub:\n dist_logger.warning(\"You set hub_model_id, but push_to_hub is False\")\n\n return None\n\n def apply_deepspeed_single_gpu(self) -> None:\n os.environ[enums.EnvironmentVariables.master_address] = \"localhost\"\n os.environ[enums.EnvironmentVariables.master_port] = str(self.master_port)\n os.environ[enums.EnvironmentVariables.rank] = \"0\"\n os.environ[enums.EnvironmentVariables.local_rank] = \"0\"\n os.environ[enums.EnvironmentVariables.world_size] = \"1\"\n\n def check_deepspeed(self) -> None:\n if self.deepspeed is not None:\n spec = find_spec(\"deepspeed\")\n\n if spec is None:\n raise ImportError(\"Deepspeed is not None, but failed to import deepspeed. Please install deepspeed.\")\n\n if self.single_gpu:\n self.apply_deepspeed_single_gpu()\n\n return None\n\n def check_flash_attention(self) -> None:\n if self.use_flash_attention_2:\n if not torch.cuda.is_available():\n raise ImportError(\"You want to use flash_attention_2, but CUDA is not available\")\n\n spec = find_spec(\"flash_attn\")\n\n if spec is None:\n raise ImportError(\n \"You want to use flash_attention_2, but flash-attn is not installed. Please install flash-attn.\"\n )\n\n return None\n\n def check_auto_gptq(self) -> None:\n spec = find_spec(\"auto_gptq\")\n\n if spec is None:\n raise ImportError(\n \"You want to quantize model using GPTQ, but auto-gptq is not installed. Please install auto-gptq.\"\n )\n\n return None\n\n def check(self) -> None:\n \"\"\"\n Performs a series of checks to validate the configuration for compatibility with the training environment.\n\n This method is responsible for ensuring that the environment is properly set up for the actions specified in\n the configuration object, such as pushing to Hugging Face's hub, using deepspeed, and using flash attention.\n\n It includes the following checks:\n - Verifies that credentials for Hugging Face hub are provided if the model is intended to be pushed to the hub.\n - Validates that deepspeed is installed if it is specified in the configuration.\n - Ensures that the necessary packages are installed for using flash attention if configured to do so.\n\n Does not return any value.\n\n Raises:\n - ValueError: If the configuration for hub interaction is incorrect.\n - ImportError: If any of the required libraries (e.g., deepspeed, flash-attn, auto-gptq) are not installed.\n\n Example usage:\n ```python\n from xllm import Config\n\n config = Config(...)\n # Before proceeding with training or other operations, run checks to ensure environment compatibility.\n config.check()\n ```\n\n Note:\n - Always invoke this method after initializing a `Config` object and before proceeding with model training\n or other operations that rely on the configuration settings.\n \"\"\"\n self.check_hub()\n self.check_deepspeed()\n self.check_flash_attention()\n\n return None\n\n @property\n def correct_tokenizer_name_or_path(self) -> str:\n \"\"\"\n Resolves the tokenizer name or path to be used for initializing the tokenizer.\n\n This property ensures that if a specific tokenizer name or path is not provided in the configuration object,\n the model name or path is used instead, maintaining consistency between model and tokenizer.\n\n Returns:\n `str`: The name or path of the tokenizer to be used. If `tokenizer_name_or_path` is specified in `Config`\n object, that value is used. Otherwise, `model_name_or_path` is returned as the default tokenizer identifier.\n\n Example usage:\n ```python\n from xllm import Config\n\n config = Config(model_name_or_path=\"gpt2\", tokenizer_name_or_path=None)\n tokenizer_name_or_path = config.correct_tokenizer_name_or_path\n # tokenizer_name_or_path now holds the value \"gpt2\"\n ```\n\n Note:\n - It is a common practice to use the same identifier for both the model and its corresponding tokenizer.\n This property handles such a case automatically when the `tokenizer_name_or_path` is not explicitly set.\n \"\"\"\n if self.tokenizer_name_or_path is not None:\n return self.tokenizer_name_or_path\n else:\n return self.model_name_or_path\n\n @property\n def lora_target_modules(self) -> Optional[List[str]]:\n \"\"\"\n Interprets the LoRA target modules setting from the configuration to determine which model modules to apply\n LoRA to.\n\n LoRA (Low-Rank Adaptation) is a parameter-efficient training method that modifies specific layers within a\n model. This property is responsible for parsing the `raw_lora_target_modules` configuration to identify\n the specific modules (like attention key, query, and value matrices) that LoRA will be applied to.\n\n Returns:\n Optional[List[str]]: A list of module names to apply LoRA to if specified, otherwise `None` if LoRA should\n be applied to all eligible modules as determined by the string \"all\" in `raw_lora_target_modules`.\n\n Raises:\n ValueError: If `raw_lora_target_modules` is not set.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a Config object with LoRA targets specified.\n config = Config(raw_lora_target_modules=\"k,q,v\")\n lora_modules = config.lora_target_modules\n # lora_modules now holds the list ['k', 'q', 'v'].\n ```\n\n Note:\n - The `raw_lora_target_modules` should be provided as a comma-separated string specifying the target\n modules. If LoRA should be applied broadly, the value \"all\" can be used.\n \"\"\"\n if self.raw_lora_target_modules == \"all\":\n return None\n elif self.raw_lora_target_modules is not None:\n modules_names = [module_name.strip() for module_name in self.raw_lora_target_modules.split(\",\")]\n return modules_names\n else:\n raise ValueError(\"raw_lora_target_modules doesn't set\")\n\n @property\n def dtype(self) -> torch.dtype:\n \"\"\"\n Determines the appropriate PyTorch data type for the model based on availability of CUDA and configuration\n settings.\n\n This property assists in setting computational precision for training and inference (e.g., FP32, FP16, BF16),\n basing the decision on system capabilities and user preferences as defined in the `Config` object. The selected\n data type can impact both the computational efficiency and memory usage of the model operations.\n\n Returns:\n `torch.dtype`: The data type to be used for the model tensors. This can be one of the following based on the\n system's CUDA support and configuration flags: `torch.float32` (FP32), `torch.float16` (FP16), or\n `torch.bfloat16` (BF16).\n\n Example usage:\n ```python\n from xllm import Config\n\n config = Config(force_fp32=False, force_fp16=True)\n model_dtype = config.dtype\n # If CUDA is available and BF16 is supported, model_dtype will be `torch.bfloat16`.\n # Otherwise, it falls back to `torch.float16` due to the forced FP16 configuration.\n ```\n\n Note:\n - This property plays a critical role in memory management and computational efficiency, especially when\n working with large models or limited system resources.\n \"\"\"\n if not torch.cuda.is_available() or self.force_fp32:\n return torch.float32\n elif self.force_fp16:\n return torch.float16\n elif torch.cuda.is_bf16_supported():\n return torch.bfloat16\n else:\n return torch.float16\n\n @property\n def deepspeed(self) -> Optional[Dict[str, Any]]:\n \"\"\"\n Retrieves the deepspeed configuration dictionary based on settings within the `Config` object.\n\n This property parses the deepspeed settings from the configuration to construct the configuration dictionary\n used for ing up deepspeed in the model's training environment. It determines whether a predefined stage\n or a custom configuration file path should be utilized.\n\n Returns:\n `Optional[Dict[str, Any]]`: A dictionary containing deepspeed configurations, or `None` if deepspeed is not\n to be used.\n\n Raises:\n ValueError: If the `deepspeed_stage` specified does not correspond to a known configuration,\n or if a custom deepspeed configuration file path does not exist.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object with deepspeed specifications.\n config = Config(deepspeed_stage=\"2\")\n ds_config = config.deepspeed\n # ds_config now contains the deepspeed configuration for stage 2.\n ```\n\n Note:\n - A deepspeed stage is a set of predefined configurations. If this is set, the corresponding configuration\n will be used and any custom deepspeed configuration file will be ignored.\n - If a custom deepspeed configuration file path is given and it exists, that configuration will be loaded\n and used.\n \"\"\"\n deepspeed_config: Optional[Dict[str, Any]] = None\n\n if self.deepspeed_config_path is not None:\n if os.path.isfile(self.deepspeed_config_path):\n with open(self.deepspeed_config_path) as file_object:\n deepspeed_config = json.load(file_object)\n return deepspeed_config\n else:\n raise ValueError(f\"deepspeed_config_path set to {self.deepspeed_config_path}, but not found\")\n\n if self.deepspeed_stage in [0, \"0\", \"stage_0\"]:\n return None\n\n if self.deepspeed_stage is not None:\n deepspeed_config = DS_CONFIG_MAPPER.get(self.deepspeed_stage, None)\n if deepspeed_config is None:\n raise ValueError(\n f'Deepspeed stage \"{self.deepspeed_stage}\" not found in keys: {list(DS_CONFIG_MAPPER.keys())}'\n )\n\n return deepspeed_config\n\n @property\n def fsdp(self) -> Union[str, List[str]]:\n \"\"\"\n Compiles the configurations for Fully Sharded Data Parallel (FSDP) based on the settings in the `Config` object.\n\n This property creates a list containing FSDP-related options, which informs the training process whether to\n enable FSDP and which FSDP strategy to employ.\n\n A list of options (fsdp_strategy) along the following:\n \"full_shard\": Shard parameters, gradients and optimizer states.\n \"shard_grad_op\": Shard optimizer states and gradients.\n \"offload\": Offload parameters and gradients to CPUs (only compatible with \"full_shard\" and \"shard_grad_op\").\n \"auto_wrap\": Automatically recursively wrap layers with FSDP using default_auto_wrap_policy.\n\n Returns:\n `Union[str, List[str]]`: A list of FSDP options as strings. It can be an empty string if FSDP is not used or\n a list with the specified FSDP strategy and options such as offloading.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object with FSDP specifications.\n config = Config(fsdp_strategy=\"full_shard\", fsdp_offload=True)\n fsdp_options = config.fsdp\n ```\n\n Note:\n - FSDP strategies and options improve memory efficiency during distributed training by sharding the model's\n parameters across multiple devices.\n - The FSDP settings in the configuration should match the target training environment and system\n capabilities.\n \"\"\"\n fsdp_options = list()\n\n if self.fsdp_strategy is not None and self.fsdp_strategy != \"\":\n fsdp_options.append(self.fsdp_strategy)\n else:\n return \"\"\n\n if self.fsdp_offload:\n fsdp_options.append(FSDPOption.OFFLOAD)\n\n return fsdp_options\n\n @property\n def lora_model_name_or_path_for_fusing(self) -> str:\n \"\"\"\n Determines the name or path of the LoRA model to be used for the fusing process.\n\n This property resolves which model should be fused by checking whether a model ID from the Hugging Face hub or a\n local path to a LoRA model is provided in the configuration object. It is essential for the fusing operation\n when LoRA weights need to be integrated into the base model.\n\n Returns:\n `str`: The Hugging Face hub model ID or the local file path to the LoRA model, depending on which is\n specified.\n\n Raises:\n ValueError: If neither `lora_hub_model_id` nor `lora_model_local_path` is set, indicating that there is no\n model specified for fusing.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a Config object with a specified LoRA model on Hugging Face Hub or locally.\n config = Config(lora_hub_model_id=\"username/model-id\", lora_model_local_path=None)\n model_name_or_path = config.lora_model_name_or_path_for_fusing\n # model_name_or_path will hold the value \"username/model-id\".\n ```\n\n Note:\n - This property is specifically used during the model fusing step and should be configured correctly in\n scenarios where LoRA is utilized.\n \"\"\"\n if self.lora_hub_model_id is not None:\n return self.lora_hub_model_id\n elif self.lora_model_local_path is not None:\n return self.lora_model_local_path\n else:\n raise ValueError(\"Please set lora_hub_model_id or lora_model_local_path for fusing\")\n\n @property\n def need_to_prepare_model_for_kbit_training(self) -> bool:\n if self.prepare_model_for_kbit_training is not None:\n return self.prepare_model_for_kbit_training\n else:\n return self.from_gptq or self.load_in_4bit or self.load_in_8bit" }, { "identifier": "build_collator", "path": "src/xllm/core/dependencies.py", "snippet": "def build_collator(config: Config, tokenizer: PreTrainedTokenizer, **kwargs: Any) -> BaseCollator:\n \"\"\"\n Creates a data collator instance, which is responsible for collating batches of data when fed to the model during\n training.\n\n This function fetches the appropriate collator class from a registry using the key provided in the configuration.\n It then instantiates the collator with the tokenizer and any additional arguments necessary to prepare the data\n according to the model's requirements.\n\n Args:\n config (`Config`):\n The configuration object containing the key to identify the appropriate collator class and other related\n settings.\n tokenizer (`PreTrainedTokenizer`):\n The tokenizer instance that will be used by the collator to tokenize and encode the input data.\n **kwargs (`Any`):\n Additional keyword arguments that may be required by the specific collator class during instantiation.\n\n Returns:\n `BaseCollator`: An instance of a subclass of `BaseCollator` that is ready to format batches of data for the\n model.\n\n The function carries out the following operations:\n - Identifies the collator class using the `collator_key` from the configuration object's registry.\n - Initializes the collator class with the tokenizer along with any custom configurations or arguments.\n\n Raises:\n ValueError: If the type of collator found in the registry does not inherit from `BaseCollator`.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object and a loaded tokenizer.\n config = Config(...)\n tokenizer = load_tokenizer(...)\n collator = build_collator(config=config, tokenizer=tokenizer)\n # collator is now ready to be used for creating model-ready data batches during training.\n ```\n\n Note:\n - The data collator prepares and formats the data in a manner suitable for the model's input requirements.\n - Ensure the correct collator key is specified in the `Config` object for proper data collator retrieval and\n initialization.\n \"\"\"\n collator_cls: Type[BaseCollator] = collators_registry.get(key=config.collator_key)\n\n if not issubclass(collator_cls, BaseCollator):\n raise ValueError(f\"Unknown type of collator: {collator_cls.__name__}\")\n\n collator = collator_cls(tokenizer=tokenizer, max_length=config.max_length, **kwargs)\n\n return collator" }, { "identifier": "build_dataset", "path": "src/xllm/core/dependencies.py", "snippet": "def build_dataset(config: Config, is_train: bool = True, **kwargs: Any) -> Optional[BaseDataset]:\n \"\"\"\n Creates an instance of the dataset class specified in the configuration object.\n\n This function is responsible for constructing the dataset to be used for training or evaluation, leveraging the\n dataset registry to find the corresponding class and initializing it with the provided configuration path and\n arguments.\n\n Args:\n config (`Config`):\n The configuration object containing the dataset-related settings including the path to data and dataset key.\n is_train (`bool`, optional, defaults to `True`):\n A flag indicating whether to construct the training dataset or evaluation dataset. If `True`, the function\n constructs the training dataset; otherwise, it constructs the evaluation dataset if specified in the config.\n **kwargs (`Any`):\n Additional keyword arguments that are passed to the dataset class upon construction.\n\n Returns:\n Optional[BaseDataset]: An instance of the derived `BaseDataset` class if successfully created, otherwise `None`.\n\n The function performs the following operations:\n - Determines the path to the dataset based on whether a training or evaluation dataset is requested.\n - Retrieves the specified dataset class from the datasets registry using the key provided in the configuration.\n - Instantiates the dataset class with the determined path and any additional keyword arguments.\n\n Raises:\n ValueError: If the dataset class cannot be found in the registry or the type is not a subclass of `BaseDataset`.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object with the dataset specifications.\n config = Config(...)\n train_dataset = build_dataset(config=config, is_train=True)\n eval_dataset = build_dataset(config=config, is_train=False)\n # train_dataset and eval_dataset are now ready to be used in the training process.\n ```\n\n Note:\n - If the path to data for the specified type of dataset does not exist in the configuration, the function will\n return `None`.\n - This function is designed to abstract away the dataset initialization, allowing for a centralized and\n consistent approach to dataset construction based on the configuration settings.\n \"\"\"\n if is_train:\n path_to_data = config.train_local_path_to_data\n elif config.eval_local_path_to_data is not None:\n path_to_data = config.eval_local_path_to_data\n else:\n return None\n\n dataset_cls: Type[BaseDataset] = datasets_registry.get(key=config.dataset_key)\n\n if issubclass(dataset_cls, BaseDataset):\n dataset = dataset_cls.load(path_to_data=path_to_data, **kwargs)\n else:\n raise ValueError(f\"Unknown type of dataset: {dataset_cls.__name__}\")\n\n return dataset" }, { "identifier": "build_model", "path": "src/xllm/core/dependencies.py", "snippet": "def build_model(\n config: Config,\n quantization_config: Union[BitsAndBytesConfig, GPTQConfig, None],\n low_cpu_mem_usage: Optional[bool] = None,\n) -> PreTrainedModel:\n \"\"\"\n Constructs the language model from a pretrained path with potential quantization configurations and customizations.\n\n This function loads the model specified in the configuration object. It can also apply quantization settings as\n defined by the quantization configuration or prepare the model for k-bit training if required.\n\n Args:\n config (`Config`):\n The configuration object containing model-related settings such as the model's name or path and other\n options.\n quantization_config (`Union[BitsAndBytesConfig, GPTQConfig, None]`):\n A configuration object guiding the quantization behavior of the model.\n low_cpu_mem_usage (`bool`, optional, defaults to `None`):\n A flag that, when set, instructs the model to optimize memory usage on CPUs. This can be helpful when\n dealing with large models or on systems with limited CPU memory resources.\n\n Returns:\n `PreTrainedModel`: An instance of a subclass of `PreTrainedModel` that has been instantiated and possibly\n quantized.\n\n The function handles the following tasks:\n - Determines whether caching should be enabled based on the gradient checkpointing setting.\n - Loads the model using the AutoModelForCausalLM class with provided configuration settings such as `dtype` and\n `device_map`.\n - Applies k-bit training preparations if configured to do so.\n - Modifies model configurations, such as disabling caching if necessary.\n\n Raises:\n ValueError: If the model's type is not supported or cannot be correctly instantiated.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object with model path and quantization settings.\n config = Config(...)\n quantization_config = build_quantization_config(config=config)\n model = build_model(config=config, quantization_config=quantization_config)\n # model is now ready for training or inference.\n ```\n\n Note:\n - If quantization is intended to be applied after model initialization, the `bnb_quantize_after_model_init` flag\n should be set in the `Config` object.\n - Before calling this function, ensure that the model path and any desired customization options are properly\n set in the `Config` object.\n \"\"\"\n if config.bnb_quantize_after_model_init:\n quantization_config = None\n dist_logger(\"bnb quantization is expected later\")\n\n if config.use_gradient_checkpointing:\n use_cache = False\n else:\n use_cache = True\n\n kwargs: Dict[str, Any] = dict()\n\n if config.use_flash_attention_2:\n kwargs[\"use_flash_attention_2\"] = True\n\n if low_cpu_mem_usage is not None:\n kwargs[\"low_cpu_mem_usage\"] = low_cpu_mem_usage\n\n model = AutoModelForCausalLM.from_pretrained(\n pretrained_model_name_or_path=config.model_name_or_path,\n quantization_config=quantization_config,\n torch_dtype=config.dtype,\n trust_remote_code=config.trust_remote_code,\n device_map=config.device_map,\n use_cache=use_cache,\n **kwargs,\n )\n model.config.pretraining_tp = 1\n\n if quantization_config is not None and config.need_to_prepare_model_for_kbit_training:\n model = prepare_model_for_kbit_training(\n model=model, use_gradient_checkpointing=config.use_gradient_checkpointing\n )\n dist_logger(\n message=f\"Model prepared for kbit training. Gradient checkpointing: {config.use_gradient_checkpointing}\",\n local_rank=config.local_rank,\n )\n\n return model" }, { "identifier": "build_quantization_config", "path": "src/xllm/core/dependencies.py", "snippet": "def build_quantization_config(\n config: Config,\n) -> Union[BitsAndBytesConfig, GPTQConfig, None]:\n \"\"\"\n Constructs a configuration for model quantization based on the settings provided in the configuration object.\n\n This function generates either a `BitsAndBytesConfig` or a `GPTQConfig` instance, which are used to inform the\n quantization process for a language model. The function decides which quantization method to apply based on the\n flags set in the `Config` object.\n\n Args:\n config (`Config`):\n The configuration object that contains the flags and settings specifying the quantization method\n and parameters.\n\n Returns:\n Union[BitsAndBytesConfig, GPTQConfig, None]:\n An instance of the quantization configuration class corresponding to the method chosen based on the\n configuration settings, or `None` if quantization is not configured.\n\n The function inspects the configuration to determine the following:\n - If GPTQ-based quantization is specified, it sets up a `GPTQConfig` with the designated bit precision and grouping\n size.\n - If bitsandbytes (bnb) methodology is specified, returns a `BitsAndBytesConfig` with the respective settings.\n - If neither quantization approach is specified or the required settings are absent, it returns `None`.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object with quantization settings.\n config = Config(...)\n quantization_config = build_quantization_config(config=config)\n # quantization_config is now ready to be applied in the model quantization process.\n ```\n\n Note:\n - Having the correct quantization settings in the `Config` object is crucial, as they dictate the behavior\n of the quantization process and impact the model size and computational speed after quantization.\n \"\"\"\n if config.from_gptq:\n quantization_config = GPTQConfig(\n bits=config.gptq_bits,\n group_size=config.gptq_group_size,\n disable_exllama=config.gptq_disable_exllama,\n )\n elif config.load_in_8bit or config.load_in_4bit:\n quantization_config = BitsAndBytesConfig(\n load_in_8bit=config.load_in_8bit,\n load_in_4bit=config.load_in_4bit,\n llm_int8_threshold=config.llm_int8_threshold,\n llm_int8_has_fp16_weight=config.llm_int8_has_fp16_weight,\n bnb_4bit_compute_dtype=config.dtype,\n bnb_4bit_use_double_quant=config.bnb_4bit_use_double_quant,\n bnb_4bit_quant_type=config.bnb_4bit_quant_type,\n )\n else:\n quantization_config = None\n\n return quantization_config" }, { "identifier": "build_tokenizer", "path": "src/xllm/core/dependencies.py", "snippet": "def build_tokenizer(config: Config, use_fast: Optional[bool] = None) -> PreTrainedTokenizer:\n \"\"\"\n Constructs the tokenizer for processing the text according to the specifications provided in the configuration\n object.\n\n This function loads the tokenizer from the path specified in the `Config` object. If requested, it ensures the\n tokenizer uses fast implementation (when available), and sets the padding token and side according to the given\n configuration.\n\n Args:\n config (`Config`):\n The configuration object containing tokenizer settings such as the path to the tokenizer and the desired\n padding side.\n use_fast (`bool`, optional, defaults to `None`):\n A flag indicating whether to use the fast version of the tokenizer if available. When set to `None`,\n falls back to the default behavior of tokenizer class.\n\n Returns:\n `PreTrainedTokenizer`: An instance of the `PreTrainedTokenizer` class loaded and configured as specified.\n\n The function carries out the following steps:\n - Loads the tokenizer from the pretrained path specified in the configuration.\n - If the tokenizer does not have a defined padding token, sets it to the `eos_token`.\n - If padding side settings are provided, configures the tokenizer to apply padding on the specified side.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object with tokenizer path and padding preferences.\n config = Config(...)\n tokenizer = build_tokenizer(config=config)\n # tokenizer is now ready for text processing.\n ```\n\n Note:\n - This function prepares the tokenizer for use in data preparation and model inputs generation.\n - It is crucial to specify the tokenizer's path in the `Config` object for the correct initialization.\n \"\"\"\n kwargs = dict()\n\n if use_fast is not None:\n kwargs[\"use_fast\"] = use_fast\n\n tokenizer = AutoTokenizer.from_pretrained(\n pretrained_model_name_or_path=config.correct_tokenizer_name_or_path,\n trust_remote_code=config.trust_remote_code,\n **kwargs,\n )\n\n if tokenizer.pad_token is None:\n tokenizer.pad_token = tokenizer.eos_token\n dist_logger.info(message=\"Tokenizer pad token set to eos token\", local_rank=config.local_rank)\n\n if config.tokenizer_padding_side is not None:\n tokenizer.padding_side = config.tokenizer_padding_side\n dist_logger.info(\n message=f\"Tokenizer padding side set to {config.tokenizer_padding_side}\", local_rank=config.local_rank\n )\n\n return tokenizer" }, { "identifier": "build_trainer", "path": "src/xllm/core/dependencies.py", "snippet": "def build_trainer(\n config: Config,\n pad_token_id: int,\n training_arguments: TrainingArguments,\n model: Union[PreTrainedModel, PeftModel],\n train_dataset: BaseDataset,\n collator: BaseCollator,\n eval_dataset: Optional[BaseDataset] = None,\n **kwargs: Any,\n) -> LMTrainer:\n \"\"\"\n Instantiates and configures a LLM trainer appropriate for the model and datasets.\n\n This function retrieves the trainer class based on the provided configuration, setting it up with the specified\n model, token padding information, training arguments, datasets, and data collator.\n\n Args:\n config (`Config`):\n The configuration object containing necessary settings for the trainer, such as trainer key and model\n configuration.\n pad_token_id (`int`):\n The ID of the padding token used by the model, necessary for correctly computing the loss during training.\n training_arguments (`TrainingArguments`):\n The training arguments specifying training and evaluation parameters, such as learning rate and batch size.\n model (`Union[PreTrainedModel, PeftModel]`):\n The language model to be trained. Can be any model that is compatible with the training process.\n train_dataset (`BaseDataset`):\n The dataset object containing the training data samples.\n collator (`BaseCollator`):\n The data collator responsible for creating model-ready batches from the data samples.\n eval_dataset (`Optional[BaseDataset]`, defaults to `None`):\n The optional dataset object for evaluation. If provided, it is used for evaluating the model's performance\n during training.\n **kwargs (`Any`):\n Additional keyword arguments that may be required by the specific trainer instantiated.\n\n Returns:\n `LMTrainer`:\n A trainer instance of type `LMTrainer`, which extends the `Trainer` class, configured with the provided\n settings.\n\n The function follows these operations:\n - Retrieves the appropriate subclass of `Trainer` from the `trainers_registry` using a key.\n - Initializes the trainer subclass with provided arguments, configuring it for the training process.\n - Modifies the model configuration, mostly to disable caching for specific model types if necessary.\n\n Raises:\n ValueError: If the trainer class fetched from the registry does not subclass from `Trainer`.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object with trainer specifications and instance of TrainingArguments.\n config = Config(...)\n training_args = build_training_arguments(config)\n trainer = build_trainer(\n config=config,\n pad_token_id=tokenizer.pad_token_id,\n training_arguments=training_args,\n model=model,\n train_dataset=train_dataset,\n collator=collator,\n eval_dataset=eval_dataset\n )\n # trainer is now ready to start the training cycle.\n ```\n\n Note:\n - The specific subclass of `LMTrainer` depends on the `trainer_key` provided in the `Config` object,\n which allows for the use of custom training behavior if needed.\n \"\"\"\n trainer_cls = trainers_registry.get(key=config.trainer_key)\n\n if not issubclass(trainer_cls, Trainer):\n raise ValueError(f\"Unknown type of trainer: {trainer_cls.__name__}\")\n\n trainer: LMTrainer = trainer_cls(\n config=config,\n model=model,\n args=training_arguments,\n data_collator=collator,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n ignore_index=pad_token_id,\n **kwargs,\n )\n\n try:\n model.config.use_cache = False # type: ignore\n except Exception as exception:\n dist_logger.warning(\n message=f\"Can't set use cache to false. Exception: {exception}\",\n local_rank=config.local_rank,\n )\n\n return trainer" }, { "identifier": "build_training_arguments", "path": "src/xllm/core/dependencies.py", "snippet": "def build_training_arguments(config: Config) -> TrainingArguments:\n \"\"\"\n Constructs `TrainingArguments` for model training from the provided configuration object.\n\n This function determines the appropriate training parameters based on the system's capabilities and the user's\n configuration, setting up arguments that control aspects of the training process such as batch size, learning\n rate, weight decay, and hardware acceleration options.\n\n Args:\n config (`Config`):\n A configuration object containing necessary specifications for setting up the training environment.\n\n Returns:\n `TrainingArguments`: An instance of the `TrainingArguments` class with all the provided configuration settings\n applied. This object is then utilized by the training process.\n\n The function checks whether training is supported using mixed precision (both FP16 and BF16) depending on CUDA\n availability and settings in the config object. It also adjusts the weight saving and evaluation strategies\n according to the specified conditions, among other settings.\n\n Example usage:\n ```python\n from xllm import Config\n\n # Assuming a predefined Config object.\n config = Config(...)\n training_args = build_training_arguments(config=config)\n # training_args is now ready to be passed to Trainer or any training loop.\n ```\n\n Note:\n - This function does not train the model but merely prepares the arguments required for training.\n - It is important to ensure that the `Config` object has accurate and intended values, as they will directly\n impact all aspects of the model's training strategy.\n \"\"\"\n if torch.cuda.is_available():\n if torch.cuda.is_bf16_supported() and not config.force_fp16:\n fp16 = False\n bf16 = True\n else:\n fp16 = True\n bf16 = False\n else:\n fp16 = False\n bf16 = False\n\n training_arguments = TrainingArguments(\n output_dir=config.output_dir,\n per_device_train_batch_size=config.per_device_train_batch_size,\n gradient_accumulation_steps=config.gradient_accumulation_steps,\n warmup_steps=config.warmup_steps,\n learning_rate=config.learning_rate,\n max_steps=config.max_steps if config.max_steps is not None else -1,\n num_train_epochs=config.num_train_epochs,\n weight_decay=config.weight_decay,\n max_grad_norm=config.max_grad_norm,\n label_smoothing_factor=config.label_smoothing_factor,\n fp16=fp16,\n bf16=bf16,\n logging_steps=config.logging_steps,\n report_to=[\"wandb\"] if config.report_to_wandb else None,\n save_strategy=\"steps\",\n save_steps=config.save_steps,\n save_total_limit=config.save_total_limit,\n hub_model_id=config.hub_model_id,\n hub_strategy=\"checkpoint\",\n hub_token=os.environ.get(enums.EnvironmentVariables.huggingface_hub_token, None),\n push_to_hub=config.push_to_hub,\n hub_private_repo=config.hub_private_repo,\n save_safetensors=config.save_safetensors,\n fsdp=config.fsdp,\n deepspeed=config.deepspeed,\n remove_unused_columns=False,\n log_level=enums.LogLevel.info,\n disable_tqdm=False,\n logging_first_step=True,\n optim=config.optim, # will be overwriten by deepspeed config if exist\n do_eval=config.do_eval,\n evaluation_strategy=\"steps\" if config.do_eval else IntervalStrategy.NO,\n per_device_eval_batch_size=config.per_device_eval_batch_size or config.per_device_train_batch_size,\n eval_accumulation_steps=config.eval_accumulation_steps or config.gradient_accumulation_steps,\n eval_delay=config.eval_delay,\n eval_steps=config.eval_steps,\n seed=config.seed,\n data_seed=config.seed,\n metric_for_best_model=\"eval_loss\" if config.do_eval else \"loss\",\n neftune_noise_alpha=config.neftune_noise_alpha,\n )\n return training_arguments" }, { "identifier": "datasets_registry", "path": "src/xllm/datasets/registry.py", "snippet": "" }, { "identifier": "SodaDataset", "path": "src/xllm/datasets/soda.py", "snippet": "class SodaDataset(BaseDataset):\n HEADER_KEY = \"header\"\n DIALOG_KEY = \"dialog\"\n\n _HF_DATASET_ID = \"allenai/soda\"\n\n def __init__(self, data: List[RawSample], header_drop_probability: float = 0.05):\n super().__init__(data=data)\n self.header_drop_probability = header_drop_probability\n\n @classmethod\n def get_data(cls, config: Config) -> Optional[Tuple[List[RawSample], Optional[List[RawSample]]]]:\n soda_dataset = datasets.load_dataset(cls._HF_DATASET_ID)\n\n parsed_data: Dict[str, List[RawSample]] = dict()\n\n known_indices = set()\n\n for split in [\"train\", \"test\"]:\n parsed_data[split] = list()\n\n for sample in tqdm(soda_dataset[split], desc=f\"Parsing SODA {split}\"):\n index = sample.get(\"original_index\")\n\n if index in known_indices:\n continue\n\n parsed_sample = {\n cls.HEADER_KEY: sample.get(\"narrative\"),\n cls.DIALOG_KEY: [\n f\"{speaker}: {phrase}\"\n for speaker, phrase in zip(sample.get(\"speakers\"), sample.get(\"dialogue\"))\n ],\n }\n\n parsed_data[split].append(parsed_sample)\n known_indices.add(index)\n\n train = parsed_data[\"train\"]\n valid = parsed_data[\"test\"]\n\n return train, valid\n\n def get_sample(self, index: int) -> RawSample:\n sample = self.data[index]\n\n dialog = sample[self.DIALOG_KEY]\n\n phrases = list()\n\n if not isinstance(dialog, list):\n raise ValueError(f\"{self.DIALOG_KEY} of sample is not a list: {type(dialog)}\")\n\n for phrase in dialog:\n if isinstance(phrase, str):\n phrases.append(phrase)\n\n if self.HEADER_KEY in sample:\n header = sample[self.HEADER_KEY]\n\n is_drop_header = np.random.rand() <= self.header_drop_probability\n\n if not is_drop_header and isinstance(header, str):\n phrases.insert(0, header)\n\n sample = {enums.General.text_parts: [phrase.replace(\"\\n\", \" \").replace(\"\\r\", \" \") for phrase in phrases]}\n\n return sample" }, { "identifier": "trainers_registry", "path": "src/xllm/trainers/registry.py", "snippet": "" }, { "identifier": "LLAMA_TOKENIZER_DIR", "path": "tests/helpers/constants.py", "snippet": "LLAMA_TOKENIZER_DIR: str = os.path.join(TOKENIZERS_DIR, \"llama/\")" }, { "identifier": "DATA", "path": "tests/helpers/dummy_data.py", "snippet": "DATA = [\n {\n enums.General.text_parts: [\n \"Person 1: Hello\",\n \"Person 2: It's me\",\n \"Person 1: I was wondering\",\n ]\n },\n {\n enums.General.text_parts: [\n \"You are a sith lord\",\n \"Kenobi: Hello there\",\n \"General Grievous: General Kenobi\",\n ]\n },\n]" }, { "identifier": "DummyDataset", "path": "tests/helpers/dummy_data.py", "snippet": "class DummyDataset(BaseDataset):\n @classmethod\n def get_data(cls, config: Config) -> Tuple[List[RawSample], Optional[List[RawSample]]]:\n return DATA, None\n\n def get_sample(self, index: int) -> RawSample:\n return self.data[index]" }, { "identifier": "patch_from_pretrained_auto_causal_lm", "path": "tests/helpers/patches.py", "snippet": "@contextmanager\ndef patch_from_pretrained_auto_causal_lm(monkeypatch: MonkeyPatch) -> Any:\n def from_pretrained(\n pretrained_model_name_or_path: str,\n quantization_config: Union[BitsAndBytesConfig, GPTQConfig, None] = None,\n torch_dtype: dtype = torch.float16,\n trust_remote_code: bool = True,\n device_map: Union[str, Dict[str, Any], None] = None,\n use_cache: bool = False,\n use_flash_attention_2: bool = True,\n ) -> LlamaForCausalLM:\n config = LlamaConfig(\n vocab_size=32_000,\n hidden_size=8,\n intermediate_size=32,\n num_hidden_layers=2,\n num_attention_heads=2,\n max_position_embeddings=32,\n )\n model = LlamaForCausalLM(config=config)\n return model\n\n monkeypatch.setattr(AutoModelForCausalLM, \"from_pretrained\", from_pretrained)\n yield True\n monkeypatch.undo()" } ]
import pytest from peft import PeftModel from pytest import MonkeyPatch from torch import Tensor from transformers import ( BitsAndBytesConfig, GPTQConfig, PreTrainedTokenizer, TrainingArguments, ) from src.xllm.collators.lm import LMCollator from src.xllm.collators.registry import collators_registry from src.xllm.core.config import Config from src.xllm.core.dependencies import ( build_collator, build_dataset, build_model, build_quantization_config, build_tokenizer, build_trainer, build_training_arguments, ) from src.xllm.datasets.registry import datasets_registry from src.xllm.datasets.soda import SodaDataset from src.xllm.trainers.registry import trainers_registry from tests.helpers.constants import LLAMA_TOKENIZER_DIR from tests.helpers.dummy_data import DATA, DummyDataset from tests.helpers.patches import patch_from_pretrained_auto_causal_lm
18,422
# Copyright 2023 Boris Zubarev. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def test_build_training_arguments(config: Config): arguments = build_training_arguments(config=config) assert arguments.per_device_train_batch_size == config.per_device_train_batch_size assert arguments.deepspeed is None def test_build_dataset_train(path_to_train_dummy_data: str): datasets_registry.add(key="dummy", value=DummyDataset) config = Config(dataset_key="dummy", train_local_path_to_data=path_to_train_dummy_data)
# Copyright 2023 Boris Zubarev. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def test_build_training_arguments(config: Config): arguments = build_training_arguments(config=config) assert arguments.per_device_train_batch_size == config.per_device_train_batch_size assert arguments.deepspeed is None def test_build_dataset_train(path_to_train_dummy_data: str): datasets_registry.add(key="dummy", value=DummyDataset) config = Config(dataset_key="dummy", train_local_path_to_data=path_to_train_dummy_data)
dataset = build_dataset(config=config, is_train=True)
4
2023-11-10 17:55:03+00:00
24k
AMAAI-Lab/mustango
diffusers/src/diffusers/models/unet_2d_condition_flax.py
[ { "identifier": "ConfigMixin", "path": "diffusers/src/diffusers/configuration_utils.py", "snippet": "class ConfigMixin:\n r\"\"\"\n Base class for all configuration classes. Stores all configuration parameters under `self.config` Also handles all\n methods for loading/downloading/saving classes inheriting from [`ConfigMixin`] with\n - [`~ConfigMixin.from_config`]\n - [`~ConfigMixin.save_config`]\n\n Class attributes:\n - **config_name** (`str`) -- A filename under which the config should stored when calling\n [`~ConfigMixin.save_config`] (should be overridden by parent class).\n - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be\n overridden by subclass).\n - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).\n - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the init function\n should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by\n subclass).\n \"\"\"\n config_name = None\n ignore_for_config = []\n has_compatibles = False\n\n _deprecated_kwargs = []\n\n def register_to_config(self, **kwargs):\n if self.config_name is None:\n raise NotImplementedError(f\"Make sure that {self.__class__} has defined a class name `config_name`\")\n # Special case for `kwargs` used in deprecation warning added to schedulers\n # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,\n # or solve in a more general way.\n kwargs.pop(\"kwargs\", None)\n for key, value in kwargs.items():\n try:\n setattr(self, key, value)\n except AttributeError as err:\n logger.error(f\"Can't set {key} with value {value} for {self}\")\n raise err\n\n if not hasattr(self, \"_internal_dict\"):\n internal_dict = kwargs\n else:\n previous_dict = dict(self._internal_dict)\n internal_dict = {**self._internal_dict, **kwargs}\n logger.debug(f\"Updating config from {previous_dict} to {internal_dict}\")\n\n self._internal_dict = FrozenDict(internal_dict)\n\n def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):\n \"\"\"\n Save a configuration object to the directory `save_directory`, so that it can be re-loaded using the\n [`~ConfigMixin.from_config`] class method.\n\n Args:\n save_directory (`str` or `os.PathLike`):\n Directory where the configuration JSON file will be saved (will be created if it does not exist).\n \"\"\"\n if os.path.isfile(save_directory):\n raise AssertionError(f\"Provided path ({save_directory}) should be a directory, not a file\")\n\n os.makedirs(save_directory, exist_ok=True)\n\n # If we save using the predefined names, we can load using `from_config`\n output_config_file = os.path.join(save_directory, self.config_name)\n\n self.to_json_file(output_config_file)\n logger.info(f\"Configuration saved in {output_config_file}\")\n\n @classmethod\n def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):\n r\"\"\"\n Instantiate a Python class from a config dictionary\n\n Parameters:\n config (`Dict[str, Any]`):\n A config dictionary from which the Python class will be instantiated. Make sure to only load\n configuration files of compatible classes.\n return_unused_kwargs (`bool`, *optional*, defaults to `False`):\n Whether kwargs that are not consumed by the Python class should be returned or not.\n\n kwargs (remaining dictionary of keyword arguments, *optional*):\n Can be used to update the configuration object (after it being loaded) and initiate the Python class.\n `**kwargs` will be directly passed to the underlying scheduler/model's `__init__` method and eventually\n overwrite same named arguments of `config`.\n\n Examples:\n\n ```python\n >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler\n\n >>> # Download scheduler from huggingface.co and cache.\n >>> scheduler = DDPMScheduler.from_pretrained(\"google/ddpm-cifar10-32\")\n\n >>> # Instantiate DDIM scheduler class with same config as DDPM\n >>> scheduler = DDIMScheduler.from_config(scheduler.config)\n\n >>> # Instantiate PNDM scheduler class with same config as DDPM\n >>> scheduler = PNDMScheduler.from_config(scheduler.config)\n ```\n \"\"\"\n # <===== TO BE REMOVED WITH DEPRECATION\n # TODO(Patrick) - make sure to remove the following lines when config==\"model_path\" is deprecated\n if \"pretrained_model_name_or_path\" in kwargs:\n config = kwargs.pop(\"pretrained_model_name_or_path\")\n\n if config is None:\n raise ValueError(\"Please make sure to provide a config as the first positional argument.\")\n # ======>\n\n if not isinstance(config, dict):\n deprecation_message = \"It is deprecated to pass a pretrained model name or path to `from_config`.\"\n if \"Scheduler\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead.\"\n \" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will\"\n \" be removed in v1.0.0.\"\n )\n elif \"Model\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a model, please use {cls}.load_config(...) followed by\"\n f\" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary\"\n \" instead. This functionality will be removed in v1.0.0.\"\n )\n deprecate(\"config-passed-as-path\", \"1.0.0\", deprecation_message, standard_warn=False)\n config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)\n\n init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)\n\n # Allow dtype to be specified on initialization\n if \"dtype\" in unused_kwargs:\n init_dict[\"dtype\"] = unused_kwargs.pop(\"dtype\")\n\n # add possible deprecated kwargs\n for deprecated_kwarg in cls._deprecated_kwargs:\n if deprecated_kwarg in unused_kwargs:\n init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)\n\n # Return model and optionally state and/or unused_kwargs\n model = cls(**init_dict)\n\n # make sure to also save config parameters that might be used for compatible classes\n model.register_to_config(**hidden_dict)\n\n # add hidden kwargs of compatible classes to unused_kwargs\n unused_kwargs = {**unused_kwargs, **hidden_dict}\n\n if return_unused_kwargs:\n return (model, unused_kwargs)\n else:\n return model\n\n @classmethod\n def get_config_dict(cls, *args, **kwargs):\n deprecation_message = (\n f\" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be\"\n \" removed in version v1.0.0\"\n )\n deprecate(\"get_config_dict\", \"1.0.0\", deprecation_message, standard_warn=False)\n return cls.load_config(*args, **kwargs)\n\n @classmethod\n def load_config(\n cls,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n return_unused_kwargs=False,\n return_commit_hash=False,\n **kwargs,\n ) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n r\"\"\"\n Instantiate a Python class from a config dictionary\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):\n Can be either:\n\n - A string, the *model id* of a model repo on huggingface.co. Valid model ids should have an\n organization name, like `google/ddpm-celebahq-256`.\n - A path to a *directory* containing model weights saved using [`~ConfigMixin.save_config`], e.g.,\n `./my_model_directory/`.\n\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory in which a downloaded pretrained model configuration should be cached if the\n standard cache should not be used.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to delete incompletely received files. Will attempt to resume the download if such a\n file exists.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n output_loading_info(`bool`, *optional*, defaults to `False`):\n Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.\n local_files_only(`bool`, *optional*, defaults to `False`):\n Whether or not to only look at local files (i.e., do not try to download the model).\n use_auth_token (`str` or *bool*, *optional*):\n The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated\n when running `transformers-cli login` (stored in `~/.huggingface`).\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a\n git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any\n identifier allowed by git.\n subfolder (`str`, *optional*, defaults to `\"\"`):\n In case the relevant files are located inside a subfolder of the model repo (either remote in\n huggingface.co or downloaded locally), you can specify the folder name here.\n return_unused_kwargs (`bool`, *optional*, defaults to `False):\n Whether unused keyword arguments of the config shall be returned.\n return_commit_hash (`bool`, *optional*, defaults to `False):\n Whether the commit_hash of the loaded configuration shall be returned.\n\n <Tip>\n\n It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated\n models](https://huggingface.co/docs/hub/models-gated#gated-models).\n\n </Tip>\n\n <Tip>\n\n Activate the special [\"offline-mode\"](https://huggingface.co/transformers/installation.html#offline-mode) to\n use this method in a firewalled environment.\n\n </Tip>\n \"\"\"\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n force_download = kwargs.pop(\"force_download\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n revision = kwargs.pop(\"revision\", None)\n _ = kwargs.pop(\"mirror\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n user_agent = kwargs.pop(\"user_agent\", {})\n\n user_agent = {**user_agent, \"file_type\": \"config\"}\n user_agent = http_user_agent(user_agent)\n\n pretrained_model_name_or_path = str(pretrained_model_name_or_path)\n\n if cls.config_name is None:\n raise ValueError(\n \"`self.config_name` is not defined. Note that one should not load a config from \"\n \"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`\"\n )\n\n if os.path.isfile(pretrained_model_name_or_path):\n config_file = pretrained_model_name_or_path\n elif os.path.isdir(pretrained_model_name_or_path):\n if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):\n # Load from a PyTorch checkpoint\n config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)\n elif subfolder is not None and os.path.isfile(\n os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n ):\n config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n else:\n raise EnvironmentError(\n f\"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}.\"\n )\n else:\n try:\n # Load from URL or cache if already cached\n config_file = hf_hub_download(\n pretrained_model_name_or_path,\n filename=cls.config_name,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n user_agent=user_agent,\n subfolder=subfolder,\n revision=revision,\n )\n except RepositoryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier\"\n \" listed on 'https://huggingface.co/models'\\nIf this is a private repository, make sure to pass a\"\n \" token having permission to this repo with `use_auth_token` or log in with `huggingface-cli\"\n \" login`.\"\n )\n except RevisionNotFoundError:\n raise EnvironmentError(\n f\"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for\"\n \" this model name. Check the model page at\"\n f\" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.\"\n )\n except EntryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}.\"\n )\n except HTTPError as err:\n raise EnvironmentError(\n \"There was a specific connection error when trying to load\"\n f\" {pretrained_model_name_or_path}:\\n{err}\"\n )\n except ValueError:\n raise EnvironmentError(\n f\"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it\"\n f\" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a\"\n f\" directory containing a {cls.config_name} file.\\nCheckout your internet connection or see how to\"\n \" run the library in offline mode at\"\n \" 'https://huggingface.co/docs/diffusers/installation#offline-mode'.\"\n )\n except EnvironmentError:\n raise EnvironmentError(\n f\"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from \"\n \"'https://huggingface.co/models', make sure you don't have a local directory with the same name. \"\n f\"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory \"\n f\"containing a {cls.config_name} file\"\n )\n\n try:\n # Load config dict\n config_dict = cls._dict_from_json_file(config_file)\n\n commit_hash = extract_commit_hash(config_file)\n except (json.JSONDecodeError, UnicodeDecodeError):\n raise EnvironmentError(f\"It looks like the config file at '{config_file}' is not a valid JSON file.\")\n\n if not (return_unused_kwargs or return_commit_hash):\n return config_dict\n\n outputs = (config_dict,)\n\n if return_unused_kwargs:\n outputs += (kwargs,)\n\n if return_commit_hash:\n outputs += (commit_hash,)\n\n return outputs\n\n @staticmethod\n def _get_init_keys(cls):\n return set(dict(inspect.signature(cls.__init__).parameters).keys())\n\n @classmethod\n def extract_init_dict(cls, config_dict, **kwargs):\n # 0. Copy origin config dict\n original_dict = dict(config_dict.items())\n\n # 1. Retrieve expected config attributes from __init__ signature\n expected_keys = cls._get_init_keys(cls)\n expected_keys.remove(\"self\")\n # remove general kwargs if present in dict\n if \"kwargs\" in expected_keys:\n expected_keys.remove(\"kwargs\")\n # remove flax internal keys\n if hasattr(cls, \"_flax_internal_args\"):\n for arg in cls._flax_internal_args:\n expected_keys.remove(arg)\n\n # 2. Remove attributes that cannot be expected from expected config attributes\n # remove keys to be ignored\n if len(cls.ignore_for_config) > 0:\n expected_keys = expected_keys - set(cls.ignore_for_config)\n\n # load diffusers library to import compatible and original scheduler\n diffusers_library = importlib.import_module(__name__.split(\".\")[0])\n\n if cls.has_compatibles:\n compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]\n else:\n compatible_classes = []\n\n expected_keys_comp_cls = set()\n for c in compatible_classes:\n expected_keys_c = cls._get_init_keys(c)\n expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)\n expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)\n config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}\n\n # remove attributes from orig class that cannot be expected\n orig_cls_name = config_dict.pop(\"_class_name\", cls.__name__)\n if orig_cls_name != cls.__name__ and hasattr(diffusers_library, orig_cls_name):\n orig_cls = getattr(diffusers_library, orig_cls_name)\n unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys\n config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}\n\n # remove private attributes\n config_dict = {k: v for k, v in config_dict.items() if not k.startswith(\"_\")}\n\n # 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments\n init_dict = {}\n for key in expected_keys:\n # if config param is passed to kwarg and is present in config dict\n # it should overwrite existing config dict key\n if key in kwargs and key in config_dict:\n config_dict[key] = kwargs.pop(key)\n\n if key in kwargs:\n # overwrite key\n init_dict[key] = kwargs.pop(key)\n elif key in config_dict:\n # use value from config dict\n init_dict[key] = config_dict.pop(key)\n\n # 4. Give nice warning if unexpected values have been passed\n if len(config_dict) > 0:\n logger.warning(\n f\"The config attributes {config_dict} were passed to {cls.__name__}, \"\n \"but are not expected and will be ignored. Please verify your \"\n f\"{cls.config_name} configuration file.\"\n )\n\n # 5. Give nice info if config attributes are initiliazed to default because they have not been passed\n passed_keys = set(init_dict.keys())\n if len(expected_keys - passed_keys) > 0:\n logger.info(\n f\"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values.\"\n )\n\n # 6. Define unused keyword arguments\n unused_kwargs = {**config_dict, **kwargs}\n\n # 7. Define \"hidden\" config parameters that were saved for compatible classes\n hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}\n\n return init_dict, unused_kwargs, hidden_config_dict\n\n @classmethod\n def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):\n with open(json_file, \"r\", encoding=\"utf-8\") as reader:\n text = reader.read()\n return json.loads(text)\n\n def __repr__(self):\n return f\"{self.__class__.__name__} {self.to_json_string()}\"\n\n @property\n def config(self) -> Dict[str, Any]:\n \"\"\"\n Returns the config of the class as a frozen dictionary\n\n Returns:\n `Dict[str, Any]`: Config of the class.\n \"\"\"\n return self._internal_dict\n\n def to_json_string(self) -> str:\n \"\"\"\n Serializes this instance to a JSON string.\n\n Returns:\n `str`: String containing all the attributes that make up this configuration instance in JSON format.\n \"\"\"\n config_dict = self._internal_dict if hasattr(self, \"_internal_dict\") else {}\n config_dict[\"_class_name\"] = self.__class__.__name__\n config_dict[\"_diffusers_version\"] = __version__\n\n def to_json_saveable(value):\n if isinstance(value, np.ndarray):\n value = value.tolist()\n elif isinstance(value, PosixPath):\n value = str(value)\n return value\n\n config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}\n return json.dumps(config_dict, indent=2, sort_keys=True) + \"\\n\"\n\n def to_json_file(self, json_file_path: Union[str, os.PathLike]):\n \"\"\"\n Save this instance to a JSON file.\n\n Args:\n json_file_path (`str` or `os.PathLike`):\n Path to the JSON file in which this configuration instance's parameters will be saved.\n \"\"\"\n with open(json_file_path, \"w\", encoding=\"utf-8\") as writer:\n writer.write(self.to_json_string())" }, { "identifier": "flax_register_to_config", "path": "diffusers/src/diffusers/configuration_utils.py", "snippet": "def flax_register_to_config(cls):\n original_init = cls.__init__\n\n @functools.wraps(original_init)\n def init(self, *args, **kwargs):\n if not isinstance(self, ConfigMixin):\n raise RuntimeError(\n f\"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does \"\n \"not inherit from `ConfigMixin`.\"\n )\n\n # Ignore private kwargs in the init. Retrieve all passed attributes\n init_kwargs = dict(kwargs.items())\n\n # Retrieve default values\n fields = dataclasses.fields(self)\n default_kwargs = {}\n for field in fields:\n # ignore flax specific attributes\n if field.name in self._flax_internal_args:\n continue\n if type(field.default) == dataclasses._MISSING_TYPE:\n default_kwargs[field.name] = None\n else:\n default_kwargs[field.name] = getattr(self, field.name)\n\n # Make sure init_kwargs override default kwargs\n new_kwargs = {**default_kwargs, **init_kwargs}\n # dtype should be part of `init_kwargs`, but not `new_kwargs`\n if \"dtype\" in new_kwargs:\n new_kwargs.pop(\"dtype\")\n\n # Get positional arguments aligned with kwargs\n for i, arg in enumerate(args):\n name = fields[i].name\n new_kwargs[name] = arg\n\n getattr(self, \"register_to_config\")(**new_kwargs)\n original_init(self, *args, **kwargs)\n\n cls.__init__ = init\n return cls" }, { "identifier": "BaseOutput", "path": "diffusers/src/diffusers/utils/outputs.py", "snippet": "class BaseOutput(OrderedDict):\n \"\"\"\n Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a\n tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular\n python dictionary.\n\n <Tip warning={true}>\n\n You can't unpack a `BaseOutput` directly. Use the [`~utils.BaseOutput.to_tuple`] method to convert it to a tuple\n before.\n\n </Tip>\n \"\"\"\n\n def __post_init__(self):\n class_fields = fields(self)\n\n # Safety and consistency checks\n if not len(class_fields):\n raise ValueError(f\"{self.__class__.__name__} has no fields.\")\n\n first_field = getattr(self, class_fields[0].name)\n other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])\n\n if other_fields_are_none and isinstance(first_field, dict):\n for key, value in first_field.items():\n self[key] = value\n else:\n for field in class_fields:\n v = getattr(self, field.name)\n if v is not None:\n self[field.name] = v\n\n def __delitem__(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.\")\n\n def setdefault(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.\")\n\n def pop(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``pop`` on a {self.__class__.__name__} instance.\")\n\n def update(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``update`` on a {self.__class__.__name__} instance.\")\n\n def __getitem__(self, k):\n if isinstance(k, str):\n inner_dict = dict(self.items())\n return inner_dict[k]\n else:\n return self.to_tuple()[k]\n\n def __setattr__(self, name, value):\n if name in self.keys() and value is not None:\n # Don't call self.__setitem__ to avoid recursion errors\n super().__setitem__(name, value)\n super().__setattr__(name, value)\n\n def __setitem__(self, key, value):\n # Will raise a KeyException if needed\n super().__setitem__(key, value)\n # Don't call self.__setattr__ to avoid recursion errors\n super().__setattr__(key, value)\n\n def to_tuple(self) -> Tuple[Any]:\n \"\"\"\n Convert self to a tuple containing all the attributes/keys that are not `None`.\n \"\"\"\n return tuple(self[k] for k in self.keys())" }, { "identifier": "FlaxTimestepEmbedding", "path": "diffusers/src/diffusers/models/embeddings_flax.py", "snippet": "class FlaxTimestepEmbedding(nn.Module):\n r\"\"\"\n Time step Embedding Module. Learns embeddings for input time steps.\n\n Args:\n time_embed_dim (`int`, *optional*, defaults to `32`):\n Time step embedding dimension\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n time_embed_dim: int = 32\n dtype: jnp.dtype = jnp.float32\n\n @nn.compact\n def __call__(self, temb):\n temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name=\"linear_1\")(temb)\n temb = nn.silu(temb)\n temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name=\"linear_2\")(temb)\n return temb" }, { "identifier": "FlaxTimesteps", "path": "diffusers/src/diffusers/models/embeddings_flax.py", "snippet": "class FlaxTimesteps(nn.Module):\n r\"\"\"\n Wrapper Module for sinusoidal Time step Embeddings as described in https://arxiv.org/abs/2006.11239\n\n Args:\n dim (`int`, *optional*, defaults to `32`):\n Time step embedding dimension\n \"\"\"\n dim: int = 32\n flip_sin_to_cos: bool = False\n freq_shift: float = 1\n\n @nn.compact\n def __call__(self, timesteps):\n return get_sinusoidal_embeddings(\n timesteps, embedding_dim=self.dim, flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.freq_shift\n )" }, { "identifier": "FlaxModelMixin", "path": "diffusers/src/diffusers/models/modeling_flax_utils.py", "snippet": "class FlaxModelMixin:\n r\"\"\"\n Base class for all flax models.\n\n [`FlaxModelMixin`] takes care of storing the configuration of the models and handles methods for loading,\n downloading and saving models.\n \"\"\"\n config_name = CONFIG_NAME\n _automatically_saved_args = [\"_diffusers_version\", \"_class_name\", \"_name_or_path\"]\n _flax_internal_args = [\"name\", \"parent\", \"dtype\"]\n\n @classmethod\n def _from_config(cls, config, **kwargs):\n \"\"\"\n All context managers that the model should be initialized under go here.\n \"\"\"\n return cls(config, **kwargs)\n\n def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:\n \"\"\"\n Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.\n \"\"\"\n\n # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27\n def conditional_cast(param):\n if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):\n param = param.astype(dtype)\n return param\n\n if mask is None:\n return jax.tree_map(conditional_cast, params)\n\n flat_params = flatten_dict(params)\n flat_mask, _ = jax.tree_flatten(mask)\n\n for masked, key in zip(flat_mask, flat_params.keys()):\n if masked:\n param = flat_params[key]\n flat_params[key] = conditional_cast(param)\n\n return unflatten_dict(flat_params)\n\n def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast\n the `params` in place.\n\n This method can be used on TPU to explicitly convert the model parameters to bfloat16 precision to do full\n half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params\n you want to cast, and should be `False` for those you want to skip.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # load model\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision\n >>> params = model.to_bf16(params)\n >>> # If you don't want to cast certain parameters (for example layer norm bias and scale)\n >>> # then pass the mask as follows\n >>> from flax import traverse_util\n\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> flat_params = traverse_util.flatten_dict(params)\n >>> mask = {\n ... path: (path[-2] != (\"LayerNorm\", \"bias\") and path[-2:] != (\"LayerNorm\", \"scale\"))\n ... for path in flat_params\n ... }\n >>> mask = traverse_util.unflatten_dict(mask)\n >>> params = model.to_bf16(params, mask)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.bfloat16, mask)\n\n def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the\n model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params\n you want to cast, and should be `False` for those you want to skip\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # Download model and configuration from huggingface.co\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model params will be in fp32, to illustrate the use of this method,\n >>> # we'll first cast to fp16 and back to fp32\n >>> params = model.to_f16(params)\n >>> # now cast back to fp32\n >>> params = model.to_fp32(params)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.float32, mask)\n\n def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the\n `params` in place.\n\n This method can be used on GPU to explicitly convert the model parameters to float16 precision to do full\n half-precision training or to save weights in float16 for inference in order to save memory and improve speed.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params\n you want to cast, and should be `False` for those you want to skip\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # load model\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model params will be in fp32, to cast these to float16\n >>> params = model.to_fp16(params)\n >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)\n >>> # then pass the mask as follows\n >>> from flax import traverse_util\n\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> flat_params = traverse_util.flatten_dict(params)\n >>> mask = {\n ... path: (path[-2] != (\"LayerNorm\", \"bias\") and path[-2:] != (\"LayerNorm\", \"scale\"))\n ... for path in flat_params\n ... }\n >>> mask = traverse_util.unflatten_dict(mask)\n >>> params = model.to_fp16(params, mask)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.float16, mask)\n\n def init_weights(self, rng: jax.random.KeyArray) -> Dict:\n raise NotImplementedError(f\"init_weights method has to be implemented for {self}\")\n\n @classmethod\n def from_pretrained(\n cls,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n dtype: jnp.dtype = jnp.float32,\n *model_args,\n **kwargs,\n ):\n r\"\"\"\n Instantiate a pretrained flax model from a pre-trained model configuration.\n\n The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come\n pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning\n task.\n\n The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those\n weights are discarded.\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`):\n Can be either:\n\n - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.\n Valid model ids are namespaced under a user or organization name, like\n `runwayml/stable-diffusion-v1-5`.\n - A path to a *directory* containing model weights saved using [`~ModelMixin.save_pretrained`],\n e.g., `./my_model_directory/`.\n dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):\n The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and\n `jax.numpy.bfloat16` (on TPUs).\n\n This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If\n specified all the computation will be performed with the given `dtype`.\n\n **Note that this only specifies the dtype of the computation and does not influence the dtype of model\n parameters.**\n\n If you wish to change the dtype of the model parameters, see [`~ModelMixin.to_fp16`] and\n [`~ModelMixin.to_bf16`].\n model_args (sequence of positional arguments, *optional*):\n All remaining positional arguments will be passed to the underlying model's `__init__` method.\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory in which a downloaded pretrained model configuration should be cached if the\n standard cache should not be used.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to delete incompletely received files. Will attempt to resume the download if such a\n file exists.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n local_files_only(`bool`, *optional*, defaults to `False`):\n Whether or not to only look at local files (i.e., do not try to download the model).\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a\n git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any\n identifier allowed by git.\n from_pt (`bool`, *optional*, defaults to `False`):\n Load the model weights from a PyTorch checkpoint save file.\n kwargs (remaining dictionary of keyword arguments, *optional*):\n Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,\n `output_attentions=True`). Behaves differently depending on whether a `config` is provided or\n automatically loaded:\n\n - If a configuration is provided with `config`, `**kwargs` will be directly passed to the\n underlying model's `__init__` method (we assume all relevant updates to the configuration have\n already been done)\n - If a configuration is not provided, `kwargs` will be first passed to the configuration class\n initialization function ([`~ConfigMixin.from_config`]). Each key of `kwargs` that corresponds to\n a configuration attribute will be used to override said attribute with the supplied `kwargs`\n value. Remaining keys that do not correspond to any configuration attribute will be passed to the\n underlying model's `__init__` function.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # Download model and configuration from huggingface.co and cache.\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"./test/saved_model/\")\n ```\"\"\"\n config = kwargs.pop(\"config\", None)\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n force_download = kwargs.pop(\"force_download\", False)\n from_pt = kwargs.pop(\"from_pt\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n revision = kwargs.pop(\"revision\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n\n user_agent = {\n \"diffusers\": __version__,\n \"file_type\": \"model\",\n \"framework\": \"flax\",\n }\n\n # Load config if we don't provide a configuration\n config_path = config if config is not None else pretrained_model_name_or_path\n model, model_kwargs = cls.from_config(\n config_path,\n cache_dir=cache_dir,\n return_unused_kwargs=True,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n revision=revision,\n subfolder=subfolder,\n # model args\n dtype=dtype,\n **kwargs,\n )\n\n # Load model\n pretrained_path_with_subfolder = (\n pretrained_model_name_or_path\n if subfolder is None\n else os.path.join(pretrained_model_name_or_path, subfolder)\n )\n if os.path.isdir(pretrained_path_with_subfolder):\n if from_pt:\n if not os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):\n raise EnvironmentError(\n f\"Error no file named {WEIGHTS_NAME} found in directory {pretrained_path_with_subfolder} \"\n )\n model_file = os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)\n elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)):\n # Load from a Flax checkpoint\n model_file = os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)\n # Check if pytorch weights exist instead\n elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):\n raise EnvironmentError(\n f\"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model\"\n \" using `from_pt=True`.\"\n )\n else:\n raise EnvironmentError(\n f\"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory \"\n f\"{pretrained_path_with_subfolder}.\"\n )\n else:\n try:\n model_file = hf_hub_download(\n pretrained_model_name_or_path,\n filename=FLAX_WEIGHTS_NAME if not from_pt else WEIGHTS_NAME,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n user_agent=user_agent,\n subfolder=subfolder,\n revision=revision,\n )\n\n except RepositoryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier \"\n \"listed on 'https://huggingface.co/models'\\nIf this is a private repository, make sure to pass a \"\n \"token having permission to this repo with `use_auth_token` or log in with `huggingface-cli \"\n \"login`.\"\n )\n except RevisionNotFoundError:\n raise EnvironmentError(\n f\"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for \"\n \"this model name. Check the model page at \"\n f\"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.\"\n )\n except EntryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}.\"\n )\n except HTTPError as err:\n raise EnvironmentError(\n f\"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\\n\"\n f\"{err}\"\n )\n except ValueError:\n raise EnvironmentError(\n f\"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it\"\n f\" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a\"\n f\" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\\nCheckout your\"\n \" internet connection or see how to run the library in offline mode at\"\n \" 'https://huggingface.co/docs/transformers/installation#offline-mode'.\"\n )\n except EnvironmentError:\n raise EnvironmentError(\n f\"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from \"\n \"'https://huggingface.co/models', make sure you don't have a local directory with the same name. \"\n f\"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory \"\n f\"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\"\n )\n\n if from_pt:\n if is_torch_available():\n from .modeling_utils import load_state_dict\n else:\n raise EnvironmentError(\n \"Can't load the model in PyTorch format because PyTorch is not installed. \"\n \"Please, install PyTorch or use native Flax weights.\"\n )\n\n # Step 1: Get the pytorch file\n pytorch_model_file = load_state_dict(model_file)\n\n # Step 2: Convert the weights\n state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)\n else:\n try:\n with open(model_file, \"rb\") as state_f:\n state = from_bytes(cls, state_f.read())\n except (UnpicklingError, msgpack.exceptions.ExtraData) as e:\n try:\n with open(model_file) as f:\n if f.read().startswith(\"version\"):\n raise OSError(\n \"You seem to have cloned a repository without having git-lfs installed. Please\"\n \" install git-lfs and run `git lfs install` followed by `git lfs pull` in the\"\n \" folder you cloned.\"\n )\n else:\n raise ValueError from e\n except (UnicodeDecodeError, ValueError):\n raise EnvironmentError(f\"Unable to convert {model_file} to Flax deserializable object. \")\n # make sure all arrays are stored as jnp.ndarray\n # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:\n # https://github.com/google/flax/issues/1261\n state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.devices(\"cpu\")[0]), state)\n\n # flatten dicts\n state = flatten_dict(state)\n\n params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))\n required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())\n\n shape_state = flatten_dict(unfreeze(params_shape_tree))\n\n missing_keys = required_params - set(state.keys())\n unexpected_keys = set(state.keys()) - required_params\n\n if missing_keys:\n logger.warning(\n f\"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. \"\n \"Make sure to call model.init_weights to initialize the missing weights.\"\n )\n cls._missing_keys = missing_keys\n\n for key in state.keys():\n if key in shape_state and state[key].shape != shape_state[key].shape:\n raise ValueError(\n f\"Trying to load the pretrained weight for {key} failed: checkpoint has shape \"\n f\"{state[key].shape} which is incompatible with the model shape {shape_state[key].shape}. \"\n )\n\n # remove unexpected keys to not be saved again\n for unexpected_key in unexpected_keys:\n del state[unexpected_key]\n\n if len(unexpected_keys) > 0:\n logger.warning(\n f\"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when\"\n f\" initializing {model.__class__.__name__}: {unexpected_keys}\\n- This IS expected if you are\"\n f\" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or\"\n \" with another architecture.\"\n )\n else:\n logger.info(f\"All model checkpoint weights were used when initializing {model.__class__.__name__}.\\n\")\n\n if len(missing_keys) > 0:\n logger.warning(\n f\"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\\nYou should probably\"\n \" TRAIN this model on a down-stream task to be able to use it for predictions and inference.\"\n )\n else:\n logger.info(\n f\"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path}.\\nIf your task is similar to the task the model of the checkpoint\"\n f\" was trained on, you can already use {model.__class__.__name__} for predictions without further\"\n \" training.\"\n )\n\n return model, unflatten_dict(state)\n\n def save_pretrained(\n self,\n save_directory: Union[str, os.PathLike],\n params: Union[Dict, FrozenDict],\n is_main_process: bool = True,\n ):\n \"\"\"\n Save a model and its configuration file to a directory, so that it can be re-loaded using the\n `[`~FlaxModelMixin.from_pretrained`]` class method\n\n Arguments:\n save_directory (`str` or `os.PathLike`):\n Directory to which to save. Will be created if it doesn't exist.\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n is_main_process (`bool`, *optional*, defaults to `True`):\n Whether the process calling this is the main process or not. Useful when in distributed training like\n TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on\n the main process to avoid race conditions.\n \"\"\"\n if os.path.isfile(save_directory):\n logger.error(f\"Provided path ({save_directory}) should be a directory, not a file\")\n return\n\n os.makedirs(save_directory, exist_ok=True)\n\n model_to_save = self\n\n # Attach architecture to the config\n # Save the config\n if is_main_process:\n model_to_save.save_config(save_directory)\n\n # save model\n output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)\n with open(output_model_file, \"wb\") as f:\n model_bytes = to_bytes(params)\n f.write(model_bytes)\n\n logger.info(f\"Model weights saved in {output_model_file}\")" }, { "identifier": "FlaxCrossAttnDownBlock2D", "path": "diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxCrossAttnDownBlock2D(nn.Module):\n r\"\"\"\n Cross Attention 2D Downsizing block - original architecture from Unet transformers:\n https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n attn_num_head_channels (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n out_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n attn_num_head_channels: int = 1\n add_downsample: bool = True\n use_linear_projection: bool = False\n only_cross_attention: bool = False\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n resnets = []\n attentions = []\n\n for i in range(self.num_layers):\n in_channels = self.in_channels if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=in_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n attn_block = FlaxTransformer2DModel(\n in_channels=self.out_channels,\n n_heads=self.attn_num_head_channels,\n d_head=self.out_channels // self.attn_num_head_channels,\n depth=1,\n use_linear_projection=self.use_linear_projection,\n only_cross_attention=self.only_cross_attention,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n if self.add_downsample:\n self.downsamplers_0 = FlaxDownsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, temb, encoder_hidden_states, deterministic=True):\n output_states = ()\n\n for resnet, attn in zip(self.resnets, self.attentions):\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n output_states += (hidden_states,)\n\n if self.add_downsample:\n hidden_states = self.downsamplers_0(hidden_states)\n output_states += (hidden_states,)\n\n return hidden_states, output_states" }, { "identifier": "FlaxCrossAttnUpBlock2D", "path": "diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxCrossAttnUpBlock2D(nn.Module):\n r\"\"\"\n Cross Attention 2D Upsampling block - original architecture from Unet transformers:\n https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n attn_num_head_channels (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n add_upsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add upsampling layer before each final output\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n out_channels: int\n prev_output_channel: int\n dropout: float = 0.0\n num_layers: int = 1\n attn_num_head_channels: int = 1\n add_upsample: bool = True\n use_linear_projection: bool = False\n only_cross_attention: bool = False\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n resnets = []\n attentions = []\n\n for i in range(self.num_layers):\n res_skip_channels = self.in_channels if (i == self.num_layers - 1) else self.out_channels\n resnet_in_channels = self.prev_output_channel if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=resnet_in_channels + res_skip_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n attn_block = FlaxTransformer2DModel(\n in_channels=self.out_channels,\n n_heads=self.attn_num_head_channels,\n d_head=self.out_channels // self.attn_num_head_channels,\n depth=1,\n use_linear_projection=self.use_linear_projection,\n only_cross_attention=self.only_cross_attention,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n if self.add_upsample:\n self.upsamplers_0 = FlaxUpsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, res_hidden_states_tuple, temb, encoder_hidden_states, deterministic=True):\n for resnet, attn in zip(self.resnets, self.attentions):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = jnp.concatenate((hidden_states, res_hidden_states), axis=-1)\n\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n\n if self.add_upsample:\n hidden_states = self.upsamplers_0(hidden_states)\n\n return hidden_states" }, { "identifier": "FlaxDownBlock2D", "path": "diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxDownBlock2D(nn.Module):\n r\"\"\"\n Flax 2D downsizing block\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n out_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n add_downsample: bool = True\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n resnets = []\n\n for i in range(self.num_layers):\n in_channels = self.in_channels if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=in_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n self.resnets = resnets\n\n if self.add_downsample:\n self.downsamplers_0 = FlaxDownsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, temb, deterministic=True):\n output_states = ()\n\n for resnet in self.resnets:\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n output_states += (hidden_states,)\n\n if self.add_downsample:\n hidden_states = self.downsamplers_0(hidden_states)\n output_states += (hidden_states,)\n\n return hidden_states, output_states" }, { "identifier": "FlaxUNetMidBlock2DCrossAttn", "path": "diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxUNetMidBlock2DCrossAttn(nn.Module):\n r\"\"\"\n Cross Attention 2D Mid-level block - original architecture from Unet transformers: https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n attn_num_head_channels (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n attn_num_head_channels: int = 1\n use_linear_projection: bool = False\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n # there is always at least one resnet\n resnets = [\n FlaxResnetBlock2D(\n in_channels=self.in_channels,\n out_channels=self.in_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n ]\n\n attentions = []\n\n for _ in range(self.num_layers):\n attn_block = FlaxTransformer2DModel(\n in_channels=self.in_channels,\n n_heads=self.attn_num_head_channels,\n d_head=self.in_channels // self.attn_num_head_channels,\n depth=1,\n use_linear_projection=self.use_linear_projection,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n res_block = FlaxResnetBlock2D(\n in_channels=self.in_channels,\n out_channels=self.in_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n def __call__(self, hidden_states, temb, encoder_hidden_states, deterministic=True):\n hidden_states = self.resnets[0](hidden_states, temb)\n for attn, resnet in zip(self.attentions, self.resnets[1:]):\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n\n return hidden_states" }, { "identifier": "FlaxUpBlock2D", "path": "diffusers/src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxUpBlock2D(nn.Module):\n r\"\"\"\n Flax 2D upsampling block\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n prev_output_channel (:obj:`int`):\n Output channels from the previous block\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n in_channels: int\n out_channels: int\n prev_output_channel: int\n dropout: float = 0.0\n num_layers: int = 1\n add_upsample: bool = True\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n resnets = []\n\n for i in range(self.num_layers):\n res_skip_channels = self.in_channels if (i == self.num_layers - 1) else self.out_channels\n resnet_in_channels = self.prev_output_channel if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=resnet_in_channels + res_skip_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n self.resnets = resnets\n\n if self.add_upsample:\n self.upsamplers_0 = FlaxUpsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, res_hidden_states_tuple, temb, deterministic=True):\n for resnet in self.resnets:\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = jnp.concatenate((hidden_states, res_hidden_states), axis=-1)\n\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n\n if self.add_upsample:\n hidden_states = self.upsamplers_0(hidden_states)\n\n return hidden_states" } ]
from typing import Tuple, Union from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_2d_blocks_flax import ( FlaxCrossAttnDownBlock2D, FlaxCrossAttnUpBlock2D, FlaxDownBlock2D, FlaxUNetMidBlock2DCrossAttn, FlaxUpBlock2D, ) import flax import flax.linen as nn import jax import jax.numpy as jnp
17,280
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @flax.struct.dataclass class FlaxUNet2DConditionOutput(BaseOutput): """ Args: sample (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)`): Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: jnp.ndarray @flax_register_to_config class FlaxUNet2DConditionModel(nn.Module, FlaxModelMixin, ConfigMixin): r""" FlaxUNet2DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep and returns sample shaped output. This model inherits from [`FlaxModelMixin`]. Check the superclass documentation for the generic methods the library implements for all the models (such as downloading or saving, etc.) Also, this model is a Flax Linen [flax.linen.Module](https://flax.readthedocs.io/en/latest/flax.linen.html#module) subclass. Use it as a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and behavior. Finally, this model supports inherent JAX features such as: - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit) - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation) - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap) - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap) Parameters: sample_size (`int`, *optional*): The size of the input sample. in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): The number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. The corresponding class names will be: "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxDownBlock2D" up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`): The tuple of upsample blocks to use. The corresponding class names will be: "FlaxUpBlock2D", "FlaxCrossAttnUpBlock2D", "FlaxCrossAttnUpBlock2D", "FlaxCrossAttnUpBlock2D" block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. attention_head_dim (`int` or `Tuple[int]`, *optional*, defaults to 8): The dimension of the attention heads. cross_attention_dim (`int`, *optional*, defaults to 768): The dimension of the cross attention features. dropout (`float`, *optional*, defaults to 0): Dropout probability for down, up and bottleneck blocks. flip_sin_to_cos (`bool`, *optional*, defaults to `True`): Whether to flip the sin to cos in the time embedding. freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding. """ sample_size: int = 32 in_channels: int = 4 out_channels: int = 4 down_block_types: Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") only_cross_attention: Union[bool, Tuple[bool]] = False block_out_channels: Tuple[int] = (320, 640, 1280, 1280) layers_per_block: int = 2 attention_head_dim: Union[int, Tuple[int]] = 8 cross_attention_dim: int = 1280 dropout: float = 0.0 use_linear_projection: bool = False dtype: jnp.dtype = jnp.float32 flip_sin_to_cos: bool = True freq_shift: int = 0 def init_weights(self, rng: jax.random.KeyArray) -> FrozenDict: # init input tensors sample_shape = (1, self.in_channels, self.sample_size, self.sample_size) sample = jnp.zeros(sample_shape, dtype=jnp.float32) timesteps = jnp.ones((1,), dtype=jnp.int32) encoder_hidden_states = jnp.zeros((1, 1, self.cross_attention_dim), dtype=jnp.float32) params_rng, dropout_rng = jax.random.split(rng) rngs = {"params": params_rng, "dropout": dropout_rng} return self.init(rngs, sample, timesteps, encoder_hidden_states)["params"] def setup(self): block_out_channels = self.block_out_channels time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = nn.Conv( block_out_channels[0], kernel_size=(3, 3), strides=(1, 1), padding=((1, 1), (1, 1)), dtype=self.dtype, ) # time
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @flax.struct.dataclass class FlaxUNet2DConditionOutput(BaseOutput): """ Args: sample (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)`): Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: jnp.ndarray @flax_register_to_config class FlaxUNet2DConditionModel(nn.Module, FlaxModelMixin, ConfigMixin): r""" FlaxUNet2DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep and returns sample shaped output. This model inherits from [`FlaxModelMixin`]. Check the superclass documentation for the generic methods the library implements for all the models (such as downloading or saving, etc.) Also, this model is a Flax Linen [flax.linen.Module](https://flax.readthedocs.io/en/latest/flax.linen.html#module) subclass. Use it as a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and behavior. Finally, this model supports inherent JAX features such as: - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit) - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation) - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap) - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap) Parameters: sample_size (`int`, *optional*): The size of the input sample. in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): The number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. The corresponding class names will be: "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxDownBlock2D" up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`): The tuple of upsample blocks to use. The corresponding class names will be: "FlaxUpBlock2D", "FlaxCrossAttnUpBlock2D", "FlaxCrossAttnUpBlock2D", "FlaxCrossAttnUpBlock2D" block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. attention_head_dim (`int` or `Tuple[int]`, *optional*, defaults to 8): The dimension of the attention heads. cross_attention_dim (`int`, *optional*, defaults to 768): The dimension of the cross attention features. dropout (`float`, *optional*, defaults to 0): Dropout probability for down, up and bottleneck blocks. flip_sin_to_cos (`bool`, *optional*, defaults to `True`): Whether to flip the sin to cos in the time embedding. freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding. """ sample_size: int = 32 in_channels: int = 4 out_channels: int = 4 down_block_types: Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") only_cross_attention: Union[bool, Tuple[bool]] = False block_out_channels: Tuple[int] = (320, 640, 1280, 1280) layers_per_block: int = 2 attention_head_dim: Union[int, Tuple[int]] = 8 cross_attention_dim: int = 1280 dropout: float = 0.0 use_linear_projection: bool = False dtype: jnp.dtype = jnp.float32 flip_sin_to_cos: bool = True freq_shift: int = 0 def init_weights(self, rng: jax.random.KeyArray) -> FrozenDict: # init input tensors sample_shape = (1, self.in_channels, self.sample_size, self.sample_size) sample = jnp.zeros(sample_shape, dtype=jnp.float32) timesteps = jnp.ones((1,), dtype=jnp.int32) encoder_hidden_states = jnp.zeros((1, 1, self.cross_attention_dim), dtype=jnp.float32) params_rng, dropout_rng = jax.random.split(rng) rngs = {"params": params_rng, "dropout": dropout_rng} return self.init(rngs, sample, timesteps, encoder_hidden_states)["params"] def setup(self): block_out_channels = self.block_out_channels time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = nn.Conv( block_out_channels[0], kernel_size=(3, 3), strides=(1, 1), padding=((1, 1), (1, 1)), dtype=self.dtype, ) # time
self.time_proj = FlaxTimesteps(
4
2023-11-14 23:29:31+00:00
24k
BraveGroup/Drive-WM
src/diffusers/models/unet_2d_condition_flax.py
[ { "identifier": "ConfigMixin", "path": "src/diffusers/configuration_utils.py", "snippet": "class ConfigMixin:\n r\"\"\"\n Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also\n provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and\n saving classes that inherit from [`ConfigMixin`].\n\n Class attributes:\n - **config_name** (`str`) -- A filename under which the config should stored when calling\n [`~ConfigMixin.save_config`] (should be overridden by parent class).\n - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be\n overridden by subclass).\n - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).\n - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function\n should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by\n subclass).\n \"\"\"\n\n config_name = None\n ignore_for_config = []\n has_compatibles = False\n\n _deprecated_kwargs = []\n\n def register_to_config(self, **kwargs):\n if self.config_name is None:\n raise NotImplementedError(f\"Make sure that {self.__class__} has defined a class name `config_name`\")\n # Special case for `kwargs` used in deprecation warning added to schedulers\n # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,\n # or solve in a more general way.\n kwargs.pop(\"kwargs\", None)\n\n if not hasattr(self, \"_internal_dict\"):\n internal_dict = kwargs\n else:\n previous_dict = dict(self._internal_dict)\n internal_dict = {**self._internal_dict, **kwargs}\n logger.debug(f\"Updating config from {previous_dict} to {internal_dict}\")\n\n self._internal_dict = FrozenDict(internal_dict)\n\n def __getattr__(self, name: str) -> Any:\n \"\"\"The only reason we overwrite `getattr` here is to gracefully deprecate accessing\n config attributes directly. See https://github.com/huggingface/diffusers/pull/3129\n\n Tihs funtion is mostly copied from PyTorch's __getattr__ overwrite:\n https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module\n \"\"\"\n\n is_in_config = \"_internal_dict\" in self.__dict__ and hasattr(self.__dict__[\"_internal_dict\"], name)\n is_attribute = name in self.__dict__\n\n if is_in_config and not is_attribute:\n deprecation_message = f\"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'.\"\n deprecate(\"direct config name access\", \"1.0.0\", deprecation_message, standard_warn=False)\n return self._internal_dict[name]\n\n raise AttributeError(f\"'{type(self).__name__}' object has no attribute '{name}'\")\n\n def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):\n \"\"\"\n Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the\n [`~ConfigMixin.from_config`] class method.\n\n Args:\n save_directory (`str` or `os.PathLike`):\n Directory where the configuration JSON file is saved (will be created if it does not exist).\n push_to_hub (`bool`, *optional*, defaults to `False`):\n Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the\n repository you want to push to with `repo_id` (will default to the name of `save_directory` in your\n namespace).\n kwargs (`Dict[str, Any]`, *optional*):\n Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.\n \"\"\"\n if os.path.isfile(save_directory):\n raise AssertionError(f\"Provided path ({save_directory}) should be a directory, not a file\")\n\n os.makedirs(save_directory, exist_ok=True)\n\n # If we save using the predefined names, we can load using `from_config`\n output_config_file = os.path.join(save_directory, self.config_name)\n\n self.to_json_file(output_config_file)\n logger.info(f\"Configuration saved in {output_config_file}\")\n\n if push_to_hub:\n commit_message = kwargs.pop(\"commit_message\", None)\n private = kwargs.pop(\"private\", False)\n create_pr = kwargs.pop(\"create_pr\", False)\n token = kwargs.pop(\"token\", None)\n repo_id = kwargs.pop(\"repo_id\", save_directory.split(os.path.sep)[-1])\n repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id\n\n self._upload_folder(\n save_directory,\n repo_id,\n token=token,\n commit_message=commit_message,\n create_pr=create_pr,\n )\n\n @classmethod\n def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):\n r\"\"\"\n Instantiate a Python class from a config dictionary.\n\n Parameters:\n config (`Dict[str, Any]`):\n A config dictionary from which the Python class is instantiated. Make sure to only load configuration\n files of compatible classes.\n return_unused_kwargs (`bool`, *optional*, defaults to `False`):\n Whether kwargs that are not consumed by the Python class should be returned or not.\n kwargs (remaining dictionary of keyword arguments, *optional*):\n Can be used to update the configuration object (after it is loaded) and initiate the Python class.\n `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually\n overwrite the same named arguments in `config`.\n\n Returns:\n [`ModelMixin`] or [`SchedulerMixin`]:\n A model or scheduler object instantiated from a config dictionary.\n\n Examples:\n\n ```python\n >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler\n\n >>> # Download scheduler from huggingface.co and cache.\n >>> scheduler = DDPMScheduler.from_pretrained(\"google/ddpm-cifar10-32\")\n\n >>> # Instantiate DDIM scheduler class with same config as DDPM\n >>> scheduler = DDIMScheduler.from_config(scheduler.config)\n\n >>> # Instantiate PNDM scheduler class with same config as DDPM\n >>> scheduler = PNDMScheduler.from_config(scheduler.config)\n ```\n \"\"\"\n # <===== TO BE REMOVED WITH DEPRECATION\n # TODO(Patrick) - make sure to remove the following lines when config==\"model_path\" is deprecated\n if \"pretrained_model_name_or_path\" in kwargs:\n config = kwargs.pop(\"pretrained_model_name_or_path\")\n\n if config is None:\n raise ValueError(\"Please make sure to provide a config as the first positional argument.\")\n # ======>\n\n if not isinstance(config, dict):\n deprecation_message = \"It is deprecated to pass a pretrained model name or path to `from_config`.\"\n if \"Scheduler\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead.\"\n \" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will\"\n \" be removed in v1.0.0.\"\n )\n elif \"Model\" in cls.__name__:\n deprecation_message += (\n f\"If you were trying to load a model, please use {cls}.load_config(...) followed by\"\n f\" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary\"\n \" instead. This functionality will be removed in v1.0.0.\"\n )\n deprecate(\"config-passed-as-path\", \"1.0.0\", deprecation_message, standard_warn=False)\n config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)\n\n init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)\n\n # Allow dtype to be specified on initialization\n if \"dtype\" in unused_kwargs:\n init_dict[\"dtype\"] = unused_kwargs.pop(\"dtype\")\n\n # add possible deprecated kwargs\n for deprecated_kwarg in cls._deprecated_kwargs:\n if deprecated_kwarg in unused_kwargs:\n init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)\n\n # Return model and optionally state and/or unused_kwargs\n model = cls(**init_dict)\n\n # make sure to also save config parameters that might be used for compatible classes\n model.register_to_config(**hidden_dict)\n\n # add hidden kwargs of compatible classes to unused_kwargs\n unused_kwargs = {**unused_kwargs, **hidden_dict}\n\n if return_unused_kwargs:\n return (model, unused_kwargs)\n else:\n return model\n\n @classmethod\n def get_config_dict(cls, *args, **kwargs):\n deprecation_message = (\n f\" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be\"\n \" removed in version v1.0.0\"\n )\n deprecate(\"get_config_dict\", \"1.0.0\", deprecation_message, standard_warn=False)\n return cls.load_config(*args, **kwargs)\n\n @classmethod\n def load_config(\n cls,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n return_unused_kwargs=False,\n return_commit_hash=False,\n **kwargs,\n ) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n r\"\"\"\n Load a model or scheduler configuration.\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):\n Can be either:\n\n - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on\n the Hub.\n - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with\n [`~ConfigMixin.save_config`].\n\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory where a downloaded pretrained model configuration is cached if the standard cache\n is not used.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to resume downloading the model weights and configuration files. If set to `False`, any\n incompletely downloaded files are deleted.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n output_loading_info(`bool`, *optional*, defaults to `False`):\n Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.\n local_files_only (`bool`, *optional*, defaults to `False`):\n Whether to only load local model weights and configuration files or not. If set to `True`, the model\n won't be downloaded from the Hub.\n use_auth_token (`str` or *bool*, *optional*):\n The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from\n `diffusers-cli login` (stored in `~/.huggingface`) is used.\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier\n allowed by Git.\n subfolder (`str`, *optional*, defaults to `\"\"`):\n The subfolder location of a model file within a larger model repository on the Hub or locally.\n return_unused_kwargs (`bool`, *optional*, defaults to `False):\n Whether unused keyword arguments of the config are returned.\n return_commit_hash (`bool`, *optional*, defaults to `False):\n Whether the `commit_hash` of the loaded configuration are returned.\n\n Returns:\n `dict`:\n A dictionary of all the parameters stored in a JSON configuration file.\n\n \"\"\"\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n force_download = kwargs.pop(\"force_download\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n revision = kwargs.pop(\"revision\", None)\n _ = kwargs.pop(\"mirror\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n user_agent = kwargs.pop(\"user_agent\", {})\n\n user_agent = {**user_agent, \"file_type\": \"config\"}\n user_agent = http_user_agent(user_agent)\n\n pretrained_model_name_or_path = str(pretrained_model_name_or_path)\n\n if cls.config_name is None:\n raise ValueError(\n \"`self.config_name` is not defined. Note that one should not load a config from \"\n \"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`\"\n )\n\n if os.path.isfile(pretrained_model_name_or_path):\n config_file = pretrained_model_name_or_path\n elif os.path.isdir(pretrained_model_name_or_path):\n if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):\n # Load from a PyTorch checkpoint\n config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)\n elif subfolder is not None and os.path.isfile(\n os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n ):\n config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)\n else:\n raise EnvironmentError(\n f\"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}.\"\n )\n else:\n try:\n # Load from URL or cache if already cached\n config_file = hf_hub_download(\n pretrained_model_name_or_path,\n filename=cls.config_name,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n user_agent=user_agent,\n subfolder=subfolder,\n revision=revision,\n )\n except RepositoryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier\"\n \" listed on 'https://huggingface.co/models'\\nIf this is a private repository, make sure to pass a\"\n \" token having permission to this repo with `use_auth_token` or log in with `huggingface-cli\"\n \" login`.\"\n )\n except RevisionNotFoundError:\n raise EnvironmentError(\n f\"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for\"\n \" this model name. Check the model page at\"\n f\" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.\"\n )\n except EntryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}.\"\n )\n except HTTPError as err:\n raise EnvironmentError(\n \"There was a specific connection error when trying to load\"\n f\" {pretrained_model_name_or_path}:\\n{err}\"\n )\n except ValueError:\n raise EnvironmentError(\n f\"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it\"\n f\" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a\"\n f\" directory containing a {cls.config_name} file.\\nCheckout your internet connection or see how to\"\n \" run the library in offline mode at\"\n \" 'https://huggingface.co/docs/diffusers/installation#offline-mode'.\"\n )\n except EnvironmentError:\n raise EnvironmentError(\n f\"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from \"\n \"'https://huggingface.co/models', make sure you don't have a local directory with the same name. \"\n f\"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory \"\n f\"containing a {cls.config_name} file\"\n )\n\n try:\n # Load config dict\n config_dict = cls._dict_from_json_file(config_file)\n\n commit_hash = extract_commit_hash(config_file)\n except (json.JSONDecodeError, UnicodeDecodeError):\n raise EnvironmentError(f\"It looks like the config file at '{config_file}' is not a valid JSON file.\")\n\n if not (return_unused_kwargs or return_commit_hash):\n return config_dict\n\n outputs = (config_dict,)\n\n if return_unused_kwargs:\n outputs += (kwargs,)\n\n if return_commit_hash:\n outputs += (commit_hash,)\n\n return outputs\n\n @staticmethod\n def _get_init_keys(cls):\n return set(dict(inspect.signature(cls.__init__).parameters).keys())\n\n @classmethod\n def extract_init_dict(cls, config_dict, **kwargs):\n # Skip keys that were not present in the original config, so default __init__ values were used\n used_defaults = config_dict.get(\"_use_default_values\", [])\n config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != \"_use_default_values\"}\n\n # 0. Copy origin config dict\n original_dict = dict(config_dict.items())\n\n # 1. Retrieve expected config attributes from __init__ signature\n expected_keys = cls._get_init_keys(cls)\n expected_keys.remove(\"self\")\n # remove general kwargs if present in dict\n if \"kwargs\" in expected_keys:\n expected_keys.remove(\"kwargs\")\n # remove flax internal keys\n if hasattr(cls, \"_flax_internal_args\"):\n for arg in cls._flax_internal_args:\n expected_keys.remove(arg)\n\n # 2. Remove attributes that cannot be expected from expected config attributes\n # remove keys to be ignored\n if len(cls.ignore_for_config) > 0:\n expected_keys = expected_keys - set(cls.ignore_for_config)\n\n # load diffusers library to import compatible and original scheduler\n diffusers_library = importlib.import_module(__name__.split(\".\")[0])\n\n if cls.has_compatibles:\n compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]\n else:\n compatible_classes = []\n\n expected_keys_comp_cls = set()\n for c in compatible_classes:\n expected_keys_c = cls._get_init_keys(c)\n expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)\n expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)\n config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}\n\n # remove attributes from orig class that cannot be expected\n orig_cls_name = config_dict.pop(\"_class_name\", cls.__name__)\n if (\n isinstance(orig_cls_name, str)\n and orig_cls_name != cls.__name__\n and hasattr(diffusers_library, orig_cls_name)\n ):\n orig_cls = getattr(diffusers_library, orig_cls_name)\n unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys\n config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}\n elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):\n raise ValueError(\n \"Make sure that the `_class_name` is of type string or list of string (for custom pipelines).\"\n )\n\n # remove private attributes\n config_dict = {k: v for k, v in config_dict.items() if not k.startswith(\"_\")}\n\n # 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments\n init_dict = {}\n for key in expected_keys:\n # if config param is passed to kwarg and is present in config dict\n # it should overwrite existing config dict key\n if key in kwargs and key in config_dict:\n config_dict[key] = kwargs.pop(key)\n\n if key in kwargs:\n # overwrite key\n init_dict[key] = kwargs.pop(key)\n elif key in config_dict:\n # use value from config dict\n init_dict[key] = config_dict.pop(key)\n\n # 4. Give nice warning if unexpected values have been passed\n if len(config_dict) > 0:\n logger.warning(\n f\"The config attributes {config_dict} were passed to {cls.__name__}, \"\n \"but are not expected and will be ignored. Please verify your \"\n f\"{cls.config_name} configuration file.\"\n )\n\n # 5. Give nice info if config attributes are initiliazed to default because they have not been passed\n passed_keys = set(init_dict.keys())\n if len(expected_keys - passed_keys) > 0:\n logger.info(\n f\"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values.\"\n )\n\n # 6. Define unused keyword arguments\n unused_kwargs = {**config_dict, **kwargs}\n\n # 7. Define \"hidden\" config parameters that were saved for compatible classes\n hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}\n\n return init_dict, unused_kwargs, hidden_config_dict\n\n @classmethod\n def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):\n with open(json_file, \"r\", encoding=\"utf-8\") as reader:\n text = reader.read()\n return json.loads(text)\n\n def __repr__(self):\n return f\"{self.__class__.__name__} {self.to_json_string()}\"\n\n @property\n def config(self) -> Dict[str, Any]:\n \"\"\"\n Returns the config of the class as a frozen dictionary\n\n Returns:\n `Dict[str, Any]`: Config of the class.\n \"\"\"\n return self._internal_dict\n\n def to_json_string(self) -> str:\n \"\"\"\n Serializes the configuration instance to a JSON string.\n\n Returns:\n `str`:\n String containing all the attributes that make up the configuration instance in JSON format.\n \"\"\"\n config_dict = self._internal_dict if hasattr(self, \"_internal_dict\") else {}\n config_dict[\"_class_name\"] = self.__class__.__name__\n config_dict[\"_diffusers_version\"] = __version__\n\n def to_json_saveable(value):\n if isinstance(value, np.ndarray):\n value = value.tolist()\n elif isinstance(value, PosixPath):\n value = str(value)\n return value\n\n config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}\n # Don't save \"_ignore_files\" or \"_use_default_values\"\n config_dict.pop(\"_ignore_files\", None)\n config_dict.pop(\"_use_default_values\", None)\n\n return json.dumps(config_dict, indent=2, sort_keys=True) + \"\\n\"\n\n def to_json_file(self, json_file_path: Union[str, os.PathLike]):\n \"\"\"\n Save the configuration instance's parameters to a JSON file.\n\n Args:\n json_file_path (`str` or `os.PathLike`):\n Path to the JSON file to save a configuration instance's parameters.\n \"\"\"\n with open(json_file_path, \"w\", encoding=\"utf-8\") as writer:\n writer.write(self.to_json_string())" }, { "identifier": "flax_register_to_config", "path": "src/diffusers/configuration_utils.py", "snippet": "def flax_register_to_config(cls):\n original_init = cls.__init__\n\n @functools.wraps(original_init)\n def init(self, *args, **kwargs):\n if not isinstance(self, ConfigMixin):\n raise RuntimeError(\n f\"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does \"\n \"not inherit from `ConfigMixin`.\"\n )\n\n # Ignore private kwargs in the init. Retrieve all passed attributes\n init_kwargs = dict(kwargs.items())\n\n # Retrieve default values\n fields = dataclasses.fields(self)\n default_kwargs = {}\n for field in fields:\n # ignore flax specific attributes\n if field.name in self._flax_internal_args:\n continue\n if type(field.default) == dataclasses._MISSING_TYPE:\n default_kwargs[field.name] = None\n else:\n default_kwargs[field.name] = getattr(self, field.name)\n\n # Make sure init_kwargs override default kwargs\n new_kwargs = {**default_kwargs, **init_kwargs}\n # dtype should be part of `init_kwargs`, but not `new_kwargs`\n if \"dtype\" in new_kwargs:\n new_kwargs.pop(\"dtype\")\n\n # Get positional arguments aligned with kwargs\n for i, arg in enumerate(args):\n name = fields[i].name\n new_kwargs[name] = arg\n\n # Take note of the parameters that were not present in the loaded config\n if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:\n new_kwargs[\"_use_default_values\"] = list(set(new_kwargs.keys()) - set(init_kwargs))\n\n getattr(self, \"register_to_config\")(**new_kwargs)\n original_init(self, *args, **kwargs)\n\n cls.__init__ = init\n return cls" }, { "identifier": "BaseOutput", "path": "src/diffusers/utils/outputs.py", "snippet": "class BaseOutput(OrderedDict):\n \"\"\"\n Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a\n tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular\n Python dictionary.\n\n <Tip warning={true}>\n\n You can't unpack a [`BaseOutput`] directly. Use the [`~utils.BaseOutput.to_tuple`] method to convert it to a tuple\n first.\n\n </Tip>\n \"\"\"\n\n def __init_subclass__(cls) -> None:\n \"\"\"Register subclasses as pytree nodes.\n\n This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with\n `static_graph=True` with modules that output `ModelOutput` subclasses.\n \"\"\"\n if is_torch_available():\n import torch.utils._pytree\n\n torch.utils._pytree._register_pytree_node(\n cls,\n torch.utils._pytree._dict_flatten,\n lambda values, context: cls(**torch.utils._pytree._dict_unflatten(values, context)),\n )\n\n def __post_init__(self) -> None:\n class_fields = fields(self)\n\n # Safety and consistency checks\n if not len(class_fields):\n raise ValueError(f\"{self.__class__.__name__} has no fields.\")\n\n first_field = getattr(self, class_fields[0].name)\n other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])\n\n if other_fields_are_none and isinstance(first_field, dict):\n for key, value in first_field.items():\n self[key] = value\n else:\n for field in class_fields:\n v = getattr(self, field.name)\n if v is not None:\n self[field.name] = v\n\n def __delitem__(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.\")\n\n def setdefault(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.\")\n\n def pop(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``pop`` on a {self.__class__.__name__} instance.\")\n\n def update(self, *args, **kwargs):\n raise Exception(f\"You cannot use ``update`` on a {self.__class__.__name__} instance.\")\n\n def __getitem__(self, k: Any) -> Any:\n if isinstance(k, str):\n inner_dict = dict(self.items())\n return inner_dict[k]\n else:\n return self.to_tuple()[k]\n\n def __setattr__(self, name: Any, value: Any) -> None:\n if name in self.keys() and value is not None:\n # Don't call self.__setitem__ to avoid recursion errors\n super().__setitem__(name, value)\n super().__setattr__(name, value)\n\n def __setitem__(self, key, value):\n # Will raise a KeyException if needed\n super().__setitem__(key, value)\n # Don't call self.__setattr__ to avoid recursion errors\n super().__setattr__(key, value)\n\n def __reduce__(self):\n if not is_dataclass(self):\n return super().__reduce__()\n callable, _args, *remaining = super().__reduce__()\n args = tuple(getattr(self, field.name) for field in fields(self))\n return callable, args, *remaining\n\n def to_tuple(self) -> Tuple[Any, ...]:\n \"\"\"\n Convert self to a tuple containing all the attributes/keys that are not `None`.\n \"\"\"\n return tuple(self[k] for k in self.keys())" }, { "identifier": "FlaxTimestepEmbedding", "path": "src/diffusers/models/embeddings_flax.py", "snippet": "class FlaxTimestepEmbedding(nn.Module):\n r\"\"\"\n Time step Embedding Module. Learns embeddings for input time steps.\n\n Args:\n time_embed_dim (`int`, *optional*, defaults to `32`):\n Time step embedding dimension\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n\n time_embed_dim: int = 32\n dtype: jnp.dtype = jnp.float32\n\n @nn.compact\n def __call__(self, temb):\n temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name=\"linear_1\")(temb)\n temb = nn.silu(temb)\n temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name=\"linear_2\")(temb)\n return temb" }, { "identifier": "FlaxTimesteps", "path": "src/diffusers/models/embeddings_flax.py", "snippet": "class FlaxTimesteps(nn.Module):\n r\"\"\"\n Wrapper Module for sinusoidal Time step Embeddings as described in https://arxiv.org/abs/2006.11239\n\n Args:\n dim (`int`, *optional*, defaults to `32`):\n Time step embedding dimension\n \"\"\"\n\n dim: int = 32\n flip_sin_to_cos: bool = False\n freq_shift: float = 1\n\n @nn.compact\n def __call__(self, timesteps):\n return get_sinusoidal_embeddings(\n timesteps, embedding_dim=self.dim, flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.freq_shift\n )" }, { "identifier": "FlaxModelMixin", "path": "src/diffusers/models/modeling_flax_utils.py", "snippet": "class FlaxModelMixin(PushToHubMixin):\n r\"\"\"\n Base class for all Flax models.\n\n [`FlaxModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and\n saving models.\n\n - **config_name** ([`str`]) -- Filename to save a model to when calling [`~FlaxModelMixin.save_pretrained`].\n \"\"\"\n\n config_name = CONFIG_NAME\n _automatically_saved_args = [\"_diffusers_version\", \"_class_name\", \"_name_or_path\"]\n _flax_internal_args = [\"name\", \"parent\", \"dtype\"]\n\n @classmethod\n def _from_config(cls, config, **kwargs):\n \"\"\"\n All context managers that the model should be initialized under go here.\n \"\"\"\n return cls(config, **kwargs)\n\n def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:\n \"\"\"\n Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.\n \"\"\"\n\n # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27\n def conditional_cast(param):\n if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):\n param = param.astype(dtype)\n return param\n\n if mask is None:\n return jax.tree_map(conditional_cast, params)\n\n flat_params = flatten_dict(params)\n flat_mask, _ = jax.tree_flatten(mask)\n\n for masked, key in zip(flat_mask, flat_params.keys()):\n if masked:\n param = flat_params[key]\n flat_params[key] = conditional_cast(param)\n\n return unflatten_dict(flat_params)\n\n def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast\n the `params` in place.\n\n This method can be used on a TPU to explicitly convert the model parameters to bfloat16 precision to do full\n half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`\n for params you want to cast, and `False` for those you want to skip.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # load model\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision\n >>> params = model.to_bf16(params)\n >>> # If you don't want to cast certain parameters (for example layer norm bias and scale)\n >>> # then pass the mask as follows\n >>> from flax import traverse_util\n\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> flat_params = traverse_util.flatten_dict(params)\n >>> mask = {\n ... path: (path[-2] != (\"LayerNorm\", \"bias\") and path[-2:] != (\"LayerNorm\", \"scale\"))\n ... for path in flat_params\n ... }\n >>> mask = traverse_util.unflatten_dict(mask)\n >>> params = model.to_bf16(params, mask)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.bfloat16, mask)\n\n def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the\n model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`\n for params you want to cast, and `False` for those you want to skip.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # Download model and configuration from huggingface.co\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model params will be in fp32, to illustrate the use of this method,\n >>> # we'll first cast to fp16 and back to fp32\n >>> params = model.to_f16(params)\n >>> # now cast back to fp32\n >>> params = model.to_fp32(params)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.float32, mask)\n\n def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n r\"\"\"\n Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the\n `params` in place.\n\n This method can be used on a GPU to explicitly convert the model parameters to float16 precision to do full\n half-precision training or to save weights in float16 for inference in order to save memory and improve speed.\n\n Arguments:\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n mask (`Union[Dict, FrozenDict]`):\n A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`\n for params you want to cast, and `False` for those you want to skip.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # load model\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # By default, the model params will be in fp32, to cast these to float16\n >>> params = model.to_fp16(params)\n >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)\n >>> # then pass the mask as follows\n >>> from flax import traverse_util\n\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> flat_params = traverse_util.flatten_dict(params)\n >>> mask = {\n ... path: (path[-2] != (\"LayerNorm\", \"bias\") and path[-2:] != (\"LayerNorm\", \"scale\"))\n ... for path in flat_params\n ... }\n >>> mask = traverse_util.unflatten_dict(mask)\n >>> params = model.to_fp16(params, mask)\n ```\"\"\"\n return self._cast_floating_to(params, jnp.float16, mask)\n\n def init_weights(self, rng: jax.Array) -> Dict:\n raise NotImplementedError(f\"init_weights method has to be implemented for {self}\")\n\n @classmethod\n def from_pretrained(\n cls,\n pretrained_model_name_or_path: Union[str, os.PathLike],\n dtype: jnp.dtype = jnp.float32,\n *model_args,\n **kwargs,\n ):\n r\"\"\"\n Instantiate a pretrained Flax model from a pretrained model configuration.\n\n Parameters:\n pretrained_model_name_or_path (`str` or `os.PathLike`):\n Can be either:\n\n - A string, the *model id* (for example `runwayml/stable-diffusion-v1-5`) of a pretrained model\n hosted on the Hub.\n - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved\n using [`~FlaxModelMixin.save_pretrained`].\n dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):\n The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and\n `jax.numpy.bfloat16` (on TPUs).\n\n This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If\n specified, all the computation will be performed with the given `dtype`.\n\n <Tip>\n\n This only specifies the dtype of the *computation* and does not influence the dtype of model\n parameters.\n\n If you wish to change the dtype of the model parameters, see [`~FlaxModelMixin.to_fp16`] and\n [`~FlaxModelMixin.to_bf16`].\n\n </Tip>\n\n model_args (sequence of positional arguments, *optional*):\n All remaining positional arguments are passed to the underlying model's `__init__` method.\n cache_dir (`Union[str, os.PathLike]`, *optional*):\n Path to a directory where a downloaded pretrained model configuration is cached if the standard cache\n is not used.\n force_download (`bool`, *optional*, defaults to `False`):\n Whether or not to force the (re-)download of the model weights and configuration files, overriding the\n cached versions if they exist.\n resume_download (`bool`, *optional*, defaults to `False`):\n Whether or not to resume downloading the model weights and configuration files. If set to `False`, any\n incompletely downloaded files are deleted.\n proxies (`Dict[str, str]`, *optional*):\n A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n local_files_only(`bool`, *optional*, defaults to `False`):\n Whether to only load local model weights and configuration files or not. If set to `True`, the model\n won't be downloaded from the Hub.\n revision (`str`, *optional*, defaults to `\"main\"`):\n The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier\n allowed by Git.\n from_pt (`bool`, *optional*, defaults to `False`):\n Load the model weights from a PyTorch checkpoint save file.\n kwargs (remaining dictionary of keyword arguments, *optional*):\n Can be used to update the configuration object (after it is loaded) and initiate the model (for\n example, `output_attentions=True`). Behaves differently depending on whether a `config` is provided or\n automatically loaded:\n\n - If a configuration is provided with `config`, `kwargs` are directly passed to the underlying\n model's `__init__` method (we assume all relevant updates to the configuration have already been\n done).\n - If a configuration is not provided, `kwargs` are first passed to the configuration class\n initialization function [`~ConfigMixin.from_config`]. Each key of the `kwargs` that corresponds\n to a configuration attribute is used to override said attribute with the supplied `kwargs` value.\n Remaining keys that do not correspond to any configuration attribute are passed to the underlying\n model's `__init__` function.\n\n Examples:\n\n ```python\n >>> from diffusers import FlaxUNet2DConditionModel\n\n >>> # Download model and configuration from huggingface.co and cache.\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"runwayml/stable-diffusion-v1-5\")\n >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).\n >>> model, params = FlaxUNet2DConditionModel.from_pretrained(\"./test/saved_model/\")\n ```\n\n If you get the error message below, you need to finetune the weights for your downstream task:\n\n ```bash\n Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:\n - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated\n You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n ```\n \"\"\"\n config = kwargs.pop(\"config\", None)\n cache_dir = kwargs.pop(\"cache_dir\", DIFFUSERS_CACHE)\n force_download = kwargs.pop(\"force_download\", False)\n from_pt = kwargs.pop(\"from_pt\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n use_auth_token = kwargs.pop(\"use_auth_token\", None)\n revision = kwargs.pop(\"revision\", None)\n subfolder = kwargs.pop(\"subfolder\", None)\n\n user_agent = {\n \"diffusers\": __version__,\n \"file_type\": \"model\",\n \"framework\": \"flax\",\n }\n\n # Load config if we don't provide one\n if config is None:\n config, unused_kwargs = cls.load_config(\n pretrained_model_name_or_path,\n cache_dir=cache_dir,\n return_unused_kwargs=True,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n revision=revision,\n subfolder=subfolder,\n **kwargs,\n )\n\n model, model_kwargs = cls.from_config(config, dtype=dtype, return_unused_kwargs=True, **unused_kwargs)\n\n # Load model\n pretrained_path_with_subfolder = (\n pretrained_model_name_or_path\n if subfolder is None\n else os.path.join(pretrained_model_name_or_path, subfolder)\n )\n if os.path.isdir(pretrained_path_with_subfolder):\n if from_pt:\n if not os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):\n raise EnvironmentError(\n f\"Error no file named {WEIGHTS_NAME} found in directory {pretrained_path_with_subfolder} \"\n )\n model_file = os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)\n elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)):\n # Load from a Flax checkpoint\n model_file = os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)\n # Check if pytorch weights exist instead\n elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):\n raise EnvironmentError(\n f\"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model\"\n \" using `from_pt=True`.\"\n )\n else:\n raise EnvironmentError(\n f\"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory \"\n f\"{pretrained_path_with_subfolder}.\"\n )\n else:\n try:\n model_file = hf_hub_download(\n pretrained_model_name_or_path,\n filename=FLAX_WEIGHTS_NAME if not from_pt else WEIGHTS_NAME,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n use_auth_token=use_auth_token,\n user_agent=user_agent,\n subfolder=subfolder,\n revision=revision,\n )\n\n except RepositoryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier \"\n \"listed on 'https://huggingface.co/models'\\nIf this is a private repository, make sure to pass a \"\n \"token having permission to this repo with `use_auth_token` or log in with `huggingface-cli \"\n \"login`.\"\n )\n except RevisionNotFoundError:\n raise EnvironmentError(\n f\"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for \"\n \"this model name. Check the model page at \"\n f\"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions.\"\n )\n except EntryNotFoundError:\n raise EnvironmentError(\n f\"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}.\"\n )\n except HTTPError as err:\n raise EnvironmentError(\n f\"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\\n\"\n f\"{err}\"\n )\n except ValueError:\n raise EnvironmentError(\n f\"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it\"\n f\" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a\"\n f\" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\\nCheckout your\"\n \" internet connection or see how to run the library in offline mode at\"\n \" 'https://huggingface.co/docs/transformers/installation#offline-mode'.\"\n )\n except EnvironmentError:\n raise EnvironmentError(\n f\"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from \"\n \"'https://huggingface.co/models', make sure you don't have a local directory with the same name. \"\n f\"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory \"\n f\"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\"\n )\n\n if from_pt:\n if is_torch_available():\n from .modeling_utils import load_state_dict\n else:\n raise EnvironmentError(\n \"Can't load the model in PyTorch format because PyTorch is not installed. \"\n \"Please, install PyTorch or use native Flax weights.\"\n )\n\n # Step 1: Get the pytorch file\n pytorch_model_file = load_state_dict(model_file)\n\n # Step 2: Convert the weights\n state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)\n else:\n try:\n with open(model_file, \"rb\") as state_f:\n state = from_bytes(cls, state_f.read())\n except (UnpicklingError, msgpack.exceptions.ExtraData) as e:\n try:\n with open(model_file) as f:\n if f.read().startswith(\"version\"):\n raise OSError(\n \"You seem to have cloned a repository without having git-lfs installed. Please\"\n \" install git-lfs and run `git lfs install` followed by `git lfs pull` in the\"\n \" folder you cloned.\"\n )\n else:\n raise ValueError from e\n except (UnicodeDecodeError, ValueError):\n raise EnvironmentError(f\"Unable to convert {model_file} to Flax deserializable object. \")\n # make sure all arrays are stored as jnp.ndarray\n # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:\n # https://github.com/google/flax/issues/1261\n state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.local_devices(backend=\"cpu\")[0]), state)\n\n # flatten dicts\n state = flatten_dict(state)\n\n params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))\n required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())\n\n shape_state = flatten_dict(unfreeze(params_shape_tree))\n\n missing_keys = required_params - set(state.keys())\n unexpected_keys = set(state.keys()) - required_params\n\n if missing_keys:\n logger.warning(\n f\"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. \"\n \"Make sure to call model.init_weights to initialize the missing weights.\"\n )\n cls._missing_keys = missing_keys\n\n for key in state.keys():\n if key in shape_state and state[key].shape != shape_state[key].shape:\n raise ValueError(\n f\"Trying to load the pretrained weight for {key} failed: checkpoint has shape \"\n f\"{state[key].shape} which is incompatible with the model shape {shape_state[key].shape}. \"\n )\n\n # remove unexpected keys to not be saved again\n for unexpected_key in unexpected_keys:\n del state[unexpected_key]\n\n if len(unexpected_keys) > 0:\n logger.warning(\n f\"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when\"\n f\" initializing {model.__class__.__name__}: {unexpected_keys}\\n- This IS expected if you are\"\n f\" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or\"\n \" with another architecture.\"\n )\n else:\n logger.info(f\"All model checkpoint weights were used when initializing {model.__class__.__name__}.\\n\")\n\n if len(missing_keys) > 0:\n logger.warning(\n f\"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\\nYou should probably\"\n \" TRAIN this model on a down-stream task to be able to use it for predictions and inference.\"\n )\n else:\n logger.info(\n f\"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at\"\n f\" {pretrained_model_name_or_path}.\\nIf your task is similar to the task the model of the checkpoint\"\n f\" was trained on, you can already use {model.__class__.__name__} for predictions without further\"\n \" training.\"\n )\n\n return model, unflatten_dict(state)\n\n def save_pretrained(\n self,\n save_directory: Union[str, os.PathLike],\n params: Union[Dict, FrozenDict],\n is_main_process: bool = True,\n push_to_hub: bool = False,\n **kwargs,\n ):\n \"\"\"\n Save a model and its configuration file to a directory so that it can be reloaded using the\n [`~FlaxModelMixin.from_pretrained`] class method.\n\n Arguments:\n save_directory (`str` or `os.PathLike`):\n Directory to save a model and its configuration file to. Will be created if it doesn't exist.\n params (`Union[Dict, FrozenDict]`):\n A `PyTree` of model parameters.\n is_main_process (`bool`, *optional*, defaults to `True`):\n Whether the process calling this is the main process or not. Useful during distributed training and you\n need to call this function on all processes. In this case, set `is_main_process=True` only on the main\n process to avoid race conditions.\n push_to_hub (`bool`, *optional*, defaults to `False`):\n Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the\n repository you want to push to with `repo_id` (will default to the name of `save_directory` in your\n namespace).\n kwargs (`Dict[str, Any]`, *optional*):\n Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.\n \"\"\"\n if os.path.isfile(save_directory):\n logger.error(f\"Provided path ({save_directory}) should be a directory, not a file\")\n return\n\n os.makedirs(save_directory, exist_ok=True)\n\n if push_to_hub:\n commit_message = kwargs.pop(\"commit_message\", None)\n private = kwargs.pop(\"private\", False)\n create_pr = kwargs.pop(\"create_pr\", False)\n token = kwargs.pop(\"token\", None)\n repo_id = kwargs.pop(\"repo_id\", save_directory.split(os.path.sep)[-1])\n repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id\n\n model_to_save = self\n\n # Attach architecture to the config\n # Save the config\n if is_main_process:\n model_to_save.save_config(save_directory)\n\n # save model\n output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)\n with open(output_model_file, \"wb\") as f:\n model_bytes = to_bytes(params)\n f.write(model_bytes)\n\n logger.info(f\"Model weights saved in {output_model_file}\")\n\n if push_to_hub:\n self._upload_folder(\n save_directory,\n repo_id,\n token=token,\n commit_message=commit_message,\n create_pr=create_pr,\n )" }, { "identifier": "FlaxCrossAttnDownBlock2D", "path": "src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxCrossAttnDownBlock2D(nn.Module):\n r\"\"\"\n Cross Attention 2D Downsizing block - original architecture from Unet transformers:\n https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n num_attention_heads (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):\n enable memory efficient attention https://arxiv.org/abs/2112.05682\n split_head_dim (`bool`, *optional*, defaults to `False`):\n Whether to split the head dimension into a new axis for the self-attention computation. In most cases,\n enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n\n in_channels: int\n out_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n num_attention_heads: int = 1\n add_downsample: bool = True\n use_linear_projection: bool = False\n only_cross_attention: bool = False\n use_memory_efficient_attention: bool = False\n split_head_dim: bool = False\n dtype: jnp.dtype = jnp.float32\n transformer_layers_per_block: int = 1\n\n def setup(self):\n resnets = []\n attentions = []\n\n for i in range(self.num_layers):\n in_channels = self.in_channels if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=in_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n attn_block = FlaxTransformer2DModel(\n in_channels=self.out_channels,\n n_heads=self.num_attention_heads,\n d_head=self.out_channels // self.num_attention_heads,\n depth=self.transformer_layers_per_block,\n use_linear_projection=self.use_linear_projection,\n only_cross_attention=self.only_cross_attention,\n use_memory_efficient_attention=self.use_memory_efficient_attention,\n split_head_dim=self.split_head_dim,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n if self.add_downsample:\n self.downsamplers_0 = FlaxDownsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, temb, encoder_hidden_states, deterministic=True):\n output_states = ()\n\n for resnet, attn in zip(self.resnets, self.attentions):\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n output_states += (hidden_states,)\n\n if self.add_downsample:\n hidden_states = self.downsamplers_0(hidden_states)\n output_states += (hidden_states,)\n\n return hidden_states, output_states" }, { "identifier": "FlaxCrossAttnUpBlock2D", "path": "src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxCrossAttnUpBlock2D(nn.Module):\n r\"\"\"\n Cross Attention 2D Upsampling block - original architecture from Unet transformers:\n https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n num_attention_heads (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n add_upsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add upsampling layer before each final output\n use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):\n enable memory efficient attention https://arxiv.org/abs/2112.05682\n split_head_dim (`bool`, *optional*, defaults to `False`):\n Whether to split the head dimension into a new axis for the self-attention computation. In most cases,\n enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n\n in_channels: int\n out_channels: int\n prev_output_channel: int\n dropout: float = 0.0\n num_layers: int = 1\n num_attention_heads: int = 1\n add_upsample: bool = True\n use_linear_projection: bool = False\n only_cross_attention: bool = False\n use_memory_efficient_attention: bool = False\n split_head_dim: bool = False\n dtype: jnp.dtype = jnp.float32\n transformer_layers_per_block: int = 1\n\n def setup(self):\n resnets = []\n attentions = []\n\n for i in range(self.num_layers):\n res_skip_channels = self.in_channels if (i == self.num_layers - 1) else self.out_channels\n resnet_in_channels = self.prev_output_channel if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=resnet_in_channels + res_skip_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n attn_block = FlaxTransformer2DModel(\n in_channels=self.out_channels,\n n_heads=self.num_attention_heads,\n d_head=self.out_channels // self.num_attention_heads,\n depth=self.transformer_layers_per_block,\n use_linear_projection=self.use_linear_projection,\n only_cross_attention=self.only_cross_attention,\n use_memory_efficient_attention=self.use_memory_efficient_attention,\n split_head_dim=self.split_head_dim,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n if self.add_upsample:\n self.upsamplers_0 = FlaxUpsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, res_hidden_states_tuple, temb, encoder_hidden_states, deterministic=True):\n for resnet, attn in zip(self.resnets, self.attentions):\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = jnp.concatenate((hidden_states, res_hidden_states), axis=-1)\n\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n\n if self.add_upsample:\n hidden_states = self.upsamplers_0(hidden_states)\n\n return hidden_states" }, { "identifier": "FlaxDownBlock2D", "path": "src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxDownBlock2D(nn.Module):\n r\"\"\"\n Flax 2D downsizing block\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n\n in_channels: int\n out_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n add_downsample: bool = True\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n resnets = []\n\n for i in range(self.num_layers):\n in_channels = self.in_channels if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=in_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n self.resnets = resnets\n\n if self.add_downsample:\n self.downsamplers_0 = FlaxDownsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, temb, deterministic=True):\n output_states = ()\n\n for resnet in self.resnets:\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n output_states += (hidden_states,)\n\n if self.add_downsample:\n hidden_states = self.downsamplers_0(hidden_states)\n output_states += (hidden_states,)\n\n return hidden_states, output_states" }, { "identifier": "FlaxUNetMidBlock2DCrossAttn", "path": "src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxUNetMidBlock2DCrossAttn(nn.Module):\n r\"\"\"\n Cross Attention 2D Mid-level block - original architecture from Unet transformers: https://arxiv.org/abs/2103.06104\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n num_attention_heads (:obj:`int`, *optional*, defaults to 1):\n Number of attention heads of each spatial transformer block\n use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):\n enable memory efficient attention https://arxiv.org/abs/2112.05682\n split_head_dim (`bool`, *optional*, defaults to `False`):\n Whether to split the head dimension into a new axis for the self-attention computation. In most cases,\n enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n\n in_channels: int\n dropout: float = 0.0\n num_layers: int = 1\n num_attention_heads: int = 1\n use_linear_projection: bool = False\n use_memory_efficient_attention: bool = False\n split_head_dim: bool = False\n dtype: jnp.dtype = jnp.float32\n transformer_layers_per_block: int = 1\n\n def setup(self):\n # there is always at least one resnet\n resnets = [\n FlaxResnetBlock2D(\n in_channels=self.in_channels,\n out_channels=self.in_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n ]\n\n attentions = []\n\n for _ in range(self.num_layers):\n attn_block = FlaxTransformer2DModel(\n in_channels=self.in_channels,\n n_heads=self.num_attention_heads,\n d_head=self.in_channels // self.num_attention_heads,\n depth=self.transformer_layers_per_block,\n use_linear_projection=self.use_linear_projection,\n use_memory_efficient_attention=self.use_memory_efficient_attention,\n split_head_dim=self.split_head_dim,\n dtype=self.dtype,\n )\n attentions.append(attn_block)\n\n res_block = FlaxResnetBlock2D(\n in_channels=self.in_channels,\n out_channels=self.in_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n self.resnets = resnets\n self.attentions = attentions\n\n def __call__(self, hidden_states, temb, encoder_hidden_states, deterministic=True):\n hidden_states = self.resnets[0](hidden_states, temb)\n for attn, resnet in zip(self.attentions, self.resnets[1:]):\n hidden_states = attn(hidden_states, encoder_hidden_states, deterministic=deterministic)\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n\n return hidden_states" }, { "identifier": "FlaxUpBlock2D", "path": "src/diffusers/models/unet_2d_blocks_flax.py", "snippet": "class FlaxUpBlock2D(nn.Module):\n r\"\"\"\n Flax 2D upsampling block\n\n Parameters:\n in_channels (:obj:`int`):\n Input channels\n out_channels (:obj:`int`):\n Output channels\n prev_output_channel (:obj:`int`):\n Output channels from the previous block\n dropout (:obj:`float`, *optional*, defaults to 0.0):\n Dropout rate\n num_layers (:obj:`int`, *optional*, defaults to 1):\n Number of attention blocks layers\n add_downsample (:obj:`bool`, *optional*, defaults to `True`):\n Whether to add downsampling layer before each final output\n dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):\n Parameters `dtype`\n \"\"\"\n\n in_channels: int\n out_channels: int\n prev_output_channel: int\n dropout: float = 0.0\n num_layers: int = 1\n add_upsample: bool = True\n dtype: jnp.dtype = jnp.float32\n\n def setup(self):\n resnets = []\n\n for i in range(self.num_layers):\n res_skip_channels = self.in_channels if (i == self.num_layers - 1) else self.out_channels\n resnet_in_channels = self.prev_output_channel if i == 0 else self.out_channels\n\n res_block = FlaxResnetBlock2D(\n in_channels=resnet_in_channels + res_skip_channels,\n out_channels=self.out_channels,\n dropout_prob=self.dropout,\n dtype=self.dtype,\n )\n resnets.append(res_block)\n\n self.resnets = resnets\n\n if self.add_upsample:\n self.upsamplers_0 = FlaxUpsample2D(self.out_channels, dtype=self.dtype)\n\n def __call__(self, hidden_states, res_hidden_states_tuple, temb, deterministic=True):\n for resnet in self.resnets:\n # pop res hidden states\n res_hidden_states = res_hidden_states_tuple[-1]\n res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n hidden_states = jnp.concatenate((hidden_states, res_hidden_states), axis=-1)\n\n hidden_states = resnet(hidden_states, temb, deterministic=deterministic)\n\n if self.add_upsample:\n hidden_states = self.upsamplers_0(hidden_states)\n\n return hidden_states" } ]
from typing import Dict, Optional, Tuple, Union from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_2d_blocks_flax import ( FlaxCrossAttnDownBlock2D, FlaxCrossAttnUpBlock2D, FlaxDownBlock2D, FlaxUNetMidBlock2DCrossAttn, FlaxUpBlock2D, ) import flax import flax.linen as nn import jax import jax.numpy as jnp
17,715
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @flax.struct.dataclass class FlaxUNet2DConditionOutput(BaseOutput): """ The output of [`FlaxUNet2DConditionModel`]. Args: sample (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)`): The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: jnp.ndarray
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @flax.struct.dataclass class FlaxUNet2DConditionOutput(BaseOutput): """ The output of [`FlaxUNet2DConditionModel`]. Args: sample (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)`): The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: jnp.ndarray
@flax_register_to_config
1
2023-11-18 01:40:55+00:00
24k
wjun0830/CGDETR
cg_detr/train.py
[ { "identifier": "BaseOptions", "path": "cg_detr/config.py", "snippet": "class BaseOptions(object):\n saved_option_filename = \"opt.json\"\n ckpt_filename = \"model.ckpt\"\n tensorboard_log_dir = \"tensorboard_log\"\n train_log_filename = \"train.log.txt\"\n eval_log_filename = \"eval.log.txt\"\n\n def __init__(self):\n self.parser = None\n self.initialized = False\n self.opt = None\n\n def initialize(self):\n self.initialized = True\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dset_name\", type=str, choices=[\"hl\", 'tvsum', 'charadesSTA', 'tacos', 'nlq','youtube_uni'])\n parser.add_argument(\"--dset_domain\", type=str, \n help=\"Domain to train for tvsum dataset. (Only used for tvsum and youtube-hl)\")\n \n parser.add_argument(\"--eval_split_name\", type=str, default=\"val\",\n help=\"should match keys in video_duration_idx_path, must set for VCMR\")\n parser.add_argument(\"--debug\", action=\"store_true\",\n help=\"debug (fast) mode, break all loops, do not load all data into memory.\")\n parser.add_argument(\"--data_ratio\", type=float, default=1.0,\n help=\"how many training and eval data to use. 1.0: use all, 0.1: use 10%.\"\n \"Use small portion for debug purposes. Note this is different from --debug, \"\n \"which works by breaking the loops, typically they are not used together.\")\n parser.add_argument(\"--results_root\", type=str, default=\"results\")\n parser.add_argument(\"--exp_id\", type=str, default=None, help=\"id of this run, required at training\")\n parser.add_argument(\"--seed\", type=int, default=2018, help=\"random seed\")\n parser.add_argument(\"--device\", type=int, default=0, help=\"0 cuda, -1 cpu\")\n parser.add_argument(\"--num_workers\", type=int, default=0,\n help=\"num subprocesses used to load the data, 0: use main process\")\n parser.add_argument(\"--no_pin_memory\", action=\"store_true\",\n help=\"Don't use pin_memory=True for dataloader. \"\n \"ref: https://discuss.pytorch.org/t/should-we-set-non-blocking-to-true/38234/4\")\n\n # training config\n parser.add_argument(\"--lr\", type=float, default=1e-4, help=\"learning rate\")\n parser.add_argument(\"--lr_drop\", type=int, default=400, help=\"drop learning rate to 1/10 every lr_drop epochs\")\n parser.add_argument(\"--wd\", type=float, default=1e-4, help=\"weight decay\")\n parser.add_argument(\"--n_epoch\", type=int, default=200, help=\"number of epochs to run\")\n parser.add_argument(\"--max_es_cnt\", type=int, default=200,\n help=\"number of epochs to early stop, use -1 to disable early stop\")\n parser.add_argument(\"--bsz\", type=int, default=32, help=\"mini-batch size\")\n parser.add_argument(\"--eval_bsz\", type=int, default=100,\n help=\"mini-batch size at inference, for query\")\n parser.add_argument(\"--eval_epoch\", type=int, default=5,\n help=\"inference epoch\")\n parser.add_argument(\"--grad_clip\", type=float, default=0.1, help=\"perform gradient clip, -1: disable\")\n parser.add_argument(\"--eval_untrained\", action=\"store_true\", help=\"Evaluate on un-trained model\")\n parser.add_argument(\"--resume\", type=str, default=None,\n help=\"checkpoint path to resume or evaluate, without --resume_all this only load weights\")\n parser.add_argument(\"--resume_all\", action=\"store_true\",\n help=\"if --resume_all, load optimizer/scheduler/epoch as well\")\n parser.add_argument(\"--start_epoch\", type=int, default=None,\n help=\"if None, will be set automatically when using --resume_all\")\n\n # Data config\n parser.add_argument(\"--max_q_l\", type=int, default=-1)\n parser.add_argument(\"--max_v_l\", type=int, default=-1)\n parser.add_argument(\"--clip_length\", type=float, default=2)\n parser.add_argument(\"--max_windows\", type=int, default=5)\n\n parser.add_argument(\"--train_path\", type=str, default=None)\n parser.add_argument(\"--eval_path\", type=str, default=None,\n help=\"Evaluating during training, for Dev set. If None, will only do training, \")\n parser.add_argument(\"--no_norm_vfeat\", action=\"store_true\", help=\"Do not do normalize video feat\")\n parser.add_argument(\"--no_norm_tfeat\", action=\"store_true\", help=\"Do not do normalize text feat\")\n parser.add_argument(\"--v_feat_dirs\", type=str, nargs=\"+\",\n help=\"video feature dirs. If more than one, will concat their features. \"\n \"Note that sub ctx features are also accepted here.\")\n parser.add_argument(\"--t_feat_dir\", type=str, help=\"text/query feature dir\")\n parser.add_argument(\"--a_feat_dir\", type=str, help=\"audio feature dir\")\n parser.add_argument(\"--v_feat_dim\", type=int, help=\"video feature dim\")\n parser.add_argument(\"--t_feat_dim\", type=int, help=\"text/query feature dim\")\n parser.add_argument(\"--a_feat_dim\", type=int, help=\"audio feature dim\")\n parser.add_argument(\"--ctx_mode\", type=str, default=\"video_tef\")\n\n # Model config\n parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'),\n help=\"Type of positional embedding to use on top of the image features\")\n # * Transformer\n parser.add_argument('--enc_layers', default=3, type=int,\n help=\"Number of encoding layers in the transformer\")\n parser.add_argument('--dec_layers', default=3, type=int,\n help=\"Number of decoding layers in the transformer\")\n parser.add_argument('--t2v_layers', default=2, type=int,\n help=\"Number of decoding layers in the transformer\")\n parser.add_argument('--sent_layers', default=1, type=int,\n help=\"Number of decoding layers in the transformer\")\n parser.add_argument('--moment_layers', default=1, type=int,\n help=\"Number of decoding layers in the transformer\")\n parser.add_argument('--dummy_layers', default=2, type=int,\n help=\"Number of encoding layers in the transformer\")\n parser.add_argument('--dim_feedforward', default=1024, type=int,\n help=\"Intermediate size of the feedforward layers in the transformer blocks\")\n parser.add_argument('--hidden_dim', default=256, type=int,\n help=\"Size of the embeddings (dimension of the transformer)\")\n parser.add_argument('--input_dropout', default=0.5, type=float,\n help=\"Dropout applied in input\")\n parser.add_argument('--dropout', default=0.1, type=float,\n help=\"Dropout applied in the transformer\")\n parser.add_argument(\"--txt_drop_ratio\", default=0, type=float,\n help=\"drop txt_drop_ratio tokens from text input. 0.1=10%\")\n parser.add_argument(\"--use_txt_pos\", action=\"store_true\", help=\"use position_embedding for text as well.\")\n parser.add_argument('--nheads', default=8, type=int,\n help=\"Number of attention heads inside the transformer's attentions\")\n parser.add_argument('--num_queries', default=10, type=int,\n help=\"Number of query slots\")\n parser.add_argument('--num_dummies', default=45, type=int,\n help=\"Number of dummy tokens\")\n parser.add_argument('--total_prompts', default=10, type=int,\n help=\"Number of query slots\")\n parser.add_argument('--num_prompts', default=1, type=int,\n help=\"Number of dummy tokens\")\n parser.add_argument('--pre_norm', action='store_true')\n # other model configs\n parser.add_argument(\"--n_input_proj\", type=int, default=2, help=\"#layers to encoder input\")\n parser.add_argument(\"--contrastive_hdim\", type=int, default=64, help=\"dim for contrastive embeddings\")\n parser.add_argument(\"--temperature\", type=float, default=0.07, help=\"temperature nce contrastive_align_loss\")\n # Loss\n\n parser.add_argument(\"--saliency_margin\", type=float, default=0.2)\n parser.add_argument('--no_aux_loss', dest='aux_loss', action='store_false',\n help=\"Disables auxiliary decoding losses (loss at each layer)\")\n parser.add_argument(\"--span_loss_type\", default=\"l1\", type=str, choices=['l1', 'ce'],\n help=\"l1: (center-x, width) regression. ce: (st_idx, ed_idx) classification.\")\n parser.add_argument(\"--contrastive_align_loss\", action=\"store_true\",\n help=\"Disable contrastive_align_loss between matched query spans and the text.\")\n # * Matcher\n parser.add_argument('--set_cost_span', default=10, type=float,\n help=\"L1 span coefficient in the matching cost\")\n parser.add_argument('--set_cost_giou', default=1, type=float,\n help=\"giou span coefficient in the matching cost\")\n parser.add_argument('--set_cost_class', default=4, type=float,\n help=\"Class coefficient in the matching cost\")\n\n # * Loss coefficients\n parser.add_argument(\"--lw_saliency\", type=float, default=1.,\n help=\"weight for saliency loss, set to 0 will ignore\")\n parser.add_argument(\"--lw_wattn\", type=float, default=1.,\n help=\"weight for saliency loss, set to 0 will ignore\")\n parser.add_argument(\"--lw_ms_align\", type=float, default=1.,\n help=\"weight for saliency loss, set to 0 will ignore\")\n parser.add_argument(\"--lw_distill\", type=float, default=1.,\n help=\"weight for saliency loss, set to 0 will ignore\")\n parser.add_argument('--span_loss_coef', default=10, type=float)\n parser.add_argument('--giou_loss_coef', default=1, type=float)\n parser.add_argument('--label_loss_coef', default=4, type=float)\n parser.add_argument('--eos_coef', default=0.1, type=float,\n help=\"Relative classification weight of the no-object class\")\n parser.add_argument(\"--contrastive_align_loss_coef\", default=0.0, type=float)\n\n parser.add_argument(\"--no_sort_results\", action=\"store_true\",\n help=\"do not sort results, use this for moment query visualization\")\n parser.add_argument(\"--max_before_nms\", type=int, default=10)\n parser.add_argument(\"--max_after_nms\", type=int, default=10)\n parser.add_argument(\"--conf_thd\", type=float, default=0.0, help=\"only keep windows with conf >= conf_thd\")\n parser.add_argument(\"--nms_thd\", type=float, default=-1,\n help=\"additionally use non-maximum suppression \"\n \"(or non-minimum suppression for distance)\"\n \"to post-processing the predictions. \"\n \"-1: do not use nms. [0, 1]\")\n self.parser = parser\n\n def display_save(self, opt):\n args = vars(opt)\n # Display settings\n print(dict_to_markdown(vars(opt), max_str_len=120))\n # Save settings\n if not isinstance(self, TestOptions):\n option_file_path = os.path.join(opt.results_dir, self.saved_option_filename) # not yaml file indeed\n save_json(args, option_file_path, save_pretty=True)\n\n def parse(self, a_feat_dir=None):\n if not self.initialized:\n self.initialize()\n opt = self.parser.parse_args()\n\n if opt.debug:\n opt.results_root = os.path.sep.join(opt.results_root.split(os.path.sep)[:-1] + [\"debug_results\", ])\n opt.num_workers = 0\n\n if isinstance(self, TestOptions):\n # modify model_dir to absolute path\n # opt.model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"results\", opt.model_dir)\n opt.model_dir = os.path.dirname(opt.resume)\n if a_feat_dir is not None:\n opt.a_feat_dir = a_feat_dir\n saved_options = load_json(os.path.join(opt.model_dir, self.saved_option_filename))\n for arg in saved_options: # use saved options to overwrite all BaseOptions args.\n if arg not in [\"results_root\", \"num_workers\", \"nms_thd\", \"debug\", # \"max_before_nms\", \"max_after_nms\"\n \"max_pred_l\", \"min_pred_l\",\n \"resume\", \"resume_all\", \"no_sort_results\"]:\n setattr(opt, arg, saved_options[arg])\n # opt.no_core_driver = True\n if opt.eval_results_dir is not None:\n opt.results_dir = opt.eval_results_dir\n else:\n if opt.exp_id is None:\n raise ValueError(\"--exp_id is required for at a training option!\")\n\n ctx_str = opt.ctx_mode + \"_sub\" if any([\"sub_ctx\" in p for p in opt.v_feat_dirs]) else opt.ctx_mode\n opt.results_dir = os.path.join(opt.results_root,\n \"-\".join([opt.dset_name, ctx_str, opt.exp_id,\n str(opt.enc_layers) + str(opt.dec_layers) + str(opt.t2v_layers) + str(opt.moment_layers) + str(opt.dummy_layers) + str(opt.sent_layers),\n 'ndum_' + str(opt.num_dummies), 'nprom_' + str(opt.num_prompts) + '_' + str(opt.total_prompts)]))\n mkdirp(opt.results_dir)\n save_fns = ['cg_detr/model.py', 'cg_detr/transformer.py']\n for save_fn in save_fns:\n shutil.copyfile(save_fn, os.path.join(opt.results_dir, os.path.basename(save_fn)))\n\n # save a copy of current code\n code_dir = os.path.dirname(os.path.realpath(__file__))\n code_zip_filename = os.path.join(opt.results_dir, \"code.zip\")\n make_zipfile(code_dir, code_zip_filename,\n enclosing_dir=\"code\",\n exclude_dirs_substring=\"results\",\n exclude_dirs=[\"results\", \"debug_results\", \"__pycache__\"],\n exclude_extensions=[\".pyc\", \".ipynb\", \".swap\"], )\n\n self.display_save(opt)\n\n opt.ckpt_filepath = os.path.join(opt.results_dir, self.ckpt_filename)\n opt.train_log_filepath = os.path.join(opt.results_dir, self.train_log_filename)\n opt.eval_log_filepath = os.path.join(opt.results_dir, self.eval_log_filename)\n opt.tensorboard_log_dir = os.path.join(opt.results_dir, self.tensorboard_log_dir)\n opt.device = torch.device(\"cuda\" if opt.device >= 0 else \"cpu\")\n opt.pin_memory = not opt.no_pin_memory\n\n opt.use_tef = \"tef\" in opt.ctx_mode\n opt.use_video = \"video\" in opt.ctx_mode\n if not opt.use_video:\n opt.v_feat_dim = 0\n if opt.use_tef:\n opt.v_feat_dim += 2\n\n self.opt = opt\n return opt" }, { "identifier": "StartEndDataset", "path": "cg_detr/start_end_dataset.py", "snippet": "class StartEndDataset(Dataset):\n Q_FEAT_TYPES = [\"pooler_output\", \"last_hidden_state\"]\n \"\"\"One line in data loaded from data_path.\"\n {\n \"qid\": 7803,\n \"query\": \"Man in gray top walks from outside to inside.\",\n \"duration\": 150,\n \"vid\": \"RoripwjYFp8_360.0_510.0\",\n \"relevant_clip_ids\": [13, 14, 15, 16, 17],\n \"relevant_windows\": [[26, 36]]\n }\n \"\"\"\n\n def __init__(self, dset_name, data_path, v_feat_dirs, q_feat_dir,\n q_feat_type=\"last_hidden_state\",\n max_q_l=32, max_v_l=75, data_ratio=1.0, ctx_mode=\"video\",\n normalize_v=True, normalize_t=True, load_labels=True,\n clip_len=2, max_windows=5, span_loss_type=\"l1\", txt_drop_ratio=0,\n dset_domain=None):\n self.dset_name = dset_name\n self.data_path = data_path\n self.data_ratio = data_ratio\n self.v_feat_dirs = v_feat_dirs \\\n if isinstance(v_feat_dirs, list) else [v_feat_dirs]\n self.q_feat_dir = q_feat_dir\n self.q_feat_type = q_feat_type\n if max_v_l == -1:\n max_v_l = 100000000\n if max_q_l == -1:\n max_q_l = 100\n self.max_q_l = max_q_l\n self.max_v_l = max_v_l\n self.ctx_mode = ctx_mode\n self.use_tef = \"tef\" in ctx_mode\n self.use_video = \"video\" in ctx_mode\n self.normalize_t = normalize_t\n self.normalize_v = normalize_v\n self.load_labels = load_labels\n self.clip_len = clip_len\n self.max_windows = max_windows # maximum number of windows to use as labels\n self.span_loss_type = span_loss_type\n self.txt_drop_ratio = txt_drop_ratio\n if \"val\" in data_path or \"test\" in data_path:\n assert txt_drop_ratio == 0\n\n\n # checks\n assert q_feat_type in self.Q_FEAT_TYPES\n\n # data\n self.data = self.load_data()\n \n # load specific domain data for tvsum dataset\n if self.dset_name in ['tvsum', 'tvsum_sfc']:\n target_domain = dset_domain\n assert target_domain in [\"BK\", \"BT\", \"DS\", \"FM\", \"GA\", \"MS\", \"PK\", \"PR\", \"VT\", \"VU\"]\n\n new_data = []\n for d in self.data:\n if target_domain == d['domain']:\n new_data.append(d)\n self.data = new_data\n \n # load specific domain data for youtube-hl dataset\n if self.dset_name == 'youtube_uni':\n target_domain = dset_domain\n assert target_domain in [\"dog\", \"gymnastics\", \"parkour\", \"skating\", \"skiing\", \"surfing\"]\n \n new_data = []\n for d in self.data:\n if target_domain == d['domain']:\n new_data.append(d)\n self.data = new_data \n \n self.use_glove = False\n self.use_glove = 'vgg' in self.v_feat_dirs[0]\n\n if self.dset_name == 'charadesSTA' and self.use_glove:\n self.vocab = vocab.pretrained_aliases['glove.6B.300d']()\n self.vocab.itos.extend(['<unk>'])\n self.vocab.stoi['<unk>'] = self.vocab.vectors.shape[0]\n self.vocab.vectors = torch.cat(\n (self.vocab.vectors, torch.zeros(1, self.vocab.dim)), dim=0)\n self.embedding = nn.Embedding.from_pretrained(self.vocab.vectors)\n \n\n def load_data(self):\n datalist = load_jsonl(self.data_path)\n if self.data_ratio != 1:\n n_examples = int(len(datalist) * self.data_ratio)\n datalist = datalist[:n_examples]\n logger.info(\"Using {}% of the data: {} examples\"\n .format(self.data_ratio * 100, n_examples))\n return datalist\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n meta = self.data[index]\n\n model_inputs = dict()\n\n if self.use_glove:\n model_inputs[\"query_feat\"] = self.get_query(meta[\"query\"])\n else:\n model_inputs[\"query_feat\"] = self._get_query_feat_by_qid(meta[\"qid\"]) # (Dq, ) or (Lq, Dq)\n \n if self.use_video:\n model_inputs[\"video_feat\"] = self._get_video_feat_by_vid(meta[\"vid\"]) # (Lv, Dv)\n ctx_l = len(model_inputs[\"video_feat\"])\n else:\n ctx_l = self.max_v_l\n\n\n if self.use_tef:\n tef_st = torch.arange(0, ctx_l, 1.0) / ctx_l\n tef_ed = tef_st + 1.0 / ctx_l\n tef = torch.stack([tef_st, tef_ed], dim=1) # (Lv, 2)\n if self.use_video:\n model_inputs[\"video_feat\"] = torch.cat(\n [model_inputs[\"video_feat\"], tef], dim=1) # (Lv, Dv+2)\n else:\n model_inputs[\"video_feat\"] = tef\n\n\n if self.dset_name in ['tvsum']:\n model_inputs[\"span_labels\"] = torch.tensor([[0., 0.]])\n meta_label = meta['label']\n model_inputs[\"saliency_pos_labels\"], model_inputs[\"saliency_neg_labels\"], model_inputs[\"saliency_all_labels\"] = \\\n self.get_saliency_labels_all_tvsum(meta_label, ctx_l)\n if len(model_inputs[\"saliency_all_labels\"]) != len(model_inputs[\"video_feat\"]):\n model_inputs[\"video_feat\"] = model_inputs[\"video_feat\"][:len(model_inputs[\"saliency_all_labels\"])]\n\n elif self.dset_name == 'youtube_uni':\n model_inputs[\"span_labels\"] = torch.tensor([[0., 0.]])\n meta_label = meta['label']\n model_inputs[\"saliency_pos_labels\"], model_inputs[\"saliency_neg_labels\"], model_inputs[\"saliency_all_labels\"] = \\\n self.get_saliency_labels_all_youtube(meta_label, ctx_l)\n else:\n if \"relevant_windows\" in meta: ## For Qvhighlights test set\n model_inputs[\"span_labels\"] = self.get_span_labels(meta[\"relevant_windows\"], ctx_l) # (#windows, 2)\n if self.dset_name in ['charadesSTA', 'tacos', 'activitynet']: ## charades, tacos, nlq\n model_inputs[\"saliency_pos_labels\"], model_inputs[\"saliency_neg_labels\"], model_inputs[\"saliency_all_labels\"] = \\\n self.get_saliency_labels_sub_as_query(meta[\"relevant_windows\"][0], meta[\"duration\"], ctx_l) # only one gt\n elif self.dset_name in ['nlq']:\n model_inputs[\"saliency_pos_labels\"], model_inputs[\"saliency_neg_labels\"], model_inputs[\"saliency_all_labels\"] = \\\n self.get_saliency_labels_sub_as_query(meta[\"relevant_windows\"][0], meta[\"duration\"], ctx_l, 2) # only one gt\n elif \"subs_train\" not in self.data_path:\n model_inputs[\"saliency_pos_labels\"], model_inputs[\"saliency_neg_labels\"], model_inputs[\"saliency_all_labels\"] = \\\n self.get_saliency_labels_all(meta[\"relevant_clip_ids\"], meta[\"saliency_scores\"], ctx_l)\n else:\n model_inputs[\"saliency_pos_labels\"], model_inputs[\"saliency_neg_labels\"], model_inputs[\n \"saliency_all_labels\"] = \\\n self.get_saliency_labels_sub_as_query(meta[\"relevant_windows\"][0], meta[\"duration\"], ctx_l) # only one gt\n\n if 'qvhighlight' in self.data_path:\n model_inputs[\"relevant_clip_ids\"] = meta[\"relevant_clip_ids\"]\n model_inputs[\"vid\"] = meta[\"vid\"]\n model_inputs[\"qid\"] = meta[\"qid\"]\n return dict(meta=meta, model_inputs=model_inputs)\n\n def get_query(self, query):\n word_inds = torch.LongTensor(\n [self.vocab.stoi.get(w.lower(), 400000) for w in query.split()])\n return self.embedding(word_inds)\n\n def get_saliency_labels_sub_as_query(self, gt_window, duration, ctx_l, max_n=2):\n clip_len = duration / ctx_l\n gt_st = int(gt_window[0] / clip_len)\n gt_ed = max(0, min(int(gt_window[1] / clip_len), ctx_l) - 1)\n if gt_st > gt_ed:\n gt_st = gt_ed\n\n if gt_st != gt_ed:\n pos_clip_indices = random.sample(range(gt_st, gt_ed + 1), k=max_n)\n else:\n if self.dset_name == 'nlq':\n pos_clip_indices = [gt_st] * 2\n else:\n pos_clip_indices = [gt_st, gt_st]\n\n neg_pool = list(range(0, gt_st)) + list(range(gt_ed+1, ctx_l))\n try:\n neg_clip_indices = random.sample(neg_pool, k=max_n)\n except:\n neg_clip_indices = pos_clip_indices\n\n # For charades_sta\n score_array = np.zeros(ctx_l)\n score_array[gt_st:gt_ed + 1] = 1\n\n return pos_clip_indices, neg_clip_indices, score_array\n \n\n def get_saliency_labels(self, rel_clip_ids, scores, ctx_l, max_n=1, add_easy_negative=True):\n \"\"\"Sum the scores from the three annotations, then take the two clips with the\n maximum scores as positive, and two with the minimum scores as negative.\n Args:\n rel_clip_ids: list(int), list of relevant clip ids\n scores: list([anno1_score, anno2_score, anno3_score]),\n ctx_l: int\n max_n: int, #clips to use as positive and negative, for easy and hard negative, respectively.\n add_easy_negative: bool, if True, sample eay negative outside the relevant_clip_ids.\n \"\"\"\n # indices inside rel_clip_ids\n scores = np.array(scores) # (#rel_clips, 3)\n agg_scores = np.sum(scores, 1) # (#rel_clips, )\n sort_indices = np.argsort(agg_scores) # increasing\n\n # indices in the whole video\n # the min(_, ctx_l-1) here is incorrect, but should not cause\n # much troubles since this should be rarely used.\n hard_pos_clip_indices = [min(rel_clip_ids[idx], ctx_l-1) for idx in sort_indices[-max_n:]]\n hard_neg_clip_indices = [min(rel_clip_ids[idx], ctx_l-1) for idx in sort_indices[:max_n]]\n easy_pos_clip_indices = []\n easy_neg_clip_indices = []\n if add_easy_negative:\n easy_neg_pool = list(set(range(ctx_l)) - set(rel_clip_ids))\n if len(easy_neg_pool) >= max_n:\n easy_pos_clip_indices = random.sample(rel_clip_ids, k=max_n)\n easy_neg_clip_indices = random.sample(easy_neg_pool, k=max_n)\n else: # copy the hard ones\n easy_pos_clip_indices = hard_pos_clip_indices\n easy_neg_clip_indices = hard_neg_clip_indices\n\n pos_clip_indices = hard_pos_clip_indices + easy_pos_clip_indices\n neg_clip_indices = hard_neg_clip_indices + easy_neg_clip_indices\n return pos_clip_indices, neg_clip_indices\n\n def get_saliency_labels_all(self, rel_clip_ids, scores, ctx_l, max_n=1, add_easy_negative=True):\n \"\"\"Sum the scores from the three annotations, then take the two clips with the\n maximum scores as positive, and two with the minimum scores as negative.\n Args:\n rel_clip_ids: list(int), list of relevant clip ids\n scores: list([anno1_score, anno2_score, anno3_score]),\n ctx_l: int\n max_n: int, #clips to use as positive and negative, for easy and hard negative, respectively.\n add_easy_negative: bool, if True, sample eay negative outside the relevant_clip_ids.\n \"\"\"\n # indices inside rel_clip_ids\n scores = np.array(scores) # (#rel_clips, 3)\n agg_scores = np.sum(scores, 1) # (#rel_clips, )\n sort_indices = np.argsort(agg_scores) # increasing\n\n # score_array = [min(agg_scores[idx], ctx_l-1) for idx in range(ctx_l)]\n score_array = np.zeros(ctx_l)\n for idx in range(len(rel_clip_ids)):\n if rel_clip_ids[idx] >= ctx_l:\n score_array_new = np.zeros(ctx_l + 1)\n score_array_new[:ctx_l] = score_array\n score_array = score_array_new\n score_array[rel_clip_ids[idx]] = agg_scores[idx]\n\n # indices in the whole video\n # the min(_, ctx_l-1) here is incorrect, but should not cause\n # much troubles since this should be rarely used.\n hard_pos_clip_indices = [min(rel_clip_ids[idx], ctx_l-1) for idx in sort_indices[-max_n:]]\n hard_neg_clip_indices = [min(rel_clip_ids[idx], ctx_l-1) for idx in sort_indices[:max_n]]\n easy_pos_clip_indices = []\n easy_neg_clip_indices = []\n if add_easy_negative:\n easy_neg_pool = list(set(range(ctx_l)) - set(rel_clip_ids))\n if len(easy_neg_pool) >= max_n:\n easy_pos_clip_indices = random.sample(rel_clip_ids, k=max_n)\n easy_neg_clip_indices = random.sample(easy_neg_pool, k=max_n)\n else: # copy the hard ones\n easy_pos_clip_indices = hard_pos_clip_indices\n easy_neg_clip_indices = hard_neg_clip_indices\n\n pos_clip_indices = hard_pos_clip_indices + easy_pos_clip_indices\n neg_clip_indices = hard_neg_clip_indices + easy_neg_clip_indices\n return pos_clip_indices, neg_clip_indices, score_array\n\n def get_saliency_labels_all_tvsum(self, labels, ctx_l, max_n=1, add_easy_negative=False):\n \n agg_scores = np.sum(labels - np.ones_like(labels), axis=-1)[:ctx_l] # start from 1, so minus 1\n score_array = agg_scores / 80 * 12\n sort_indices = np.argsort(agg_scores) # increasing\n\n hard_pos_clip_indices = [min(idx, ctx_l-1) for idx in sort_indices[-max_n:]]\n hard_neg_clip_indices = [min(idx, ctx_l-1) for idx in sort_indices[:max_n]]\n easy_pos_clip_indices = []\n easy_neg_clip_indices = []\n if add_easy_negative:\n easy_neg_pool = list(set(range(ctx_l)))\n if len(easy_neg_pool) >= max_n:\n easy_pos_clip_indices = random.sample(rel_clip_ids, k=max_n)\n easy_neg_clip_indices = random.sample(easy_neg_pool, k=max_n)\n else: # copy the hard ones\n easy_pos_clip_indices = hard_pos_clip_indices\n easy_neg_clip_indices = hard_neg_clip_indices\n\n pos_clip_indices = hard_pos_clip_indices + easy_pos_clip_indices\n neg_clip_indices = hard_neg_clip_indices + easy_neg_clip_indices\n\n return pos_clip_indices, neg_clip_indices, score_array\n\n def get_saliency_labels_all_youtube(self, labels, ctx_l, max_n=1, add_easy_negative=False):\n \n # Youtube-hl only have binary score\n agg_scores = np.array(labels)[:, 0] # (L, 1) --> (L, )\n score_array = agg_scores * 1\n \n sort_indices = np.argsort(agg_scores) # increasing\n\n hard_pos_clip_indices = [min(idx, ctx_l-1) for idx in sort_indices[-max_n:]]\n hard_neg_clip_indices = [min(idx, ctx_l-1) for idx in sort_indices[:max_n]]\n easy_pos_clip_indices = []\n easy_neg_clip_indices = []\n if add_easy_negative:\n easy_neg_pool = list(set(range(ctx_l)))\n if len(easy_neg_pool) >= max_n:\n easy_pos_clip_indices = random.sample(rel_clip_ids, k=max_n)\n easy_neg_clip_indices = random.sample(easy_neg_pool, k=max_n)\n else: # copy the hard ones\n easy_pos_clip_indices = hard_pos_clip_indices\n easy_neg_clip_indices = hard_neg_clip_indices\n\n pos_clip_indices = hard_pos_clip_indices + easy_pos_clip_indices\n neg_clip_indices = hard_neg_clip_indices + easy_neg_clip_indices\n\n return pos_clip_indices, neg_clip_indices, score_array\n \n \n def get_span_labels(self, windows, ctx_l):\n \"\"\"\n windows: list([st, ed]) in seconds. E.g. [[26, 36]], corresponding st_ed clip_indices [[13, 17]] (inclusive)\n Note a maximum of `self.max_windows` windows are used.\n returns Tensor of shape (#windows, 2), each row is [center, width] normalized by video length\n \"\"\"\n if len(windows) > self.max_windows:\n random.shuffle(windows)\n windows = windows[:self.max_windows]\n if self.span_loss_type == \"l1\":\n windows = torch.Tensor(windows) / (ctx_l * self.clip_len) # normalized windows in xx\n windows = span_xx_to_cxw(windows) # normalized windows in cxw\n elif self.span_loss_type == \"ce\":\n windows = torch.Tensor([\n [int(w[0] / self.clip_len), min(int(w[1] / self.clip_len), ctx_l) - 1]\n for w in windows]).long() # inclusive\n else:\n raise NotImplementedError\n return windows\n\n def _get_query_feat_by_qid(self, qid):\n if self.dset_name == 'tvsum':\n q_feat = np.load(join(self.q_feat_dir, \"{}.npz\".format(qid))) # 'token', 'text'\n return torch.from_numpy(q_feat['token'])\n # youtube-hl\n elif self.dset_name == 'youtube_uni':\n q_feat = np.load(join(self.q_feat_dir, \"{}.npz\".format(qid)))\n return torch.from_numpy(q_feat['last_hidden_state'])\n \n elif self.dset_name in ['tacos', 'nlq']:\n q_feat_path = join(self.q_feat_dir, f\"{qid}.npz\")\n q_feat = np.load(q_feat_path)[self.q_feat_type].astype(np.float32)\n if self.q_feat_type == \"last_hidden_state\":\n q_feat = q_feat[:self.max_q_l]\n if self.normalize_t:\n q_feat = l2_normalize_np_array(q_feat)\n if self.txt_drop_ratio > 0:\n q_feat = self.random_drop_rows(q_feat)\n else:\n # QVhighlight dataset\n q_feat_path = join(self.q_feat_dir, f\"qid{qid}.npz\")\n q_feat = np.load(q_feat_path)[self.q_feat_type].astype(np.float32)\n if self.q_feat_type == \"last_hidden_state\":\n q_feat = q_feat[:self.max_q_l]\n if self.normalize_t:\n q_feat = l2_normalize_np_array(q_feat)\n if self.txt_drop_ratio > 0:\n q_feat = self.random_drop_rows(q_feat)\n return torch.from_numpy(q_feat) # (D, ) or (Lq, D)\n\n def random_drop_rows(self, embeddings):\n \"\"\"randomly mask num_drop rows in embeddings to be zero.\n Args:\n embeddings: np.ndarray (L, D)\n \"\"\"\n num_drop_rows = round(len(embeddings) * self.txt_drop_ratio)\n if num_drop_rows > 0:\n row_indices = np.random.choice(\n len(embeddings), size=num_drop_rows, replace=False)\n embeddings[row_indices] = 0\n return embeddings\n\n def _get_video_feat_by_vid(self, vid):\n if self.dset_name == 'tvsum':\n v_feat_list = []\n for _feat_dir in self.v_feat_dirs:\n _feat_path = join(_feat_dir, f\"{vid}_rgb.npy\")\n _feat_rgb = np.load(_feat_path)[:self.max_v_l].astype(np.float32)\n\n _feat_path = join(_feat_dir, f\"{vid}_opt.npy\")\n _feat_opt = np.load(_feat_path)[:self.max_v_l].astype(np.float32)\n \n _feat = np.concatenate([_feat_rgb, _feat_opt], axis=-1)\n # _feat = _feat_rgb\n if self.normalize_v:\n _feat = l2_normalize_np_array(_feat)\n v_feat_list.append(_feat)\n # some features are slightly longer than the others\n min_len = min([len(e) for e in v_feat_list])\n v_feat_list = [e[:min_len] for e in v_feat_list]\n v_feat = np.concatenate(v_feat_list, axis=1)\n\n elif self.dset_name == 'youtube_uni':\n v_feat_list = []\n for _feat_dir in self.v_feat_dirs:\n # Only single npz files per directory\n try:\n _feat_path = join(_feat_dir, f\"{vid}.npz\")\n _feat = np.load(_feat_path)[\"features\"][:self.max_v_l].astype(np.float32)\n except:\n _feat_path = join(_feat_dir, f\"{vid}.npy\")\n _feat = np.load(_feat_path)[:self.max_v_l].astype(np.float32)\n \n # _feat = _feat_rgb\n if self.normalize_v:\n _feat = l2_normalize_np_array(_feat)\n v_feat_list.append(_feat)\n # some features are slightly longer than the others\n min_len = min([len(e) for e in v_feat_list])\n v_feat_list = [e[:min_len] for e in v_feat_list] # TODO do we need to cut the length over the min_len?\n v_feat = np.concatenate(v_feat_list, axis=1)\n\n else:\n v_feat_list = []\n for _feat_dir in self.v_feat_dirs:\n try:\n _feat_path = join(_feat_dir, f\"{vid}.npz\")\n _feat = np.load(_feat_path)[\"features\"][:self.max_v_l].astype(np.float32)\n except:\n _feat_path = join(_feat_dir, f\"{vid}.npy\")\n _feat = np.load(_feat_path)[:self.max_v_l].astype(np.float32)\n if self.normalize_v:\n _feat = l2_normalize_np_array(_feat)\n v_feat_list.append(_feat)\n # some features are slightly longer than the others\n min_len = min([len(e) for e in v_feat_list])\n v_feat_list = [e[:min_len] for e in v_feat_list]\n v_feat = np.concatenate(v_feat_list, axis=1)\n return torch.from_numpy(v_feat) # (Lv, D)" }, { "identifier": "start_end_collate", "path": "cg_detr/start_end_dataset.py", "snippet": "def start_end_collate(batch):\n batch_meta = [e[\"meta\"] for e in batch] # seems no need to collate ?\n\n model_inputs_keys = batch[0][\"model_inputs\"].keys()\n batched_data = dict()\n for k in model_inputs_keys:\n if k == \"span_labels\":\n batched_data[k] = [dict(spans=e[\"model_inputs\"][\"span_labels\"]) for e in batch]\n continue\n if k in [\"saliency_pos_labels\", \"saliency_neg_labels\"]:\n batched_data[k] = torch.LongTensor([e[\"model_inputs\"][k] for e in batch])\n continue\n if k == \"saliency_all_labels\":\n pad_data, mask_data = pad_sequences_1d([e[\"model_inputs\"][k] for e in batch], dtype=np.float32, fixed_length=None)\n batched_data[k] = torch.tensor(pad_data, dtype=torch.float32)\n continue\n if k == 'qid':\n batched_data[k] = [e[\"model_inputs\"][k] for e in batch]\n continue\n if k == 'vid':\n batched_data[k] = [e[\"model_inputs\"][k] for e in batch]\n continue\n batched_data[k] = pad_sequences_1d(\n [e[\"model_inputs\"][k] for e in batch], dtype=torch.float32, fixed_length=None)\n return batch_meta, batched_data" }, { "identifier": "prepare_batch_inputs", "path": "cg_detr/start_end_dataset.py", "snippet": "def prepare_batch_inputs(batched_model_inputs, device, non_blocking=False):\n model_inputs = dict(\n src_txt=batched_model_inputs[\"query_feat\"][0].to(device, non_blocking=non_blocking),\n src_txt_mask=batched_model_inputs[\"query_feat\"][1].to(device, non_blocking=non_blocking),\n src_vid=batched_model_inputs[\"video_feat\"][0].to(device, non_blocking=non_blocking),\n src_vid_mask=batched_model_inputs[\"video_feat\"][1].to(device, non_blocking=non_blocking),\n vid=batched_model_inputs[\"vid\"],\n qid=batched_model_inputs[\"qid\"],\n )\n targets = {}\n\n if \"span_labels\" in batched_model_inputs:\n targets[\"span_labels\"] = [\n dict(spans=e[\"spans\"].to(device, non_blocking=non_blocking))\n for e in batched_model_inputs[\"span_labels\"]\n ]\n if \"saliency_pos_labels\" in batched_model_inputs:\n for name in [\"saliency_pos_labels\", \"saliency_neg_labels\"]:\n targets[name] = batched_model_inputs[name].to(device, non_blocking=non_blocking)\n\n if \"saliency_all_labels\" in batched_model_inputs:\n targets[\"saliency_all_labels\"] = batched_model_inputs[\"saliency_all_labels\"].to(device, non_blocking=non_blocking)\n targets[\"relevant_clips\"] = batched_model_inputs[\"saliency_all_labels\"].to(device, non_blocking=non_blocking)\n targets = None if len(targets) == 0 else targets\n return model_inputs, targets" }, { "identifier": "eval_epoch", "path": "cg_detr/inference.py", "snippet": "def eval_epoch(model, eval_dataset, opt, save_submission_filename, epoch_i=None, criterion=None, tb_writer=None):\n logger.info(\"Generate submissions\")\n model.eval()\n if criterion is not None and eval_dataset.load_labels:\n criterion.eval()\n else:\n criterion = None\n\n if opt.dset_name == 'tacos':\n shuffle = True\n else:\n shuffle = False\n\n eval_loader = DataLoader(\n eval_dataset,\n collate_fn=start_end_collate,\n batch_size=opt.eval_bsz,\n num_workers=opt.num_workers,\n shuffle=shuffle,\n pin_memory=opt.pin_memory\n )\n\n\n # tvsum \n if opt.dset_name in ['tvsum', 'youtube_uni']:\n metrics, eval_loss_meters = compute_hl_results(model, eval_loader, opt, epoch_i, criterion, tb_writer)\n \n # to match original save format\n submission = [\n {\"brief\": metrics}\n ]\n submission_path = os.path.join(opt.results_dir, \"latest_metric.jsonl\")\n save_jsonl(submission, submission_path)\n\n return submission[0], submission[0], eval_loss_meters, [submission_path]\n\n else:\n submission, eval_loss_meters = get_eval_res(model, eval_loader, opt, epoch_i, criterion, tb_writer)\n\n if opt.dset_name in ['charadesSTA', 'tacos', 'nlq']:\n new_submission = []\n for s in submission:\n s.pop('pred_saliency_scores', None)\n new_submission.append(s)\n submission = new_submission\n\n if opt.no_sort_results:\n save_submission_filename = save_submission_filename.replace(\".jsonl\", \"_unsorted.jsonl\")\n metrics, metrics_nms, latest_file_paths = eval_epoch_post_processing(\n submission, opt, eval_dataset.data, save_submission_filename)\n return metrics, metrics_nms, eval_loss_meters, latest_file_paths" }, { "identifier": "start_inference", "path": "cg_detr/inference.py", "snippet": "def start_inference(train_opt=None, split=None, splitfile=None):\n if train_opt is not None:\n opt = TestOptions().parse(train_opt.a_feat_dir)\n else:\n opt = TestOptions().parse()\n if split is not None:\n opt.eval_split_name = split\n if splitfile is not None:\n opt.eval_path = splitfile\n\n print(opt.eval_split_name)\n print(opt.eval_path)\n logger.info(\"Setup config, data and model...\")\n\n\n cudnn.benchmark = True\n cudnn.deterministic = False\n\n assert opt.eval_path is not None\n if opt.eval_split_name == 'val':\n loadlabel = True\n else:\n loadlabel = False\n\n eval_dataset = StartEndDataset(\n dset_name=opt.dset_name,\n data_path=opt.eval_path,\n v_feat_dirs=opt.v_feat_dirs,\n q_feat_dir=opt.t_feat_dir,\n q_feat_type=\"last_hidden_state\",\n max_q_l=opt.max_q_l,\n max_v_l=opt.max_v_l,\n ctx_mode=opt.ctx_mode,\n data_ratio=opt.data_ratio,\n normalize_v=not opt.no_norm_vfeat,\n normalize_t=not opt.no_norm_tfeat,\n clip_len=opt.clip_length,\n max_windows=opt.max_windows,\n load_labels=loadlabel, # opt.eval_split_name == \"val\",\n span_loss_type=opt.span_loss_type,\n txt_drop_ratio=0,\n dset_domain=opt.dset_domain,\n )\n\n\n\n model, criterion, _, _ = setup_model(opt)\n\n save_submission_filename = \"hl_{}_submission.jsonl\".format(\n opt.eval_split_name)\n # save_submission_filename = \"inference_{}_{}_{}_preds.jsonl\".format(\n # opt.dset_name, opt.eval_split_name, opt.eval_id)\n logger.info(\"Starting inference...\")\n with torch.no_grad():\n metrics_no_nms, metrics_nms, eval_loss_meters, latest_file_paths = \\\n eval_epoch(model, eval_dataset, opt, save_submission_filename, criterion=criterion)\n if opt.eval_split_name == 'val':\n logger.info(\"metrics_no_nms {}\".format(pprint.pformat(metrics_no_nms[\"brief\"], indent=4)))\n if metrics_nms is not None:\n logger.info(\"metrics_nms {}\".format(pprint.pformat(metrics_nms[\"brief\"], indent=4)))" }, { "identifier": "setup_model", "path": "cg_detr/inference.py", "snippet": "def setup_model(opt):\n \"\"\"setup model/optimizer/scheduler and load checkpoints when needed\"\"\"\n logger.info(\"setup model/optimizer/scheduler\")\n model, criterion = build_model(opt)\n if opt.device.type == \"cuda\":\n logger.info(\"CUDA enabled.\")\n model.to(opt.device)\n criterion.to(opt.device)\n\n param_dicts = [{\"params\": [p for n, p in model.named_parameters() if p.requires_grad]}]\n optimizer = torch.optim.AdamW(param_dicts, lr=opt.lr, weight_decay=opt.wd)\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, opt.lr_drop)\n\n if opt.resume is not None:\n logger.info(f\"Load checkpoint from {opt.resume}\")\n checkpoint = torch.load(opt.resume, map_location=\"cpu\")\n from collections import OrderedDict\n new_state_dict = OrderedDict()\n if 'pt' in opt.resume[:-4]:\n if 'asr' in opt.resume[:25]:\n model.load_state_dict(checkpoint[\"model\"])\n else:\n for k, v in checkpoint[\"model\"].items():\n name = k[7:] # remove `module.`\n new_state_dict[name] = v\n # model.load_state_dict(checkpoint[\"model\"])\n model.load_state_dict(new_state_dict)\n else:\n model.load_state_dict(checkpoint[\"model\"])\n if opt.resume_all:\n optimizer.load_state_dict(checkpoint['optimizer'])\n lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n opt.start_epoch = checkpoint['epoch'] + 1\n logger.info(f\"Loaded model saved at epoch {checkpoint['epoch']} from checkpoint: {opt.resume}\")\n else:\n logger.warning(\"If you intend to evaluate the model, please specify --resume with ckpt path\")\n\n return model, criterion, optimizer, lr_scheduler" }, { "identifier": "AverageMeter", "path": "utils/basic_utils.py", "snippet": "class AverageMeter(object):\n \"\"\"Computes and stores the average and current/max/min value\"\"\"\n def __init__(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n self.max = -1e10\n self.min = 1e10\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n self.max = -1e10\n self.min = 1e10\n\n def update(self, val, n=1):\n self.max = max(val, self.max)\n self.min = min(val, self.min)\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count" }, { "identifier": "dict_to_markdown", "path": "utils/basic_utils.py", "snippet": "def dict_to_markdown(d, max_str_len=120):\n # convert list into its str representation\n d = {k: v.__repr__() if isinstance(v, list) else v for k, v in d.items()}\n # truncate string that is longer than max_str_len\n if max_str_len is not None:\n d = {k: v[-max_str_len:] if isinstance(v, str) else v for k, v in d.items()}\n return pd.DataFrame(d, index=[0]).transpose().to_markdown()" }, { "identifier": "count_parameters", "path": "utils/model_utils.py", "snippet": "def count_parameters(model, verbose=True):\n \"\"\"Count number of parameters in PyTorch model,\n References: https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/7.\n\n from utils.utils import count_parameters\n count_parameters(model)\n import sys\n sys.exit(1)\n \"\"\"\n n_all = sum(p.numel() for p in model.parameters())\n n_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n if verbose:\n print(\"Parameter Count: all {:,d}; trainable {:,d}\".format(n_all, n_trainable))\n return n_all, n_trainable" } ]
import os import time import json import pprint import random import numpy as np import torch import torch.nn as nn import torch.backends.cudnn as cudnn import logging import sys from tqdm import tqdm, trange from collections import defaultdict from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from cg_detr.config import BaseOptions from cg_detr.start_end_dataset import \ StartEndDataset, start_end_collate, prepare_batch_inputs from cg_detr.inference import eval_epoch, start_inference, setup_model from utils.basic_utils import AverageMeter, dict_to_markdown from utils.model_utils import count_parameters
14,890
metrics_no_nms, metrics_nms, eval_loss_meters, latest_file_paths = \ eval_epoch(model, val_dataset, opt, save_submission_filename, epoch_i, criterion, tb_writer) # log to_write = opt.eval_log_txt_formatter.format( time_str=time.strftime("%Y_%m_%d_%H_%M_%S"), epoch=epoch_i, loss_str=" ".join(["{} {:.4f}".format(k, v.avg) for k, v in eval_loss_meters.items()]), eval_metrics_str=json.dumps(metrics_no_nms)) with open(opt.eval_log_filepath, "a") as f: f.write(to_write) logger.info("metrics_no_nms {}".format(pprint.pformat(metrics_no_nms["brief"], indent=4))) if metrics_nms is not None: logger.info("metrics_nms {}".format(pprint.pformat(metrics_nms["brief"], indent=4))) metrics = metrics_no_nms for k, v in metrics["brief"].items(): tb_writer.add_scalar(f"Eval/{k}", float(v), epoch_i+1) # stop_score = metrics["brief"]["MR-full-mAP"] stop_score = metrics["brief"]["mAP"] if stop_score > prev_best_score: es_cnt = 0 prev_best_score = stop_score checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "lr_scheduler": lr_scheduler.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", "_best.ckpt")) best_file_paths = [e.replace("latest", "best") for e in latest_file_paths] for src, tgt in zip(latest_file_paths, best_file_paths): os.renames(src, tgt) logger.info("The checkpoint file has been updated.") else: es_cnt += 1 if opt.max_es_cnt != -1 and es_cnt > opt.max_es_cnt: # early stop with open(opt.train_log_filepath, "a") as f: f.write(f"Early Stop at epoch {epoch_i}") logger.info(f"\n>>>>> Early stop at epoch {epoch_i} {prev_best_score}\n") break # save ckpt checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "lr_scheduler": lr_scheduler.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", "_latest.ckpt")) save_interval = 10 if "subs_train" in opt.train_path else 50 # smaller for pretrain if (epoch_i + 1) % save_interval == 0 or (epoch_i + 1) % opt.lr_drop == 0: # additional copies checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", f"_e{epoch_i:04d}.ckpt")) if opt.debug: break tb_writer.close() def start_training(): logger.info("Setup config, data and model...") opt = BaseOptions().parse() set_seed(opt.seed) if opt.debug: # keep the model run deterministically # 'cudnn.benchmark = True' enabled auto finding the best algorithm for a specific input/net config. # Enable this only when input size is fixed. cudnn.benchmark = False cudnn.deterministic = True dataset_config = dict( dset_name=opt.dset_name, data_path=opt.train_path, v_feat_dirs=opt.v_feat_dirs, q_feat_dir=opt.t_feat_dir, q_feat_type="last_hidden_state", max_q_l=opt.max_q_l, max_v_l=opt.max_v_l, ctx_mode=opt.ctx_mode, data_ratio=opt.data_ratio, normalize_v=not opt.no_norm_vfeat, normalize_t=not opt.no_norm_tfeat, clip_len=opt.clip_length, max_windows=opt.max_windows, span_loss_type=opt.span_loss_type, txt_drop_ratio=opt.txt_drop_ratio, dset_domain=opt.dset_domain, ) dataset_config["data_path"] = opt.train_path train_dataset = StartEndDataset(**dataset_config) if opt.eval_path is not None: dataset_config["data_path"] = opt.eval_path dataset_config["txt_drop_ratio"] = 0 dataset_config["q_feat_dir"] = opt.t_feat_dir.replace("sub_features", "text_features") # for pretraining # dataset_config["load_labels"] = False # uncomment to calculate eval loss eval_dataset = StartEndDataset(**dataset_config) else: eval_dataset = None model, criterion, optimizer, lr_scheduler = setup_model(opt) logger.info(f"Model {model}")
logger = logging.getLogger(__name__) logging.basicConfig(format="%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) def set_seed(seed, use_cuda=True): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if use_cuda: torch.cuda.manual_seed_all(seed) def train_epoch(model, criterion, train_loader, optimizer, opt, epoch_i, tb_writer): logger.info(f"[Epoch {epoch_i+1}]") model.train() criterion.train() # init meters time_meters = defaultdict(AverageMeter) loss_meters = defaultdict(AverageMeter) num_training_examples = len(train_loader) timer_dataloading = time.time() for batch_idx, batch in tqdm(enumerate(train_loader), desc="Training Iteration", total=num_training_examples): time_meters["dataloading_time"].update(time.time() - timer_dataloading) timer_start = time.time() model_inputs, targets = prepare_batch_inputs(batch[1], opt.device, non_blocking=opt.pin_memory) time_meters["prepare_inputs_time"].update(time.time() - timer_start) timer_start = time.time() outputs = model(**model_inputs, targets=targets) loss_dict = criterion(outputs, targets) weight_dict = criterion.weight_dict losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) time_meters["model_forward_time"].update(time.time() - timer_start) timer_start = time.time() optimizer.zero_grad() losses.backward() if opt.grad_clip > 0: nn.utils.clip_grad_norm_(model.parameters(), opt.grad_clip) optimizer.step() time_meters["model_backward_time"].update(time.time() - timer_start) loss_dict["loss_overall"] = float(losses) # for logging only for k, v in loss_dict.items(): loss_meters[k].update(float(v) * weight_dict[k] if k in weight_dict else float(v)) timer_dataloading = time.time() if opt.debug and batch_idx == 3: break # print/add logs tb_writer.add_scalar("Train/lr", float(optimizer.param_groups[0]["lr"]), epoch_i+1) for k, v in loss_meters.items(): tb_writer.add_scalar("Train/{}".format(k), v.avg, epoch_i+1) to_write = opt.train_log_txt_formatter.format( time_str=time.strftime("%Y_%m_%d_%H_%M_%S"), epoch=epoch_i+1, loss_str=" ".join(["{} {:.4f}".format(k, v.avg) for k, v in loss_meters.items()])) with open(opt.train_log_filepath, "a") as f: f.write(to_write) logger.info("Epoch time stats:") for name, meter in time_meters.items(): d = {k: f"{getattr(meter, k):.4f}" for k in ["max", "min", "avg"]} logger.info(f"{name} ==> {d}") def train(model, criterion, optimizer, lr_scheduler, train_dataset, val_dataset, opt): if opt.device.type == "cuda": logger.info("CUDA enabled.") model.to(opt.device) tb_writer = SummaryWriter(opt.tensorboard_log_dir) tb_writer.add_text("hyperparameters", dict_to_markdown(vars(opt), max_str_len=None)) opt.train_log_txt_formatter = "{time_str} [Epoch] {epoch:03d} [Loss] {loss_str}\n" opt.eval_log_txt_formatter = "{time_str} [Epoch] {epoch:03d} [Loss] {loss_str} [Metrics] {eval_metrics_str}\n" train_loader = DataLoader( train_dataset, collate_fn=start_end_collate, batch_size=opt.bsz, num_workers=opt.num_workers, shuffle=True, pin_memory=opt.pin_memory ) prev_best_score = 0. es_cnt = 0 # start_epoch = 0 if opt.start_epoch is None: start_epoch = -1 if opt.eval_untrained else 0 else: start_epoch = opt.start_epoch save_submission_filename = "latest_{}_{}_preds.jsonl".format(opt.dset_name, opt.eval_split_name) for epoch_i in trange(start_epoch, opt.n_epoch, desc="Epoch"): if epoch_i > -1: train_epoch(model, criterion, train_loader, optimizer, opt, epoch_i, tb_writer) lr_scheduler.step() eval_epoch_interval = opt.eval_epoch if opt.eval_path is not None and (epoch_i + 1) % eval_epoch_interval == 0: with torch.no_grad(): metrics_no_nms, metrics_nms, eval_loss_meters, latest_file_paths = \ eval_epoch(model, val_dataset, opt, save_submission_filename, epoch_i, criterion, tb_writer) # log to_write = opt.eval_log_txt_formatter.format( time_str=time.strftime("%Y_%m_%d_%H_%M_%S"), epoch=epoch_i, loss_str=" ".join(["{} {:.4f}".format(k, v.avg) for k, v in eval_loss_meters.items()]), eval_metrics_str=json.dumps(metrics_no_nms)) with open(opt.eval_log_filepath, "a") as f: f.write(to_write) logger.info("metrics_no_nms {}".format(pprint.pformat(metrics_no_nms["brief"], indent=4))) if metrics_nms is not None: logger.info("metrics_nms {}".format(pprint.pformat(metrics_nms["brief"], indent=4))) metrics = metrics_no_nms for k, v in metrics["brief"].items(): tb_writer.add_scalar(f"Eval/{k}", float(v), epoch_i+1) if opt.dset_name in ['hl']: stop_score = metrics["brief"]["MR-full-mAP"] else: stop_score = (metrics["brief"]["[email protected]"] + metrics["brief"]["[email protected]"]) / 2 if stop_score > prev_best_score: es_cnt = 0 prev_best_score = stop_score checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "lr_scheduler": lr_scheduler.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", "_best.ckpt")) best_file_paths = [e.replace("latest", "best") for e in latest_file_paths] for src, tgt in zip(latest_file_paths, best_file_paths): os.renames(src, tgt) logger.info("The checkpoint file has been updated.") else: es_cnt += 1 if opt.max_es_cnt != -1 and es_cnt > opt.max_es_cnt: # early stop with open(opt.train_log_filepath, "a") as f: f.write(f"Early Stop at epoch {epoch_i}") logger.info(f"\n>>>>> Early stop at epoch {epoch_i} {prev_best_score}\n") break # save ckpt checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "lr_scheduler": lr_scheduler.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", "_latest.ckpt")) # save_interval = 10 if "subs_train" in opt.train_path else 50 # smaller for pretrain # if (epoch_i + 1) % save_interval == 0 or (epoch_i + 1) % opt.lr_drop == 0: # additional copies # checkpoint = { # "model": model.state_dict(), # "optimizer": optimizer.state_dict(), # "epoch": epoch_i, # "opt": opt # } # torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", f"_e{epoch_i:04d}.ckpt")) if opt.debug: break tb_writer.close() def train_hl(model, criterion, optimizer, lr_scheduler, train_dataset, val_dataset, opt): if opt.device.type == "cuda": logger.info("CUDA enabled.") model.to(opt.device) tb_writer = SummaryWriter(opt.tensorboard_log_dir) tb_writer.add_text("hyperparameters", dict_to_markdown(vars(opt), max_str_len=None)) opt.train_log_txt_formatter = "{time_str} [Epoch] {epoch:03d} [Loss] {loss_str}\n" opt.eval_log_txt_formatter = "{time_str} [Epoch] {epoch:03d} [Loss] {loss_str} [Metrics] {eval_metrics_str}\n" train_loader = DataLoader( train_dataset, collate_fn=start_end_collate, batch_size=opt.bsz, num_workers=opt.num_workers, shuffle=True, pin_memory=opt.pin_memory ) prev_best_score = 0. es_cnt = 0 # start_epoch = 0 if opt.start_epoch is None: start_epoch = -1 if opt.eval_untrained else 0 else: start_epoch = opt.start_epoch save_submission_filename = "latest_{}_{}_preds.jsonl".format(opt.dset_name, opt.eval_split_name) for epoch_i in trange(start_epoch, opt.n_epoch, desc="Epoch"): if epoch_i > -1: train_epoch(model, criterion, train_loader, optimizer, opt, epoch_i, tb_writer) lr_scheduler.step() eval_epoch_interval = 5 if opt.eval_path is not None and (epoch_i + 1) % eval_epoch_interval == 0: with torch.no_grad(): metrics_no_nms, metrics_nms, eval_loss_meters, latest_file_paths = \ eval_epoch(model, val_dataset, opt, save_submission_filename, epoch_i, criterion, tb_writer) # log to_write = opt.eval_log_txt_formatter.format( time_str=time.strftime("%Y_%m_%d_%H_%M_%S"), epoch=epoch_i, loss_str=" ".join(["{} {:.4f}".format(k, v.avg) for k, v in eval_loss_meters.items()]), eval_metrics_str=json.dumps(metrics_no_nms)) with open(opt.eval_log_filepath, "a") as f: f.write(to_write) logger.info("metrics_no_nms {}".format(pprint.pformat(metrics_no_nms["brief"], indent=4))) if metrics_nms is not None: logger.info("metrics_nms {}".format(pprint.pformat(metrics_nms["brief"], indent=4))) metrics = metrics_no_nms for k, v in metrics["brief"].items(): tb_writer.add_scalar(f"Eval/{k}", float(v), epoch_i+1) # stop_score = metrics["brief"]["MR-full-mAP"] stop_score = metrics["brief"]["mAP"] if stop_score > prev_best_score: es_cnt = 0 prev_best_score = stop_score checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "lr_scheduler": lr_scheduler.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", "_best.ckpt")) best_file_paths = [e.replace("latest", "best") for e in latest_file_paths] for src, tgt in zip(latest_file_paths, best_file_paths): os.renames(src, tgt) logger.info("The checkpoint file has been updated.") else: es_cnt += 1 if opt.max_es_cnt != -1 and es_cnt > opt.max_es_cnt: # early stop with open(opt.train_log_filepath, "a") as f: f.write(f"Early Stop at epoch {epoch_i}") logger.info(f"\n>>>>> Early stop at epoch {epoch_i} {prev_best_score}\n") break # save ckpt checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "lr_scheduler": lr_scheduler.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", "_latest.ckpt")) save_interval = 10 if "subs_train" in opt.train_path else 50 # smaller for pretrain if (epoch_i + 1) % save_interval == 0 or (epoch_i + 1) % opt.lr_drop == 0: # additional copies checkpoint = { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "epoch": epoch_i, "opt": opt } torch.save(checkpoint, opt.ckpt_filepath.replace(".ckpt", f"_e{epoch_i:04d}.ckpt")) if opt.debug: break tb_writer.close() def start_training(): logger.info("Setup config, data and model...") opt = BaseOptions().parse() set_seed(opt.seed) if opt.debug: # keep the model run deterministically # 'cudnn.benchmark = True' enabled auto finding the best algorithm for a specific input/net config. # Enable this only when input size is fixed. cudnn.benchmark = False cudnn.deterministic = True dataset_config = dict( dset_name=opt.dset_name, data_path=opt.train_path, v_feat_dirs=opt.v_feat_dirs, q_feat_dir=opt.t_feat_dir, q_feat_type="last_hidden_state", max_q_l=opt.max_q_l, max_v_l=opt.max_v_l, ctx_mode=opt.ctx_mode, data_ratio=opt.data_ratio, normalize_v=not opt.no_norm_vfeat, normalize_t=not opt.no_norm_tfeat, clip_len=opt.clip_length, max_windows=opt.max_windows, span_loss_type=opt.span_loss_type, txt_drop_ratio=opt.txt_drop_ratio, dset_domain=opt.dset_domain, ) dataset_config["data_path"] = opt.train_path train_dataset = StartEndDataset(**dataset_config) if opt.eval_path is not None: dataset_config["data_path"] = opt.eval_path dataset_config["txt_drop_ratio"] = 0 dataset_config["q_feat_dir"] = opt.t_feat_dir.replace("sub_features", "text_features") # for pretraining # dataset_config["load_labels"] = False # uncomment to calculate eval loss eval_dataset = StartEndDataset(**dataset_config) else: eval_dataset = None model, criterion, optimizer, lr_scheduler = setup_model(opt) logger.info(f"Model {model}")
count_parameters(model)
9
2023-11-10 12:45:25+00:00
24k
ej0cl6/TextEE
TextEE/models/Degree/E2Etrainer.py
[ { "identifier": "BasicTrainer", "path": "TextEE/models/trainer.py", "snippet": "class BasicTrainer(object):\n def __init__(self, config, type_set=None):\n self.config = config\n self.type_set = type_set\n \n @classmethod\n def add_extra_info_fn(cls, instances, raw_data, config):\n for instance in instances:\n instance[\"extra_info\"] = None\n return instances\n \n def load_model(self, checkpoint=None):\n pass\n \n def train(self, train_data, dev_data, **kwargs):\n pass\n \n def predict(self, data, **kwargs):\n pass" }, { "identifier": "DegreeE2EModel", "path": "TextEE/models/Degree/E2Emodel.py", "snippet": "class DegreeE2EModel(nn.Module):\n def __init__(self, config, tokenizer, type_set):\n super().__init__()\n self.config = config\n self.tokenizer = tokenizer\n self.type_set = type_set\n \n if self.config.pretrained_model_name.startswith('facebook/bart'):\n self.model_config = AutoConfig.from_pretrained(self.config.pretrained_model_name,\n cache_dir=self.config.cache_dir)\n self.model = AutoModelForPreTraining.from_pretrained(self.config.pretrained_model_name,\n cache_dir=self.config.cache_dir, config=self.model_config)\n else:\n raise ValueError(\"Not implemented.\")\n \n self.model.resize_token_embeddings(len(self.tokenizer))\n \n def process_data(self, batch):\n # encoder inputs\n inputs = self.tokenizer(batch.batch_input, return_tensors='pt', padding=True)\n enc_idxs = inputs['input_ids']\n enc_attn = inputs['attention_mask']\n\n # decoder inputs\n targets = self.tokenizer(batch.batch_target, return_tensors='pt', padding=True)\n batch_size = enc_idxs.size(0)\n \n if self.config.pretrained_model_name.startswith('facebook/bart'):\n padding = torch.ones((batch_size, 1), dtype=torch.long)\n padding[:] = self.tokenizer.eos_token_id\n # for BART, the decoder input should be:\n # PAD => BOS\n # BOS => A\n # A => B \n else:\n # t5 case\n padding = torch.ones((batch_size, 1), dtype=torch.long)\n padding[:] = self.tokenizer.pad_token_id\n # for t5, the decoder input should be:\n # PAD => A\n # A => B\n \n dec_idxs = torch.cat((padding, targets['input_ids']), dim=1)\n dec_attn = torch.cat((torch.ones((batch_size, 1), dtype=torch.long), targets['attention_mask']), dim=1)\n # dec_idxs = targets['input_ids']\n # dec_idxs[:, 0] = self.tokenizer.eos_token_id\n # dec_attn = targets['attention_mask']\n \n # labels\n padding = torch.ones((batch_size, 1), dtype=torch.long)\n padding[:] = self.tokenizer.pad_token_id\n raw_lbl_idxs = torch.cat((dec_idxs[:, 1:], padding), dim=1)\n lbl_attn = torch.cat((dec_attn[:, 1:], torch.zeros((batch_size, 1), dtype=torch.long)), dim=1)\n lbl_idxs = raw_lbl_idxs.masked_fill(lbl_attn==0, -100) # ignore padding\n \n enc_idxs = enc_idxs.cuda()\n enc_attn = enc_attn.cuda()\n dec_idxs = dec_idxs.cuda()\n dec_attn = dec_attn.cuda()\n raw_lbl_idxs = raw_lbl_idxs.cuda()\n lbl_idxs = lbl_idxs.cuda()\n \n return enc_idxs, enc_attn, dec_idxs, dec_attn, raw_lbl_idxs, lbl_idxs\n\n def forward(self, batch):\n enc_idxs, enc_attn, dec_idxs, dec_attn, raw_lbl_idxs, lbl_idxs = self.process_data(batch)\n outputs = self.model(input_ids=enc_idxs, \n attention_mask=enc_attn, \n decoder_input_ids=dec_idxs, \n decoder_attention_mask=dec_attn, \n labels=lbl_idxs, \n return_dict=True)\n \n loss = outputs['loss']\n \n return loss\n \n def predict(self, batch, num_beams=4, max_length=50):\n enc_idxs, enc_attn, dec_idxs, dec_attn, raw_lbl_idxs, lbl_idxs = self.process_data(batch)\n return self.generate(enc_idxs, enc_attn, num_beams, max_length)\n \n def generate(self, input_ids, attention_mask, num_beams=4, max_length=50, **kwargs):\n self.eval()\n with torch.no_grad():\n outputs = self.model.generate(input_ids=input_ids, \n attention_mask=attention_mask, \n num_beams=num_beams, \n max_length=max_length)\n final_output = []\n for bid in range(len(input_ids)):\n # if self.config.model_name.startswith('google/t5') or self.config.model_name.startswith('t5'):\n # output_sentence = t5_decode(self.tokenizer, outputs[bid])\n # else:\n # output_sentence = self.tokenizer.decode(outputs[bid], skip_special_tokens=True, clean_up_tokenization_spaces=True)\n output_sentence = self.tokenizer.decode(outputs[bid], skip_special_tokens=True, clean_up_tokenization_spaces=True)\n final_output.append(output_sentence)\n self.train()\n return final_output\n \n def save_model(self, save_path):\n self.model.save_pretrained(save_path)\n\n def load_model(self, load_path):\n self.model.from_pretrained(load_path)" }, { "identifier": "event_template", "path": "TextEE/models/Degree/template_generate.py", "snippet": "class event_template():\n def __init__(self, event_type, info_dict, input_style, output_style, passage, ROLE_PH_MAP, gold_event=None):\n self.ROLE_PH_MAP = ROLE_PH_MAP\n self.info_dict = info_dict\n self.event_type = event_type\n self.input_style = input_style\n self.output_style = output_style\n self.output_template = self.get_output_template()\n self.passage = ' '.join(passage) # Assume this is English\n self.tokens = passage\n \n if gold_event is not None:\n self.gold_event = gold_event\n if isinstance(gold_event, list):\n # instance base\n self.trigger_text = f\" {AND} \".join([x['trigger text'] for x in gold_event if x['event type']==event_type])\n self.trigger_span = [x['trigger span'] for x in gold_event if x['event type']==event_type]\n self.arguments = [x['arguments'] for x in gold_event if x['event type']==event_type]\n else:\n # trigger base\n self.trigger_text = gold_event['trigger text']\n self.trigger_span = [gold_event['trigger span']]\n self.arguments = [gold_event['arguments']] \n else:\n self.gold_event = None\n \n def get_keywords(self):\n return self.info_dict['keywords']\n\n def get_output_template(self):\n output_template = ''\n for o_style in OUTPUT_STYLE_SET:\n if o_style in self.output_style:\n if o_style == 'trigger:sentence':\n output_template += ' {} {}'.format(SEP, format_template(self.info_dict['ED template'], self.ROLE_PH_MAP))\n if o_style == 'argument:sentence':\n output_template += ' {} {}'.format(SEP, format_template(self.info_dict['EAE template'], self.ROLE_PH_MAP))\n return (f'{SEP}'.join(output_template.split(f'{SEP}')[1:])).strip()\n\n def generate_pair(self, query_trigger):\n \"\"\"\n Generate model input sentence and output sentence pair\n \"\"\"\n input_str, supplements = self.generate_input_str_detail(query_trigger)\n output_str, gold_sample = self.generate_output_str(query_trigger)\n return (input_str, output_str, self.gold_event, gold_sample, self.event_type, self.tokens, supplements)\n\n def generate_input_str_detail(self, query_trigger):\n input_str = ''\n for i_style in INPUT_STYLE_SET:\n if i_style in self.input_style:\n if i_style == 'event_type':\n input_str += ' {} {}'.format(SEP, self.info_dict['event type'])\n if i_style == 'event_type_sent':\n input_str += ' {} {}'.format(SEP, self.info_dict['event description'])\n if i_style == 'keywords':\n input_str += ' {} Similar triggers such as {}'.format(SEP, ', '.join(self.get_keywords()))\n if i_style == 'triggers':\n input_str += ' {} The event trigger word is {}'.format(SEP, query_trigger)\n if i_style == 'template':\n input_str += ' {} {}'.format(SEP, self.output_template)\n return self.passage+input_str, input_str\n\n def generate_input_str(self, query_trigger):\n input_str = self.passage\n for i_style in INPUT_STYLE_SET:\n if i_style in self.input_style:\n if i_style == 'event_type':\n input_str += ' {} {}'.format(SEP, self.info_dict['event type'])\n if i_style == 'event_type_sent':\n input_str += ' {} {}'.format(SEP, self.info_dict['event description'])\n if i_style == 'keywords':\n input_str += ' {} Similar triggers such as {}'.format(SEP, ', '.join(self.get_keywords()))\n if i_style == 'triggers':\n input_str += ' {} The event trigger word is {}'.format(SEP, query_trigger)\n if i_style == 'template':\n input_str += ' {} {}'.format(SEP, self.output_template)\n return input_str\n\n def generate_output_str(self, query_trigger):\n assert self.gold_event is not None\n output_str = ''\n gold_sample = False\n for o_style in OUTPUT_STYLE_SET:\n if o_style in self.output_style:\n if o_style == 'trigger:sentence':\n filler = dict()\n if self.trigger_text != '':\n filler[\"Trigger\"] = self.trigger_text\n gold_sample = True\n else:\n filler[\"Trigger\"] = TRIGGER_PH_MAP['Trigger']\n output_str += ' {} {}'.format(SEP, self.info_dict['ED template'].format(**filler))\n\n if o_style == 'argument:sentence':\n output_texts = []\n for argu in self.arguments:\n filler = dict()\n roles = re.findall(r\"{[^/}][^}]*}\", self.info_dict['EAE template'])\n roles = [role[1:-1].split(ROLE_TEMPLATE_PREFIX, 1)[1] for role in roles]\n for role_type in roles:\n filler['{}{}'.format(ROLE_TEMPLATE_PREFIX, role_type)] = f\" {AND} \".join([ a['argument text'] for a in argu[role_type]]) if role_type in argu.keys() else self.ROLE_PH_MAP['ROLE_{}'.format(role_type)]\n output_texts.append(self.info_dict['EAE template'].format(**filler))\n gold_sample = True\n output_str += ' {} {}'.format(SEP, ' <sep> '.join(output_texts))\n\n output_str = (f'{SEP}'.join(output_str.split(f'{SEP}')[1:])).strip()\n return (output_str, gold_sample)\n\n def decode(self, preds):\n output = []\n for cnt, pred in enumerate(preds.split(f'{SEP}')):\n used_o_cnt = 0\n full_pred = pred.strip()\n for o_style in OUTPUT_STYLE_SET:\n if o_style in self.output_style:\n if o_style == 'trigger:sentence':\n if used_o_cnt == cnt:\n # try:\n # contexts = re.split(r\"{[^/}][^}]*}\", self.info_dict['ED template'])\n # triggers = []\n # for idx in range(len(contexts)-1):\n # trigger = full_pred.split(contexts[idx], 1)[1]\n # trigger = trigger.split(contexts[idx+1], 1)[0]\n # triggers.append(trigger.strip())\n # triggers = [tri for trigger in triggers for tri in trigger.split(' and ') ]\n # for t_cnt, t in enumerate(triggers):\n # if t != TRIGGER_PH_MAP['Trigger'] and t != '':\n # output.append((t, self.event_type, {'tri counter': t_cnt})) # (text, type, kwargs)\n # except:\n # pass\n contexts = re.split(r\"{[^/}][^}]*}\", self.info_dict['ED template'])\n triggers = []\n for idx in range(len(contexts)-1):\n try:\n trigger = full_pred.split(contexts[idx], 1)[1]\n trigger = trigger.split(contexts[idx+1], 1)[0]\n triggers.append(trigger.strip())\n except:\n pass\n triggers = [tri for trigger in triggers for tri in trigger.split(f' {AND} ')]\n for t_cnt, t in enumerate(triggers):\n if t != TRIGGER_PH_MAP['Trigger'] and t != '':\n output.append((t, self.event_type, {'tri counter': t_cnt})) # (text, type, kwargs)\n used_o_cnt += 1\n if o_style == 'argument:sentence':\n if used_o_cnt == cnt:\n for a_cnt, prediction in enumerate(full_pred.split(' <sep> ')):\n contexts = re.split(r\"{[^/}][^}]*}\", self.info_dict['EAE template'])\n roles = re.findall(r\"{[^/}][^}]*}\", self.info_dict['EAE template'])\n roles = [role[1:-1].split(ROLE_TEMPLATE_PREFIX, 1)[1] for role in roles]\n assert len(contexts) == len(roles)+1\n\n for idx in range(len(contexts)-1):\n try:\n if contexts[idx] != '':\n pred_argu = prediction.split(contexts[idx], 1)[1]\n else:\n pred_argu = prediction\n if contexts[idx+1] != '':\n pred_argu = pred_argu.split(contexts[idx+1], 1)[0]\n pred_argu = pred_argu.split(f' {AND} ')\n for argu in pred_argu:\n if argu != self.ROLE_PH_MAP[\"{}{}\".format(ROLE_TEMPLATE_PREFIX, roles[idx])]:\n if argu != '':\n output.append((argu, roles[idx], {'cor tri cnt': a_cnt}))\n except:\n pass\n used_o_cnt += 1\n \n return output\n\n def evaluate(self, predict_output):\n assert self.gold_event is not None\n # categorize prediction\n pred_trigger = []\n pred_argument = []\n for pred in predict_output:\n if pred[1] == self.event_type:\n pred_trigger.append(pred)\n else:\n pred_argument.append(pred)\n \n # get trigger id map\n pred_trigger_map = {}\n for p_tri in pred_trigger:\n # assert p_tri[2]['tri counter'] not in pred_trigger_map.keys()\n pred_trigger_map[p_tri[2]['tri counter']] = p_tri\n\n # trigger score\n gold_tri_num = len(self.trigger_span)\n pred_tris = []\n for pred in pred_trigger:\n pred_span = self.predstr2span(pred[0])\n if pred_span[0] > -1:\n pred_tris.append((pred_span[0], pred_span[1], pred[1]))\n pred_tri_num = len(pred_tris)\n match_tri = 0\n for pred in pred_tris:\n id_flag = False\n for gold_span in self.trigger_span:\n if gold_span[0] == pred[0] and gold_span[1] == pred[1]:\n id_flag = True\n match_tri += int(id_flag)\n\n # argument score\n converted_gold = self.get_converted_gold()\n gold_arg_num = len(converted_gold)\n pred_arg = []\n for pred in pred_argument:\n # find corresponding trigger\n pred_span = None\n if isinstance(self.gold_event, list):\n # end2end case\n try:\n # we need this ``try'' because we cannot gurantee the model will be bug-free on the matching\n cor_tri = pred_trigger_map[pred[2]['cor tri cnt']]\n cor_tri_span_head = self.predstr2span(cor_tri[0])[0]\n if cor_tri_span_head > -1:\n pred_span = self.predstr2span(pred[0], cor_tri_span_head)\n else:\n continue\n except Exception as e:\n print('unmatch exception')\n print(e)\n else:\n # argument only case\n pred_span = self.predstr2span(pred[0], self.trigger_span[0][0])\n if (pred_span is not None) and (pred_span[0] > -1):\n pred_arg.append((pred_span[0], pred_span[1], pred[1]))\n pred_arg = list(set(pred_arg))\n pred_arg_num = len(pred_arg)\n \n target = converted_gold\n match_id = 0\n match_type = 0\n for pred in pred_arg:\n id_flag = False\n id_type = False\n for gold in target:\n if gold[0]==pred[0] and gold[1]==pred[1]:\n id_flag = True\n if gold[2] == pred[2]:\n id_type = True\n break\n match_id += int(id_flag)\n match_type += int(id_type)\n return {\n 'gold_tri_num': gold_tri_num, \n 'pred_tri_num': pred_tri_num,\n 'match_tri_num': match_tri,\n 'gold_arg_num': gold_arg_num,\n 'pred_arg_num': pred_arg_num,\n 'match_arg_id': match_id,\n 'match_arg_cls': match_type\n }\n \n def get_converted_gold(self):\n converted_gold = []\n for argu in self.arguments:\n for arg_type, arg_list in argu.items():\n for arg in arg_list:\n converted_gold.append((arg['argument span'][0], arg['argument span'][1], arg_type))\n return list(set(converted_gold))\n \n def predstr2span(self, pred_str, trigger_idx=None):\n sub_words = [_.strip() for _ in pred_str.strip().lower().split()]\n candidates=[]\n for i in range(len(self.tokens)):\n j = 0\n while j < len(sub_words) and i+j < len(self.tokens):\n if self.tokens[i+j].lower() == sub_words[j]:\n j += 1\n else:\n break\n if j == len(sub_words):\n candidates.append((i, i+len(sub_words)))\n if len(candidates) < 1:\n return -1, -1\n else:\n if trigger_idx is not None:\n return sorted(candidates, key=lambda x: abs(trigger_idx-x[0]))[0]\n else:\n return candidates[0]" }, { "identifier": "eve_template_generator", "path": "TextEE/models/Degree/template_generate.py", "snippet": "class eve_template_generator():\n def __init__(self, dataset, passage, triggers, roles, input_style, output_style, vocab, instance_base=False):\n \"\"\"\n generate strctured information for events\n \n args:\n dataset(str): which dataset is used\n passage(List): a list of tokens\n triggers(List): a list of triggers\n roles(List): a list of Roles\n input_style(List): List of elements; elements belongs to INPUT_STYLE_SET\n input_style(List): List of elements; elements belongs to OUTPUT_STYLE_SET\n instance_base(Bool): if instance_base, we generate only one pair (use for trigger generation), else, we generate trigger_base (use for argument generation)\n \"\"\"\n self.raw_passage = passage\n self.triggers = triggers\n self.roles = roles\n self.events = self.process_events(passage, triggers, roles)\n self.input_style = input_style\n self.output_style = output_style\n self.vocab = vocab\n self.event_templates = []\n if instance_base:\n for e_type in self.vocab['event_type_itos']:\n self.event_templates.append(\n event_template(e_type, patterns[dataset][e_type], \n self.input_style, self.output_style, passage, ROLE_PH_MAP[dataset], self.events)\n )\n else:\n for event in self.events:\n self.event_templates.append(\n event_template(event['event type'], patterns[dataset][event['event type']], \n self.input_style, self.output_style, event['tokens'], ROLE_PH_MAP[dataset], event)\n )\n self.data = [x.generate_pair(x.trigger_text) for x in self.event_templates]\n self.data = [x for x in self.data if x]\n\n def get_training_data(self):\n return self.data\n\n def process_events(self, passage, triggers, roles):\n \"\"\"\n Given a list of token and event annotation, return a list of structured event\n\n structured_event:\n {\n 'trigger text': str,\n 'trigger span': (start, end),\n 'event type': EVENT_TYPE(str),\n 'arguments':{\n ROLE_TYPE(str):[{\n 'argument text': str,\n 'argument span': (start, end)\n }],\n ROLE_TYPE(str):...,\n ROLE_TYPE(str):....\n }\n 'passage': PASSAGE\n }\n \"\"\"\n \n events = {trigger: [] for trigger in triggers}\n\n for argument in roles:\n trigger = argument[0]\n events[trigger].append(argument)\n \n event_structures = []\n for trigger, arguments in events.items():\n eve_type = trigger[2]\n eve_text = ' '.join(passage[trigger[0]:trigger[1]])\n eve_span = (trigger[0], trigger[1])\n argus = {}\n for argument in arguments:\n role_type = argument[1][2]\n if role_type not in argus.keys():\n argus[role_type] = []\n argus[role_type].append({\n 'argument text': ' '.join(passage[argument[1][0]:argument[1][1]]),\n 'argument span': (argument[1][0], argument[1][1]),\n })\n event_structures.append({\n 'trigger text': eve_text,\n 'trigger span': eve_span,\n 'event type': eve_type,\n 'arguments': argus,\n 'passage': ' '.join(passage),\n 'tokens': passage\n })\n return event_structures" }, { "identifier": "patterns", "path": "TextEE/models/Degree/pattern.py", "snippet": "ROLE_PH_MAP = {\n \"ace05-en\": {\n 'ROLE_Person': 'somebody',\n 'ROLE_Entity': 'some people or some organization',\n 'ROLE_Defendant': 'somebody',\n 'ROLE_Prosecutor': 'some other',\n 'ROLE_Plaintiff': 'some other',\n 'ROLE_Buyer': 'someone',\n 'ROLE_Artifact': 'something',\n 'ROLE_Seller': 'some seller',\n 'ROLE_Destination': 'somewhere',\n 'ROLE_Origin': 'some place',\n 'ROLE_Vehicle': 'some vehicle',\n 'ROLE_Agent': 'somebody or some organization',\n 'ROLE_Attacker': 'some attacker',\n 'ROLE_Target': 'some facility, someone, or some organization',\n 'ROLE_Victim': 'some victim',\n 'ROLE_Instrument': 'some way',\n 'ROLE_Giver': 'someone',\n 'ROLE_Recipient': 'some other',\n 'ROLE_Org': 'some organization',\n 'ROLE_Place': 'somewhere',\n 'ROLE_Adjudicator': 'some adjudicator',\n },\n \"richere-en\": {\n 'ROLE_Person': 'somebody',\n 'ROLE_Entity': 'some people or some organization',\n 'ROLE_Defendant': 'somebody',\n 'ROLE_Prosecutor': 'some other',\n 'ROLE_Plaintiff': 'some other',\n 'ROLE_Buyer': 'someone',\n 'ROLE_Artifact': 'something',\n 'ROLE_Seller': 'some seller',\n 'ROLE_Destination': 'somewhere',\n 'ROLE_Origin': 'some place',\n 'ROLE_Vehicle': 'some vehicle',\n 'ROLE_Agent': 'somebody or some organization',\n 'ROLE_Attacker': 'some attacker',\n 'ROLE_Target': 'some facility, someone, or some organization',\n 'ROLE_Victim': 'some victim',\n 'ROLE_Instrument': 'some way',\n 'ROLE_Giver': 'someone',\n 'ROLE_Recipient': 'some other',\n 'ROLE_Org': 'some organization',\n 'ROLE_Place': 'somewhere',\n 'ROLE_Adjudicator': 'some adjudicator',\n 'ROLE_Thing': 'something',\n 'ROLE_Audience': 'some publicity',\n },\n \"m2e2\": {\n 'ROLE_Person': 'somebody',\n 'ROLE_Entity': 'some people or some organization',\n 'ROLE_Artifact': 'something',\n 'ROLE_Destination': 'somewhere',\n 'ROLE_Origin': 'some place',\n 'ROLE_Vehicle': 'some vehicle',\n 'ROLE_Agent': 'somebody or some organization',\n 'ROLE_Attacker': 'some attacker',\n 'ROLE_Target': 'some facility, someone, or some organization',\n 'ROLE_Victim': 'some victim',\n 'ROLE_Instrument': 'some way',\n 'ROLE_Giver': 'someone',\n 'ROLE_Recipient': 'some other',\n 'ROLE_Place': 'somewhere',\n 'ROLE_Police': 'some police',\n },\n \"geneva\": {\n \"ROLE_Act\": \"some act\",\n \"ROLE_Action\": \"some action\",\n \"ROLE_Activity\": \"some activity\",\n \"ROLE_Actor\": \"some actor\",\n \"ROLE_Addressee\": \"some addressee\",\n \"ROLE_Affected\": \"some affected\",\n \"ROLE_Affliction\": \"some affliction\",\n \"ROLE_Agent\": \"some agent\",\n \"ROLE_Agreement\": \"some agreement\",\n \"ROLE_Area\": \"some area\",\n \"ROLE_Arguer\": \"some arguer\",\n \"ROLE_Arguer2\": \"some arguer2\",\n \"ROLE_Arguers\": \"some arguers\",\n \"ROLE_Assailant\": \"some assailant\",\n \"ROLE_Asset\": \"some asset\",\n \"ROLE_Attendees\": \"some attendees\",\n \"ROLE_Attribute\": \"some attribute\",\n \"ROLE_Author\": \"some author\",\n \"ROLE_Authorities\": \"some authorities\",\n \"ROLE_Avenger\": \"some avenger\",\n \"ROLE_Barrier\": \"some barrier\",\n \"ROLE_Behavior\": \"some behavior\",\n \"ROLE_Beneficiary\": \"some beneficiary\",\n \"ROLE_Benefited_party\": \"some benefited party\",\n \"ROLE_Body\": \"some body\",\n \"ROLE_Body_location\": \"some body location\",\n \"ROLE_Body_part\": \"some body part\",\n \"ROLE_Buyer\": \"some buyer\",\n \"ROLE_Carrier\": \"some carrier\",\n \"ROLE_Cause\": \"some cause\",\n \"ROLE_Charges\": \"some charges\",\n \"ROLE_Chosen\": \"some chosen\",\n \"ROLE_Circumstances\": \"some circumstances\",\n \"ROLE_Clothing\": \"some clothing\",\n \"ROLE_Cognizer\": \"some cognizer\",\n \"ROLE_Communicator\": \"some communicator\",\n \"ROLE_Competition\": \"some competition\",\n \"ROLE_Components\": \"some components\",\n \"ROLE_Configuration\": \"some configuration\",\n \"ROLE_Conqueror\": \"some conqueror\",\n \"ROLE_Container\": \"some container\",\n \"ROLE_Content\": \"some content\",\n \"ROLE_Contents\": \"some contents\",\n \"ROLE_Controlling_variable\": \"some controlling variable\",\n \"ROLE_Course\": \"some course\",\n \"ROLE_Created_entity\": \"some created entity\",\n \"ROLE_Creator\": \"some creator\",\n \"ROLE_Crime\": \"some crime\",\n \"ROLE_Culture\": \"some culture\",\n \"ROLE_Deceased\": \"some deceased\",\n \"ROLE_Decision\": \"some decision\",\n \"ROLE_Defender\": \"some defender\",\n \"ROLE_Dependent_variable\": \"some dependent variable\",\n \"ROLE_Destroyer\": \"some destroyer\",\n \"ROLE_Difference\": \"some difference\",\n \"ROLE_Dimension\": \"some dimension\",\n \"ROLE_Direction\": \"some direction\",\n \"ROLE_Distance\": \"some distance\",\n \"ROLE_Domain\": \"some domain\",\n \"ROLE_Donor\": \"some donor\",\n \"ROLE_Duration\": \"some duration\",\n \"ROLE_Earner\": \"some earner\",\n \"ROLE_Earnings\": \"some earnings\",\n \"ROLE_Effect\": \"some effect\",\n \"ROLE_Employee\": \"some employee\",\n \"ROLE_Employer\": \"some employer\",\n \"ROLE_Entity\": \"some entity\",\n \"ROLE_Evaluee\": \"some evaluee\",\n \"ROLE_Event\": \"some event\",\n \"ROLE_Evidence\": \"some evidence\",\n \"ROLE_Exchanger_1\": \"some exchanger 1\",\n \"ROLE_Exchanger_2\": \"some exchanger 2\",\n \"ROLE_Exchangers\": \"some exchangers\",\n \"ROLE_Experiencer\": \"some experiencer\",\n \"ROLE_Fact\": \"some fact\",\n \"ROLE_Factory\": \"some factory\",\n \"ROLE_Field\": \"some field\",\n \"ROLE_Figures\": \"some figures\",\n \"ROLE_Final_category\": \"some final category\",\n \"ROLE_Final_quality\": \"some final quality\",\n \"ROLE_Final_subevent\": \"some final subevent\",\n \"ROLE_Final_value\": \"some final value\",\n \"ROLE_Focal_entity\": \"some focal entity\",\n \"ROLE_Goal\": \"some goal\",\n \"ROLE_Goal_area\": \"some goal area\",\n \"ROLE_Goods\": \"some goods\",\n \"ROLE_Ground\": \"some ground\",\n \"ROLE_Group\": \"some group\",\n \"ROLE_Helper\": \"some helper\",\n \"ROLE_Hindrance\": \"some hindrance\",\n \"ROLE_Host\": \"some host\",\n \"ROLE_Imposed_purpose\": \"some imposed purpose\",\n \"ROLE_Incident\": \"some incident\",\n \"ROLE_Individuals\": \"some individuals\",\n \"ROLE_Information\": \"some information\",\n \"ROLE_Ingestibles\": \"some ingestibles\",\n \"ROLE_Ingestor\": \"some ingestor\",\n \"ROLE_Inherent_purpose\": \"some inherent purpose\",\n \"ROLE_Initial_category\": \"some initial category\",\n \"ROLE_Initial_size\": \"some initial size\",\n \"ROLE_Initial_subevent\": \"some initial subevent\",\n \"ROLE_Injured_party\": \"some injured party\",\n \"ROLE_Injury\": \"some injury\",\n \"ROLE_Inspector\": \"some inspector\",\n \"ROLE_Instrument\": \"some instrument\",\n \"ROLE_Intended_event\": \"some intended event\",\n \"ROLE_Interlocutors\": \"some interlocutors\",\n \"ROLE_Investigator\": \"some investigator\",\n \"ROLE_Issue\": \"some issue\",\n \"ROLE_Item\": \"some item\",\n \"ROLE_Killer\": \"some killer\",\n \"ROLE_Label\": \"some label\",\n \"ROLE_Location\": \"some location\",\n \"ROLE_Manipulator\": \"some manipulator\",\n \"ROLE_Manner\": \"some manner\",\n \"ROLE_Means\": \"some means\",\n \"ROLE_Medication\": \"some medication\",\n \"ROLE_Medium\": \"some medium\",\n \"ROLE_Member\": \"some member\",\n \"ROLE_Message\": \"some message\",\n \"ROLE_Money\": \"some money\",\n \"ROLE_New_leader\": \"some new leader\",\n \"ROLE_New_member\": \"some new member\",\n \"ROLE_Object\": \"some object\",\n \"ROLE_Occasion\": \"some occasion\",\n \"ROLE_Offender\": \"some offender\",\n \"ROLE_Offense\": \"some offense\",\n \"ROLE_Offerer\": \"some offerer\",\n \"ROLE_Old_leader\": \"some old leader\",\n \"ROLE_Old_order\": \"some old order\",\n \"ROLE_Part_1\": \"some part 1\",\n \"ROLE_Part_2\": \"some part 2\",\n \"ROLE_Participants\": \"some participants\",\n \"ROLE_Partners\": \"some partners\",\n \"ROLE_Parts\": \"some parts\",\n \"ROLE_Path\": \"some path\",\n \"ROLE_Patient\": \"some patient\",\n \"ROLE_Payer\": \"some payer\",\n \"ROLE_Perceiver_agentive\": \"some perceiver agentive\",\n \"ROLE_Perpetrator\": \"some perpetrator\",\n \"ROLE_Phenomenon\": \"some phenomenon\",\n \"ROLE_Place\": \"some place\",\n \"ROLE_Place_of_employment\": \"some place of employment\",\n \"ROLE_Position\": \"some position\",\n \"ROLE_Possibilities\": \"some possibilities\",\n \"ROLE_Potential_hindrance\": \"some potential hindrance\",\n \"ROLE_Problem\": \"some problem\",\n \"ROLE_Process\": \"some process\",\n \"ROLE_Producer\": \"some producer\",\n \"ROLE_Product\": \"some product\",\n \"ROLE_Project\": \"some project\",\n \"ROLE_Proposal\": \"some proposal\",\n \"ROLE_Proposed_action\": \"some proposed action\",\n \"ROLE_Protagonist\": \"some protagonist\",\n \"ROLE_Punishment\": \"some punishment\",\n \"ROLE_Purpose\": \"some purpose\",\n \"ROLE_Rate\": \"some rate\",\n \"ROLE_Ratifier\": \"some ratifier\",\n \"ROLE_Reason\": \"some reason\",\n \"ROLE_Recipient\": \"some recipient\",\n \"ROLE_Researcher\": \"some researcher\",\n \"ROLE_Resource\": \"some resource\",\n \"ROLE_Responding_entity\": \"some responding entity\",\n \"ROLE_Response\": \"some response\",\n \"ROLE_Result\": \"some result\",\n \"ROLE_Result_size\": \"some result size\",\n \"ROLE_Role\": \"some role\",\n \"ROLE_Selector\": \"some selector\",\n \"ROLE_Self_mover\": \"some self mover\",\n \"ROLE_Seller\": \"some seller\",\n \"ROLE_Sender\": \"some sender\",\n \"ROLE_Side_1\": \"some side 1\",\n \"ROLE_Side_2\": \"some side 2\",\n \"ROLE_Sides\": \"some sides\",\n \"ROLE_Signatory\": \"some signatory\",\n \"ROLE_Situation\": \"some situation\",\n \"ROLE_Skill\": \"some skill\",\n \"ROLE_Social_event\": \"some social event\",\n \"ROLE_Source\": \"some source\",\n \"ROLE_Speaker\": \"some speaker\",\n \"ROLE_Specified_entity\": \"some specified entity\",\n \"ROLE_Speed\": \"some speed\",\n \"ROLE_State\": \"some state\",\n \"ROLE_Student\": \"some student\",\n \"ROLE_Subject\": \"some subject\",\n \"ROLE_Supplier\": \"some supplier\",\n \"ROLE_Supported\": \"some supported\",\n \"ROLE_Supporter\": \"some supporter\",\n \"ROLE_Suspect\": \"some suspect\",\n \"ROLE_Task\": \"some task\",\n \"ROLE_Teacher\": \"some teacher\",\n \"ROLE_Terrorist\": \"some terrorist\",\n \"ROLE_Tested_property\": \"some tested property\",\n \"ROLE_Tester\": \"some tester\",\n \"ROLE_Text\": \"some text\",\n \"ROLE_Theme\": \"some theme\",\n \"ROLE_Theme_1\": \"some theme 1\",\n \"ROLE_Theme_2\": \"some theme 2\",\n \"ROLE_Themes\": \"some themes\",\n \"ROLE_Time\": \"some time\",\n \"ROLE_Topic\": \"some topic\",\n \"ROLE_Transferors\": \"some transferors\",\n \"ROLE_Traveler\": \"some traveler\",\n \"ROLE_Traveller\": \"some traveller\",\n \"ROLE_Treatment\": \"some treatment\",\n \"ROLE_Trigger\": \"some trigger\",\n \"ROLE_Type\": \"some type\",\n \"ROLE_Unconfirmed_content\": \"some unconfirmed content\",\n \"ROLE_Undertaking\": \"some undertaking\",\n \"ROLE_Undesirable_event\": \"some undesirable event\",\n \"ROLE_Unwanted_entity\": \"some unwanted entity\",\n \"ROLE_Useful_location\": \"some useful location\",\n \"ROLE_Value_1\": \"some value 1\",\n \"ROLE_Value_2\": \"some value 2\",\n \"ROLE_Vehicle\": \"some vehicle\",\n \"ROLE_Venue\": \"some venue\",\n \"ROLE_Victim\": \"some victim\",\n \"ROLE_Weapon\": \"some weapon\",\n \"ROLE_Wearer\": \"some wearer\",\n \"ROLE_Whole\": \"some whole\",\n },\n \"maven\": {\n },\n \"mee-en\": {\n },\n \"fewevent\": {\n },\n \"rams\": {\n \"ROLE_artifact\": \"some artifact\",\n \"ROLE_artifactmoney\": \"some artifact money\",\n \"ROLE_attacker\": \"some attacker\",\n \"ROLE_ballot\": \"some ballot\",\n \"ROLE_beneficiary\": \"some beneficiary\",\n \"ROLE_candidate\": \"some candidate\",\n \"ROLE_communicator\": \"some communicator\",\n \"ROLE_crashobject\": \"some crash object\",\n \"ROLE_crime\": \"some crime\",\n \"ROLE_damager\": \"some damager\",\n \"ROLE_damagerdestroyer\": \"some damager destroyer\",\n \"ROLE_deceased\": \"some deceased\",\n \"ROLE_defendant\": \"some defendant\",\n \"ROLE_demonstrator\": \"some demonstrator\",\n \"ROLE_destination\": \"some destination\",\n \"ROLE_destroyer\": \"some destroyer\",\n \"ROLE_detainee\": \"some detainee\",\n \"ROLE_driverpassenger\": \"some driver passenger\",\n \"ROLE_employee\": \"some employee\",\n \"ROLE_executioner\": \"some executioner\",\n \"ROLE_extraditer\": \"some extraditer\",\n \"ROLE_fireexplosionobject\": \"some fire explosion object\",\n \"ROLE_founder\": \"some founder\",\n \"ROLE_giver\": \"some giver\",\n \"ROLE_governmentbody\": \"some government body\",\n \"ROLE_gpe\": \"some gpe\",\n \"ROLE_granter\": \"some granter\",\n \"ROLE_hidingplace\": \"some hiding place\",\n \"ROLE_injurer\": \"some injurer\",\n \"ROLE_inspectedentity\": \"some inspected entity\",\n \"ROLE_inspector\": \"some inspector\",\n \"ROLE_instrument\": \"some instrument\",\n \"ROLE_investigator\": \"some investigator\",\n \"ROLE_jailer\": \"some jailer\",\n \"ROLE_judgecourt\": \"some judge court\",\n \"ROLE_killer\": \"some killer\",\n \"ROLE_law\": \"some law\",\n \"ROLE_manufacturer\": \"some manufacturer\",\n \"ROLE_money\": \"some money\",\n \"ROLE_monitor\": \"some monitor\",\n \"ROLE_monitoredentity\": \"some monitored entity\",\n \"ROLE_observedentity\": \"some observed entity\",\n \"ROLE_observer\": \"some observer\",\n \"ROLE_origin\": \"some origin\",\n \"ROLE_otherparticipant\": \"some other participant\",\n \"ROLE_participant\": \"some participant\",\n \"ROLE_passenger\": \"some passenger\",\n \"ROLE_place\": \"some place\",\n \"ROLE_placeofemployment\": \"some place of employment\",\n \"ROLE_preventer\": \"some preventer\",\n \"ROLE_prosecutor\": \"some prosecutor\",\n \"ROLE_recipient\": \"some recipient\",\n \"ROLE_rejecternullifier\": \"some rejecter nullifier\",\n \"ROLE_result\": \"some result\",\n \"ROLE_retreater\": \"some retreater\",\n \"ROLE_spy\": \"some spy\",\n \"ROLE_surrenderer\": \"some surrenderer\",\n \"ROLE_target\": \"some target\",\n \"ROLE_territoryorfacility\": \"some territoryor facility\",\n \"ROLE_transporter\": \"some transporter\",\n \"ROLE_vehicle\": \"some vehicle\",\n \"ROLE_victim\": \"some victim\",\n \"ROLE_violator\": \"some violator\",\n \"ROLE_voter\": \"some voter\",\n \"ROLE_yielder\": \"some yielder\", \n },\n \"wikievents\": {\n 'ROLE_AcquiredEntity': 'some acquired entity',\n 'ROLE_Artifact': 'some artifact',\n 'ROLE_ArtifactMoney': 'some artifact money',\n 'ROLE_Attacker': 'some attacker',\n 'ROLE_BodyPart': 'some body part',\n 'ROLE_Communicator': 'some communicator',\n 'ROLE_Components': 'some components',\n 'ROLE_CrashObject': 'some crash object',\n 'ROLE_Damager': 'some damager',\n 'ROLE_DamagerDestroyer': 'some damager destroyer',\n 'ROLE_Defeated': 'some defeated',\n 'ROLE_Defendant': 'some defendant',\n 'ROLE_Demonstrator': 'some demonstrator',\n 'ROLE_Destination': 'some destination',\n 'ROLE_Destroyer': 'some destroyer',\n 'ROLE_Detainee': 'some detainee',\n 'ROLE_Disabler': 'some disabler',\n 'ROLE_Dismantler': 'some dismantler',\n 'ROLE_Employee': 'some employee',\n 'ROLE_ExplosiveDevice': 'some explosive device',\n 'ROLE_Giver': 'some giver',\n 'ROLE_IdentifiedObject': 'some identified object',\n 'ROLE_IdentifiedRole': 'some identified role',\n 'ROLE_Identifier': 'some identifier',\n 'ROLE_Impeder': 'some impeder',\n 'ROLE_Injurer': 'some injurer',\n 'ROLE_Instrument': 'some instrument',\n 'ROLE_Investigator': 'some investigator',\n 'ROLE_Jailer': 'some jailer',\n 'ROLE_JudgeCourt': 'some judge court',\n 'ROLE_Killer': 'some killer',\n 'ROLE_Learner': 'some learner',\n 'ROLE_ManufacturerAssembler': 'some manufacturer assembler',\n 'ROLE_ObservedEntity': 'some observed entity',\n 'ROLE_Observer': 'some observer',\n 'ROLE_Origin': 'some origin',\n 'ROLE_Participant': 'some participant',\n 'ROLE_PassengerArtifact': 'some passenger artifact',\n 'ROLE_Patient': 'some patient',\n 'ROLE_PaymentBarter': 'some payment barter',\n 'ROLE_Perpetrator': 'some perpetrator',\n 'ROLE_Place': 'some place',\n 'ROLE_PlaceOfEmployment': 'some place of employment',\n 'ROLE_Position': 'some position',\n 'ROLE_Preventer': 'some preventer',\n 'ROLE_Prosecutor': 'some prosecutor',\n 'ROLE_Recipient': 'some recipient',\n 'ROLE_Regulator': 'some regulator',\n 'ROLE_Researcher': 'some researcher',\n 'ROLE_Subject': 'some subject',\n 'ROLE_Target': 'some target',\n 'ROLE_TeacherTrainer': 'some teacher trainer',\n 'ROLE_Topic': 'some topic',\n 'ROLE_Transporter': 'some transporter',\n 'ROLE_Treater': 'some treater',\n 'ROLE_Vehicle': 'some vehicle',\n 'ROLE_Victim': 'some victim',\n 'ROLE_Victor': 'some victor',\n },\n \"phee\": {\n \"ROLE_Combination_Drug\": \"some combination drug\",\n \"ROLE_Effect\": \"some effect\",\n \"ROLE_Subject\": \"some subject\",\n \"ROLE_Subject_Age\": \"some subject age\",\n \"ROLE_Subject_Disorder\": \"some subject disorder\",\n \"ROLE_Subject_Gender\": \"some subject gender\",\n \"ROLE_Subject_Population\": \"some subject population\",\n \"ROLE_Subject_Race\": \"some subject race\",\n \"ROLE_Treatment\": \"some treatment\",\n \"ROLE_Treatment_Disorder\": \"some treatment disorder\",\n \"ROLE_Treatment_Dosage\": \"some treatment dosage\",\n \"ROLE_Treatment_Drug\": \"some treatment drug\",\n \"ROLE_Treatment_Duration\": \"some treatment duration\",\n \"ROLE_Treatment_Freq\": \"some treatment frequency\",\n \"ROLE_Treatment_Route\": \"some treatment route\",\n \"ROLE_Treatment_Time_elapsed\": \"some treatment time elapsed\",\n },\n \"casie\": {\n \"ROLE_Attack-Pattern\": \"some attack pattern\",\n \"ROLE_Attacker\": \"some attacker\",\n \"ROLE_CVE\": \"some cve\",\n \"ROLE_Capabilities\": \"some capabilities\",\n \"ROLE_Compromised-Data\": \"some compromised data\",\n \"ROLE_Damage-Amount\": \"some damage amount\",\n \"ROLE_Discoverer\": \"some discoverer\",\n \"ROLE_Issues-Addressed\": \"some issues addressed\",\n \"ROLE_Number-of-Data\": \"some number of data\",\n \"ROLE_Number-of-Victim\": \"some number of victim\",\n \"ROLE_Patch\": \"some patch\",\n \"ROLE_Patch-Number\": \"some patch number\",\n \"ROLE_Payment-Method\": \"some payment method\",\n \"ROLE_Place\": \"some place\",\n \"ROLE_Price\": \"some price\",\n \"ROLE_Purpose\": \"some purpose\",\n \"ROLE_Releaser\": \"some releaser\",\n \"ROLE_Supported_Platform\": \"some supported platform\",\n \"ROLE_Time\": \"some time\",\n \"ROLE_Tool\": \"some tool\",\n \"ROLE_Trusted-Entity\": \"some trusted entity\",\n \"ROLE_Victim\": \"some victim\",\n \"ROLE_Vulnerability\": \"some vulnerability\",\n \"ROLE_Vulnerable_System\": \"some vulnerable system\",\n \"ROLE_Vulnerable_System_Owner\": \"some vulnerable system owner\",\n \"ROLE_Vulnerable_System_Version\": \"some vulnerable system version\",\n },\n \"mlee\": {\n \"ROLE_AtLoc\": \"some at loc\",\n \"ROLE_CSite\": \"some csite\",\n \"ROLE_Cause\": \"some cause\",\n \"ROLE_FromLoc\": \"some from loc\",\n \"ROLE_Instrument\": \"some instrument\",\n \"ROLE_Instrument2\": \"some instrument 2\",\n \"ROLE_Participant\": \"some participant\",\n \"ROLE_Participant2\": \"some participant 2\",\n \"ROLE_Participant3\": \"some participant 3\",\n \"ROLE_Participant4\": \"some participant 4\",\n \"ROLE_Site\": \"some site\",\n \"ROLE_Theme\": \"some theme\",\n \"ROLE_Theme2\": \"some theme 2\",\n \"ROLE_ToLoc\": \"some to loc\",\n },\n \"genia2011\": {\n \"ROLE_AtLoc\": \"some at loc\",\n \"ROLE_CSite\": \"some csite\",\n \"ROLE_Cause\": \"some cause\",\n \"ROLE_Site\": \"some site\",\n \"ROLE_Site2\": \"some site 2\",\n \"ROLE_Theme\": \"some theme\",\n \"ROLE_Theme2\": \"some theme 2\",\n \"ROLE_Theme3\": \"some theme 3\",\n \"ROLE_Theme4\": \"some theme 4\",\n \"ROLE_ToLoc\": \"some to loc\",\n\n },\n \"genia2013\": {\n \"ROLE_CSite\": \"some csite\",\n \"ROLE_Cause\": \"some cause\",\n \"ROLE_Site\": \"some site\",\n \"ROLE_Site2\": \"some site 2\",\n \"ROLE_Theme\": \"some theme\",\n \"ROLE_Theme2\": \"some theme 2\",\n \"ROLE_ToLoc\": \"some to loc\",\n },\n}" } ]
import os, sys, logging, tqdm, pprint import torch import numpy as np import ipdb from collections import namedtuple from transformers import BartTokenizer, AutoTokenizer, get_linear_schedule_with_warmup from torch.utils.data import DataLoader from torch.optim import AdamW from ..trainer import BasicTrainer from .E2Emodel import DegreeE2EModel from .template_generate import event_template, eve_template_generator from .pattern import patterns, ROLE_PH_MAP from scorer import compute_f1, print_scores
14,407
"piece_idxs": piece_idxs, "token_start_idxs": token_start_idxs, "input": data_[0], "target": data_[1], "info": (data_[2], data_[4], data_[5]) } new_data.append(new_dt) logger.info(f"Generate {len(new_data)} Degree E2E instances from {n_total} E2E instances") return new_data def process_data_for_testing(self, data): assert self.tokenizer, "Please load model and tokneizer before processing data!" n_total = 0 new_data = [] for dt in data: n_total += 1 pieces = [self.tokenizer.tokenize(t) for t in dt["tokens"]] token_lens = [len(p) for p in pieces] pieces = [p for piece in pieces for p in piece] piece_idxs = self.tokenizer.convert_tokens_to_ids(pieces) assert sum(token_lens) == len(piece_idxs) token_start_idxs = [sum(token_lens[:_]) for _ in range(len(token_lens))] + [sum(token_lens)] new_dt = {"doc_id": dt["doc_id"], "wnd_id": dt["wnd_id"], "tokens": dt["tokens"], "text": dt["text"], "piece_idxs": piece_idxs, "token_start_idxs": token_start_idxs, "input": "", "target": "", "info": "", } new_data.append(new_dt) logger.info(f"Generate {len(new_data)} Degree E2E instances from {n_total} E2E instances") return new_data def train(self, train_data, dev_data, **kwargs): self.load_model() internal_train_data = self.process_data_for_training(train_data) internal_dev_data = self.process_data_for_training(dev_data) param_groups = [{'params': self.model.parameters(), 'lr': self.config.learning_rate, 'weight_decay': self.config.weight_decay}] train_batch_num = len(internal_train_data) // self.config.train_batch_size + (len(internal_train_data) % self.config.train_batch_size != 0) optimizer = AdamW(params=param_groups) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=train_batch_num*self.config.warmup_epoch, num_training_steps=train_batch_num*self.config.max_epoch) best_scores = {"argument_cls": {"f1": 0.0}} best_epoch = -1 for epoch in range(1, self.config.max_epoch+1): logger.info(f"Log path: {self.config.log_path}") logger.info(f"Epoch {epoch}") # training step progress = tqdm.tqdm(total=train_batch_num, ncols=100, desc='Train {}'.format(epoch)) self.model.train() optimizer.zero_grad() cummulate_loss = [] for batch_idx, batch in enumerate(DataLoader(internal_train_data, batch_size=self.config.train_batch_size // self.config.accumulate_step, shuffle=True, drop_last=False, collate_fn=ED_collate_fn)): loss = self.model(batch) loss = loss * (1 / self.config.accumulate_step) cummulate_loss.append(loss.item()) loss.backward() if (batch_idx + 1) % self.config.accumulate_step == 0: progress.update(1) torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.config.grad_clipping) optimizer.step() scheduler.step() optimizer.zero_grad() progress.close() logger.info(f"Average training loss: {np.mean(cummulate_loss)}") # eval dev dev_scores = self.internal_eval(internal_dev_data, split="Dev") # print scores print(f"Dev {epoch}") print_scores(dev_scores) if dev_scores["argument_cls"]["f1"] >= best_scores["argument_cls"]["f1"]: logger.info("Saving best model") state = dict(model=self.model.state_dict(), tokenizer=self.tokenizer, type_set=self.type_set) torch.save(state, os.path.join(self.config.output_dir, "best_model.state")) best_scores = dev_scores best_epoch = epoch logger.info(pprint.pformat({"epoch": epoch, "dev_scores": dev_scores})) logger.info(pprint.pformat({"best_epoch": best_epoch, "best_scores": best_scores})) def internal_eval(self, eval_data, split="Dev"): eval_batch_num = len(eval_data) // self.config.eval_batch_size + (len(eval_data) % self.config.eval_batch_size != 0) progress = tqdm.tqdm(total=eval_batch_num, ncols=100, desc=split) eval_gold_tri_num, eval_pred_tri_num, eval_match_tri_num = 0, 0, 0 eval_gold_arg_num, eval_pred_arg_num, eval_match_arg_id, eval_match_arg_cls = 0, 0, 0, 0 for batch_idx, batch in enumerate(DataLoader(eval_data, batch_size=self.config.eval_batch_size, shuffle=False, collate_fn=ED_collate_fn)): progress.update(1) pred_texts = self.model.predict(batch, num_beams=self.config.beam_size, max_length=self.config.max_output_length) for doc_id, wnd_id, tokens, text, piece_idxs, token_start_idxs, info, pred_text in zip(batch.batch_doc_id, batch.batch_wnd_id, batch.batch_tokens, batch.batch_text, batch.batch_piece_idxs, batch.batch_token_start_idxs, batch.batch_info, pred_texts):
logger = logging.getLogger(__name__) EDBatch_fields = ['batch_doc_id', 'batch_wnd_id', 'batch_tokens', 'batch_text', 'batch_piece_idxs', 'batch_token_start_idxs', 'batch_input', 'batch_target', 'batch_info'] EDBatch = namedtuple('EDBatch', field_names=EDBatch_fields, defaults=[None] * len(EDBatch_fields)) def ED_collate_fn(batch): return EDBatch( batch_doc_id=[instance["doc_id"] for instance in batch], batch_wnd_id=[instance["wnd_id"] for instance in batch], batch_tokens=[instance["tokens"] for instance in batch], batch_text=[instance["text"] for instance in batch], batch_piece_idxs=[instance["piece_idxs"] for instance in batch], batch_token_start_idxs=[instance["token_start_idxs"] for instance in batch], batch_input=[instance["input"] for instance in batch], batch_target=[instance["target"] for instance in batch], batch_info=[instance["info"] for instance in batch], ) def get_span_idx(pieces, token_start_idxs, span, tokenizer, trigger_span=None): """ This function is how we map the generated prediction back to span prediction. Detailed Explanation: We will first split our prediction and use tokenizer to tokenize our predicted "span" into pieces. Then, we will find whether we can find a continuous span in the original "pieces" can match tokenized "span". If it is an argument/relation extraction task, we will return the one which is closest to the trigger_span. """ words = [] for s in span.split(' '): words.extend(tokenizer.encode(s, add_special_tokens=False)) candidates = [] for i in range(len(pieces)): j = 0 k = 0 while j < len(words) and i+k < len(pieces): if pieces[i+k] == words[j]: j += 1 k += 1 elif tokenizer.decode(words[j]) == "": j += 1 elif tokenizer.decode(pieces[i+k]) == "": k += 1 else: break if j == len(words): candidates.append((i, i+k)) candidates = [(token_start_idxs.index(c1), token_start_idxs.index(c2)) for c1, c2 in candidates if c1 in token_start_idxs and c2 in token_start_idxs] if len(candidates) < 1: return -1, -1 else: if trigger_span is None: return candidates[0] else: return sorted(candidates, key=lambda x: np.abs(trigger_span[0]-x[0]))[0] def get_span_idx_tri(pieces, token_start_idxs, span, tokenizer, trigger_span=None): """ This function is how we map the generated prediction back to span prediction. Detailed Explanation: We will first split our prediction and use tokenizer to tokenize our predicted "span" into pieces. Then, we will find whether we can find a continuous span in the original "pieces" can match tokenized "span". If it is an argument/relation extraction task, we will return the one which is closest to the trigger_span. """ words = [] for s in span.split(' '): words.extend(tokenizer.encode(s, add_special_tokens=False)) candidates = [] for i in range(len(pieces)): j = 0 k = 0 while j < len(words) and i+k < len(pieces): if pieces[i+k] == words[j]: j += 1 k += 1 elif tokenizer.decode(words[j]) == "": j += 1 elif tokenizer.decode(pieces[i+k]) == "": k += 1 else: break if j == len(words): candidates.append((i, i+k)) candidates = [(token_start_idxs.index(c1), token_start_idxs.index(c2)) for c1, c2 in candidates if c1 in token_start_idxs and c2 in token_start_idxs] if len(candidates) < 1: return [(-1, -1)] else: if trigger_span is None: return candidates else: return sorted(candidates, key=lambda x: np.abs(trigger_span[0]-x[0])) class DegreeE2ETrainer(BasicTrainer): def __init__(self, config, type_set=None): super().__init__(config, type_set) self.tokenizer = None self.model = None def load_model(self, checkpoint=None): if checkpoint: logger.info(f"Loading model from {checkpoint}") state = torch.load(os.path.join(checkpoint, "best_model.state"), map_location=f'cuda:{self.config.gpu_device}') self.tokenizer = state["tokenizer"] self.type_set = state["type_set"] self.model = DegreeE2EModel(self.config, self.tokenizer, self.type_set) self.model.load_state_dict(state['model']) self.model.cuda(device=self.config.gpu_device) else: logger.info(f"Loading model from {self.config.pretrained_model_name}") if self.config.pretrained_model_name.startswith('facebook/bart-'): self.tokenizer = BartTokenizer.from_pretrained(self.config.pretrained_model_name, cache_dir=self.config.cache_dir) else: self.tokenizer = AutoTokenizer.from_pretrained(self.config.pretrained_model_name, cache_dir=self.config.cache_dir, use_fast=False) special_tokens = ['<Trigger>', '<sep>', '<None>'] logger.info(f"Add tokens {special_tokens}") self.tokenizer.add_tokens(special_tokens) self.model = DegreeE2EModel(self.config, self.tokenizer, self.type_set) self.model.cuda(device=self.config.gpu_device) self.generate_vocab() def generate_vocab(self): event_type_itos = sorted(self.type_set["trigger"]) event_type_stoi = {e: i for i, e in enumerate(event_type_itos)} self.vocab = {"event_type_itos": event_type_itos, "event_type_stoi": event_type_stoi, } def process_data_for_training(self, data): assert self.tokenizer, "Please load model and tokneizer before processing data!" logger.info("Processing data...") n_total = 0 new_data = [] for dt in tqdm.tqdm(data, ncols=100): n_total += 1 _triggers = [t["trigger"][:3] for t in dt["events"]] _arguments = [(t["trigger"][:3], r[:3]) for t in dt["events"] for r in t["arguments"]] event_template = eve_template_generator(self.config.dataset, dt["tokens"], _triggers, _arguments, self.config.input_style, self.config.output_style, self.vocab, True) all_data_ = event_template.get_training_data() pos_data_ = [data_ for data_ in all_data_ if data_[3]] neg_data_ = [data_ for data_ in all_data_ if not data_[3]] np.random.shuffle(neg_data_) for data_ in pos_data_: if len(self.tokenizer.tokenize(data_[0])) > self.config.max_length: continue pieces = [self.tokenizer.tokenize(t) for t in dt["tokens"]] token_lens = [len(p) for p in pieces] pieces = [p for piece in pieces for p in piece] piece_idxs = self.tokenizer.convert_tokens_to_ids(pieces) assert sum(token_lens) == len(piece_idxs) token_start_idxs = [sum(token_lens[:_]) for _ in range(len(token_lens))] + [sum(token_lens)] new_dt = {"doc_id": dt["doc_id"], "wnd_id": dt["wnd_id"], "tokens": dt["tokens"], "text": dt["text"], "piece_idxs": piece_idxs, "token_start_idxs": token_start_idxs, "input": data_[0], "target": data_[1], "info": (data_[2], data_[4], data_[5]) } new_data.append(new_dt) for data_ in neg_data_[:self.config.n_negative]: if len(self.tokenizer.tokenize(data_[0])) > self.config.max_length: continue pieces = [self.tokenizer.tokenize(t) for t in dt["tokens"]] token_lens = [len(p) for p in pieces] pieces = [p for piece in pieces for p in piece] piece_idxs = self.tokenizer.convert_tokens_to_ids(pieces) assert sum(token_lens) == len(piece_idxs) token_start_idxs = [sum(token_lens[:_]) for _ in range(len(token_lens))] + [sum(token_lens)] new_dt = {"doc_id": dt["doc_id"], "wnd_id": dt["wnd_id"], "tokens": dt["tokens"], "text": dt["text"], "piece_idxs": piece_idxs, "token_start_idxs": token_start_idxs, "input": data_[0], "target": data_[1], "info": (data_[2], data_[4], data_[5]) } new_data.append(new_dt) logger.info(f"Generate {len(new_data)} Degree E2E instances from {n_total} E2E instances") return new_data def process_data_for_testing(self, data): assert self.tokenizer, "Please load model and tokneizer before processing data!" n_total = 0 new_data = [] for dt in data: n_total += 1 pieces = [self.tokenizer.tokenize(t) for t in dt["tokens"]] token_lens = [len(p) for p in pieces] pieces = [p for piece in pieces for p in piece] piece_idxs = self.tokenizer.convert_tokens_to_ids(pieces) assert sum(token_lens) == len(piece_idxs) token_start_idxs = [sum(token_lens[:_]) for _ in range(len(token_lens))] + [sum(token_lens)] new_dt = {"doc_id": dt["doc_id"], "wnd_id": dt["wnd_id"], "tokens": dt["tokens"], "text": dt["text"], "piece_idxs": piece_idxs, "token_start_idxs": token_start_idxs, "input": "", "target": "", "info": "", } new_data.append(new_dt) logger.info(f"Generate {len(new_data)} Degree E2E instances from {n_total} E2E instances") return new_data def train(self, train_data, dev_data, **kwargs): self.load_model() internal_train_data = self.process_data_for_training(train_data) internal_dev_data = self.process_data_for_training(dev_data) param_groups = [{'params': self.model.parameters(), 'lr': self.config.learning_rate, 'weight_decay': self.config.weight_decay}] train_batch_num = len(internal_train_data) // self.config.train_batch_size + (len(internal_train_data) % self.config.train_batch_size != 0) optimizer = AdamW(params=param_groups) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=train_batch_num*self.config.warmup_epoch, num_training_steps=train_batch_num*self.config.max_epoch) best_scores = {"argument_cls": {"f1": 0.0}} best_epoch = -1 for epoch in range(1, self.config.max_epoch+1): logger.info(f"Log path: {self.config.log_path}") logger.info(f"Epoch {epoch}") # training step progress = tqdm.tqdm(total=train_batch_num, ncols=100, desc='Train {}'.format(epoch)) self.model.train() optimizer.zero_grad() cummulate_loss = [] for batch_idx, batch in enumerate(DataLoader(internal_train_data, batch_size=self.config.train_batch_size // self.config.accumulate_step, shuffle=True, drop_last=False, collate_fn=ED_collate_fn)): loss = self.model(batch) loss = loss * (1 / self.config.accumulate_step) cummulate_loss.append(loss.item()) loss.backward() if (batch_idx + 1) % self.config.accumulate_step == 0: progress.update(1) torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.config.grad_clipping) optimizer.step() scheduler.step() optimizer.zero_grad() progress.close() logger.info(f"Average training loss: {np.mean(cummulate_loss)}") # eval dev dev_scores = self.internal_eval(internal_dev_data, split="Dev") # print scores print(f"Dev {epoch}") print_scores(dev_scores) if dev_scores["argument_cls"]["f1"] >= best_scores["argument_cls"]["f1"]: logger.info("Saving best model") state = dict(model=self.model.state_dict(), tokenizer=self.tokenizer, type_set=self.type_set) torch.save(state, os.path.join(self.config.output_dir, "best_model.state")) best_scores = dev_scores best_epoch = epoch logger.info(pprint.pformat({"epoch": epoch, "dev_scores": dev_scores})) logger.info(pprint.pformat({"best_epoch": best_epoch, "best_scores": best_scores})) def internal_eval(self, eval_data, split="Dev"): eval_batch_num = len(eval_data) // self.config.eval_batch_size + (len(eval_data) % self.config.eval_batch_size != 0) progress = tqdm.tqdm(total=eval_batch_num, ncols=100, desc=split) eval_gold_tri_num, eval_pred_tri_num, eval_match_tri_num = 0, 0, 0 eval_gold_arg_num, eval_pred_arg_num, eval_match_arg_id, eval_match_arg_cls = 0, 0, 0, 0 for batch_idx, batch in enumerate(DataLoader(eval_data, batch_size=self.config.eval_batch_size, shuffle=False, collate_fn=ED_collate_fn)): progress.update(1) pred_texts = self.model.predict(batch, num_beams=self.config.beam_size, max_length=self.config.max_output_length) for doc_id, wnd_id, tokens, text, piece_idxs, token_start_idxs, info, pred_text in zip(batch.batch_doc_id, batch.batch_wnd_id, batch.batch_tokens, batch.batch_text, batch.batch_piece_idxs, batch.batch_token_start_idxs, batch.batch_info, pred_texts):
template = event_template(info[1], patterns[self.config.dataset][info[1]], self.config.input_style, self.config.output_style, tokens, ROLE_PH_MAP[self.config.dataset], info[0])
4
2023-11-15 21:32:56+00:00
24k
ahayler/s4c
models/bts/evaluator.py
[ { "identifier": "make_test_dataset", "path": "datasets/data_util.py", "snippet": "def make_test_dataset(config):\n type = config.get(\"type\", \"KITTI_Raw\")\n if type == \"KITTI_Raw\":\n test_dataset = KittiRawDataset(\n data_path=config[\"data_path\"],\n pose_path=config[\"pose_path\"],\n split_path=os.path.join(config[\"split_path\"], \"test_files.txt\"),\n target_image_size=config.get(\"image_size\", (192, 640)),\n return_depth=True,\n frame_count=1,\n return_stereo=config.get(\"data_stereo\", False),\n keyframe_offset=0\n )\n return test_dataset\n elif type == \"KITTI_360\":\n test_dataset = Kitti360Dataset(\n data_path=config[\"data_path\"],\n pose_path=config[\"pose_path\"],\n split_path=os.path.join(config.get(\"split_path\", None), \"test_files.txt\"),\n target_image_size=tuple(config.get(\"image_size\", (192, 640))),\n frame_count=config.get(\"data_fc\", 1),\n return_stereo=config.get(\"data_stereo\", False),\n return_fisheye=config.get(\"data_fisheye\", False),\n return_3d_bboxes=config.get(\"data_3d_bboxes\", False),\n return_segmentation=config.get(\"data_segmentation\", False),\n keyframe_offset=0,\n fisheye_rotation=config.get(\"fisheye_rotation\", 0),\n fisheye_offset=config.get(\"fisheye_offset\", 1),\n dilation=config.get(\"dilation\", 1),\n is_preprocessed=config.get(\"is_preprocessed\", False)\n )\n return test_dataset\n elif type == \"RealEstate10k\":\n test_dataset = RealEstate10kDataset(\n data_path=config[\"data_path\"],\n split_path=os.path.join(config[\"split_path\"], \"test_files.txt\"),\n target_image_size=config.get(\"image_size\", (256, 384)),\n frame_count=config.get(\"data_fc\", 2),\n keyframe_offset=0,\n dilation=config.get(\"dilation\", 10),\n color_aug=False\n )\n return test_dataset\n elif type == \"NYU_Depth_V2\":\n test_dataset = NYUDepthV2Dataset(\n data_path=config[\"data_path\"],\n target_image_size=config.get(\"image_size\", (256, 384)),\n )\n return test_dataset\n else:\n raise NotImplementedError(f\"Unsupported dataset type: {type}\")" }, { "identifier": "NeRFRenderer", "path": "models/common/render/nerf.py", "snippet": "class NeRFRenderer(torch.nn.Module):\n \"\"\"\n NeRF differentiable renderer\n :param n_coarse number of coarse (binned uniform) samples\n :param n_fine number of fine (importance) samples\n :param n_fine_depth number of expected depth samples\n :param noise_std noise to add to sigma. We do not use it\n :param depth_std noise for depth samples\n :param eval_batch_size ray batch size for evaluation\n :param white_bkgd if true, background color is white; else black\n :param lindisp if to use samples linear in disparity instead of distance\n :param sched ray sampling schedule. list containing 3 lists of equal length.\n sched[0] is list of iteration numbers,\n sched[1] is list of coarse sample numbers,\n sched[2] is list of fine sample numbers\n \"\"\"\n\n def __init__(\n self,\n n_coarse=128,\n n_fine=0,\n n_fine_depth=0,\n noise_std=0.0,\n depth_std=0.01,\n eval_batch_size=100000,\n white_bkgd=False,\n lindisp=False,\n sched=None, # ray sampling schedule for coarse and fine rays\n hard_alpha_cap=False\n ):\n super().__init__()\n self.n_coarse = n_coarse\n self.n_fine = n_fine\n self.n_fine_depth = n_fine_depth\n\n self.noise_std = noise_std\n self.depth_std = depth_std\n\n self.eval_batch_size = eval_batch_size\n self.white_bkgd = white_bkgd\n self.lindisp = lindisp\n if lindisp:\n print(\"Using linear displacement rays\")\n self.using_fine = n_fine > 0\n self.sched = sched\n if sched is not None and len(sched) == 0:\n self.sched = None\n self.register_buffer(\n \"iter_idx\", torch.tensor(0, dtype=torch.long), persistent=True\n )\n self.register_buffer(\n \"last_sched\", torch.tensor(0, dtype=torch.long), persistent=True\n )\n self.hard_alpha_cap = hard_alpha_cap\n\n def sample_coarse(self, rays):\n \"\"\"\n Stratified sampling. Note this is different from original NeRF slightly.\n :param rays ray [origins (3), directions (3), near (1), far (1)] (B, 8)\n :return (B, Kc)\n \"\"\"\n device = rays.device\n near, far = rays[:, -2:-1], rays[:, -1:] # (B, 1)\n\n step = 1.0 / self.n_coarse\n B = rays.shape[0]\n z_steps = torch.linspace(0, 1 - step, self.n_coarse, device=device) # (Kc)\n z_steps = z_steps.unsqueeze(0).repeat(B, 1) # (B, Kc)\n z_steps += torch.rand_like(z_steps) * step\n if not self.lindisp: # Use linear sampling in depth space\n return near * (1 - z_steps) + far * z_steps # (B, Kf)\n else: # Use linear sampling in disparity space\n return 1 / (1 / near * (1 - z_steps) + 1 / far * z_steps) # (B, Kf)\n\n # Use linear sampling in depth space\n return near * (1 - z_steps) + far * z_steps # (B, Kc)\n\n def sample_coarse_from_dist(self, rays, weights, z_samp):\n device = rays.device\n B = rays.shape[0]\n\n num_bins = weights.shape[-1]\n num_samples = self.n_coarse\n\n weights = weights.detach() + 1e-5 # Prevent division by zero\n pdf = weights / torch.sum(weights, -1, keepdim=True) # (B, Kc)\n cdf = torch.cumsum(pdf, -1) # (B, Kc)\n cdf = torch.cat([torch.zeros_like(cdf[:, :1]), cdf], -1) # (B, Kc+1)\n\n u = torch.rand(B, num_samples, dtype=torch.float32, device=device) # (B, Kf)\n interval_ids = torch.searchsorted(cdf, u, right=True) - 1 # (B, Kf)\n interval_ids = torch.clamp(interval_ids, 0, num_samples-1)\n interval_interp = torch.rand_like(interval_ids, dtype=torch.float32)\n\n # z_samps describe the centers of the respective histogram bins. Therefore, we have to extend them to the left and right\n if self.lindisp:\n z_samp = 1 / z_samp\n\n centers = .5 * (z_samp[:, 1:] + z_samp[:, :-1])\n interval_borders = torch.cat((z_samp[:, :1], centers, z_samp[:, -1:]), dim=-1)\n\n left_border = torch.gather(interval_borders, dim=-1, index=interval_ids)\n right_border = torch.gather(interval_borders, dim=-1, index=interval_ids+1)\n\n z_samp_new = left_border * (1 - interval_interp) + right_border * interval_interp\n\n if self.lindisp:\n z_samp_new = 1 / z_samp_new\n\n assert not torch.any(torch.isnan(z_samp_new))\n\n return z_samp_new\n\n def sample_fine(self, rays, weights):\n \"\"\"min\n Weighted stratified (importance) sample\n :param rays ray [origins (3), directions (3), near (1), far (1)] (B, 8)\n :param weights (B, Kc)\n :return (B, Kf-Kfd)\n \"\"\"\n device = rays.device\n B = rays.shape[0]\n\n weights = weights.detach() + 1e-5 # Prevent division by zero\n pdf = weights / torch.sum(weights, -1, keepdim=True) # (B, Kc)\n cdf = torch.cumsum(pdf, -1) # (B, Kc)\n cdf = torch.cat([torch.zeros_like(cdf[:, :1]), cdf], -1) # (B, Kc+1)\n\n u = torch.rand(\n B, self.n_fine - self.n_fine_depth, dtype=torch.float32, device=device\n ) # (B, Kf)\n inds = torch.searchsorted(cdf, u, right=True).float() - 1.0 # (B, Kf)\n inds = torch.clamp_min(inds, 0.0)\n\n z_steps = (inds + torch.rand_like(inds)) / self.n_coarse # (B, Kf)\n\n near, far = rays[:, -2:-1], rays[:, -1:] # (B, 1)\n if not self.lindisp: # Use linear sampling in depth space\n z_samp = near * (1 - z_steps) + far * z_steps # (B, Kf)\n else: # Use linear sampling in disparity space\n z_samp = 1 / (1 / near * (1 - z_steps) + 1 / far * z_steps) # (B, Kf)\n\n assert not torch.any(torch.isnan(z_samp))\n\n return z_samp\n\n def sample_fine_depth(self, rays, depth):\n \"\"\"\n Sample around specified depth\n :param rays ray [origins (3), directions (3), near (1), far (1)] (B, 8)\n :param depth (B)\n :return (B, Kfd)\n \"\"\"\n z_samp = depth.unsqueeze(1).repeat((1, self.n_fine_depth))\n z_samp += torch.randn_like(z_samp) * self.depth_std\n # Clamp does not support tensor bounds\n z_samp = torch.max(torch.min(z_samp, rays[:, -1:]), rays[:, -2:-1])\n\n assert not torch.any(torch.isnan(z_samp))\n\n return z_samp\n\n def composite(self, model, rays, z_samp, coarse=True, sb=0, predict_segmentation=False):\n \"\"\"\n Render RGB and depth for each ray using NeRF alpha-compositing formula,\n given sampled positions along each ray (see sample_*)\n :param model should return (B, (r, g, b, sigma)) when called with (B, (x, y, z))\n should also support 'coarse' boolean argument\n :param rays ray [origins (3), directions (3), near (1), far (1)] (B, 8)\n :param z_samp z positions sampled for each ray (B, K)\n :param coarse whether to evaluate using coarse NeRF\n :param predict_segmentation if true also predict the semantic distribution\n :param sb super-batch dimension; 0 = disable\n :return weights (B, K), rgb (B, 3), depth (B)\n \"\"\"\n with profiler.record_function(\"renderer_composite\"):\n B, K = z_samp.shape\n\n deltas = z_samp[:, 1:] - z_samp[:, :-1] # (B, K-1)\n delta_inf = 1e10 * torch.ones_like(deltas[:, :1]) # infty (B, 1)\n # delta_inf = rays[:, -1:] - z_samp[:, -1:]\n deltas = torch.cat([deltas, delta_inf], -1) # (B, K)\n\n # (B, K, 3)\n points = rays[:, None, :3] + z_samp.unsqueeze(2) * rays[:, None, 3:6]\n points = points.reshape(-1, 3) # (B*K, 3)\n\n use_viewdirs = hasattr(model, \"use_viewdirs\") and model.use_viewdirs\n\n rgbs_all, invalid_all, sigmas_all, segs_all = [], [], [], []\n if sb > 0:\n points = points.reshape(\n sb, -1, 3\n ) # (SB, B'*K, 3) B' is real ray batch size\n eval_batch_size = (self.eval_batch_size - 1) // sb + 1\n eval_batch_dim = 1\n else:\n eval_batch_size = self.eval_batch_size\n eval_batch_dim = 0\n\n split_points = torch.split(points, eval_batch_size, dim=eval_batch_dim)\n if use_viewdirs:\n dim1 = K\n viewdirs = rays[:, None, 3:6].expand(-1, dim1, -1) # (B, K, 3)\n if sb > 0:\n viewdirs = viewdirs.reshape(sb, -1, 3) # (SB, B'*K, 3)\n else:\n viewdirs = viewdirs.reshape(-1, 3) # (B*K, 3)\n split_viewdirs = torch.split(\n viewdirs, eval_batch_size, dim=eval_batch_dim\n )\n for pnts, dirs in zip(split_points, split_viewdirs):\n rgbs, invalid, sigmas = model(pnts, coarse=coarse, viewdirs=dirs)\n rgbs_all.append(rgbs)\n invalid_all.append(invalid)\n sigmas_all.append(sigmas)\n else:\n for pnts in split_points:\n if predict_segmentation:\n rgbs, invalid, sigmas, segs = model(pnts, coarse=coarse,\n predict_segmentation=predict_segmentation)\n segs_all.append(segs)\n else:\n rgbs, invalid, sigmas = model(pnts, coarse=coarse,\n predict_segmentation=predict_segmentation)\n rgbs_all.append(rgbs)\n invalid_all.append(invalid)\n sigmas_all.append(sigmas)\n points = None\n viewdirs = None\n # (B*K, 4) OR (SB, B'*K, 4)\n rgbs = torch.cat(rgbs_all, dim=eval_batch_dim)\n invalid = torch.cat(invalid_all, dim=eval_batch_dim)\n sigmas = torch.cat(sigmas_all, dim=eval_batch_dim)\n\n if predict_segmentation:\n segs = torch.cat(segs_all, dim=eval_batch_dim)\n segs = segs.reshape(B, K, -1) # (B, K, n_classes)\n\n rgbs = rgbs.reshape(B, K, -1) # (B, K, 4 or 5)\n invalid = invalid.reshape(B, K, -1)\n sigmas = sigmas.reshape(B, K)\n\n if self.training and self.noise_std > 0.0:\n sigmas = sigmas + torch.randn_like(sigmas) * self.noise_std\n\n alphas = 1 - torch.exp(-deltas.abs() * torch.relu(sigmas)) # (B, K) (delta should be positive anyways)\n\n if self.hard_alpha_cap:\n alphas[:, -1] = 1\n\n deltas = None\n sigmas = None\n alphas_shifted = torch.cat(\n [torch.ones_like(alphas[:, :1]), 1 - alphas + 1e-10], -1\n ) # (B, K+1) = [1, a1, a2, ...]\n T = torch.cumprod(alphas_shifted, -1) # (B)\n weights = alphas * T[:, :-1] # (B, K)\n # alphas = None\n alphas_shifted = None\n\n rgb_final = torch.sum(weights.unsqueeze(-1) * rgbs, -2) # (B, 3)\n depth_final = torch.sum(weights * z_samp, -1) # (B)\n\n\n\n if self.white_bkgd:\n # White background\n pix_alpha = weights.sum(dim=1) # (B), pixel alpha\n rgb_final = rgb_final + 1 - pix_alpha.unsqueeze(-1) # (B, 3)\n\n if predict_segmentation:\n segs_final = torch.sum(weights.unsqueeze(-1) * segs, dim=-2) # (B, n_classes)\n return (\n weights,\n rgb_final,\n depth_final,\n alphas,\n invalid,\n z_samp,\n rgbs,\n # segs,\n segs_final\n )\n else:\n return (\n weights,\n rgb_final,\n depth_final,\n alphas,\n invalid,\n z_samp,\n rgbs\n )\n\n def forward(\n self, model, rays, want_weights=False, want_alphas=False, want_z_samps=False, want_rgb_samps=False, predict_segmentation=False, sample_from_dist=None):\n \"\"\"\n :model nerf model, should return (SB, B, (r, g, b, sigma))\n when called with (SB, B, (x, y, z)), for multi-object:\n SB = 'super-batch' = size of object batch,\n B = size of per-object ray batch.\n Should also support 'coarse' boolean argument for coarse NeRF.\n :param rays ray spec [origins (3), directions (3), near (1), far (1)] (SB, B, 8)\n :param want_weights if true, returns compositing weights (SB, B, K)\n :param predict_segmentation if true, return the segmentation class distribution for each pixel\n :return render dict\n \"\"\"\n with profiler.record_function(\"renderer_forward\"):\n if self.sched is not None and self.last_sched.item() > 0:\n self.n_coarse = self.sched[1][self.last_sched.item() - 1]\n self.n_fine = self.sched[2][self.last_sched.item() - 1]\n\n assert len(rays.shape) == 3\n superbatch_size = rays.shape[0]\n rays = rays.reshape(-1, 8) # (SB * B, 8)\n\n if sample_from_dist is None:\n z_coarse = self.sample_coarse(rays) # (B, Kc)\n else:\n prop_weights, prop_z_samp = sample_from_dist\n n_samples = prop_weights.shape[-1]\n prop_weights = prop_weights.reshape(-1, n_samples)\n prop_z_samp = prop_z_samp.reshape(-1, n_samples)\n z_coarse = self.sample_coarse_from_dist(rays, prop_weights, prop_z_samp)\n z_coarse, _ = torch.sort(z_coarse, dim=-1)\n\n coarse_composite = self.composite(\n model, rays, z_coarse, coarse=True, sb=superbatch_size, predict_segmentation=predict_segmentation\n )\n\n outputs = DotMap(\n coarse=self._format_outputs(\n coarse_composite, superbatch_size, want_weights=want_weights, want_alphas=want_alphas,\n want_z_samps=want_z_samps, want_rgb_samps=want_rgb_samps, want_segmentation=predict_segmentation\n ),\n )\n\n if self.using_fine:\n all_samps = [z_coarse]\n if self.n_fine - self.n_fine_depth > 0:\n all_samps.append(\n self.sample_fine(rays, coarse_composite[0].detach())\n ) # (B, Kf - Kfd)\n if self.n_fine_depth > 0:\n all_samps.append(\n self.sample_fine_depth(rays, coarse_composite[2])\n ) # (B, Kfd)\n z_combine = torch.cat(all_samps, dim=-1) # (B, Kc + Kf)\n z_combine_sorted, argsort = torch.sort(z_combine, dim=-1)\n fine_composite = self.composite(\n model, rays, z_combine_sorted, coarse=False, sb=superbatch_size,\n )\n outputs.fine = self._format_outputs(\n fine_composite, superbatch_size, want_weights=want_weights, want_alphas=want_alphas, want_z_samps=want_z_samps, want_rgb_samps=want_rgb_samps\n )\n\n return outputs\n\n def _format_outputs(\n self, rendered_outputs, superbatch_size, want_weights=False, want_alphas=False, want_z_samps=False, want_rgb_samps=False, want_segmentation=False\n ):\n if want_segmentation:\n weights, rgb_final, depth, alphas, invalid, z_samps, rgb_samps, segs_final = rendered_outputs\n else:\n weights, rgb_final, depth, alphas, invalid, z_samps, rgb_samps = rendered_outputs\n\n n_smps = weights.shape[-1]\n out_d_rgb = rgb_final.shape[-1]\n out_d_i = invalid.shape[-1]\n\n if superbatch_size > 0:\n rgb_final = rgb_final.reshape(superbatch_size, -1, out_d_rgb)\n depth = depth.reshape(superbatch_size, -1)\n weights = weights.reshape(superbatch_size, -1, n_smps)\n alphas = alphas.reshape(superbatch_size, -1, n_smps)\n invalid = invalid.reshape(superbatch_size, -1, n_smps, out_d_i)\n z_samps = z_samps.reshape(superbatch_size, -1, n_smps)\n rgb_samps = rgb_samps.reshape(superbatch_size, -1, n_smps, out_d_rgb)\n\n if want_segmentation:\n out_segs = segs_final.shape[-1]\n segs_final = segs_final.reshape(superbatch_size, -1, out_segs)\n\n ret_dict = DotMap(rgb=rgb_final, depth=depth, invalid=invalid)\n if want_weights:\n ret_dict.weights = weights\n if want_alphas:\n ret_dict.alphas = alphas\n if want_z_samps:\n ret_dict.z_samps = z_samps\n if want_rgb_samps:\n ret_dict.rgb_samps = rgb_samps\n if want_segmentation:\n ret_dict.segs = segs_final\n # ret_dict.segs_raw = segs_raw\n return ret_dict\n\n def sched_step(self, steps=1):\n \"\"\"\n Called each training iteration to update sample numbers\n according to schedule\n \"\"\"\n if self.sched is None:\n return\n self.iter_idx += steps\n while (\n self.last_sched.item() < len(self.sched[0])\n and self.iter_idx.item() >= self.sched[0][self.last_sched.item()]\n ):\n self.n_coarse = self.sched[1][self.last_sched.item()]\n self.n_fine = self.sched[2][self.last_sched.item()]\n print(\n \"INFO: NeRF sampling resolution changed on schedule ==> c\",\n self.n_coarse,\n \"f\",\n self.n_fine,\n )\n self.last_sched += 1\n\n @classmethod\n def from_conf(cls, conf, white_bkgd=False, eval_batch_size=100000):\n return cls(\n conf.get(\"n_coarse\", 128),\n conf.get(\"n_fine\", 0),\n n_fine_depth=conf.get(\"n_fine_depth\", 0),\n noise_std=conf.get(\"noise_std\", 0.0),\n depth_std=conf.get(\"depth_std\", 0.01),\n white_bkgd=conf.get(\"white_bkgd\", white_bkgd),\n lindisp=conf.get(\"lindisp\", True),\n eval_batch_size=conf.get(\"eval_batch_size\", eval_batch_size),\n sched=conf.get(\"sched\", None),\n hard_alpha_cap=conf.get(\"hard_alpha_cap\", False)\n )\n\n def bind_parallel(self, net, gpus=None, simple_output=False):\n \"\"\"\n Returns a wrapper module compatible with DataParallel.\n Specifically, it renders rays with this renderer\n but always using the given network instance.\n Specify a list of GPU ids in 'gpus' to apply DataParallel automatically.\n :param net A PixelNeRF network\n :param gpus list of GPU ids to parallize to. If length is 1,\n does not parallelize\n :param simple_output only returns rendered (rgb, depth) instead of the \n full render output map. Saves data tranfer cost.\n :return torch module\n \"\"\"\n wrapped = _RenderWrapper(net, self, simple_output=simple_output)\n if gpus is not None and len(gpus) > 1:\n print(\"Using multi-GPU\", gpus)\n wrapped = torch.nn.DataParallel(wrapped, gpus, dim=1)\n return wrapped" }, { "identifier": "make_image_processor", "path": "models/bts/model/image_processor.py", "snippet": "def make_image_processor(config):\n type = config.get(\"type\", \"RGB\").lower()\n if type == \"rgb\":\n ip = RGBProcessor()\n elif type == \"perceptual\":\n ip = PerceptualProcessor(config.get(\"layers\", 1))\n elif type == \"patch\":\n ip = PatchProcessor(config.get(\"patch_size\", 3))\n else:\n raise NotImplementedError(f\"Unsupported image processor type: {type}\")\n return ip" }, { "identifier": "RGBProcessor", "path": "models/bts/model/image_processor.py", "snippet": "class RGBProcessor(nn.Module):\n def __init__(self):\n super().__init__()\n self.channels = 3\n\n def forward(self, images):\n images = images * .5 + .5\n return images" }, { "identifier": "ReconstructionLoss", "path": "models/bts/model/loss.py", "snippet": "class ReconstructionLoss:\n def __init__(self, config, use_automasking=False) -> None:\n super().__init__()\n self.criterion_str = config.get(\"criterion\", \"l2\")\n if self.criterion_str == \"l2\":\n self.rgb_coarse_crit = torch.nn.MSELoss(reduction=\"none\")\n self.rgb_fine_crit = torch.nn.MSELoss(reduction=\"none\")\n elif self.criterion_str == \"l1\":\n self.rgb_coarse_crit = torch.nn.L1Loss(reduction=\"none\")\n self.rgb_fine_crit = torch.nn.L1Loss(reduction=\"none\")\n elif self.criterion_str == \"l1+ssim\":\n self.rgb_coarse_crit = compute_errors_l1ssim\n self.rgb_fine_crit = compute_errors_l1ssim\n self.invalid_policy = config.get(\"invalid_policy\", \"strict\")\n assert self.invalid_policy in [\"strict\", \"weight_guided\", \"weight_guided_diverse\", None, \"none\"]\n self.ignore_invalid = self.invalid_policy is not None and self.invalid_policy != \"none\"\n self.lambda_coarse = config.get(\"lambda_coarse\", 1)\n self.lambda_fine = config.get(\"lambda_fine\", 1)\n self.lambda_segmentation = config.get(\"lambda_segmentation\", 1)\n self.segmentation_class_weights = config.get(\"segmentation_class_weights\", None)\n\n if self.segmentation_class_weights is not None:\n self.segmentation_class_weights = torch.tensor(list(config.get(\"segmentation_class_weights\", None).values()))\n\n self.use_automasking = use_automasking\n\n self.lambda_entropy = config.get(\"lambda_entropy\", 0)\n self.lambda_density_entropy = config.get(\"lambda_density_entropy\", 0)\n self.lambda_depth_reg = config.get(\"lambda_depth_reg\", 0)\n self.lambda_alpha_reg = config.get(\"lambda_alpha_reg\", 0)\n self.lambda_surfaceness_reg = config.get(\"lambda_surfaceness_reg\", 0)\n self.lambda_edge_aware_smoothness = config.get(\"lambda_edge_aware_smoothness\", 0)\n self.lambda_depth_smoothness = config.get(\"lambda_depth_smoothness\", 0)\n\n self.median_thresholding = config.get(\"median_thresholding\", False)\n\n self.alpha_reg_reduction = config.get(\"alpha_reg_reduction\", \"ray\")\n self.alpha_reg_fraction = config.get(\"alpha_reg_fraction\", 1/8)\n\n if self.alpha_reg_reduction not in (\"ray\", \"slice\"):\n raise ValueError(f\"Unknown reduction for alpha regularization: {self.alpha_reg_reduction}\")\n\n @staticmethod\n def get_loss_metric_names():\n return [\"loss\", \"loss_rgb_coarse\", \"loss_rgb_fine\", \"loss_ray_entropy\", \"loss_depth_reg\"]\n\n def __call__(self, data):\n with profiler.record_function(\"loss_computation\"):\n n_scales = len(data[\"coarse\"])\n\n loss_dict = {}\n\n loss_coarse_all = 0\n loss_fine_all = 0\n loss_segmentation = 0\n loss = 0\n\n coarse_0 = data[\"coarse\"][0]\n fine_0 = data[\"fine\"][0]\n segmentation_0 = data[\"segmentation\"][0]\n invalid_coarse = coarse_0[\"invalid\"]\n invalid_fine = fine_0[\"invalid\"]\n invalid_segmentation = segmentation_0[\"invalid\"]\n\n weights_coarse = coarse_0[\"weights\"]\n weights_fine = fine_0[\"weights\"]\n weights_segmentation = segmentation_0[\"weights\"]\n\n if self.invalid_policy == \"strict\":\n # Consider all rays invalid where there is at least one invalidly sampled color\n invalid_coarse = torch.all(torch.any(invalid_coarse > .5, dim=-2), dim=-1).unsqueeze(-1)\n invalid_fine = torch.all(torch.any(invalid_fine > .5, dim=-2), dim=-1).unsqueeze(-1)\n invalid_segmentation = torch.all(torch.any(invalid_segmentation > .5, dim=-2), dim=-1).unsqueeze(-1)\n elif self.invalid_policy == \"weight_guided\":\n # Integrate invalid indicator function over the weights. It is invalid if > 90% of the mass is invalid. (Arbitrary threshold)\n invalid_coarse = torch.all((invalid_coarse.to(torch.float32) * weights_coarse.unsqueeze(-1)).sum(-2) > .9, dim=-1, keepdim=True)\n invalid_fine = torch.all((invalid_fine.to(torch.float32) * weights_fine.unsqueeze(-1)).sum(-2) > .9, dim=-1, keepdim=True)\n invalid_segmentation = torch.all((invalid_segmentation.to(torch.float32) * weights_segmentation.unsqueeze(-1)).sum(-2) > .9,\n dim=-1, keepdim=True)\n elif self.invalid_policy == \"weight_guided_diverse\":\n # We now also consider, whether there is enough variance in the ray colors to give a meaningful supervision signal.\n rgb_samps_c = coarse_0[\"rgb_samps\"]\n rgb_samps_f = fine_0[\"rgb_samps\"]\n ray_std_c = torch.std(rgb_samps_c, dim=-3).mean(-1)\n ray_std_f = torch.std(rgb_samps_f, dim=-3).mean(-1)\n\n # Integrate invalid indicator function over the weights. It is invalid if > 90% of the mass is invalid. (Arbitrary threshold)\n invalid_coarse = torch.all(((invalid_coarse.to(torch.float32) * weights_coarse.unsqueeze(-1)).sum(-2) > .9) | (ray_std_c < 0.01), dim=-1, keepdim=True)\n invalid_fine = torch.all(((invalid_fine.to(torch.float32) * weights_fine.unsqueeze(-1)).sum(-2) > .9) | (ray_std_f < 0.01), dim=-1, keepdim=True)\n\n # for now we just do the weight guided invalids for the segmentation\n invalid_segmentation = torch.all(\n (invalid_segmentation.to(torch.float32) * weights_segmentation.unsqueeze(-1)).sum(-2) > .9,\n dim=-1, keepdim=True)\n elif self.invalid_policy == \"none\":\n invalid_coarse = torch.zeros_like(torch.all(torch.any(invalid_coarse > .5, dim=-2), dim=-1).unsqueeze(-1), dtype=torch.bool)\n invalid_fine = torch.zeros_like(torch.all(torch.any(invalid_fine > .5, dim=-2), dim=-1).unsqueeze(-1), dtype=torch.bool)\n invalid_segmentation = torch.zeros_like(torch.all(torch.any(invalid_segmentation > .5, dim=-2), dim=-1).unsqueeze(-1),\n dtype=torch.bool)\n else:\n raise NotImplementedError\n\n loss_depth_reg = torch.tensor(0.0, device=invalid_fine.device)\n loss_alpha_reg = torch.tensor(0.0, device=invalid_fine.device)\n loss_surfaceness_reg = torch.tensor(0.0, device=invalid_fine.device)\n loss_eas = torch.tensor(0.0, device=invalid_fine.device)\n loss_depth_smoothness = torch.tensor(0.0, device=invalid_fine.device)\n\n for scale in range(n_scales):\n coarse = data[\"coarse\"][scale]\n fine = data[\"fine\"][scale]\n segmentation = data[\"segmentation\"][scale]\n\n rgb_coarse = coarse[\"rgb\"]\n rgb_fine = fine[\"rgb\"]\n rgb_gt = data[\"rgb_gt\"]\n segmentation_gt = data[\"segmentation_gt\"].permute(0, 4, 1, 2, 3).squeeze(1) #(batch_size, n_patches, h, w)\n bs, n_patch, ph, pw, n_classes = segmentation[\"segs\"].shape\n segmentation_gt = segmentation_gt.view(-1, ph, pw)\n\n # do cross entropy loss\n self.segmentation_class_weights = self.segmentation_class_weights.to(segmentation_gt.device).float()\n cp_loss_fn = torch.nn.NLLLoss(weight=self.segmentation_class_weights)\n # log_segmentation = torch.log(segmentation[\"segs\"] + 1e-5).permute(0, 4, 1, 2, 3) #(batch_size, n_classes, n_patches, h, w)\n patch_to_image = data[\"patch_to_image\"]\n front_indices = patch_to_image <= 4\n side_indices = patch_to_image > 4\n\n log_segmentation = torch.log(segmentation[\"segs\"] + 1e-5).reshape(-1, ph, pw, n_classes).permute(0, 3, 1, 2)\n\n # Account for the invalids\n # TODO: Adjust the mean so that we don't have a low loss just because we have a lot of invalids\n invalid_segmentation = invalid_segmentation.squeeze(-1).to(torch.float32).reshape(-1, ph, pw)\n\n cp_loss = cp_loss_fn(\n ((1 - invalid_segmentation.contiguous()).unsqueeze(1) * log_segmentation.contiguous()).float(),\n ((1 - invalid_segmentation.contiguous()) * segmentation_gt.contiguous()).long())\n\n loss_segmentation += self.lambda_segmentation * cp_loss.item()\n\n loss += self.lambda_segmentation * cp_loss\n\n if self.use_automasking:\n thresh_gt = rgb_gt[..., -1:]\n rgb_coarse = rgb_coarse[..., :-1]\n rgb_fine = rgb_fine[..., :-1]\n rgb_gt = rgb_gt[..., :-1]\n\n rgb_coarse = rgb_coarse\n rgb_fine = rgb_fine\n rgb_gt = rgb_gt.unsqueeze(-2)\n\n using_fine = len(fine) > 0\n\n b, pc, h, w, nv, c = rgb_coarse.shape\n\n # Take minimum across all reconstructed views\n rgb_loss = self.rgb_coarse_crit(rgb_coarse, rgb_gt)\n rgb_loss = rgb_loss.amin(-2)\n\n if self.use_automasking:\n rgb_loss = torch.min(rgb_loss, thresh_gt)\n\n if self.ignore_invalid:\n rgb_loss = rgb_loss * (1 - invalid_coarse.to(torch.float32))\n\n if self.median_thresholding:\n threshold = torch.median(rgb_loss.view(b, -1), dim=-1)[0].view(-1, 1, 1, 1, 1)\n rgb_loss = rgb_loss[rgb_loss <= threshold]\n\n rgb_loss = rgb_loss.mean()\n\n loss_coarse_all += rgb_loss.item() * self.lambda_coarse\n if using_fine:\n fine_loss = self.rgb_fine_crit(rgb_fine, rgb_gt)\n fine_loss = fine_loss.amin(-2)\n\n if self.use_automasking:\n fine_loss = torch.min(fine_loss, thresh_gt)\n\n if self.ignore_invalid:\n fine_loss = fine_loss * (1 - invalid_fine.to(torch.float32))\n\n if self.median_thresholding:\n threshold = torch.median(fine_loss.view(b, -1), dim=-1)[0].view(-1, 1, 1, 1, 1)\n fine_loss = fine_loss[fine_loss <= threshold]\n\n fine_loss = fine_loss.mean()\n rgb_loss = rgb_loss * self.lambda_coarse + fine_loss * self.lambda_fine\n loss_fine_all += fine_loss.item() * self.lambda_fine\n else:\n loss_dict[\"loss_rgb_fine\"] = 0\n\n loss += rgb_loss\n\n if self.lambda_depth_reg > 0:\n depths = coarse[\"depth\"]\n diffs_x = depths[:, :, 1:, :] - depths[:, :, :-1, :]\n diffs_y = depths[:, :, :, 1:] - depths[:, :, :, :-1]\n loss_depth_reg_s = (diffs_x ** 2).mean() + (diffs_y ** 2).mean()\n loss_depth_reg += loss_depth_reg_s # * self.lambda_depth_reg\n loss += loss_depth_reg_s * self.lambda_depth_reg\n\n if self.lambda_alpha_reg > 0:\n alphas = coarse[\"alphas\"]\n n_smps = alphas.shape[-1]\n\n # alphas = alphas[..., :-1].sum(-1)\n # loss_alpha_reg_s = (alphas - (n_smps * self.alpha_reg_fraction)).clamp_min(0)\n # if self.ignore_invalid:\n # loss_alpha_reg_s = loss_alpha_reg_s * (1 - invalid_coarse.squeeze(-1).to(torch.float32))\n\n alpha_sum = alphas[..., :-1].sum(-1)\n min_cap = torch.ones_like(alpha_sum) * (n_smps * self.alpha_reg_fraction)\n\n if self.ignore_invalid:\n alpha_sum = alpha_sum * (1 - invalid_coarse.squeeze(-1).to(torch.float32))\n min_cap = min_cap * (1 - invalid_coarse.squeeze(-1).to(torch.float32))\n\n if self.alpha_reg_reduction == \"ray\":\n loss_alpha_reg_s = (alpha_sum - min_cap).clamp_min(0)\n elif self.alpha_reg_reduction == \"slice\":\n loss_alpha_reg_s = (alpha_sum.sum(dim=-1) - min_cap.sum(dim=-1)).clamp_min(0) / alpha_sum.shape[-1]\n\n # alphas = alphas[..., :-n_smps//16]\n # alpha_deltas = alphas[..., 1:] - alphas[..., :-1]\n # The sum of deltas should be zero. This means that the number of peaks (ie objects) is not limited, but there needs to be free space afterwards again.\n # We don't consider the last 1/16 samples. They are likely background.\n # loss_alpha_reg_s = alpha_deltas.sum(-1).clamp_min(0)\n\n loss_alpha_reg_s = loss_alpha_reg_s.mean()\n\n loss_alpha_reg += loss_alpha_reg_s\n loss += loss_alpha_reg_s * self.lambda_alpha_reg\n\n if self.lambda_surfaceness_reg > 0:\n alphas = coarse[\"alphas\"]\n n_smps = alphas.shape[-1]\n\n p = -torch.log(torch.exp(-alphas.abs()) + torch.exp(-(1 - alphas).abs()))\n p = p.mean(-1)\n\n if self.ignore_invalid:\n p = p * (1 - invalid_coarse.squeeze(-1).to(torch.float32))\n\n loss_surfaceness_reg_s = p.mean()\n\n loss_surfaceness_reg += loss_surfaceness_reg_s\n loss += loss_surfaceness_reg_s * self.lambda_surfaceness_reg\n\n if self.lambda_edge_aware_smoothness > 0:\n gt_img = rgb_gt\n depths = coarse[\"depth\"]\n loss_eas_s = edge_aware_smoothness(gt_img, depths)\n\n if self.ignore_invalid:\n invalid_scale = torch.ceil(F.interpolate(invalid_coarse.squeeze(-1).to(torch.float32), size=(depths.shape[-2:])))\n loss_eas_s = loss_eas_s * (1 - invalid_scale)\n\n loss_eas_s = loss_eas_s.mean()\n\n loss_eas += loss_eas_s\n loss += loss_eas_s * self.lambda_edge_aware_smoothness / (2 ** scale)\n\n if self.lambda_depth_smoothness > 0:\n depths = coarse[\"depth\"]\n loss_depth_smoothness_s = ((depths[..., :-1, :] - depths[..., 1:, :]) ** 2).mean() + ((depths[..., :, :-1] - depths[..., :, 1:]) ** 2).mean()\n\n loss_depth_smoothness += loss_depth_smoothness_s\n loss += loss_depth_smoothness_s * self.lambda_depth_smoothness\n\n\n loss = loss / n_scales\n\n loss_ray_entropy = torch.tensor(0.0, device=loss.device)\n if self.lambda_entropy > 0:\n alphas = coarse_0[\"alphas\"]\n alphas = alphas + 1e-5\n\n ray_density = alphas / alphas.sum(dim=-1, keepdim=True)\n ray_entropy = -(ray_density * torch.log(ray_density)).sum(-1) / (math.log2(alphas.shape[-1]))\n ray_entropy = ray_entropy * (1 - invalid_coarse.squeeze(-1).to(torch.float32))\n loss_ray_entropy = ray_entropy.mean()\n\n loss = loss + loss_ray_entropy * self.lambda_entropy\n\n # add density entropy loss\n loss_density_entropy = torch.tensor(0.0, device=loss.device)\n\n if self.lambda_density_entropy > 0:\n alphas = coarse_0[\"alphas\"]\n alphas = alphas + 1e-5\n density_entropy = (1 - alphas)*alphas\n loss_density_entropy = torch.mean(density_entropy) * self.lambda_density_entropy\n\n loss = loss + loss_density_entropy\n\n loss_dict[\"loss_rgb_coarse\"] = loss_coarse_all\n loss_dict[\"loss_rgb_fine\"] = loss_fine_all\n loss_dict[\"loss_segmentation\"] = loss_segmentation\n loss_dict[\"loss_ray_entropy\"] = loss_ray_entropy.item()\n loss_dict[\"loss_density_entropy\"] = loss_density_entropy.item()\n loss_dict[\"loss_depth_reg\"] = loss_depth_reg.item()\n loss_dict[\"loss_alpha_reg\"] = loss_alpha_reg.item()\n loss_dict[\"loss_eas\"] = loss_eas.item()\n loss_dict[\"loss_depth_smoothness\"] = loss_depth_smoothness.item()\n loss_dict[\"loss_invalid_ratio\"] = invalid_coarse.float().mean().item()\n loss_dict[\"loss\"] = loss.item()\n\n return loss, loss_dict" }, { "identifier": "BTSNet", "path": "models/bts/model/models_bts.py", "snippet": "class BTSNet(torch.nn.Module):\n def __init__(self, conf):\n super().__init__()\n\n self.d_min = conf.get(\"z_near\")\n self.d_max = conf.get(\"z_far\")\n\n self.learn_empty = conf.get(\"learn_empty\", True)\n self.empty_empty = conf.get(\"empty_empty\", False)\n self.inv_z = conf.get(\"inv_z\", True)\n\n self.color_interpolation = conf.get(\"color_interpolation\", \"bilinear\")\n self.code_mode = conf.get(\"code_mode\", \"z\")\n if self.code_mode not in [\"z\", \"distance\"]:\n raise NotImplementedError(f\"Unknown mode for positional encoding: {self.code_mode}\")\n\n self.encoder = make_backbone(conf[\"encoder\"])\n self.code_xyz = PositionalEncoding.from_conf(conf[\"code\"], d_in=3)\n\n self.flip_augmentation = conf.get(\"flip_augmentation\", False)\n\n self.return_sample_depth = conf.get(\"return_sample_depth\", False)\n\n self.sample_color = conf.get(\"sample_color\", True)\n\n d_in = self.encoder.latent_size + self.code_xyz.d_out\n d_out = 1 if self.sample_color else 4\n\n self._d_in = d_in\n self._d_out = d_out\n\n self.mlp_coarse = make_mlp(conf[\"mlp_coarse\"], d_in, d_out=d_out)\n self.mlp_fine = make_mlp(conf[\"mlp_fine\"], d_in, d_out=d_out, allow_empty=True)\n\n # MLP for segmentation classes\n # TODO: Find the output dimensions automatically\n self.segmentation_mode = conf.get('segmentation_mode', None)\n if self.segmentation_mode == 'KITTI-360':\n self.mlp_segmentation = make_mlp(conf[\"mlp_coarse\"], d_in, d_out=21)\n # self.mlp_segmentation = make_segnet(d_in=d_in, d_out=21, d_hidden_list=[64])\n elif self.segmentation_mode == 'panoptic_deeplab':\n # self.mlp_segmentation = make_mlp(conf[\"mlp_coarse\"], d_in, d_out=19)\n self.mlp_segmentation = make_segnet(d_in=d_in, d_out=19, d_hidden_list=[64])\n # self.mlp_segmentation = make_intercept_model(d_in, d_out=21)\n\n if self.learn_empty:\n self.empty_feature = nn.Parameter(torch.randn((self.encoder.latent_size,), requires_grad=True))\n\n self._scale = 0\n\n def set_scale(self, scale):\n self._scale = scale\n\n def get_scale(self):\n return self._scale\n\n def compute_grid_transforms(self, *args, **kwargs):\n pass\n\n def encode(self, images, Ks, poses_c2w, ids_encoder=None, ids_render=None, images_alt=None, combine_ids=None):\n poses_w2c = torch.inverse(poses_c2w)\n\n if ids_encoder is None:\n images_encoder = images\n Ks_encoder = Ks\n poses_w2c_encoder = poses_w2c\n ids_encoder = list(range(len(images)))\n else:\n images_encoder = images[:, ids_encoder]\n Ks_encoder = Ks[:, ids_encoder]\n poses_w2c_encoder = poses_w2c[:, ids_encoder]\n\n if images_alt is not None:\n images = images_alt\n else:\n images = images * .5 + .5\n\n if ids_render is None:\n images_render = images\n Ks_render = Ks\n poses_w2c_render = poses_w2c\n ids_render = list(range(len(images)))\n else:\n images_render = images[:, ids_render]\n Ks_render = Ks[:, ids_render]\n poses_w2c_render = poses_w2c[:, ids_render]\n\n if combine_ids is not None:\n combine_ids = list(list(group) for group in combine_ids)\n get_combined = set(sum(combine_ids, []))\n for i in range(images.shape[1]):\n if i not in get_combined:\n combine_ids.append((i,))\n remap_encoder = {v: i for i, v in enumerate(ids_encoder)}\n remap_render = {v: i for i, v in enumerate(ids_render)}\n comb_encoder = [[remap_encoder[i] for i in group if i in ids_encoder] for group in combine_ids]\n comb_render = [[remap_render[i] for i in group if i in ids_render] for group in combine_ids]\n comb_encoder = [group for group in comb_encoder if len(group) > 0]\n comb_render = [group for group in comb_render if len(group) > 0]\n else:\n comb_encoder = None\n comb_render = None\n\n n, nv, c, h, w = images_encoder.shape\n c_l = self.encoder.latent_size\n\n if self.flip_augmentation and self.training:\n do_flip = (torch.rand(1) > .5).item()\n else:\n do_flip = False\n\n if do_flip:\n images_encoder = torch.flip(images_encoder, dims=(-1, ))\n\n image_latents_ms = self.encoder(images_encoder.view(n * nv, c, h, w))\n\n if do_flip:\n image_latents_ms = [torch.flip(il, dims=(-1, )) for il in image_latents_ms]\n\n _, _, h_, w_ = image_latents_ms[0].shape\n image_latents_ms = [F.interpolate(image_latents, (h_, w_)).view(n, nv, c_l, h_, w_) for image_latents in image_latents_ms]\n\n if torch.any(torch.isnan(torch.stack(image_latents_ms))):\n self.encoder(images_encoder.view(n * nv, c, h, w))\n # raise Exception(\"NaN in encoded features.\")\n\n self.grid_f_features = image_latents_ms\n self.grid_f_Ks = Ks_encoder\n self.grid_f_poses_w2c = poses_w2c_encoder\n self.grid_f_combine = comb_encoder\n\n self.grid_c_imgs = images_render\n self.grid_c_Ks = Ks_render\n self.grid_c_poses_w2c = poses_w2c_render\n self.grid_c_combine = comb_render\n\n def sample_features(self, xyz, use_single_featuremap=True):\n n, n_pts, _ = xyz.shape\n n, nv, c, h, w = self.grid_f_features[self._scale].shape\n\n # if use_single_featuremap:\n # nv = 1\n\n xyz = xyz.unsqueeze(1) # (n, 1, pts, 3)\n ones = torch.ones_like(xyz[..., :1])\n xyz = torch.cat((xyz, ones), dim=-1)\n xyz_projected = ((self.grid_f_poses_w2c[:, :nv, :3, :]) @ xyz.permute(0, 1, 3, 2))\n distance = torch.norm(xyz_projected, dim=-2).unsqueeze(-1)\n xyz_projected = (self.grid_f_Ks[:, :nv] @ xyz_projected).permute(0, 1, 3, 2)\n xy = xyz_projected[:, :, :, [0, 1]]\n z = xyz_projected[:, :, :, 2:3]\n\n xy = xy / z.clamp_min(EPS)\n invalid = (z <= EPS) | (xy[:, :, :, :1] < -1) | (xy[:, :, :, :1] > 1) | (xy[:, :, :, 1:2] < -1) | (xy[:, :, :, 1:2] > 1)\n\n if self.code_mode == \"z\":\n # Get z into [-1, 1] range\n if self.inv_z:\n z = (1 / z.clamp_min(EPS) - 1 / self.d_max) / (1 / self.d_min - 1 / self.d_max)\n else:\n z = (z - self.d_min) / (self.d_max - self.d_min)\n z = 2 * z - 1\n xyz_projected = torch.cat((xy, z), dim=-1)\n elif self.code_mode == \"distance\":\n if self.inv_z:\n distance = (1 / distance.clamp_min(EPS) - 1 / self.d_max) / (1 / self.d_min - 1 / self.d_max)\n else:\n distance = (distance - self.d_min) / (self.d_max - self.d_min)\n distance = 2 * distance - 1\n xyz_projected = torch.cat((xy, distance), dim=-1)\n xyz_code = self.code_xyz(xyz_projected.view(n * nv * n_pts, -1)).view(n, nv, n_pts, -1)\n\n feature_map = self.grid_f_features[self._scale][:, :nv]\n # These samples are from different scales\n if self.learn_empty:\n empty_feature_expanded = self.empty_feature.view(1, 1, 1, c).expand(n, nv, n_pts, c)\n\n sampled_features = F.grid_sample(feature_map.view(n * nv, c, h, w), xy.view(n * nv, 1, -1, 2), mode=\"bilinear\", padding_mode=\"border\", align_corners=False).view(n, nv, c, n_pts).permute(0, 1, 3, 2)\n\n if self.learn_empty:\n sampled_features[invalid.expand(-1, -1, -1, c)] = empty_feature_expanded[invalid.expand(-1, -1, -1, c)]\n\n sampled_features = torch.cat((sampled_features, xyz_code), dim=-1)\n\n # If there are multiple frames with predictions, reduce them.\n # TODO: Technically, this implementations should be improved if we use multiple frames.\n # The reduction should only happen after we perform the unprojection.\n\n if self.grid_f_combine is not None:\n invalid_groups = []\n sampled_features_groups = []\n\n for group in self.grid_f_combine:\n if len(group) == 1:\n invalid_groups.append(invalid[:, group])\n sampled_features_groups.append(sampled_features[:, group])\n\n invalid_to_combine = invalid[:, group]\n features_to_combine = sampled_features[:, group]\n\n indices = torch.min(invalid_to_combine, dim=1, keepdim=True)[1]\n invalid_picked = torch.gather(invalid_to_combine, dim=1, index=indices)\n features_picked = torch.gather(features_to_combine, dim=1, index=indices.expand(-1, -1, -1, features_to_combine.shape[-1]))\n\n invalid_groups.append(invalid_picked)\n sampled_features_groups.append(features_picked)\n\n invalid = torch.cat(invalid_groups, dim=1)\n sampled_features = torch.cat(sampled_features_groups, dim=1)\n\n if use_single_featuremap:\n sampled_features = sampled_features.mean(dim=1)\n invalid = torch.any(invalid, dim=1)\n\n return sampled_features, invalid\n\n def sample_colors(self, xyz):\n n, n_pts, _ = xyz.shape\n n, nv, c, h, w = self.grid_c_imgs.shape\n xyz = xyz.unsqueeze(1) # (n, 1, pts, 3)\n ones = torch.ones_like(xyz[..., :1])\n xyz = torch.cat((xyz, ones), dim=-1)\n xyz_projected = ((self.grid_c_poses_w2c[:, :, :3, :]) @ xyz.permute(0, 1, 3, 2))\n distance = torch.norm(xyz_projected, dim=-2).unsqueeze(-1)\n xyz_projected = (self.grid_c_Ks @ xyz_projected).permute(0, 1, 3, 2)\n xy = xyz_projected[:, :, :, [0, 1]]\n z = xyz_projected[:, :, :, 2:3]\n\n # This scales the x-axis into the right range.\n xy = xy / z.clamp_min(EPS)\n invalid = (z <= EPS) | (xy[:, :, :, :1] < -1) | (xy[:, :, :, :1] > 1) | (xy[:, :, :, 1:2] < -1) | (xy[:, :, :, 1:2] > 1)\n\n sampled_colors = F.grid_sample(self.grid_c_imgs.view(n * nv, c, h, w), xy.view(n * nv, 1, -1, 2), mode=self.color_interpolation, padding_mode=\"border\", align_corners=False).view(n, nv, c, n_pts).permute(0, 1, 3, 2)\n assert not torch.any(torch.isnan(sampled_colors))\n\n if self.grid_c_combine is not None:\n invalid_groups = []\n sampled_colors_groups = []\n\n for group in self.grid_c_combine:\n if len(group) == 1:\n invalid_groups.append(invalid[:, group])\n sampled_colors_groups.append(sampled_colors[:, group])\n continue\n\n invalid_to_combine = invalid[:, group]\n colors_to_combine = sampled_colors[:, group]\n\n indices = torch.min(invalid_to_combine, dim=1, keepdim=True)[1]\n invalid_picked = torch.gather(invalid_to_combine, dim=1, index=indices)\n colors_picked = torch.gather(colors_to_combine, dim=1, index=indices.expand(-1, -1, -1, colors_to_combine.shape[-1]))\n\n invalid_groups.append(invalid_picked)\n sampled_colors_groups.append(colors_picked)\n\n invalid = torch.cat(invalid_groups, dim=1)\n sampled_colors = torch.cat(sampled_colors_groups, dim=1)\n\n if self.return_sample_depth:\n distance = distance.view(n, nv, n_pts, 1)\n sampled_colors = torch.cat((sampled_colors, distance), dim=-1)\n\n return sampled_colors, invalid\n\n def forward(self, xyz, coarse=True, viewdirs=None, far=False, only_density=False, predict_segmentation=False):\n \"\"\"\n Predict (r, g, b, sigma) at world space points xyz.\n Please call encode first!\n :param xyz (B, 3)\n B is batch of points (in rays)\n :param predict_segmentation, if true also return the segmentation distribution for all the points\n :return (B, 4) r g b sigma\n \"\"\"\n\n with profiler.record_function(\"model_inference\"):\n n, n_pts, _ = xyz.shape\n nv = self.grid_c_imgs.shape[1]\n\n if self.grid_c_combine is not None:\n nv = len(self.grid_c_combine)\n\n # Sampled features all has shape: scales [n, n_pts, c + xyz_code]\n sampled_features, invalid_features = self.sample_features(xyz, use_single_featuremap=not only_density) # invalid features (n, n_pts, 1)\n sampled_features = sampled_features.reshape(n * n_pts, -1)\n\n mlp_input = sampled_features.view(n, n_pts, -1)\n\n # Camera frustum culling stuff, currently disabled\n combine_index = None\n dim_size = None\n\n # Run main NeRF network\n if coarse or self.mlp_fine is None:\n mlp_output = self.mlp_coarse(\n mlp_input,\n combine_inner_dims=(n_pts,),\n combine_index=combine_index,\n dim_size=dim_size,\n )\n else:\n mlp_output = self.mlp_fine(\n mlp_input,\n combine_inner_dims=(n_pts,),\n combine_index=combine_index,\n dim_size=dim_size,\n )\n\n segs = None\n if predict_segmentation:\n segs = self.mlp_segmentation(mlp_input)\n # print(next(self.mlp_segmentation.parameters()))\n # softmax to get a class distribution\n segs = F.softmax(segs, dim=2)\n # (n, pts, c) -> (n, n_pts, c)\n mlp_output = mlp_output.reshape(n, n_pts, self._d_out)\n\n if self.sample_color:\n sigma = mlp_output[..., :1]\n sigma = F.softplus(sigma)\n rgb, invalid_colors = self.sample_colors(xyz) # (n, nv, pts, 3)\n else:\n sigma = mlp_output[..., :1]\n sigma = F.relu(sigma)\n rgb = mlp_output[..., 1:4].reshape(n, 1, n_pts, 3)\n rgb = F.sigmoid(rgb)\n invalid_colors = invalid_features.unsqueeze(-2)\n nv = 1\n\n if self.empty_empty:\n sigma[invalid_features[..., 0]] = 0\n # TODO: Think about this!\n # Since we don't train the colors directly, lets use softplus instead of relu\n\n if not only_density:\n _, _, _, c = rgb.shape\n rgb = rgb.permute(0, 2, 1, 3).reshape(n, n_pts, nv * c) # (n, pts, nv * 3)\n invalid_colors = invalid_colors.permute(0, 2, 1, 3).reshape(n, n_pts, nv)\n\n invalid = invalid_colors | invalid_features # Invalid features gets broadcasted to (n, n_pts, nv)\n invalid = invalid.to(rgb.dtype)\n else:\n rgb = torch.zeros((n, n_pts, nv * 3), device=sigma.device)\n invalid = invalid_features.to(sigma.dtype)\n\n if predict_segmentation:\n return rgb, invalid, sigma, segs\n else:\n return rgb, invalid, sigma" }, { "identifier": "ImageRaySampler", "path": "models/bts/model/ray_sampler.py", "snippet": "class ImageRaySampler(RaySampler):\n def __init__(self, z_near, z_far, height=None, width=None, channels=3, norm_dir=True):\n self.z_near = z_near\n self.z_far = z_far\n self.height = height\n self.width = width\n self.channels = channels\n self.norm_dir = norm_dir\n\n def sample(self, images, poses, projs, segs=None, sample_segs=False):\n n, v, _, _ = poses.shape\n\n if self.height is None:\n self.height, self.width = images.shape[-2:]\n\n all_rgb_gt = []\n all_rays = []\n all_segs_gt = []\n\n for n_ in range(n):\n focals = projs[n_, :, [0, 1], [0, 1]]\n centers = projs[n_, :, [0, 1], [2, 2]]\n\n rays = util.gen_rays(poses[n_].view(-1, 4, 4), self.width, self.height, focal=focals, c=centers, z_near=self.z_near, z_far=self.z_far, norm_dir=self.norm_dir).view(-1, 8)\n all_rays.append(rays)\n\n if images is not None:\n rgb_gt = images[n_].view(-1, self.channels, self.height, self.width)\n rgb_gt = (rgb_gt.permute(0, 2, 3, 1).contiguous().reshape(-1, self.channels))\n all_rgb_gt.append(rgb_gt)\n\n if sample_segs:\n segs_gt = segs[n_].view(-1, 1, self.height, self.width)\n segs_gt = (segs_gt.permute(0, 2, 3, 1).contiguous().reshape(-1, 1))\n all_segs_gt.append(segs_gt)\n\n all_rays = torch.stack(all_rays)\n if images is not None:\n all_rgb_gt = torch.stack(all_rgb_gt)\n else:\n all_rgb_gt = None\n\n if sample_segs:\n all_segs_gt = torch.stack(all_segs_gt)\n # the None accounts for the patch_to_image\n return all_rays, all_rgb_gt, all_segs_gt, None\n else:\n return all_rays, all_rgb_gt\n\n def reconstruct(self, render_dict, channels=None, reconstruct_segmentation=False):\n coarse = render_dict[\"coarse\"]\n fine = render_dict[\"fine\"]\n\n if channels is None:\n channels = self.channels\n\n if reconstruct_segmentation:\n c_segmentation = coarse[\"segs\"]\n # c_segmentation_raw = coarse[\"segs_raw\"]\n n_classes = c_segmentation.shape[-1]\n # n_samples = c_segmentation_raw.shape[-2]\n\n c_rgb = coarse[\"rgb\"] # n, n_pts, v * 3\n c_weights = coarse[\"weights\"]\n c_depth = coarse[\"depth\"]\n c_invalid = coarse[\"invalid\"]\n\n f_rgb = fine[\"rgb\"] # n, n_pts, v * 3\n f_weights = fine[\"weights\"]\n f_depth = fine[\"depth\"]\n f_invalid = fine[\"invalid\"]\n\n n, n_pts, v_c = c_rgb.shape\n v_in = n_pts // (self.height * self.width)\n v_render = v_c // channels\n c_n_smps = c_weights.shape[-1]\n f_n_smps = f_weights.shape[-1]\n # (This can be a different v from the sample method)\n\n if reconstruct_segmentation:\n coarse[\"segs\"] = c_segmentation.view(n, v_in, self.height, self.width, n_classes)\n # coarse[\"segs_raw\"] = c_segmentation_raw.view(n, v_in, self.height, self.width, n_samples, n_classes)\n\n coarse[\"rgb\"] = c_rgb.view(n, v_in, self.height, self.width, v_render, channels)\n coarse[\"weights\"] = c_weights.view(n, v_in, self.height, self.width, c_n_smps)\n coarse[\"depth\"] = c_depth.view(n, v_in, self.height, self.width)\n coarse[\"invalid\"] = c_invalid.view(n, v_in, self.height, self.width, c_n_smps, v_render)\n\n fine[\"rgb\"] = f_rgb.view(n, v_in, self.height, self.width, v_render, channels)\n fine[\"weights\"] = f_weights.view(n, v_in, self.height, self.width, f_n_smps)\n fine[\"depth\"] = f_depth.view(n, v_in, self.height, self.width)\n fine[\"invalid\"] = f_invalid.view(n, v_in, self.height, self.width, f_n_smps, v_render)\n\n if \"alphas\" in coarse:\n c_alphas = coarse[\"alphas\"]\n f_alphas = fine[\"alphas\"]\n coarse[\"alphas\"] = c_alphas.view(n, v_in, self.height, self.width, c_n_smps)\n fine[\"alphas\"] = f_alphas.view(n, v_in, self.height, self.width, f_n_smps)\n\n if \"z_samps\" in coarse:\n c_z_samps = coarse[\"z_samps\"]\n f_z_samps = fine[\"z_samps\"]\n coarse[\"z_samps\"] = c_z_samps.view(n, v_in, self.height, self.width, c_n_smps)\n fine[\"z_samps\"] = f_z_samps.view(n, v_in, self.height, self.width, f_n_smps)\n\n if \"rgb_samps\" in coarse:\n c_rgb_samps = coarse[\"rgb_samps\"]\n f_rgb_samps = fine[\"rgb_samps\"]\n coarse[\"rgb_samps\"] = c_rgb_samps.view(n, v_in, self.height, self.width, c_n_smps, v_render, channels)\n fine[\"rgb_samps\"] = f_rgb_samps.view(n, v_in, self.height, self.width, f_n_smps, v_render, channels)\n\n render_dict[\"coarse\"] = coarse\n render_dict[\"fine\"] = fine\n\n if \"rgb_gt\" in render_dict:\n rgb_gt = render_dict[\"rgb_gt\"]\n render_dict[\"rgb_gt\"] = rgb_gt.view(n, v_in, self.height, self.width, channels)\n\n return render_dict" }, { "identifier": "PatchRaySampler", "path": "models/bts/model/ray_sampler.py", "snippet": "class PatchRaySampler(RaySampler):\n def __init__(self, ray_batch_size, z_near, z_far, patch_size, channels=3):\n self.ray_batch_size = ray_batch_size\n self.z_near = z_near\n self.z_far = z_far\n if isinstance(patch_size, int):\n self.patch_size_x, self.patch_size_y = patch_size, patch_size\n elif isinstance(patch_size, tuple) or isinstance(patch_size, list) or isinstance(patch_size, ListConfig):\n self.patch_size_y = patch_size[0]\n self.patch_size_x = patch_size[1]\n else:\n raise ValueError(f\"Invalid format for patch size\")\n self.channels = channels\n assert (ray_batch_size % (self.patch_size_x * self.patch_size_y)) == 0\n self._patch_count = self.ray_batch_size // (self.patch_size_x * self.patch_size_y)\n\n def sample(self, images, poses, projs, segs=None, sample_segs=False):\n n, v, c, h, w = images.shape\n device = images.device\n\n images = images.permute(0, 1, 3, 4, 2) # n, v, h, w, c\n\n all_rgb_gt = []\n all_rays = []\n all_segs_gt = []\n\n patch_coords_v_list = []\n\n for n_ in range(n):\n focals = projs[n_, :, [0, 1], [0, 1]]\n centers = projs[n_, :, [0, 1], [2, 2]]\n\n rays = util.gen_rays(poses[n_].view(-1, 4, 4), w, h, focal=focals, c=centers, z_near=self.z_near, z_far=self.z_far)\n\n patch_coords_v = torch.randint(0, v, (self._patch_count, ))\n patch_coords_y = torch.randint(0, h-self.patch_size_y, (self._patch_count, ))\n patch_coords_x = torch.randint(0, w-self.patch_size_x, (self._patch_count, ))\n\n patch_coords_v_list.append(patch_coords_v)\n\n sample_rgb_gt = []\n sample_rays = []\n sample_segs_gt = []\n\n for v_, y, x in zip(patch_coords_v, patch_coords_y, patch_coords_x):\n rgb_gt_patch = images[n_][v_, y:y+self.patch_size_y, x:x+self.patch_size_x, :].reshape(-1, self.channels)\n rays_patch = rays[v_, y:y+self.patch_size_y, x:x+self.patch_size_x, :].reshape(-1, 8)\n\n if sample_segs:\n segs_gt_patch = segs[n_][v_, y:y + self.patch_size_y, x:x + self.patch_size_x].reshape(-1)\n sample_segs_gt.append(segs_gt_patch)\n\n sample_rgb_gt.append(rgb_gt_patch)\n sample_rays.append(rays_patch)\n\n sample_rgb_gt = torch.cat(sample_rgb_gt, dim=0)\n sample_rays = torch.cat(sample_rays, dim=0)\n\n if sample_segs:\n sample_segs_gt = torch.cat(sample_segs_gt, dim=0)\n\n all_rgb_gt.append(sample_rgb_gt)\n all_rays.append(sample_rays)\n all_segs_gt.append(sample_segs_gt)\n\n all_rgb_gt = torch.stack(all_rgb_gt)\n all_rays = torch.stack(all_rays)\n\n patch_coords_v = torch.cat(patch_coords_v_list)\n\n if sample_segs:\n all_segs_gt = torch.stack(all_segs_gt)\n\n if sample_segs:\n return all_rays, all_rgb_gt, all_segs_gt, patch_coords_v\n else:\n return all_rays, all_rgb_gt\n\n def reconstruct(self, render_dict, channels=None, reconstruct_segmentation=False):\n coarse = render_dict[\"coarse\"]\n fine = render_dict[\"fine\"]\n\n if channels is None:\n channels = self.channels\n\n c_rgb = coarse[\"rgb\"] # n, n_pts, v * 3\n c_weights = coarse[\"weights\"]\n c_depth = coarse[\"depth\"]\n c_invalid = coarse[\"invalid\"]\n\n if reconstruct_segmentation:\n c_segmentation = coarse[\"segs\"]\n c_segmentation_gt = render_dict[\"segmentation_gt\"]\n # c_segmentation_raw = coarse[\"segs_raw\"]\n n_classes = c_segmentation.shape[-1]\n # n_samples = c_segmentation_raw.shape[-2]\n\n f_rgb = fine[\"rgb\"] # n, n_pts, v * 3\n f_weights = fine[\"weights\"]\n f_depth = fine[\"depth\"]\n f_invalid = fine[\"invalid\"]\n\n rgb_gt = render_dict[\"rgb_gt\"]\n\n n, n_pts, v_c = c_rgb.shape\n v = v_c // channels\n c_n_smps = c_weights.shape[-1]\n f_n_smps = f_weights.shape[-1]\n # (This can be a different v from the sample method)\n\n coarse[\"rgb\"] = c_rgb.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, v, channels)\n coarse[\"weights\"] = c_weights.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, c_n_smps)\n coarse[\"depth\"] = c_depth.view(n, self._patch_count, self.patch_size_y, self.patch_size_x)\n coarse[\"invalid\"] = c_invalid.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, c_n_smps, v)\n\n if reconstruct_segmentation:\n coarse[\"segs\"] = c_segmentation.view(n, self._patch_count,\n self.patch_size_y, self.patch_size_x, n_classes)\n # coarse[\"segs_raw\"] = c_segmentation_raw.view(n, self._patch_count, self.patch_size_y, self.patch_size_x,\n # n_samples, n_classes)\n render_dict[\"segmentation_gt\"] = c_segmentation_gt.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, 1)\n\n fine[\"rgb\"] = f_rgb.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, v, channels)\n fine[\"weights\"] = f_weights.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, f_n_smps)\n fine[\"depth\"] = f_depth.view(n, self._patch_count, self.patch_size_y, self.patch_size_x)\n fine[\"invalid\"] = f_invalid.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, f_n_smps, v)\n\n if \"alphas\" in coarse:\n c_alphas = coarse[\"alphas\"]\n f_alphas = fine[\"alphas\"]\n coarse[\"alphas\"] = c_alphas.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, c_n_smps)\n fine[\"alphas\"] = f_alphas.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, f_n_smps)\n\n if \"z_samps\" in coarse:\n c_z_samps = coarse[\"z_samps\"]\n f_z_samps = fine[\"z_samps\"]\n coarse[\"z_samps\"] = c_z_samps.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, c_n_smps)\n fine[\"z_samps\"] = f_z_samps.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, f_n_smps)\n\n if \"rgb_samps\" in coarse:\n c_rgb_samps = coarse[\"rgb_samps\"]\n f_rgb_samps = fine[\"rgb_samps\"]\n coarse[\"rgb_samps\"] = c_rgb_samps.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, c_n_smps, v, channels)\n fine[\"rgb_samps\"] = f_rgb_samps.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, f_n_smps, v, channels)\n\n render_dict[\"coarse\"] = coarse\n render_dict[\"fine\"] = fine\n render_dict[\"rgb_gt\"] = rgb_gt.view(n, self._patch_count, self.patch_size_y, self.patch_size_x, channels)\n\n return render_dict" }, { "identifier": "RandomRaySampler", "path": "models/bts/model/ray_sampler.py", "snippet": "class RandomRaySampler(RaySampler):\n def __init__(self, ray_batch_size, z_near, z_far, channels=3):\n self.ray_batch_size = ray_batch_size\n self.z_near = z_near\n self.z_far = z_far\n self.channels = channels\n\n def sample(self, images, poses, projs):\n n, v, c, h, w = images.shape\n\n all_rgb_gt = []\n all_rays = []\n\n for n_ in range(n):\n focals = projs[n_, :, [0, 1], [0, 1]]\n centers = projs[n_, :, [0, 1], [2, 2]]\n\n rays = util.gen_rays(poses[n_].view(-1, 4, 4), w, h, focal=focals, c=centers, z_near=self.z_near, z_far=self.z_far).view(-1, 8)\n\n rgb_gt = images[n_].view(-1, self.channels, h, w)\n rgb_gt = (rgb_gt.permute(0, 2, 3, 1).contiguous().reshape(-1, self.channels))\n\n pix_inds = torch.randint(0, v * h * w, (self.ray_batch_size,))\n\n rgb_gt = rgb_gt[pix_inds]\n rays = rays[pix_inds]\n\n all_rgb_gt.append(rgb_gt)\n all_rays.append(rays)\n\n all_rgb_gt = torch.stack(all_rgb_gt)\n all_rays = torch.stack(all_rays)\n\n return all_rays, all_rgb_gt\n\n def reconstruct(self, render_dict, channels=None):\n coarse = render_dict[\"coarse\"]\n fine = render_dict[\"fine\"]\n\n if channels is None:\n channels = self.channels\n\n c_rgb = coarse[\"rgb\"] # n, n_pts, v * 3\n c_weights = coarse[\"weights\"]\n c_depth = coarse[\"depth\"]\n c_invalid = coarse[\"invalid\"]\n\n f_rgb = fine[\"rgb\"] # n, n_pts, v * 3\n f_weights = fine[\"weights\"]\n f_depth = fine[\"depth\"]\n f_invalid = fine[\"invalid\"]\n\n rgb_gt = render_dict[\"rgb_gt\"]\n\n n, n_pts, v_c = c_rgb.shape\n v = v_c // self.channels\n c_n_smps = c_weights.shape[-1]\n f_n_smps = f_weights.shape[-1]\n\n coarse[\"rgb\"] = c_rgb.view(n, n_pts, v, channels)\n coarse[\"weights\"] = c_weights.view(n, n_pts, c_n_smps)\n coarse[\"depth\"] = c_depth.view(n, n_pts)\n coarse[\"invalid\"] = c_invalid.view(n, n_pts, c_n_smps, v)\n\n fine[\"rgb\"] = f_rgb.view(n, n_pts, v, channels)\n fine[\"weights\"] = f_weights.view(n, n_pts, f_n_smps)\n fine[\"depth\"] = f_depth.view(n, n_pts)\n fine[\"invalid\"] = f_invalid.view(n, n_pts, f_n_smps, v)\n\n if \"alphas\" in coarse:\n c_alphas = coarse[\"alphas\"]\n f_alphas = fine[\"alphas\"]\n coarse[\"alphas\"] = c_alphas.view(n, n_pts, c_n_smps)\n fine[\"alphas\"] = f_alphas.view(n, n_pts, f_n_smps)\n\n if \"z_samps\" in coarse:\n c_z_samps = coarse[\"z_samps\"]\n f_z_samps = fine[\"z_samps\"]\n coarse[\"z_samps\"] = c_z_samps.view(n, n_pts, c_n_smps)\n fine[\"z_samps\"] = f_z_samps.view(n, n_pts, f_n_smps)\n\n if \"rgb_samps\" in coarse:\n c_rgb_samps = coarse[\"rgb_samps\"]\n f_rgb_samps = fine[\"rgb_samps\"]\n coarse[\"rgb_samps\"] = c_rgb_samps.view(n, n_pts, c_n_smps, v, channels)\n fine[\"rgb_samps\"] = f_rgb_samps.view(n, n_pts, f_n_smps, v, channels)\n\n render_dict[\"coarse\"] = coarse\n render_dict[\"fine\"] = fine\n render_dict[\"rgb_gt\"] = rgb_gt.view(n, n_pts, channels)\n\n return render_dict" }, { "identifier": "base_evaluation", "path": "utils/base_evaluator.py", "snippet": "def base_evaluation(local_rank, config, get_dataflow, initialize, get_metrics):\n rank = idist.get_rank()\n manual_seed(config[\"seed\"] + rank)\n device = idist.device()\n\n logger = setup_logger(name=config[\"name\"])\n\n log_basic_info(logger, config)\n\n output_path = config[\"output_path\"]\n if rank == 0:\n if config[\"stop_iteration\"] is None:\n now = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n else:\n now = f\"stop-on-{config['stop_iteration']}\"\n\n folder_name = f\"{config['name']}_backend-{idist.backend()}-{idist.get_world_size()}_{now}\"\n output_path = Path(output_path) / folder_name\n if not output_path.exists():\n output_path.mkdir(parents=True)\n config[\"output_path\"] = output_path.as_posix()\n logger.info(f\"Output path: {config['output_path']}\")\n\n if \"cuda\" in device.type:\n config[\"cuda device name\"] = torch.cuda.get_device_name(local_rank)\n\n # Setup dataflow, model, optimizer, criterion\n test_loader = get_dataflow(config)\n\n if hasattr(test_loader, \"dataset\"):\n logger.info(f\"Dataset length: Test: {len(test_loader.dataset)}\")\n\n config[\"num_iters_per_epoch\"] = len(test_loader)\n model = initialize(config, logger)\n\n cp_path = config[\"checkpoint\"]\n if not cp_path.endswith(\".pt\"):\n cp_path = Path(cp_path)\n cp_path = next(cp_path.glob(\"training*.pt\"))\n checkpoint = torch.load(cp_path, map_location=device)\n if \"model\" in checkpoint:\n model.load_state_dict(checkpoint[\"model\"], strict=False)\n else:\n model.load_state_dict(checkpoint, strict=False)\n model.to(device)\n\n logger.info(f\"Model parameters: {sum(p.numel() for p in model.parameters())}\")\n\n # Let's now setup evaluator engine to perform model's validation and compute metrics\n metrics = get_metrics(config, device)\n\n # We define two evaluators as they wont have exactly similar roles:\n # - `evaluator` will save the best model based on validation score\n evaluator = create_evaluator(model, metrics=metrics, config=config)\n\n evaluator.add_event_handler(Events.ITERATION_COMPLETED(every=config[\"log_every\"]), log_metrics_current(logger, metrics))\n\n try:\n state = evaluator.run(test_loader, max_epochs=1)\n log_metrics(logger, state.times[\"COMPLETED\"], \"Test\", state.metrics)\n logger.info(f\"Checkpoint: {str(cp_path)}\")\n except Exception as e:\n logger.exception(\"\")\n raise e" }, { "identifier": "MeanMetric", "path": "utils/metrics.py", "snippet": "class MeanMetric(Metric):\n def __init__(self, output_transform=lambda x: x[\"output\"], device=\"cpu\"):\n self._sum = None\n self._num_examples = None\n self.required_output_keys = ()\n super(MeanMetric, self).__init__(output_transform=output_transform, device=device)\n\n @reinit__is_reduced\n def reset(self):\n self._sum = torch.tensor(0, device=self._device, dtype=float)\n self._num_examples = 0\n super(MeanMetric, self).reset()\n\n @reinit__is_reduced\n def update(self, value):\n if torch.any(torch.isnan(torch.tensor(value))):\n return\n self._sum += value\n self._num_examples += 1\n\n @sync_all_reduce(\"_num_examples:SUM\", \"_sum:SUM\")\n def compute(self):\n if self._num_examples == 0:\n raise NotComputableError('CustomAccuracy must have at least one example before it can be computed.')\n return self._sum.item() / self._num_examples\n\n @torch.no_grad()\n def iteration_completed(self, engine: Engine) -> None:\n output = self._output_transform(engine.state.output)\n self.update(output)" }, { "identifier": "distance_to_z", "path": "utils/projection_operations.py", "snippet": "def distance_to_z(depths: torch.Tensor, projs: torch.Tensor):\n n, nv, h, w = depths.shape\n device = depths.device\n\n inv_K = torch.inverse(projs)\n\n grid_x = torch.linspace(-1, 1, w, device=device).view(1, 1, 1, -1).expand(-1, -1, h, -1)\n grid_y = torch.linspace(-1, 1, h, device=device).view(1, 1, -1, 1).expand(-1, -1, -1, w)\n img_points = torch.stack((grid_x, grid_y, torch.ones_like(grid_x)), dim=2).expand(n, nv, -1, -1, -1)\n cam_points = (inv_K @ img_points.view(n, nv, 3, -1)).view(n, nv, 3, h, w)\n factors = cam_points[:, :, 2, :, :] / torch.norm(cam_points, dim=2)\n\n return depths * factors" } ]
import math import torch import lpips import skimage.metrics from ignite.contrib.handlers import TensorboardLogger from ignite.engine import Engine from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader from datasets.data_util import make_test_dataset from models.common.render import NeRFRenderer from models.bts.model.image_processor import make_image_processor, RGBProcessor from models.bts.model.loss import ReconstructionLoss from models.bts.model.models_bts import BTSNet from models.bts.model.ray_sampler import ImageRaySampler, PatchRaySampler, RandomRaySampler from utils.base_evaluator import base_evaluation from utils.metrics import MeanMetric from utils.projection_operations import distance_to_z
20,642
IDX = 0 class BTSWrapper(nn.Module): def __init__(self, renderer, config, ) -> None: super().__init__() self.renderer = renderer self.z_near = config["z_near"] self.z_far = config["z_far"] self.ray_batch_size = config["ray_batch_size"]
IDX = 0 class BTSWrapper(nn.Module): def __init__(self, renderer, config, ) -> None: super().__init__() self.renderer = renderer self.z_near = config["z_near"] self.z_far = config["z_far"] self.ray_batch_size = config["ray_batch_size"]
self.sampler = ImageRaySampler(self.z_near, self.z_far)
6
2023-11-12 21:53:27+00:00
24k
newcastleuniversity/DISPEL
dispel/providers/generic/tasks/sbt_utt/sbt.py
[ { "identifier": "EntityType", "path": "dispel/data/core.py", "snippet": "class ReadingSchema:\nclass Evaluation(Epoch):\nclass Session(Epoch):\nclass Reading(FlagMixIn):\n def __init__(\n self,\n *args,\n uuid: str,\n finished: Optional[bool] = None,\n exit_reason: Optional[str] = None,\n user_id: Optional[str] = None,\n **kwargs,\n ):\n def to_dict(self):\n def __init__(\n self,\n *args,\n uuid: Optional[str] = None,\n evaluation_codes: Optional[Iterable[str]] = None,\n **kwargs,\n ):\n def __init__(\n self,\n evaluation: Evaluation,\n session: Optional[Session] = None,\n levels: Optional[Iterable[Level]] = None,\n measure_set: Optional[MeasureSet] = None,\n schema: Optional[ReadingSchema] = None,\n date: Any = None,\n device: Optional[Device] = None,\n ):\n def get_level(self, level_id: Optional[LevelIdType] = None) -> Level:\n def __repr__(self) -> str:\n def __iter__(self) -> Iterable[Tuple[LevelIdType, Level]]:\n def __len__(self) -> int:\n def empty(self) -> bool:\n def levels(self) -> ValuesView[Level]:\n def level_ids(self) -> List[LevelId]:\n def has_raw_data_set(\n self,\n data_set_id: str,\n level_id: LevelIdType,\n ) -> bool:\n def get_raw_data_set(\n self,\n data_set_id: str,\n level_id: LevelIdType,\n ) -> RawDataSet:\n def get_measure_set(self, level_id: Optional[LevelIdType] = None) -> MeasureSet:\n def get_merged_measure_set(self) -> MeasureSet:\n def set(self, value, **kwargs):\n def _get_level(self, level: Optional[Union[LevelIdType, Level]] = None) -> Level:\n def _measure_set(\n self,\n value: MeasureSet,\n level: Optional[Union[LevelIdType, Level]] = None,\n ):\n def _measure_value(\n self,\n value: MeasureValue,\n level: Optional[Union[LevelIdType, Level]] = None,\n epoch: Optional[LevelEpoch] = None,\n ):\n def _raw_data_set(\n self,\n value: RawDataSet,\n level: Union[LevelIdType, Level],\n concatenate: bool = False,\n overwrite: bool = False,\n ):\n def _epoch_measure_set(self, value: LevelEpoch, level: Union[LevelIdType, Level]):\n def _level(self, value: Level):\n def _set_flag(self, value: Flag):" }, { "identifier": "FlagSeverity", "path": "dispel/data/flags.py", "snippet": "class FlagSeverity(AVEnum):\n \"\"\"An enumeration for flag severity.\"\"\"\n\n DEVIATION = \"deviation\"\n INVALIDATION = \"invalidation\"" }, { "identifier": "FlagType", "path": "dispel/data/flags.py", "snippet": "class FlagType(AVEnum):\n \"\"\"An enumeration for flag types.\"\"\"\n\n TECHNICAL = \"technical\"\n BEHAVIORAL = \"behavioral\"" }, { "identifier": "Level", "path": "dispel/data/levels.py", "snippet": "class Level(Epoch):\n \"\"\"An entity to separate sub-task inside each test (Levels).\n\n FIXME: DOC\n\n Attributes\n ----------\n context\n Contextual information about the level\n measure_set\n A :class:'~dispel.data.measures.MeasureSet' of a given Level\n\n Parameters\n ----------\n id_\n The identifier of a given Level.\n start\n The timestamp of the beginning of the level\n end\n The timestamp of the end of the level\n context\n Contextual information about the level\n raw_data_sets\n An iterable of :class:'~dispel.data.raw.RawDataSet' of a given Level\n measure_set\n A :class:'~dispel.data.measures.MeasureSet' of a given Level\n epochs\n An iterable of :class:`~dispel.data.measures.EpochMeasureSet` to be added to the\n level.\n \"\"\"\n\n def __init__(\n self,\n id_: Union[str, List[str], LevelId],\n start: Any,\n end: Any,\n context: Optional[Context] = None,\n raw_data_sets: Optional[Iterable[RawDataSet]] = None,\n measure_set: Optional[MeasureSet] = None,\n epochs: Optional[Iterable[LevelEpoch]] = None,\n ):\n if not isinstance(id_, LevelId):\n id_ = LevelId(id_)\n\n definition = EpochDefinition(id_=id_)\n super().__init__(start=start, end=end, definition=definition)\n\n self.context = context or Context()\n self.measure_set = measure_set or MeasureSet()\n\n # create dictionary of raw data sets\n self._raw_data_sets: Dict[str, RawDataSet] = {}\n\n # set raw data sets if arg is provided\n if raw_data_sets:\n for raw_data_set in raw_data_sets:\n self.set(raw_data_set)\n\n # create data frame for each epoch\n self._epochs = pd.DataFrame(columns=[\"definition_id\", \"start\", \"end\", \"epoch\"])\n if epochs:\n for epoch in epochs:\n self.set(epoch)\n\n @property\n def id(self) -> LevelId:\n \"\"\"Get the ID of the level from its definition.\n\n Returns\n -------\n LevelId\n The ID of the definition provided via `definition`.\n \"\"\"\n assert self.definition is not None, \"Require definition to access id\"\n return cast(LevelId, self.definition.id)\n\n @id.setter\n def id(self, value: Union[str, DefinitionId]):\n \"\"\"Set the ID of the level's definition.\n\n Parameters\n ----------\n value\n The ID to be set.\n \"\"\"\n assert self.definition is not None, \"Require definition to set id\"\n self.definition.id = value # type: ignore\n\n def __hash__(self):\n return hash(self.id)\n\n def __repr__(self):\n return f\"<Level: {self.id} ({self.flag_count_repr})>\"\n\n @property\n def raw_data_sets(self) -> List[RawDataSet]:\n \"\"\"Get all raw data sets.\"\"\"\n return list(self._raw_data_sets.values())\n\n def has_raw_data_set(self, id_: str) -> bool:\n \"\"\"Return ``True`` if the level contains the desired raw data set.\"\"\"\n return id_ in self._raw_data_sets\n\n def get_raw_data_set(self, id_: str) -> RawDataSet:\n \"\"\"Get the raw data set for a given data set id.\n\n Parameters\n ----------\n id_\n The id of the raw data set to be returned\n\n Returns\n -------\n RawDataSet\n The raw data set with the matching id\n\n Raises\n ------\n ValueError\n If the given id does not correspond to any existing raw data set within the\n level.\n \"\"\"\n if id_ not in self._raw_data_sets:\n raise ValueError(\n f'Unknown data set with id: \"{id_}\" for level_id == \"{self.id}\" '\n f\"please provide an id within {list(self._raw_data_sets.keys())}\"\n )\n\n return self._raw_data_sets[id_]\n\n @property\n def epochs(self) -> List[LevelEpoch]:\n \"\"\"Get all epoch measure sets.\"\"\"\n return self._epochs[\"epoch\"].tolist()\n\n @singledispatchmethod\n def set(self, value, **kwargs):\n \"\"\"Set a value inside a level.\"\"\"\n raise TypeError(f\"Unsupported set type: {type(value)}\")\n\n @set.register(MeasureSet)\n def _set_measure_set(self, value: MeasureSet):\n self.measure_set += value\n\n @set.register(MeasureValue)\n def _set_measure_value(self, value: MeasureValue):\n self.measure_set.set(value)\n\n @set.register(RawDataSet)\n def _set_raw_data_set(\n self, value: RawDataSet, concatenate: bool = False, overwrite: bool = False\n ):\n if overwrite and concatenate:\n raise ValueError(\n \"You cannot both concatenate and overwrite an existing raw data set. \"\n \"Only one of these arguments must be set to ``True``.\"\n )\n\n if (id_ := value.id) in self._raw_data_sets: # pylint: disable=all\n if concatenate:\n value = value.concat(self.get_raw_data_set(id_))\n elif not overwrite:\n raise RawDataSetAlreadyExists(\n id_, self.id, \"Use overwrite=True to overwrite\"\n )\n\n self._raw_data_sets[id_] = value\n\n @set.register(LevelEpoch)\n def _set_epoch(self, value: LevelEpoch):\n new_index = len(self._epochs)\n self._epochs.loc[new_index] = pd.Series(\n dict(\n definition_id=value.id if value.definition else None,\n start=value.start,\n end=value.end,\n epoch=value,\n )\n )\n\n @set.register(Flag)\n def _set_flag(self, value: Flag):\n self.add_flag(value)" }, { "identifier": "MeasureValueDefinitionPrototype", "path": "dispel/data/measures.py", "snippet": "class MeasureValueDefinitionPrototype(ValueDefinitionPrototype):\n \"\"\"A task measure value definition prototype.\n\n This is a convenience method that populates the ``cls`` argument with the\n :class:`~dispel.data.measures.MeasureValueDefinition` class.\n \"\"\"\n\n def __init__(self, **kwargs: Any):\n cls = kwargs.pop(\"cls\", MeasureValueDefinition)\n super().__init__(cls=cls, **kwargs)" }, { "identifier": "ACCELEROMETER_COLUMNS", "path": "dispel/data/raw.py", "snippet": "ACCELEROMETER_COLUMNS = [f\"userAcceleration{x}\" for x in \"XYZ\"]" }, { "identifier": "RawDataValueDefinition", "path": "dispel/data/raw.py", "snippet": "class RawDataValueDefinition(ValueDefinition):\n \"\"\"The definition of raw data set values.\n\n Attributes\n ----------\n is_index\n ``True`` if the values are part of the raw data set index. Otherwise, ``False``.\n \"\"\"\n\n def __init__(\n self,\n id_: str,\n name: str,\n unit: Optional[str] = None,\n description: Optional[str] = None,\n data_type: Optional[str] = None,\n precision: Optional[int] = None,\n is_index: bool = False,\n ):\n super().__init__(\n id_=id_,\n name=name,\n unit=unit,\n description=description,\n data_type=data_type,\n precision=precision,\n )\n self.is_index = is_index" }, { "identifier": "GREATER_THAN_ZERO", "path": "dispel/data/validators.py", "snippet": "GREATER_THAN_ZERO = RangeValidator(lower_bound=0)" }, { "identifier": "AbbreviatedValue", "path": "dispel/data/values.py", "snippet": "class AbbreviatedValue:\n \"\"\"An abbreviated value.\n\n Examples\n --------\n This class allows to consistently handle abbreviated terms. Assuming you have a name\n of an assessment, e.g. `Cognitive Processing Speed` test and the respective\n abbreviation would be `CPS`, then you can create an abbreviated value like this:\n\n >>> from dispel.data.values import AbbreviatedValue as AV\n >>> value = AV('Cognitive Processing Speed test', 'CPS')\n >>> value\n Cognitive Processing Speed test (CPS)\n\n While this seems like a lot of overhead, it comes in handy when describing value\n definitions or higher-level abstractions, such as measure definitions.\n\n Parameters\n ----------\n value\n The full description of the value\n abbr\n The abbreviated form of the value\n\n Attributes\n ----------\n value\n The full description of the value\n \"\"\"\n\n def __init__(self, value: str, abbr: Optional[str] = None):\n self.value = value\n self._abbr = abbr\n\n @property\n def abbr(self):\n \"\"\"Get the abbreviated form of the value.\"\"\"\n return self._abbr or self.value\n\n def __str__(self):\n return self.value\n\n def __repr__(self):\n if self._abbr:\n return f\"{self.value} ({self._abbr})\"\n return self.value\n\n def __hash__(self):\n return hash((self.value, self._abbr))\n\n def __eq__(self, other):\n if isinstance(other, str):\n return self._abbr is None and self.value == other\n if isinstance(other, AbbreviatedValue):\n return self.value == other.value and self.abbr == other.abbr\n return False\n\n def __lt__(self, other):\n if not isinstance(other, AbbreviatedValue):\n raise ValueError(f\"Unsupported type in comparison: {type(other)}\")\n if self.value == other.value:\n return self.abbr < other.abbr\n return self.value < other.value\n\n def format(self, *args, **kwargs):\n \"\"\"Format an abbreviated value.\"\"\"\n return AbbreviatedValue(\n self.value.format(*args, **kwargs),\n self._abbr.format(*args, **kwargs) if self._abbr else None,\n )\n\n @classmethod\n def wrap(cls, value):\n \"\"\"Wrap a value into an abbreviated value.\n\n This is a small helper class to conveniently wrap values into an abbreviated\n value, if they are not already one.\n\n Parameters\n ----------\n value\n The value to be wrapped\n\n Returns\n -------\n AbbreviatedValue\n The passed ``value`` if it is an instance of :class:`AbbreviatedValue`. If a\n string is passed, then the string is passed as ``value`` argument to the\n constructor.\n\n Raises\n ------\n ValueError\n If the passed value is neither a string nor an instance of\n :class:`AbbreviatedValue`.\n \"\"\"\n if isinstance(value, cls):\n return value\n if isinstance(value, str):\n return cls(value)\n\n raise ValueError(f\"Can only wrap string values. Got: {type(value)}\")" }, { "identifier": "ProcessingStep", "path": "dispel/processing/core.py", "snippet": "class ProcessingStep:\n r\"\"\"A processing step in a processing sequence.\n\n :class:`ProcessingStep` is the basic entity through which\n :class:`~dispel.data.core.Reading`\\ s are processed. The processing step's\n :meth:`process_reading` function is called with the reading and additional arguments\n passed to :func:`process`. Results from the process step are expected to be an\n instance of :class:`ProcessingResult`. For a comprehensive description see\n :ref:`measure-extraction`.\n\n The method :meth:`flag_reading` can be overwritten to ensure that the reading\n about to be processed is valid, and return\n :class:`~dispel.data.flags.Flag`\\ s if that is not the case.\n\n Examples\n --------\n .. testsetup:: processing-step\n\n >>> import pandas as pd\n >>> import numpy as np\n\n >>> from dispel.data.core import Reading\n >>> from dispel.data.levels import Level\n >>> from dispel.data.raw import (RawDataSet, RawDataSetDefinition,\n ... RawDataValueDefinition)\n\n >>> reading = Reading(\n ... evaluation=None,\n ... levels=[\n ... Level(id_='my-level', start=0, end=1, raw_data_sets=[\n ... RawDataSet(\n ... RawDataSetDefinition('my-data-set', None, [\n ... RawDataValueDefinition('dummy', 'dummy')\n ... ]),\n ... pd.DataFrame({'dummy': list(range(6))})\n ... )\n ... ])\n ... ])\n\n .. doctest:: processing-step\n\n >>> from dispel.data.measures import MeasureValue\n >>> from dispel.data.values import ValueDefinition\n >>> from dispel.processing import process\n >>> from dispel.processing.core import ProcessingResult, ProcessingStep\n >>> class MyStep(ProcessingStep):\n ... def process_reading(self, reading, **kwargs):\n ... level = reading.get_level('my-level')\n ... raw_data_set = level.get_raw_data_set('my-data-set')\n ... data = raw_data_set.data\n ... yield ProcessingResult(\n ... step=self,\n ... sources=raw_data_set,\n ... result=MeasureValue(\n ... ValueDefinition('my-measure-id','max value'),\n ... data.max().max()\n ... )\n ... )\n >>> _ = process(reading, MyStep())\n >>> reading.measure_set.get_raw_value('my-measure-id')\n 5\n \"\"\"\n\n def __init__(self):\n self.predecessor = None\n self.successor = None\n\n def process(self, reading: Reading, **kwargs) -> ProcessResultType:\n \"\"\"Check reading for validity and process it.\n\n Parameters\n ----------\n reading\n The reading to be processed\n kwargs\n Additional arguments passed by :func:`process`.\n\n Yields\n ------\n ProcessResultType\n The results from processing readings.\n \"\"\"\n for flag in self.flag_reading(reading, **kwargs):\n yield ProcessingControlResult.from_flag(\n flag=flag,\n step=self,\n targets=self.get_reading_flag_targets(reading, **kwargs),\n )\n try:\n self.assert_valid_reading(reading, **kwargs)\n except AssertionError as error:\n yield ProcessingControlResult.from_assertion_error(step=self, error=error)\n else:\n yield from self.process_reading(reading, **kwargs)\n\n def assert_valid_reading(self, reading: Reading, **kwargs):\n \"\"\"Assert that reading is valid.\"\"\"\n\n def flag_reading(self, reading: Reading, **kwargs) -> Generator[Flag, None, None]:\n \"\"\"Flag the provided reading.\n\n Parameters\n ----------\n reading\n The reading to be flagged.\n kwargs\n Additional arguments passed by :func:`~dispel.processing.process`.\n\n Yields\n ------\n Flag\n The resulted flags.\n \"\"\"\n # pylint: disable=unused-argument\n yield from []\n\n def get_reading_flag_targets(\n self, reading: Reading, **kwargs\n ) -> Iterable[EntityType]:\n \"\"\"Get the reading flag targets.\n\n Parameters\n ----------\n reading\n The reading that is concerned with flagging.\n kwargs\n Additional keyword arguments eventually used for flag targets\n extraction.\n\n Returns\n -------\n Iterable[EntityType]\n An iterable of entities that are flagged.\n \"\"\"\n # pylint: disable=unused-argument\n return [reading]\n\n @abstractmethod\n def process_reading(self, reading: Reading, **kwargs) -> ProcessResultType:\n \"\"\"Process the provided reading.\n\n Parameters\n ----------\n reading\n The reading to be processed\n kwargs\n Additional arguments passed by :func:`~dispel.processing.process`.\n\n Yields\n ------\n ProcessResultType\n The results from processing readings.\n \"\"\"\n yield NotImplemented\n\n def set_previous(self, step: \"ProcessingStep\"):\n \"\"\"Set the previous step in a processing chain of this step.\"\"\"\n if self.predecessor is not None:\n warnings.warn(\n \"Changing predecessors can lead to side-effects. Previous predecessor \"\n f\"was {self.predecessor}\",\n UserWarning,\n )\n self.predecessor = step\n\n def set_next(self, step: \"ProcessingStep\"):\n \"\"\"Set the next step in a processing chain of this step.\"\"\"\n if self.successor is not None:\n warnings.warn(\n \"Changing successors can lead to side-effects. Previous successor was \"\n f\"{self.successor}\",\n UserWarning,\n )\n self.successor = step\n\n def chain(self, successor: \"ProcessingStep\") -> \"ProcessingStep\":\n \"\"\"Chain this step with the successor step.\"\"\"\n assert isinstance(successor, ProcessingStep), \"Can only chain processing steps\"\n\n self.set_next(successor)\n successor.set_previous(self)\n return _ChainedProcesses([self, successor])\n\n def __and__(self, other):\n \"\"\"See :meth:`ProcessingStep.chain`.\"\"\"\n return self.chain(other)\n\n def get_parameters(self) -> List[Tuple[str, Parameter]]:\n \"\"\"Get all parameters defined by the processing step.\n\n Returns\n -------\n List[Tuple[str, Parameter]]\n A list of tuples of parameter name and :class:`Parameter`\n objects defined by the processing step.\n \"\"\"\n return inspect.getmembers(self, lambda x: isinstance(x, Parameter))" }, { "identifier": "FlagDataSetStep", "path": "dispel/processing/data_set.py", "snippet": "class FlagDataSetStep(FlagStepMixin, DataSetProcessingStep, metaclass=ABCMeta):\n \"\"\"A data set flag class.\n\n Parameters\n ----------\n data_set_ids\n An optional id or iterable of ids for raw data set(s) to be used for the\n flag. See :class:`DataSetProcessingStepMixin`.\n level_filter\n An optional filter to limit the levels being processed.\n See :class:`~dispel.processing.level.LevelProcessingStep`.\n task_name\n An optional abbreviated name value of the task used for the flag.\n See :class:`~dispel.processing.flags.FLagStepMixin`.\n flag_name\n An optional abbreviated name value of the considered flag.\n See :class:`~dispel.processing.flags.FlagStepMixin`.\n flag_type\n An optional flag type.\n See :class:`~dispel.data.flags.FlagType`.\n flag_severity\n An optional flag severity.\n See :class:`~dispel.data.flags.FlagSeverity`.\n reason\n An optional string reason of the considered flag.\n See :class:`~dispel.processing.flags.FlagStepMixin`.\n stop_processing\n An optional boolean that specifies whether the flag is stop_processing,\n i.e., raises an error or not.\n See :class:`~dispel.processing.flags.FlagStepMixin`.\n flagging_function\n An optional flagging function to be applied to the pandas data frames of the\n provided raw data sets.\n See :class:`~dispel.processing.flags.FlagStepMixin`.\n target_ids\n An optional id(s) of the target data sets to be flagged. If the user doesn't\n specify the targets then the targets will automatically be the used data sets.\n\n Examples\n --------\n Assuming you want to flag the accelerometer signal data of the U-Turn task to\n verify that it doesn't exceed a certain threshold, you can use the following\n flag step:\n\n >>> from dispel.data.values import AbbreviatedValue as AV\n >>> from dispel.processing.data_set import FlagDataSetStep\n >>> step = FlagDataSetStep(\n ... data_set_ids = 'accelerometer',\n ... level_filter = 'utt',\n ... task_name = AV('U-Turn test', 'utt'),\n ... flag_name = AV('accelerometer signal threshold', 'ast'),\n ... flag_type = FlagType.TECHNICAL,\n ... flag_severity = FlagSeverity.INVALIDATION,\n ... reason = 'The U-Turn accelerometer signal exceeds 50 m/s^2.',\n ... stop_processing=False,\n ... flagging_function=lambda data: data.max().max() < 50.\n ... )\n\n The flagging function will be called with the level ``'utt'`` as specified in the\n ``level_filter`` argument. If the function has a named parameter matching\n ``reading``, the reading will be passed to the flagging function.\n\n Another common scenario is to define a class that can be reused.\n\n >>> from dispel.data.flags import FlagType\n >>> from dispel.processing.data_set import FlagDataSetStep\n >>> class UTTAccelerometerSignal(FlagDataSetStep):\n ... data_set_ids = 'accelerometer'\n ... level_filter = 'utt'\n ... task_name = AV('U-Turn test', 'utt')\n ... flag_name = AV('u-turn duration', 'utt_dur')\n ... flag_type = FlagType.TECHNICAL\n ... flag_severity = FlagSeverity.INVALIDATION\n ... reason = 'The U-Turn accelerometer signal exceeds 50 m/s^2.'\n ... stop_processing = True\n ... flagging_function = lambda data: data.max().max() < 50\n\n Another convenient way to provide the flagging function is to use the\n ``@flag`` decorator, one can also use multiple flags for the same class\n as well as multiple data sets. Below is an example of the flag of a data set\n (``userInput``) through the use of multiple ones in the flagging function\n (``userInput``, ``screen``).\n\n >>> import pandas as pd\n >>> from dispel.processing.flags import flag\n >>> from dispel.processing.level import FlagLevelStep\n >>> class UTTAccelerometerSignal(FlagDataSetStep):\n ... data_set_ids = ['userInput', 'screen']\n ... target_ids = 'userInput'\n ... level_filter = 'cps'\n ... task_name = AV('Cognitive processing speed test', 'cps')\n ... flag_name = AV('answer timestamps', 'at')\n ... flag_type = FlagType.TECHNICAL\n ... flag_severity = FlagSeverity.INVALIDATION\n ... reason = 'The user answer timestamps do not match the screen info.'\n ... stop_processing = False\n ...\n ... @flag\n ... def _timestamps(\n ... self,\n ... user_input: pd.DataFrame,\n ... screen: pd.DataFrame\n ... ) -> bool:\n ... return list(user_input.ts) == list(screen.ts)\n\n Note that the ``@flag`` decorator can take keyword arguments. These kwargs are\n merged with any keyword arguments that come from processing step groups in order to\n format the flag ``reason``.\n \"\"\"\n\n target_ids: Optional[Union[Iterable[str], str]] = None\n\n def __init__(\n self,\n data_set_ids: Optional[Union[str, Iterable[str]]] = None,\n level_filter: Optional[LevelFilterType] = None,\n task_name: Optional[Union[AV, str]] = None,\n flag_name: Optional[Union[AV, str]] = None,\n flag_type: Optional[Union[FlagType, str]] = None,\n flag_severity: Optional[Union[FlagSeverity, str]] = None,\n reason: Optional[Union[AV, str]] = None,\n stop_processing: bool = False,\n flagging_function: Optional[Callable[..., bool]] = None,\n target_ids: Optional[Union[Iterable[str], str]] = None,\n ):\n if target_ids:\n self.target_ids = target_ids\n\n super().__init__(\n data_set_ids=data_set_ids,\n level_filter=level_filter,\n task_name=task_name,\n flag_name=flag_name,\n flag_type=flag_type,\n flag_severity=flag_severity,\n reason=reason,\n stop_processing=stop_processing,\n flagging_function=flagging_function,\n )\n\n def get_target_ids(self) -> Iterable[str]:\n \"\"\"Get the ids of the target data sets to be flagged.\n\n Returns\n -------\n str\n The identifiers of the target data sets.\n \"\"\"\n if self.target_ids is None:\n return self.get_data_set_ids()\n if isinstance(self.target_ids, str):\n return [self.target_ids]\n return self.target_ids\n\n def process_data_sets(\n self,\n data_sets: Sequence[pd.DataFrame],\n level: Level,\n reading: Reading,\n **kwargs,\n ) -> ProcessResultType:\n \"\"\"Process the provided data sets.\"\"\"\n yield from []\n\n def get_data_sets_flag_targets(\n self,\n data_sets: Sequence[pd.DataFrame],\n level: Level,\n reading: Reading,\n **kwargs,\n ) -> Iterable[EntityType]:\n \"\"\"Get flag targets for data sets flagging.\"\"\"\n return self.get_flag_targets(reading, level, **kwargs)\n\n def get_flag_targets(\n self, reading: Reading, level: Optional[Level] = None, **kwargs\n ) -> Iterable[EntityType]:\n \"\"\"Get flag targets for data set flagging.\"\"\"\n assert level is not None, \"Missing level in kwargs.\"\n return [level.get_raw_data_set(id_) for id_ in self.get_target_ids()]\n\n def flag_data_sets(\n self,\n data_sets: Sequence[pd.DataFrame],\n level: Level,\n reading: Reading,\n **kwargs,\n ) -> Generator[Flag, None, None]:\n \"\"\"Flag the provided data sets.\"\"\"\n for func, func_kwargs in self.get_flagging_functions():\n if not decorated_processing_function(func, data_sets, reading, level):\n (merged_kwargs := kwargs.copy()).update(func_kwargs)\n yield self.get_flag(**merged_kwargs)" }, { "identifier": "transformation", "path": "dispel/processing/data_set.py", "snippet": "def transformation(_func=None, **kwargs):\n \"\"\"Decorate a function as a transformation function.\"\"\"\n\n def wrapper(func):\n func.__transform_function__ = True\n func.__transform_kwargs__ = kwargs\n return func\n\n if _func is None:\n return wrapper\n\n return wrapper(_func)" }, { "identifier": "ExtractStep", "path": "dispel/processing/extract.py", "snippet": "class ExtractStep(\n MeasureDefinitionMixin, TransformStepChainMixIn, MutateDataSetProcessingStepBase\n):\n r\"\"\"A measure extraction processing step.\n\n This class provides a convenient way to extract a measure from one or more data sets\n by specifying their id, their level_ids or level filter, a transformation function\n and a measure value definition.\n\n Parameters\n ----------\n data_set_ids\n An optional list of data set ids to be used for the transformation. See\n :class:`~dispel.processing.data_set.DataSetProcessingStepMixin`.\n transform_function\n An optional function to be applied to the data sets. See\n :class:`~dispel.processing.data_set.MutateDataSetProcessingStepBase`.\n definition\n An optional value definition or prototype. See\n :class:`MeasureDefinitionMixin`.\n level_filter\n An optional filter to limit the levels being processed. See\n :class:`~dispel.processing.level.LevelProcessingStep`.\n yield_if_nan\n If ``True``, yield null values as measure values. Otherwise, processing\n will not return a measure value in case of a null result for the extraction.\n\n Examples\n --------\n Assuming we wanted to compute the maximum value of a raw data set we can create the\n following step\n\n >>> from dispel.data.values import ValueDefinition\n >>> from dispel.processing.extract import ExtractStep\n >>> step = ExtractStep(\n ... 'data-set-id',\n ... lambda data: data.max(axis=0),\n ... ValueDefinition('maximum','Maximum value')\n ... )\n\n A common approach is to define a processing step for re-use and leveraging the\n ``@transformation`` decorator to specify the transformation function:\n\n >>> import pandas as pd\n >>> from dispel.data.values import ValueDefinition\n >>> from dispel.processing.extract import ExtractStep\n >>> from dispel.processing.data_set import transformation\n >>> class MyExtractStep(ExtractStep):\n ... data_set_ids = 'data-set-id'\n ... definition = ValueDefinition('maximum','Maximum value')\n ...\n ... @transformation\n ... def _max(self, data: pd.DataFrame) -> float:\n ... return data.max(axis=0)\n\n Often one wants to extract multiple measures from one data set. This can be achieved\n by using prototypes and optional named arguments with ``@transformation``:\n\n >>> import pandas as pd\n >>> from dispel.data.values import ValueDefinitionPrototype\n >>> from dispel.processing.extract import ExtractStep\n >>> from dispel.processing.data_set import transformation\n >>> class MyExtractStep(ExtractStep):\n ... data_set_ids = 'data-set-id'\n ... definition = ValueDefinitionPrototype(\n ... id_='id-{agg_abbr}',\n ... name='{agg} value'\n ... )\n ...\n ... @transformation(agg='Maximum', agg_abbr='max')\n ... def _max(self, data: pd.DataFrame) -> float:\n ... return data.max(axis=0)\n ...\n ... @transformation(agg='Minimum', agg_abbr='min')\n ... def _min(self, data: pd.DataFrame) -> float:\n ... return data.min(axis=0)\n\n \"\"\"\n\n yield_if_nan: bool = False\n\n def __init__(\n self,\n data_set_ids: Optional[Union[str, Iterable[str]]] = None,\n transform_function: Optional[Callable[..., Any]] = None,\n definition: Optional[Union[ValueDefinition, ValueDefinitionPrototype]] = None,\n level_filter: Optional[LevelFilterType] = None,\n yield_if_nan: Optional[bool] = None,\n ):\n super().__init__(\n definition=definition,\n data_set_ids=data_set_ids,\n transform_function=transform_function,\n level_filter=level_filter,\n )\n self.yield_if_nan = yield_if_nan or self.yield_if_nan\n\n def wrap_result(\n self, res: Any, level: Level, reading: Reading, **kwargs: Any\n ) -> WrapResultGeneratorType:\n \"\"\"Wrap the result from the processing function into a class.\n\n Parameters\n ----------\n res\n Any result returned by the extraction step. If res is a\n :class:`~dispel.data.flags.WrappedResult`, the flag contained\n in the object will be automatically added to the\n :class:`~dispel.data.measures.MeasureValue`, hence the flagged wrapped\n results will always translate into flagged\n :class:`~dispel.data.measures.MeasureValue`.\n level\n The current level\n reading\n The current reading\n kwargs\n Additional kwargs\n\n Yields\n ------\n LevelProcessingResult\n The processing result\n \"\"\"\n try:\n if len(res) == 0:\n res = math.nan\n warnings.warn(\"Extract step returned an iterable!\", UserWarning)\n except TypeError:\n pass\n if is_wrapped := isinstance(res, WrappedResult):\n measure_value = res.measure_value\n else:\n measure_value = res\n\n if not (is_nan := math.isnan(measure_value)) or (is_nan and self.yield_if_nan):\n value = self.get_value(measure_value, **kwargs)\n # If result is wrapped, add the flag to the measure value\n if is_wrapped:\n value.add_flags(res, ignore_duplicates=True)\n\n yield LevelProcessingResult(\n step=self,\n sources=self.get_raw_data_sets(level),\n result=value,\n level=level,\n )" }, { "identifier": "flag", "path": "dispel/processing/flags.py", "snippet": "def flag(_func=None, **kwargs):\n \"\"\"Decorate a function as a flagging function.\"\"\"\n\n def wrapper(func):\n func.__flagging_function__ = True\n func.__flag_kwargs__ = {\n **kwargs,\n **getattr(func, \"__flag_kwargs__\", {}),\n }\n return func\n\n if _func is None:\n return wrapper\n\n return wrapper(_func)" }, { "identifier": "LevelIdFilter", "path": "dispel/processing/level.py", "snippet": "class LevelIdFilter(LevelFilter):\n \"\"\"A level filter based on level ids.\n\n Parameters\n ----------\n level_ids\n The level id(s) to be filtered for processing. The level id can be provided as\n :class:`str`, :class:`~dispel.data.core.LevelId` or lists of either. Levels with\n the respective provided ids will be considered during processing.\n \"\"\"\n\n def __init__(self, level_ids: MultipleLevelIdsType):\n if isinstance(level_ids, str):\n level_ids = [LevelId(level_ids)]\n if isinstance(level_ids, LevelId):\n level_ids = [level_ids]\n if isinstance(level_ids, list):\n if all(isinstance(level_id, str) for level_id in level_ids):\n level_ids = [LevelId(cast(str, level_id)) for level_id in level_ids]\n elif any(not isinstance(level_id, LevelId) for level_id in level_ids):\n raise ValueError(\n \"The list of level_ids has to be filled only by {str}s or {\"\n \"LevelId}s, never both.\"\n )\n\n self.level_ids = level_ids\n\n def repr(self) -> str:\n \"\"\"Get representation of the filter.\"\"\"\n return f\"level id in {self.level_ids}\"\n\n def filter(self, levels: Iterable[Level]) -> Set[Level]:\n \"\"\"Filter levels being part of a predefined level id set.\"\"\"\n return set(filter(lambda x: x.id in self.level_ids, levels))" }, { "identifier": "ProcessingStepGroup", "path": "dispel/processing/level.py", "snippet": "class ProcessingStepGroup(LevelFilterProcessingStepMixin, CoreProcessingStepGroup):\n r\"\"\"A group of processing steps with an optional level filter.\n\n For examples see :class:`dispel.processing.core.CoreProcessingStepGroup`. This class\n ensures that level filters are injected to the steps of this group.\n \"\"\"\n\n def set_steps(self, steps: List[ProcessingStep]):\n \"\"\"Set processing steps part of the group.\n\n This method ensures that steps added to the group inherit the level filter of\n the group.\n\n Parameters\n ----------\n steps\n The steps contained in the processing group.\n \"\"\"\n for step in steps:\n if isinstance(step, LevelFilterProcessingStepMixin):\n step.inject_level_filter_from_step(self)\n\n super().set_steps(steps)\n\n def inject_level_filter_from_step(self, step: LevelFilterProcessingStepMixin):\n \"\"\"Inject level filter into group and steps in group.\"\"\"\n super().inject_level_filter_from_step(step)\n for group_step in self.get_steps():\n if isinstance(group_step, LevelFilterProcessingStepMixin):\n group_step.inject_level_filter_from_step(self)" }, { "identifier": "LimbModality", "path": "dispel/processing/modalities.py", "snippet": "class LimbModality(AVEnum):\n \"\"\"Type of limb exercises enumerator.\"\"\"\n\n UPPER_LIMB = (\"upper limb\", \"upper\")\n LOWER_LIMB = (\"lower limb\", \"lower\")" }, { "identifier": "SensorModality", "path": "dispel/processing/modalities.py", "snippet": "class SensorModality(AVEnum):\n # FIXME remove class\n \"\"\"Sensor types enumerator.\"\"\"\n\n def unit(self, order: int = 1) -> str:\n \"\"\"Get the unit of the sensor signal.\n\n Parameters\n ----------\n order\n The unit order.\n\n Returns\n -------\n str\n The unit of the sensor.\n \"\"\"\n basis = {\"acc\": \"G\", \"gyr\": \"rad/s\", \"itrem\": \"pixel\"}[self.abbr]\n if order == 1:\n return basis\n return \"/\".join([x + f\"^{order}\" for x in basis.split(\"/\")])\n\n ACCELEROMETER = (\"accelerometer\", \"acc\")\n GYROSCOPE = (\"gyroscope\", \"gyr\")\n INTENTIONAL = (\"intentional tremors\", \"itrem\")" }, { "identifier": "TransformStep", "path": "dispel/processing/transform.py", "snippet": "class TransformStep(TransformStepChainMixIn, MutateDataSetProcessingStepBase):\n r\"\"\"A raw data set transformation processing step.\n\n This class provides a convenient way to transform one or more data sets by\n specifying their ids, their level_ids or a level filter, a transformation function\n and specifications of a new data set to be returned as result of the processing\n step.\n\n Parameters\n ----------\n data_set_ids\n An optional list of data set ids to be used for the transformation. See\n :class:`~dispel.processing.data_set.DataSetProcessingStepMixin`.\n transform_function\n An optional function to be applied to the data sets. See\n :class:`~dispel.processing.data_set.MutateDataSetProcessingStepBase`. The transform\n function is expected to produce one or more columns of a data set according to\n the specification in `definitions`. The function can return NumPy unidimensional\n arrays, Pandas series and data frames.\n new_data_set_id\n An optional id used for the\n :class:`~dispel.data.raw.RawDataSetDefinition`. If no id was provided, the\n :data:`new_data_set_id` class variable will be used. Alternatively, one can\n overwrite :meth:`get_new_data_set_id` to provide the new data set id.\n definitions\n An optional list of :class:`~dispel.data.raw.RawDataValueDefinition` that has to\n match the number of columns returned by the :attr:`transform_function`. If no\n definitions were provided, the :data:`definitions` class variable will be used.\n Alternatively, one can overwrite :meth:`get_definitions` to provide the list of\n definitions.\n level_filter\n An optional filter to limit the levels being processed. See\n :class:`~dispel.processing.level.LevelProcessingStep`.\n storage_error\n This argument is only useful when the given new data id already exists.\n In which case, the following options are available:\n\n - ``'ignore'``: the computation of the transformation step for the concerned\n level will be ignored.\n - ``'overwrite'``: the existing data set id will be overwritten by the\n result of transform step computation.\n - ``'concatenate'``: the existing data set id will be concatenated with the\n result of transform step computation.\n - ``'raise'``: An error will be raised if we want to overwrite on an\n existing data set id.\n\n Examples\n --------\n Assuming you want to calculate the euclidean norm of a data set ``'acceleration'``\n for a specific level ``'left-small'`` and then name the new data set\n ``'accelerometer-norm'``, you can create the following step:\n\n >>> from dispel.data.raw import RawDataValueDefinition\n >>> from dispel.processing.transform import TransformStep\n >>> from dispel.signal.core import euclidean_norm\n >>> step = TransformStep(\n ... 'accelerometer',\n ... euclidean_norm,\n ... 'accelerometer-norm',\n ... [RawDataValueDefinition('norm', 'Accelerometer norm', 'm/s^2')]\n ... )\n\n The transformation function will be called with the specified data sets as\n arguments. If the function has named parameters matching ``level`` or ``reading``,\n the respective level and reading will be passed to the transformation function.\n\n Another common scenario is to define a class that can be reused.\n\n >>> from dispel.data.raw import RawDataValueDefinition\n >>> from dispel.processing.transform import TransformStep\n >>> class MyTransformStep(TransformStep):\n ... data_set_ids = 'accelerometer'\n ... transform_function = euclidean_norm\n ... new_data_set_id = 'accelerometer-norm'\n ... definitions = [\n ... RawDataValueDefinition('norm', 'Accelerometer norm', 'm/s^2')\n ... ]\n\n Another convenient way to provide the transformation function is to use the\n ``@transformation`` decorator:\n\n >>> import pandas as pd\n >>> import numpy as np\n >>> from dispel.data.raw import RawDataValueDefinition\n >>> from dispel.processing.data_set import transformation\n >>> from dispel.processing.transform import TransformStep\n >>> class MyTransformStep(TransformStep):\n ... data_set_ids = 'accelerometer'\n ... new_data_set_id = 'accelerometer-norm'\n ... definitions = [\n ... RawDataValueDefinition('norm', 'Accelerometer norm', 'm/s^2')\n ... ]\n ...\n ... @transformation\n ... def _euclidean_norm(self, data: pd.DataFrame) -> pd.Series:\n ... return data.pow(2).sum(axis=1).apply(np.sqrt)\n\n Note that the decorated functions can also use ``level`` and ``reading`` as\n parameters to gain access to the respective level and reading being processed.\n \"\"\"\n\n new_data_set_id: str\n\n definitions: List[RawDataValueDefinition]\n\n storage_error: StorageError = StorageError.RAISE\n\n def __init__(\n self,\n data_set_ids: Optional[Union[str, Iterable[str]]] = None,\n transform_function: Optional[Callable[..., Any]] = None,\n new_data_set_id: Optional[str] = None,\n definitions: Optional[List[RawDataValueDefinition]] = None,\n level_filter: Optional[LevelFilterType] = None,\n storage_error: Optional[\n Union[StorageError, Literal[\"raise\", \"ignore\", \"overwrite\", \"concatenate\"]]\n ] = None,\n ):\n super().__init__(\n data_set_ids=data_set_ids,\n transform_function=transform_function,\n level_filter=level_filter,\n )\n\n if new_data_set_id:\n self.new_data_set_id = new_data_set_id\n if definitions:\n self.definitions = definitions\n if storage_error:\n self.storage_error = StorageError(storage_error)\n\n def get_new_data_set_id(self) -> str:\n \"\"\"Get the id of the new data set to be created.\"\"\"\n return self.new_data_set_id\n\n def get_definitions(self) -> List[RawDataValueDefinition]:\n \"\"\"Get the definitions of the raw data set values.\"\"\"\n return self.definitions\n\n def get_raw_data_set_definition(self):\n \"\"\"Get the raw data set definition.\"\"\"\n return RawDataSetDefinition(\n id=self.get_new_data_set_id(),\n source=RawDataSetSource(self.__class__.__name__),\n value_definitions_list=self.get_definitions(),\n is_computed=True,\n )\n\n def wrap_result(\n self, res: Any, level: Level, reading: Reading, **kwargs: Any\n ) -> WrapResultGeneratorType:\n \"\"\"Wrap the result from the processing function into a class.\"\"\"\n # handle series should they be provided\n if isinstance(res, (pd.Series, np.ndarray)):\n # Wrap into series if it is numpy array\n if isinstance(res, np.ndarray):\n assert res.ndim == 1, \"Cannot handle multidimensional arrays\"\n res = pd.Series(res)\n\n def_ids = [\n d.id for d in filter(lambda d: ~d.is_index, self.get_definitions())\n ]\n if len(def_ids) != 1:\n raise ValueError(\n \"Processing returned a series but did not get single \"\n \"RawDataValueDefinition\"\n )\n res = res.to_frame(def_ids[0])\n\n raw_data_set = RawDataSet(self.get_raw_data_set_definition(), res)\n\n yield RawDataSetProcessingResult(\n step=self,\n sources=self.get_raw_data_sets(level),\n result=raw_data_set,\n level=level,\n concatenate=self.storage_error.concatenate,\n overwrite=self.storage_error.overwrite,\n )\n\n def process_level(\n self, level: Level, reading: Reading, **kwargs\n ) -> ProcessResultType:\n \"\"\"Process the provided Level.\"\"\"\n raw_data_set_exists = level.has_raw_data_set(self.get_new_data_set_id())\n\n if raw_data_set_exists and self.storage_error == StorageError.RAISE:\n raise RawDataSetAlreadyExists(\n self.get_new_data_set_id(),\n level.id,\n 'Please select for `storage_error` either \"ignore\" to ignore the '\n 'transformation if the data set already exists, \"overwrite\" to '\n \"overwrite the existing data set with the newly computed one, \"\n '\"concatenate\" to try and concatenate the two raw data sets or simply '\n \"change the name of the new data set to a valid one.\",\n )\n if raw_data_set_exists and self.storage_error == StorageError.IGNORE:\n pass\n else:\n yield from super().process_level(level, reading, **kwargs)" }, { "identifier": "FrequencyLowerThanSBTThres", "path": "dispel/providers/generic/flags/generic.py", "snippet": "class FrequencyLowerThanSBTThres(FrequencyLowerThanThres):\n \"\"\"Flag SBT record with sampling rate less than a threshold.\"\"\"\n\n @flag(min_freq=MIN_FREQ_SBT)\n def _median_instant_freq_lower_than_thres(\n self, level: Level, **kwargs # pylint: disable=all\n ) -> bool:\n self.set_flag_kwargs(min_freq=MIN_FREQ_SBT)\n return detect_fs_below_threshold(level, min_freq=MIN_FREQ_SBT)" }, { "identifier": "MaxTimeIncrement", "path": "dispel/providers/generic/flags/generic.py", "snippet": "class MaxTimeIncrement(FlagLevelStep):\n \"\"\"Flag record with maximum time increment larger than threshold.\"\"\"\n\n flag_name = AV(\n f\"Maximum time increment larger than {MAX_TIME_INCR} seconds\",\n f\"max_time_inc_greater_than_{MAX_TIME_INCR}_sec\",\n )\n flag_type = FlagType.TECHNICAL\n flag_severity = FlagSeverity.INVALIDATION\n reason = f\"The maximum time increment is higher than \" f\"{MAX_TIME_INCR} seconds.\"\n\n @flag\n def _max_time_increment_larger_than(\n self, level: Level, **kwargs # pylint: disable=all\n ) -> bool:\n acc = level.get_raw_data_set(\"accelerometer\").data\n time_inc = acc.ts.diff().dt.total_seconds().max()\n return time_inc < MAX_TIME_INCR" }, { "identifier": "FlagAdjustmentNonBeltSBT", "path": "dispel/providers/generic/flags/le_flags.py", "snippet": "class FlagAdjustmentNonBeltSBT(NonBeltPostAdjustmentDetected):\n \"\"\"Flag SBT records with non-belt post-adjustment period.\"\"\"\n\n acceptance_threshold: float = MAX_SBT_PERC_NOT_IN_BELT\n placements: list = []\n\n @flag\n def _off_belt_period(\n self,\n level: Level,\n acceptance_threshold: float = acceptance_threshold,\n start_time: float = END_POSTURAL_ADJUSTMENT,\n **_kwargs,\n ) -> bool:\n non_belt_portion, placements = perc_non_belt(\n level, \"placement_bouts\", start_time\n )\n\n self.set_flag_kwargs(\n acceptance_threshold=acceptance_threshold,\n non_belt_portion=non_belt_portion,\n placements=placements,\n )\n\n return non_belt_portion <= acceptance_threshold" }, { "identifier": "FlagNonBeltSBT", "path": "dispel/providers/generic/flags/le_flags.py", "snippet": "class FlagNonBeltSBT(NonBeltDetected):\n \"\"\"Flag SBT records with non-belt period greater than threshold.\"\"\"\n\n acceptance_threshold: float = MAX_SBT_PERC_NOT_IN_BELT\n placements: list = []\n\n @flag\n def _off_belt_period(\n self,\n level: Level,\n acceptance_threshold: float = acceptance_threshold,\n start_time: float = START_TIME_ASSESSMENT,\n **_kwargs,\n ) -> bool:\n non_belt_portion, placements = perc_non_belt(\n level, \"placement_bouts\", start_time\n )\n\n self.set_flag_kwargs(\n acceptance_threshold=acceptance_threshold,\n non_belt_portion=non_belt_portion,\n placements=placements,\n )\n\n return non_belt_portion <= acceptance_threshold" }, { "identifier": "FlagPostAdjustExcessiveMotion", "path": "dispel/providers/generic/flags/le_flags.py", "snippet": "class FlagPostAdjustExcessiveMotion(ExcessiveMotionFlagger):\n \"\"\"Flag minimum length of valid recording without excessive motion.\"\"\"\n\n flag_name = AV(\"Excessive Motion Detected during Stabilisation\", \"excessive_motion\")\n reason = (\n \"{excessive_motion_portion}% excessive motion portion detected \"\n \"(exceeds {acceptance_threshold}% accepted)\"\n )\n\n def __init__(self, **kwargs):\n self.start_time = (END_POSTURAL_ADJUSTMENT,)\n\n super().__init__(**kwargs)" }, { "identifier": "FlagStabilisationExcessiveMotion", "path": "dispel/providers/generic/flags/le_flags.py", "snippet": "class FlagStabilisationExcessiveMotion(ExcessiveMotionFlagger):\n \"\"\"Flag minimum length of valid recording without excessive motion.\"\"\"\n\n flag_name = AV(\n \"Excessive Motion Detected Post-adjustment\", \"excessive_post_adjustment_motion\"\n )\n reason = (\n \"{excessive_motion_portion:.1f}% excessive motion post-adjustment portion \"\n \"detected (exceeds {acceptance_threshold}% accepted)\"\n )\n\n def __init__(self, **kwargs):\n self.start_time = (START_TIME_ASSESSMENT,)\n\n super().__init__(**kwargs)" }, { "identifier": "PlacementClassificationGroup", "path": "dispel/providers/generic/flags/le_flags.py", "snippet": "class PlacementClassificationGroup(ProcessingStepGroup):\n \"\"\"A ProcessingStepGroup concatenating PlacementClassificationGroup steps.\"\"\"\n\n steps = [\n Resample(\n data_set_id=\"acc_ts\",\n freq=FREQ_50HZ,\n aggregations=[\"mean\", \"ffill\"],\n columns=ACCELEROMETER_COLUMNS + GRAVITY_COLUMNS,\n ),\n EuclideanNorm(\n data_set_id=\"acc_ts_resampled\",\n columns=ACCELEROMETER_COLUMNS,\n ),\n # Format Accelerometer and detect walking bouts\n ClassifyPlacement(),\n ]" }, { "identifier": "FilterPhysiologicalNoise", "path": "dispel/providers/generic/preprocessing.py", "snippet": "class FilterPhysiologicalNoise(Apply):\n r\"\"\"Apply a filter that will remove any physiological noise into a dataset.\n\n This filter is a butterworth high-pass one.\n\n Parameters\n ----------\n data_set_id\n The data set id on which the transformation is to be performed ('accelerometer',\n 'gyroscope').\n columns\n The columns onto which the filtering step has to be applied.\n sampling_frequency\n Optional the initial sampling frequency.\n kwargs\n Additional arguments that are passed to the\n :meth:`~dispel.processing.core.ProcessingStep.process` function of each step. This\n allows to provide additional values, such as placeholder values in value\n definitions to the actual processing function.\n\n Notes\n -----\n The Butterwoth highpass filter is tuned as in [Martinez et. al. 2012]_ to remove\n physiological noise. The cut-off of is of 0.2HZ which is the standard breath\n frequency.\n\n .. [Martinez et. al. 2012] MARTINEZ-MENDEZ, Rigoberto, SEKINE,\n Masaki, et TAMURA, Toshiyo.\n Postural sway parameters using a triaxial accelerometer: comparing elderly\n and young healthy adults. Computer methods in biomechanics and biomedical\n engineering, 2012, vol. 15, no 9, p. 899-910.\n\n \"\"\"\n\n def __init__(\n self,\n data_set_id: str,\n columns: Optional[List[str]] = None,\n sampling_frequency: Optional[float] = None,\n **kwargs,\n ):\n columns = columns or DEFAULT_COLUMNS\n\n super().__init__(\n data_set_id=data_set_id,\n method=butterworth_high_pass_filter,\n method_kwargs=dict(\n order=2, cutoff=0.3, freq=sampling_frequency, zero_phase=True\n ),\n columns=columns,\n new_data_set_id=f\"{data_set_id}_bhpf\",\n drop_nan=True,\n **kwargs,\n )" }, { "identifier": "FilterSensorNoise", "path": "dispel/providers/generic/preprocessing.py", "snippet": "class FilterSensorNoise(Apply):\n r\"\"\"Apply a filter that will remove any sensor noise into a given dataset.\n\n This filter is a Savitzky-Golay one.\n\n Parameters\n ----------\n data_set_id\n The data set id on which the transformation is to be performed ('accelerometer',\n 'gyroscope').\n columns\n The columns onto which the filtering step has to be applied.\n kwargs\n Additional arguments that are passed to the\n :meth:`~dispel.processing.core.ProcessingStep.process` function of each step. This\n allows to provide additional values, such as placeholder values in value\n definitions to the actual processing function.\n\n Notes\n -----\n The Savitzky-Golay is tuned as in [Martinez et. al. 2012]_ to remove sensor noise\n and to smooth the signal. The windows size is thus set up to 41 points and the\n filter is of order-3.\n\n \"\"\"\n\n def __init__(self, data_set_id: str, columns: Optional[List[str]] = None, **kwargs):\n columns = columns or DEFAULT_COLUMNS\n\n super().__init__(\n data_set_id=data_set_id,\n method=savgol_filter,\n method_kwargs=dict(window=41, order=3),\n columns=columns,\n new_data_set_id=f\"{data_set_id}_svgf\",\n drop_nan=True,\n **kwargs,\n )" }, { "identifier": "PreprocessingSteps", "path": "dispel/providers/generic/preprocessing.py", "snippet": "class PreprocessingSteps(ProcessingStepGroup):\n r\"\"\"A changing referential preprocessing step according a given data set.\n\n Parameters\n ----------\n data_set_id\n The data set id on which the transformation is to be performed.\n limb\n The modality regarding if the exercise is upper or lower limb.\n sensor\n The modality regarding the type of sensor either accelerometer or gyroscope.\n resample_freq\n Optionally, the frequency to which resample the data during the resample step.\n columns\n Optionally, the columns on which the preprocessing steps need to be applied.\n level_filter\n An optional :class:`~dispel.processing.level.LevelFilter` to determine the levels\n to be transformed. If no filter is provided, all levels will be transformed. The\n ``level_filter`` also accepts :class:`str`, :class:`~dispel.data.core.LevelId`\\ s\n and lists of either and passes them to a\n :class:`~dispel.processing.level.LevelIdFilter` for convenience.\n \"\"\"\n\n def __init__(\n self,\n data_set_id: str,\n limb: LimbModality,\n sensor: SensorModality,\n resample_freq: Optional[float] = None,\n columns: Optional[List[str]] = None,\n level_filter: LevelFilterType = DefaultLevelFilter(),\n ):\n columns = columns or DEFAULT_COLUMNS\n extra_columns = []\n\n if not isinstance(level_filter, LevelFilter):\n level_filter = LevelIdFilter(level_filter)\n\n # Need to be computed even if only gyroscope signals are preprocessed to make\n # sure `acc` data set is available to compute gravity rotation matrices\n steps: List[ProcessingStep] = [\n TransformUserAcceleration(storage_error=\"ignore\"),\n TransformGyroscope(storage_error=\"overwrite\"),\n ]\n\n if sensor == SensorModality.ACCELEROMETER:\n data_set_id = \"acc\"\n extra_columns = GRAVITY_COLUMNS\n\n steps += [\n SetTimestampIndex(\n data_set_id, list(set(columns).union(extra_columns)), duplicates=\"first\"\n )\n ]\n\n if limb == LimbModality.LOWER_LIMB:\n steps += [\n RotateFrame(\n data_set_id=f\"{data_set_id}_ts\",\n gravity_data_set_id=\"acc_ts\",\n frame=(-1, 0, 0),\n columns=columns,\n ),\n Resample(\n data_set_id=f\"{data_set_id}_ts_rotated\",\n freq=resample_freq,\n aggregations=[\"mean\", \"ffill\"],\n columns=columns,\n ),\n Detrend(\n data_set_id=f\"{data_set_id}_ts_rotated_resampled\", columns=columns\n ),\n ]\n else:\n steps += [\n Resample(\n data_set_id=f\"{data_set_id}_ts\",\n freq=resample_freq,\n aggregations=[\"mean\", \"ffill\"],\n columns=columns,\n ),\n Detrend(data_set_id=f\"{data_set_id}_ts_resampled\", columns=columns),\n ]\n\n super().__init__(steps, level_filter=level_filter)" }, { "identifier": "RenameColumns", "path": "dispel/providers/generic/sensor.py", "snippet": "class RenameColumns(TransformStep):\n r\"\"\"Rename and select columns of a raw data set.\n\n Parameters\n ----------\n data_set_id\n The data set id of the time series to be renamed.\n level_filter\n An optional :class:`~dispel.processing.level.LevelFilter` to determine\n the levels to be transformed. If no filter is provided, all levels\n will be transformed. The ``level_filter`` also accepts :class:`str`,\n :class:`~dispel.data.core.LevelId`\\ s and lists of either and passes them\n to a :class:`~dispel.processing.level.LevelFilter` for convenience.\n kwargs\n All arguments passed into this class will serve as a renaming mapping\n for the raw data set.\n \"\"\"\n\n def __init__(\n self, data_set_id: str, level_filter: Optional[LevelFilterType] = None, **kwargs\n ):\n def _transform_function(data: pd.DataFrame) -> pd.DataFrame:\n data_ = data.rename(columns=kwargs)\n return data_[kwargs.values()]\n\n super().__init__(\n data_set_id,\n _transform_function,\n f\"{data_set_id}_renamed\",\n [RawDataValueDefinition(column, column) for column in kwargs.values()],\n level_filter=level_filter,\n )" }, { "identifier": "TransformUserAcceleration", "path": "dispel/providers/generic/sensor.py", "snippet": "class TransformUserAcceleration(TransformStep):\n r\"\"\"Format accelerometer data to ADS format if not already the case.\n\n Prior to formatting, linear acceleration and gravity are decoupled\n from acceleration.\n\n Parameters\n ----------\n level_filter\n An optional :class:`dispel.processing.level.LevelFilter` to determine the\n levels to be transformed. If no filter is provided, all levels will be\n transformed. The ``level_filter`` also accepts :class:`str`,\n :class:`~dispel.data.core.LevelId`\\ s and lists of either and passes them\n to a :class:`~dispel.processing.level.LevelFilter` for convenience.\n \"\"\"\n\n data_set_ids = \"accelerometer\"\n new_data_set_id = \"acc\"\n\n definitions = (\n [\n RawDataValueDefinition(\n f\"userAcceleration{axis}\",\n f\"Linear Acceleration along the {axis} axis.\",\n data_type=\"float\",\n )\n for axis in \"XYZ\"\n ]\n + [\n RawDataValueDefinition(\n f\"gravity{axis}\",\n f\"gravity component along the {axis} axis.\",\n data_type=\"float\",\n )\n for axis in \"XYZ\"\n ]\n + [RawDataValueDefinition(\"ts\", \"time index\")]\n )\n\n @staticmethod\n def add_gravity(\n accelerometer: pd.DataFrame,\n level: Level,\n gravity: Optional[pd.DataFrame] = None,\n ) -> pd.DataFrame:\n \"\"\"Format gravity data to ADS format.\"\"\"\n if gravity is None:\n cols = [\"x\", \"y\", \"z\"]\n raw_acc = level.get_raw_data_set(\"raw_accelerometer\").data\n accelerometer = raw_acc\n if level.has_raw_data_set(\"attitude\"):\n ori = level.get_raw_data_set(\"attitude\").data\n ori_cols = [\"w\", \"x\", \"y\", \"z\"]\n lin_accelerometer, gravity = remove_gravity_component_ori(\n accelerometer[cols].values, ori[ori_cols].values\n )\n lin_accelerometer = pd.DataFrame(lin_accelerometer, columns=cols)\n gravity = pd.DataFrame(gravity, columns=cols)\n else:\n lin_accelerometer, gravity = remove_gravity_component(\n accelerometer[cols]\n )\n\n res = pd.DataFrame(\n {\n \"userAccelerationX\": lin_accelerometer[\"x\"],\n \"userAccelerationY\": lin_accelerometer[\"y\"],\n \"userAccelerationZ\": lin_accelerometer[\"z\"],\n }\n )\n res[\"gravityX\"] = gravity[\"x\"]\n res[\"gravityY\"] = gravity[\"y\"]\n res[\"gravityZ\"] = gravity[\"z\"]\n res[\"ts\"] = accelerometer[\"ts\"]\n else:\n # Merging on the timestamps vs. on the indexes\n acc_renamed = accelerometer.rename(\n mapper={\n \"x\": \"userAccelerationX\",\n \"y\": \"userAccelerationY\",\n \"z\": \"userAccelerationZ\",\n },\n axis=1,\n )\n gravity_renamed = gravity.rename(\n mapper={\"x\": \"gravityX\", \"y\": \"gravityY\", \"z\": \"gravityZ\"}, axis=1\n )\n merged = acc_renamed.merge(gravity_renamed, how=\"outer\")\n merged = merged.set_index(\"ts\")\n merged_sorted = merged.sort_index()\n merged_sorted_interpolated = merged_sorted.interpolate(\n method=\"nearest\", limit_direction=\"both\"\n )\n res = merged_sorted_interpolated.loc[acc_renamed.ts].reset_index()\n return res.dropna()\n\n @staticmethod\n @transformation\n def _reformat(accelerometer: pd.DataFrame, level: Level) -> pd.DataFrame:\n target_cols = {\n f\"{sensor}{axis}\"\n for sensor in (\"userAcceleration\", \"gravity\")\n for axis in \"XYZ\"\n }\n if not target_cols.issubset(accelerometer.columns):\n try:\n return TransformUserAcceleration.add_gravity(\n accelerometer, level, level.get_raw_data_set(\"gravity\").data\n )\n except ValueError:\n # Happens in BDH pinch\n return TransformUserAcceleration.add_gravity(accelerometer, level)\n return accelerometer" }, { "identifier": "FIXED_SIGN_AMP_THRESHOLD", "path": "dispel/providers/generic/tasks/sbt_utt/const.py", "snippet": "FIXED_SIGN_AMP_THRESHOLD = 0.1" }, { "identifier": "KERNEL_WINDOW_SEGMENT", "path": "dispel/providers/generic/tasks/sbt_utt/const.py", "snippet": "KERNEL_WINDOW_SEGMENT = 151" }, { "identifier": "MIN_COVERAGE_THRESHOLD", "path": "dispel/providers/generic/tasks/sbt_utt/const.py", "snippet": "MIN_COVERAGE_THRESHOLD = 80.0" }, { "identifier": "TASK_NAME_SBT", "path": "dispel/providers/generic/tasks/sbt_utt/const.py", "snippet": "TASK_NAME_SBT = AV(\"Static Balance Test\", \"sbt\")" }, { "identifier": "SBTBoutExtractStep", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_bouts.py", "snippet": "class SBTBoutExtractStep(ExtractStep):\n \"\"\"Base class for SBT bouts measure extraction.\"\"\"\n\n bout_strategy: SBTBoutStrategy\n\n def __init__(self, *args, **kwargs):\n bout_strategy = kwargs.pop(\"bout_strategy\", None)\n kwargs_copy = kwargs.copy()\n if \"modalities\" in kwargs:\n kwargs_copy.pop(\"modalities\")\n\n super().__init__(*args, **kwargs_copy)\n if bout_strategy:\n self.bout_strategy = bout_strategy\n\n def process_level(\n self, level: Level, reading: Reading, **kwargs\n ) -> ProcessResultType:\n \"\"\"Overwrite process_level.\"\"\"\n # pylint: disable=unpacking-non-sequence\n data_sets = self.get_data_frames(level)\n filtered_data_sets = self.bout_strategy.get_view(data_sets)\n\n for function, func_kwargs in self.get_transform_functions():\n merged_kwargs = kwargs.copy()\n merged_kwargs.update(func_kwargs)\n yield from self.wrap_result(\n decorated_processing_function(\n function, filtered_data_sets, reading, level\n ),\n level,\n reading,\n **merged_kwargs,\n )" }, { "identifier": "SBTBoutStrategyModality", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_bouts.py", "snippet": "class SBTBoutStrategyModality(AVEnum):\n \"\"\"Enumerate bout strategy modalities.\"\"\"\n\n FIRST_FIVE = AV(\"first five seconds\", \"first5s\")\n AFTER_FIVE = AV(\"after five seconds\", \"after5s\")\n BASIC = AV(\"complete signal\", \"full\")\n\n @property\n def bout_cls(self):\n \"\"\"Return BoutStrategy instance.\"\"\"\n mapping = {\n self.FIRST_FIVE: FirstFiveSec(),\n self.AFTER_FIVE: AfterFiveSec(),\n self.BASIC: SBTBoutStrategy(),\n }\n return mapping[self]" }, { "identifier": "circle_area", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_func.py", "snippet": "def circle_area(comp1: pd.Series, comp2: pd.Series) -> float:\n \"\"\"Compute the area of a circle comprising data within the 95-percentile.\n\n The area of the circle comprising data points of a timeseries within the\n 95-percentile is computed following Original paper (eq.12) by\n Prieto(1996) https://doi.org/10.1109/10.532130\n\n Parameters\n ----------\n comp1\n The first component of the signal\n comp2\n The second component of the signal\n\n Returns\n -------\n float\n The value of the estimated area covering the 95-percentile of the data\n of a 2-dimensional timeseries.\n \"\"\"\n # Being z095 the z-statistic at the 95% confidence level\n z095 = 1.645\n\n # Based on the average acceleration magnitude and the root-mean-square\n # acceleration\n rmsa_r = rms_planar(comp1, comp2)\n aam_r = mean_norm_planar(comp1, comp2)\n\n # Computing the Standard Deviation of the 2-dimensional timeseries as in\n # (eq.13) in Prieto(1996)\n std_resultant = np.sqrt(rmsa_r**2 - aam_r**2)\n\n # To obtain the area of a circle that includes 95% of the resultant\n # norms of the acceleration (see (eq.12) in Prieto(1996))\n return np.pi * (aam_r + z095 * std_resultant) ** 2" }, { "identifier": "data_coverage_fraction", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_func.py", "snippet": "def data_coverage_fraction(data: pd.Series) -> float:\n \"\"\"Compute the portion of data covered by a binary flag over signal length.\n\n Parameters\n ----------\n data\n A binary Series flag (0/1) that flags some behaviour of interest.\n\n Returns\n -------\n float\n A value between 0 and 1 that represents how much of the data\n flag signal covers the totality of the recording.\n \"\"\"\n return round(float(1 - len(data[data.values]) / len(data)), 2)" }, { "identifier": "ellipse_area", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_func.py", "snippet": "def ellipse_area(comp1: pd.Series, comp2: pd.Series) -> float:\n \"\"\"Compute Ellipse Area as the 95% percentile of the PCA-fitted axes.\n\n The Ellipse Area is computed from the values of the estimated minor and\n major (a,b) axes of an ellipse. The axes are estimated using a 2-PCA\n component analyses on the 2-dimensional timeseries of data. The Ellipse\n area is computed as the multiplication of its semi-axes and the number pi.\n\n Parameters\n ----------\n comp1\n The first component of the signal\n comp2\n The second component of the signal\n\n Returns\n -------\n float\n The value of the estimated ellipse area covering the 95-percentile of\n the data of a 2-dimensional timeseries.\n \"\"\"\n df = pd.concat([comp1, comp2], axis=1)\n # The axes are estimated using a 2-PCA component analyses on\n # the 2-dimensional timeseries of data.\n a, b = extract_ellipse_axes(df)\n # The Ellipse area is computed as the multiplication of its semi-axes\n # and the number pi.\n return np.pi * (a / 2) * (b / 2)" }, { "identifier": "label_bouts", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_func.py", "snippet": "def label_bouts(data: pd.Series) -> pd.Series:\n \"\"\"Label each valid and invalid chunk as a bout.\n\n Parameters\n ----------\n data\n A Series that contains one column including the flag continuous\n signal\n\n Returns\n -------\n Series\n A labelled pd.Series where each valid/invalid bout is assigned an\n increasing integer number\n \"\"\"\n # We increase a counter number everytime the flag changes (solution\n # inspired in StakOverflow community\n return data.astype(bool).diff().fillna(method=\"bfill\").cumsum()" }, { "identifier": "reject_short_bouts", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_func.py", "snippet": "def reject_short_bouts(bout_mask: pd.Series, flag: pd.Series) -> pd.Series:\n \"\"\"Reject bouts whose duration is less than MIN_MOTION_DUR seconds.\n\n Parameters\n ----------\n bout_mask\n A Series containing a flag_signal and a bout_number.\n flag\n A Series containing a flag_signal and a bout_number.\n\n Returns\n -------\n Series\n A Series with a flag_signal where the valence has been inverted\n in case its duration is below MIN_MOTION_DUR seconds.\n\n \"\"\"\n flag = flag.astype(bool)\n for _, bout in bout_mask.groupby(bout_mask):\n if signal_duration(bout) < MIN_MOTION_DUR:\n flag.loc[bout.index] = ~flag.loc[bout.index]\n return flag" }, { "identifier": "sway_jerk", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_func.py", "snippet": "def sway_jerk(comp1: pd.Series, comp2: pd.Series) -> float:\n \"\"\"Compute the jerk of the sway.\n\n The Sway Jerk provides a means of quantifying the average sway occurred\n on a plane per time unit over the total of an assessment .\n It is a complementary measure to the sway areas, as it covers also the\n amount of sway occurred within a given geometric area. It takes special\n relevance when algorithms to remove outliers are applied and the\n timeseries span used for different measures is different. In other\n words, a normalised version of the sway total excursion. See an example\n of concomitant use with sway total excursion in Mancini(2012),\n https://doi.org/10.1186/1743-0003-9-59\n\n Parameters\n ----------\n comp1\n The first component of the signal\n comp2\n The second component of the signal\n\n Returns\n -------\n float\n The sway total excursion value\n \"\"\"\n total_excursion = sway_total_excursion(comp1, comp2)\n\n trial_time = (comp1.last_valid_index() - comp1.first_valid_index()).seconds\n\n return total_excursion / trial_time" }, { "identifier": "sway_total_excursion", "path": "dispel/providers/generic/tasks/sbt_utt/sbt_func.py", "snippet": "def sway_total_excursion(comp1: pd.Series, comp2: pd.Series) -> float:\n \"\"\"Compute the total amount of acceleration increments on a plane.\n\n The Sway Total Excursion (a.k.a. TOTEX) provides a means of quantifying\n how much sway occurred on a plane over the total of an assessment.\n It is a complementary measure to the sway areas, as it covers also the\n amount of sway occurred within a given geometric area.\n\n Parameters\n ----------\n comp1\n The first component of the signal\n comp2\n The second component of the signal\n\n Returns\n -------\n float\n The sway total excursion value\n \"\"\"\n # We take the sum of the norm of all acceleration increments\n return resultant_norm_planar(comp1.diff(), comp2.diff()).sum()" }, { "identifier": "TremorMeasures", "path": "dispel/providers/generic/tremor.py", "snippet": "class TremorMeasures(ProcessingStepGroup):\n r\"\"\"A group of tremor processing steps according a given data set.\n\n Parameters\n ----------\n sensor\n The type of sensor on which the extraction is to be performed.\n data_set_id\n The data set id on which the transformation is to be performed ('accelerometer',\n 'gyroscope').\n columns\n The columns onto which the signal's tremor measures are to be extracted.\n lower_bound\n The lower bound of frequencies below which the signal is filtered.\n upper_bound\n The upper bound of frequencies above which the signal is filtered.\n level_filter\n An optional :class:`~dispel.processing.level.LevelFilter` to determine the levels\n to be transformed. If no filter is provided, all levels will be transformed. The\n ``level_filter`` also accepts :class:`str`, :class:`~dispel.data.core.LevelId`\\ s\n and lists of either and passes them to a\n :class:`~dispel.processing.level.LevelIdFilter` for convenience.\n add_norm\n An optional boolean to determine if the norm should be added to the columns.\n\n Notes\n -----\n The lower and upper bound of the band filter values are set by default to 2.0 and\n 5.0.\n \"\"\"\n\n def __init__(\n self,\n sensor: SensorModality,\n data_set_id: str,\n lower_bound: float = 2.0,\n upper_bound: float = 5.0,\n add_norm: bool = True,\n add_average_signal: bool = True,\n columns: Optional[List[str]] = None,\n level_filter: Optional[LevelFilterType] = None,\n ):\n # initialize the columns if they are not specified\n columns = columns or list(\"xyz\")\n\n # initialize processing steps\n steps: List[ProcessingStep] = []\n\n # Define a new data set id specific to the power spectrum measures\n power_spectrum_id = data_set_id\n\n # Optional addition of the norm\n if add_norm:\n add_euclidean_norm = Add(\n data_set_id=data_set_id, method=euclidean_norm, columns=columns\n )\n steps.append(add_euclidean_norm)\n power_spectrum_id = add_euclidean_norm.new_data_set_id\n all_columns = [*columns, \"\".join(columns)]\n else:\n all_columns = columns\n\n # PSD Transformation\n psd_step = PowerSpectrumDensity(\n data_set_id=power_spectrum_id,\n columns=all_columns,\n )\n steps.append(psd_step)\n power_spectrum_id = psd_step.new_data_set_id\n\n # Extraction\n if add_average_signal:\n steps.append(\n ExtractAverageSignalEnergy(\n sensor=sensor,\n data_set_id=data_set_id,\n columns=columns,\n )\n )\n steps.append(\n ExtractPowerSpectrumMeasures(\n sensor=sensor,\n data_set_id=power_spectrum_id,\n columns=all_columns,\n lower_bound=lower_bound,\n upper_bound=upper_bound,\n )\n )\n\n super().__init__(steps, level_filter=level_filter)" }, { "identifier": "AP_ML_COLUMN_MAPPINGS", "path": "dispel/signal/accelerometer.py", "snippet": "AP_ML_COLUMN_MAPPINGS = {\n \"userAccelerationZ\": \"ap\",\n \"userAccelerationY\": \"ml\",\n \"userAccelerationX\": \"v\",\n}" }, { "identifier": "transform_ap_ml_acceleration", "path": "dispel/signal/accelerometer.py", "snippet": "def transform_ap_ml_acceleration(data: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Transform accelerometer axis from X,Y,Z to AP,ML, and v.\"\"\"\n return data.rename(columns=AP_ML_COLUMN_MAPPINGS) * -1" }, { "identifier": "derive_time_data_frame", "path": "dispel/signal/core.py", "snippet": "def derive_time_data_frame(data: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Derive a data frame based on its time-based index.\n\n This method is preferably used for data frames for which one wants to derive for\n each column (instead of using ``data.apply(derive_time_series)``).\n\n Parameters\n ----------\n data\n The pandas data frame for which to derive the values based on time. The data\n frame must have a time-based index. See :func:`index_time_diff`.\n\n Returns\n -------\n pandas.DataFrame\n The time derivative of the values of ``data``.\n\n \"\"\"\n delta_t = index_time_diff(data)\n return (data.diff().T / delta_t).T" }, { "identifier": "euclidean_norm", "path": "dispel/signal/core.py", "snippet": "def euclidean_norm(data: pd.DataFrame) -> pd.Series:\n \"\"\"Calculate the euclidean norm of a pandas Data Frame.\n\n Parameters\n ----------\n data\n A pandas data frame for which to compute the euclidean norm\n\n Returns\n -------\n pandas.Series\n The euclidean norm of ``data``\n \"\"\"\n return data.pow(2).sum(axis=1).apply(np.sqrt)" } ]
from typing import Iterable, List, Optional from scipy.signal import medfilt from scipy.stats import iqr as scipy_iqr from dispel.data.core import EntityType, Reading from dispel.data.flags import FlagSeverity, FlagType from dispel.data.levels import Level from dispel.data.measures import MeasureValueDefinitionPrototype from dispel.data.raw import ACCELEROMETER_COLUMNS, RawDataValueDefinition from dispel.data.validators import GREATER_THAN_ZERO from dispel.data.values import AbbreviatedValue as AV from dispel.processing import ProcessingStep from dispel.processing.data_set import FlagDataSetStep, transformation from dispel.processing.extract import ExtractStep from dispel.processing.flags import flag from dispel.processing.level import LevelIdFilter, ProcessingStepGroup from dispel.processing.modalities import LimbModality, SensorModality from dispel.processing.transform import TransformStep from dispel.providers.generic.flags.generic import ( FrequencyLowerThanSBTThres, MaxTimeIncrement, ) from dispel.providers.generic.flags.le_flags import ( FlagAdjustmentNonBeltSBT, FlagNonBeltSBT, FlagPostAdjustExcessiveMotion, FlagStabilisationExcessiveMotion, PlacementClassificationGroup, ) from dispel.providers.generic.preprocessing import ( FilterPhysiologicalNoise, FilterSensorNoise, PreprocessingSteps, ) from dispel.providers.generic.sensor import RenameColumns, TransformUserAcceleration from dispel.providers.generic.tasks.sbt_utt.const import ( FIXED_SIGN_AMP_THRESHOLD, KERNEL_WINDOW_SEGMENT, MIN_COVERAGE_THRESHOLD, TASK_NAME_SBT, ) from dispel.providers.generic.tasks.sbt_utt.sbt_bouts import ( SBTBoutExtractStep, SBTBoutStrategyModality, ) from dispel.providers.generic.tasks.sbt_utt.sbt_func import ( circle_area, data_coverage_fraction, ellipse_area, label_bouts, reject_short_bouts, sway_jerk, sway_total_excursion, ) from dispel.providers.generic.tremor import TremorMeasures from dispel.signal.accelerometer import ( AP_ML_COLUMN_MAPPINGS, transform_ap_ml_acceleration, ) from dispel.signal.core import derive_time_data_frame, euclidean_norm import pandas as pd
19,859
"""Static Balance Test module. A module containing the functionality to process the *Static Balance* test (SBT). """ class SBTTremorMeasuresGroup(ProcessingStepGroup): """Tremor measure for the SBT from accelerometer.""" def __init__(self, data_set_id, **kwargs): new_column_names = { "userAccelerationX": "x", "userAccelerationY": "y", "userAccelerationZ": "z", } steps = [
"""Static Balance Test module. A module containing the functionality to process the *Static Balance* test (SBT). """ class SBTTremorMeasuresGroup(ProcessingStepGroup): """Tremor measure for the SBT from accelerometer.""" def __init__(self, data_set_id, **kwargs): new_column_names = { "userAccelerationX": "x", "userAccelerationY": "y", "userAccelerationZ": "z", } steps = [
RenameColumns(data_set_id, **new_column_names),
29
2023-11-14 10:06:46+00:00
24k
Jisencc/yolov5_dual_weighting
segment/val.py
[ { "identifier": "DetectMultiBackend", "path": "models/common.py", "snippet": "class DetectMultiBackend(nn.Module):\n # YOLOv5 MultiBackend class for python inference on various backends\n def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):\n # Usage:\n # PyTorch: weights = *.pt\n # TorchScript: *.torchscript\n # ONNX Runtime: *.onnx\n # ONNX OpenCV DNN: *.onnx --dnn\n # OpenVINO: *_openvino_model\n # CoreML: *.mlmodel\n # TensorRT: *.engine\n # TensorFlow SavedModel: *_saved_model\n # TensorFlow GraphDef: *.pb\n # TensorFlow Lite: *.tflite\n # TensorFlow Edge TPU: *_edgetpu.tflite\n # PaddlePaddle: *_paddle_model\n from models.experimental import attempt_download, attempt_load # scoped to avoid circular import\n\n super().__init__()\n w = str(weights[0] if isinstance(weights, list) else weights)\n pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)\n fp16 &= pt or jit or onnx or engine or triton # FP16\n nhwc = coreml or saved_model or pb or tflite or edgetpu # BHWC formats (vs torch BCWH)\n stride = 32 # default stride\n cuda = torch.cuda.is_available() and device.type != 'cpu' # use CUDA\n if not (pt or triton):\n w = attempt_download(w) # download if not local\n\n if pt: # PyTorch\n model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)\n stride = max(int(model.stride.max()), 32) # model stride\n names = model.module.names if hasattr(model, 'module') else model.names # get class names\n model.half() if fp16 else model.float()\n self.model = model # explicitly assign for to(), cpu(), cuda(), half()\n elif jit: # TorchScript\n LOGGER.info(f'Loading {w} for TorchScript inference...')\n extra_files = {'config.txt': ''} # model metadata\n model = torch.jit.load(w, _extra_files=extra_files, map_location=device)\n model.half() if fp16 else model.float()\n if extra_files['config.txt']: # load metadata dict\n d = json.loads(extra_files['config.txt'],\n object_hook=lambda d: {\n int(k) if k.isdigit() else k: v\n for k, v in d.items()})\n stride, names = int(d['stride']), d['names']\n elif dnn: # ONNX OpenCV DNN\n LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')\n check_requirements('opencv-python>=4.5.4')\n net = cv2.dnn.readNetFromONNX(w)\n elif onnx: # ONNX Runtime\n LOGGER.info(f'Loading {w} for ONNX Runtime inference...')\n check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))\n import onnxruntime\n providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']\n session = onnxruntime.InferenceSession(w, providers=providers)\n output_names = [x.name for x in session.get_outputs()]\n meta = session.get_modelmeta().custom_metadata_map # metadata\n if 'stride' in meta:\n stride, names = int(meta['stride']), eval(meta['names'])\n elif xml: # OpenVINO\n LOGGER.info(f'Loading {w} for OpenVINO inference...')\n check_requirements('openvino>=2023.0') # requires openvino-dev: https://pypi.org/project/openvino-dev/\n from openvino.runtime import Core, Layout, get_batch\n core = Core()\n if not Path(w).is_file(): # if not *.xml\n w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir\n ov_model = core.read_model(model=w, weights=Path(w).with_suffix('.bin'))\n if ov_model.get_parameters()[0].get_layout().empty:\n ov_model.get_parameters()[0].set_layout(Layout('NCHW'))\n batch_dim = get_batch(ov_model)\n if batch_dim.is_static:\n batch_size = batch_dim.get_length()\n ov_compiled_model = core.compile_model(ov_model, device_name='AUTO') # AUTO selects best available device\n stride, names = self._load_metadata(Path(w).with_suffix('.yaml')) # load metadata\n elif engine: # TensorRT\n LOGGER.info(f'Loading {w} for TensorRT inference...')\n import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download\n check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0\n if device.type == 'cpu':\n device = torch.device('cuda:0')\n Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))\n logger = trt.Logger(trt.Logger.INFO)\n with open(w, 'rb') as f, trt.Runtime(logger) as runtime:\n model = runtime.deserialize_cuda_engine(f.read())\n context = model.create_execution_context()\n bindings = OrderedDict()\n output_names = []\n fp16 = False # default updated below\n dynamic = False\n for i in range(model.num_bindings):\n name = model.get_binding_name(i)\n dtype = trt.nptype(model.get_binding_dtype(i))\n if model.binding_is_input(i):\n if -1 in tuple(model.get_binding_shape(i)): # dynamic\n dynamic = True\n context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))\n if dtype == np.float16:\n fp16 = True\n else: # output\n output_names.append(name)\n shape = tuple(context.get_binding_shape(i))\n im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)\n bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))\n binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())\n batch_size = bindings['images'].shape[0] # if dynamic, this is instead max batch size\n elif coreml: # CoreML\n LOGGER.info(f'Loading {w} for CoreML inference...')\n import coremltools as ct\n model = ct.models.MLModel(w)\n elif saved_model: # TF SavedModel\n LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')\n import tensorflow as tf\n keras = False # assume TF1 saved_model\n model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)\n elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt\n LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')\n import tensorflow as tf\n\n def wrap_frozen_graph(gd, inputs, outputs):\n x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=''), []) # wrapped\n ge = x.graph.as_graph_element\n return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))\n\n def gd_outputs(gd):\n name_list, input_list = [], []\n for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef\n name_list.append(node.name)\n input_list.extend(node.input)\n return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))\n\n gd = tf.Graph().as_graph_def() # TF GraphDef\n with open(w, 'rb') as f:\n gd.ParseFromString(f.read())\n frozen_func = wrap_frozen_graph(gd, inputs='x:0', outputs=gd_outputs(gd))\n elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python\n try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu\n from tflite_runtime.interpreter import Interpreter, load_delegate\n except ImportError:\n import tensorflow as tf\n Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,\n if edgetpu: # TF Edge TPU https://coral.ai/software/#edgetpu-runtime\n LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')\n delegate = {\n 'Linux': 'libedgetpu.so.1',\n 'Darwin': 'libedgetpu.1.dylib',\n 'Windows': 'edgetpu.dll'}[platform.system()]\n interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])\n else: # TFLite\n LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')\n interpreter = Interpreter(model_path=w) # load TFLite model\n interpreter.allocate_tensors() # allocate\n input_details = interpreter.get_input_details() # inputs\n output_details = interpreter.get_output_details() # outputs\n # load metadata\n with contextlib.suppress(zipfile.BadZipFile):\n with zipfile.ZipFile(w, 'r') as model:\n meta_file = model.namelist()[0]\n meta = ast.literal_eval(model.read(meta_file).decode('utf-8'))\n stride, names = int(meta['stride']), meta['names']\n elif tfjs: # TF.js\n raise NotImplementedError('ERROR: YOLOv5 TF.js inference is not supported')\n elif paddle: # PaddlePaddle\n LOGGER.info(f'Loading {w} for PaddlePaddle inference...')\n check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')\n import paddle.inference as pdi\n if not Path(w).is_file(): # if not *.pdmodel\n w = next(Path(w).rglob('*.pdmodel')) # get *.pdmodel file from *_paddle_model dir\n weights = Path(w).with_suffix('.pdiparams')\n config = pdi.Config(str(w), str(weights))\n if cuda:\n config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)\n predictor = pdi.create_predictor(config)\n input_handle = predictor.get_input_handle(predictor.get_input_names()[0])\n output_names = predictor.get_output_names()\n elif triton: # NVIDIA Triton Inference Server\n LOGGER.info(f'Using {w} as Triton Inference Server...')\n check_requirements('tritonclient[all]')\n from utils.triton import TritonRemoteModel\n model = TritonRemoteModel(url=w)\n nhwc = model.runtime.startswith('tensorflow')\n else:\n raise NotImplementedError(f'ERROR: {w} is not a supported format')\n\n # class names\n if 'names' not in locals():\n names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)}\n if names[0] == 'n01440764' and len(names) == 1000: # ImageNet\n names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] # human-readable names\n\n self.__dict__.update(locals()) # assign all variables to self\n\n def forward(self, im, augment=False, visualize=False):\n # YOLOv5 MultiBackend inference\n b, ch, h, w = im.shape # batch, channel, height, width\n if self.fp16 and im.dtype != torch.float16:\n im = im.half() # to FP16\n if self.nhwc:\n im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)\n\n if self.pt: # PyTorch\n y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)\n elif self.jit: # TorchScript\n y = self.model(im)\n elif self.dnn: # ONNX OpenCV DNN\n im = im.cpu().numpy() # torch to numpy\n self.net.setInput(im)\n y = self.net.forward()\n elif self.onnx: # ONNX Runtime\n im = im.cpu().numpy() # torch to numpy\n y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})\n elif self.xml: # OpenVINO\n im = im.cpu().numpy() # FP32\n y = list(self.ov_compiled_model(im).values())\n elif self.engine: # TensorRT\n if self.dynamic and im.shape != self.bindings['images'].shape:\n i = self.model.get_binding_index('images')\n self.context.set_binding_shape(i, im.shape) # reshape if dynamic\n self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)\n for name in self.output_names:\n i = self.model.get_binding_index(name)\n self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))\n s = self.bindings['images'].shape\n assert im.shape == s, f\"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}\"\n self.binding_addrs['images'] = int(im.data_ptr())\n self.context.execute_v2(list(self.binding_addrs.values()))\n y = [self.bindings[x].data for x in sorted(self.output_names)]\n elif self.coreml: # CoreML\n im = im.cpu().numpy()\n im = Image.fromarray((im[0] * 255).astype('uint8'))\n # im = im.resize((192, 320), Image.BILINEAR)\n y = self.model.predict({'image': im}) # coordinates are xywh normalized\n if 'confidence' in y:\n box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels\n conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)\n y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)\n else:\n y = list(reversed(y.values())) # reversed for segmentation models (pred, proto)\n elif self.paddle: # PaddlePaddle\n im = im.cpu().numpy().astype(np.float32)\n self.input_handle.copy_from_cpu(im)\n self.predictor.run()\n y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]\n elif self.triton: # NVIDIA Triton Inference Server\n y = self.model(im)\n else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)\n im = im.cpu().numpy()\n if self.saved_model: # SavedModel\n y = self.model(im, training=False) if self.keras else self.model(im)\n elif self.pb: # GraphDef\n y = self.frozen_func(x=self.tf.constant(im))\n else: # Lite or Edge TPU\n input = self.input_details[0]\n int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model\n if int8:\n scale, zero_point = input['quantization']\n im = (im / scale + zero_point).astype(np.uint8) # de-scale\n self.interpreter.set_tensor(input['index'], im)\n self.interpreter.invoke()\n y = []\n for output in self.output_details:\n x = self.interpreter.get_tensor(output['index'])\n if int8:\n scale, zero_point = output['quantization']\n x = (x.astype(np.float32) - zero_point) * scale # re-scale\n y.append(x)\n y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]\n y[0][..., :4] *= [w, h, w, h] # xywh normalized to pixels\n\n if isinstance(y, (list, tuple)):\n return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]\n else:\n return self.from_numpy(y)\n\n def from_numpy(self, x):\n return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x\n\n def warmup(self, imgsz=(1, 3, 640, 640)):\n # Warmup model by running inference once\n warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton\n if any(warmup_types) and (self.device.type != 'cpu' or self.triton):\n im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input\n for _ in range(2 if self.jit else 1): #\n self.forward(im) # warmup\n\n @staticmethod\n def _model_type(p='path/to/model.pt'):\n # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx\n # types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]\n from export import export_formats\n from utils.downloads import is_url\n sf = list(export_formats().Suffix) # export suffixes\n if not is_url(p, check=False):\n check_suffix(p, sf) # checks\n url = urlparse(p) # if url may be Triton inference server\n types = [s in Path(p).name for s in sf]\n types[8] &= not types[9] # tflite &= not edgetpu\n triton = not any(types) and all([any(s in url.scheme for s in ['http', 'grpc']), url.netloc])\n return types + [triton]\n\n @staticmethod\n def _load_metadata(f=Path('path/to/meta.yaml')):\n # Load metadata from meta.yaml if it exists\n if f.exists():\n d = yaml_load(f)\n return d['stride'], d['names'] # assign stride, names\n return None, None" }, { "identifier": "SegmentationModel", "path": "models/yolo.py", "snippet": "class SegmentationModel(DetectionModel):\n # YOLOv5 segmentation model\n def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None):\n super().__init__(cfg, ch, nc, anchors)" }, { "identifier": "Callbacks", "path": "utils/callbacks.py", "snippet": "class Callbacks:\n \"\"\"\"\n Handles all registered callbacks for YOLOv5 Hooks\n \"\"\"\n\n def __init__(self):\n # Define the available callbacks\n self._callbacks = {\n 'on_pretrain_routine_start': [],\n 'on_pretrain_routine_end': [],\n 'on_train_start': [],\n 'on_train_epoch_start': [],\n 'on_train_batch_start': [],\n 'optimizer_step': [],\n 'on_before_zero_grad': [],\n 'on_train_batch_end': [],\n 'on_train_epoch_end': [],\n 'on_val_start': [],\n 'on_val_batch_start': [],\n 'on_val_image_end': [],\n 'on_val_batch_end': [],\n 'on_val_end': [],\n 'on_fit_epoch_end': [], # fit = train + val\n 'on_model_save': [],\n 'on_train_end': [],\n 'on_params_update': [],\n 'teardown': [], }\n self.stop_training = False # set True to interrupt training\n\n def register_action(self, hook, name='', callback=None):\n \"\"\"\n Register a new action to a callback hook\n\n Args:\n hook: The callback hook name to register the action to\n name: The name of the action for later reference\n callback: The callback to fire\n \"\"\"\n assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n assert callable(callback), f\"callback '{callback}' is not callable\"\n self._callbacks[hook].append({'name': name, 'callback': callback})\n\n def get_registered_actions(self, hook=None):\n \"\"\"\"\n Returns all the registered actions by callback hook\n\n Args:\n hook: The name of the hook to check, defaults to all\n \"\"\"\n return self._callbacks[hook] if hook else self._callbacks\n\n def run(self, hook, *args, thread=False, **kwargs):\n \"\"\"\n Loop through the registered actions and fire all callbacks on main thread\n\n Args:\n hook: The name of the hook to check, defaults to all\n args: Arguments to receive from YOLOv5\n thread: (boolean) Run callbacks in daemon thread\n kwargs: Keyword Arguments to receive from YOLOv5\n \"\"\"\n\n assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n for logger in self._callbacks[hook]:\n if thread:\n threading.Thread(target=logger['callback'], args=args, kwargs=kwargs, daemon=True).start()\n else:\n logger['callback'](*args, **kwargs)" }, { "identifier": "LOGGER", "path": "utils/general.py", "snippet": "FILE = Path(__file__).resolve()\nROOT = FILE.parents[1] # YOLOv5 root directory\nRANK = int(os.getenv('RANK', -1))\nNUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads\nDATASETS_DIR = Path(os.getenv('YOLOv5_DATASETS_DIR', ROOT.parent / 'datasets')) # global datasets directory\nAUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode\nVERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode\nTQDM_BAR_FORMAT = '{l_bar}{bar:10}{r_bar}' # tqdm bar format\nFONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf\nLOGGING_NAME = 'yolov5'\nLOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)\nCONFIG_DIR = user_config_dir() # Ultralytics settings dir\ndef is_ascii(s=''):\ndef is_chinese(s='人工智能'):\ndef is_colab():\ndef is_jupyter():\ndef is_kaggle():\ndef is_docker() -> bool:\ndef is_writeable(dir, test=False):\ndef set_logging(name=LOGGING_NAME, verbose=True):\ndef user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):\n def __init__(self, t=0.0):\n def __enter__(self):\n def __exit__(self, type, value, traceback):\n def time(self):\n def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):\n def _timeout_handler(self, signum, frame):\n def __enter__(self):\n def __exit__(self, exc_type, exc_val, exc_tb):\n def __init__(self, new_dir):\n def __enter__(self):\n def __exit__(self, exc_type, exc_val, exc_tb):\ndef methods(instance):\ndef print_args(args: Optional[dict] = None, show_file=True, show_func=False):\ndef init_seeds(seed=0, deterministic=False):\ndef intersect_dicts(da, db, exclude=()):\ndef get_default_args(func):\ndef get_latest_run(search_dir='.'):\ndef file_age(path=__file__):\ndef file_date(path=__file__):\ndef file_size(path):\ndef check_online():\n def run_once():\ndef git_describe(path=ROOT): # path must be a directory\ndef check_git_status(repo='ultralytics/yolov5', branch='master'):\ndef check_git_info(path='.'):\ndef check_python(minimum='3.8.0'):\ndef check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):\ndef check_img_size(imgsz, s=32, floor=0):\ndef check_imshow(warn=False):\ndef check_suffix(file='yolov5s.pt', suffix=('.pt', ), msg=''):\ndef check_yaml(file, suffix=('.yaml', '.yml')):\ndef check_file(file, suffix=''):\ndef check_font(font=FONT, progress=False):\ndef check_dataset(data, autodownload=True):\ndef check_amp(model):\n def amp_allclose(model, im):\ndef yaml_load(file='data.yaml'):\ndef yaml_save(file='data.yaml', data={}):\ndef unzip_file(file, path=None, exclude=('.DS_Store', '__MACOSX')):\ndef url2file(url):\ndef download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3):\n def download_one(url, dir):\ndef make_divisible(x, divisor):\ndef clean_str(s):\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\ndef colorstr(*input):\ndef labels_to_class_weights(labels, nc=80):\ndef labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):\ndef coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)\ndef xyxy2xywh(x):\ndef xywh2xyxy(x):\ndef xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):\ndef xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):\ndef xyn2xy(x, w=640, h=640, padw=0, padh=0):\ndef segment2box(segment, width=640, height=640):\ndef segments2boxes(segments):\ndef resample_segments(segments, n=1000):\ndef scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):\ndef scale_segments(img1_shape, segments, img0_shape, ratio_pad=None, normalize=False):\ndef clip_boxes(boxes, shape):\ndef clip_segments(segments, shape):\ndef non_max_suppression(\n prediction,\n conf_thres=0.25,\n iou_thres=0.45,\n classes=None,\n agnostic=False,\n multi_label=False,\n labels=(),\n max_det=300,\n nm=0, # number of masks\n):\ndef strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()\ndef print_mutation(keys, results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')):\ndef apply_classifier(x, model, img, im0):\ndef increment_path(path, exist_ok=False, sep='', mkdir=False):\ndef imread(filename, flags=cv2.IMREAD_COLOR):\ndef imwrite(filename, img):\ndef imshow(path, im):\nclass Profile(contextlib.ContextDecorator):\nclass Timeout(contextlib.ContextDecorator):\nclass WorkingDirectory(contextlib.ContextDecorator):" }, { "identifier": "ConfusionMatrix", "path": "utils/metrics.py", "snippet": "class ConfusionMatrix:\n # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix\n def __init__(self, nc, conf=0.25, iou_thres=0.45):\n self.matrix = np.zeros((nc + 1, nc + 1))\n self.nc = nc # number of classes\n self.conf = conf\n self.iou_thres = iou_thres\n\n def process_batch(self, detections, labels):\n \"\"\"\n Return intersection-over-union (Jaccard index) of boxes.\n Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n Arguments:\n detections (Array[N, 6]), x1, y1, x2, y2, conf, class\n labels (Array[M, 5]), class, x1, y1, x2, y2\n Returns:\n None, updates confusion matrix accordingly\n \"\"\"\n if detections is None:\n gt_classes = labels.int()\n for gc in gt_classes:\n self.matrix[self.nc, gc] += 1 # background FN\n return\n\n detections = detections[detections[:, 4] > self.conf]\n gt_classes = labels[:, 0].int()\n detection_classes = detections[:, 5].int()\n iou = box_iou(labels[:, 1:], detections[:, :4])\n\n x = torch.where(iou > self.iou_thres)\n if x[0].shape[0]:\n matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n if x[0].shape[0] > 1:\n matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n else:\n matches = np.zeros((0, 3))\n\n n = matches.shape[0] > 0\n m0, m1, _ = matches.transpose().astype(int)\n for i, gc in enumerate(gt_classes):\n j = m0 == i\n if n and sum(j) == 1:\n self.matrix[detection_classes[m1[j]], gc] += 1 # correct\n else:\n self.matrix[self.nc, gc] += 1 # true background\n\n if n:\n for i, dc in enumerate(detection_classes):\n if not any(m1 == i):\n self.matrix[dc, self.nc] += 1 # predicted background\n\n def tp_fp(self):\n tp = self.matrix.diagonal() # true positives\n fp = self.matrix.sum(1) - tp # false positives\n # fn = self.matrix.sum(0) - tp # false negatives (missed detections)\n return tp[:-1], fp[:-1] # remove background class\n\n @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')\n def plot(self, normalize=True, save_dir='', names=()):\n import seaborn as sn\n\n array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns\n array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)\n\n fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)\n nc, nn = self.nc, len(names) # number of classes, names\n sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size\n labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels\n ticklabels = (names + ['background']) if labels else 'auto'\n with warnings.catch_warnings():\n warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered\n sn.heatmap(array,\n ax=ax,\n annot=nc < 30,\n annot_kws={\n 'size': 8},\n cmap='Blues',\n fmt='.2f',\n square=True,\n vmin=0.0,\n xticklabels=ticklabels,\n yticklabels=ticklabels).set_facecolor((1, 1, 1))\n ax.set_xlabel('True')\n ax.set_ylabel('Predicted')\n ax.set_title('Confusion Matrix')\n fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)\n plt.close(fig)\n\n def print(self):\n for i in range(self.nc + 1):\n print(' '.join(map(str, self.matrix[i])))" }, { "identifier": "box_iou", "path": "utils/metrics.py", "snippet": "def box_iou(box1, box2, eps=1e-7):\n # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n \"\"\"\n Return intersection-over-union (Jaccard index) of boxes.\n Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n Arguments:\n box1 (Tensor[N, 4])\n box2 (Tensor[M, 4])\n Returns:\n iou (Tensor[N, M]): the NxM matrix containing the pairwise\n IoU values for every element in boxes1 and boxes2\n \"\"\"\n\n # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)\n inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\n\n # IoU = inter / (area1 + area2 - inter)\n return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)" }, { "identifier": "output_to_target", "path": "utils/plots.py", "snippet": "def output_to_target(output, max_det=300):\n # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting\n targets = []\n for i, o in enumerate(output):\n box, conf, cls = o[:max_det, :6].cpu().split((4, 1, 1), 1)\n j = torch.full((conf.shape[0], 1), i)\n targets.append(torch.cat((j, cls, xyxy2xywh(box), conf), 1))\n return torch.cat(targets, 0).numpy()" }, { "identifier": "plot_val_study", "path": "utils/plots.py", "snippet": "def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study()\n # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)\n save_dir = Path(file).parent if file else Path(dir)\n plot2 = False # plot additional results\n if plot2:\n ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()\n\n fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)\n # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:\n for f in sorted(save_dir.glob('study*.txt')):\n y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T\n x = np.arange(y.shape[1]) if x is None else np.array(x)\n if plot2:\n s = ['P', 'R', '[email protected]', '[email protected]:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']\n for i in range(7):\n ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)\n ax[i].set_title(s[i])\n\n j = y[3].argmax() + 1\n ax2.plot(y[5, 1:j],\n y[3, 1:j] * 1E2,\n '.-',\n linewidth=2,\n markersize=8,\n label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))\n\n ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],\n 'k.-',\n linewidth=2,\n markersize=8,\n alpha=.25,\n label='EfficientDet')\n\n ax2.grid(alpha=0.2)\n ax2.set_yticks(np.arange(20, 60, 5))\n ax2.set_xlim(0, 57)\n ax2.set_ylim(25, 55)\n ax2.set_xlabel('GPU Speed (ms/img)')\n ax2.set_ylabel('COCO AP val')\n ax2.legend(loc='lower right')\n f = save_dir / 'study.png'\n print(f'Saving {f}...')\n plt.savefig(f, dpi=300)" }, { "identifier": "create_dataloader", "path": "utils/segment/dataloaders.py", "snippet": "def create_dataloader(path,\n imgsz,\n batch_size,\n stride,\n single_cls=False,\n hyp=None,\n augment=False,\n cache=False,\n pad=0.0,\n rect=False,\n rank=-1,\n workers=8,\n image_weights=False,\n quad=False,\n prefix='',\n shuffle=False,\n mask_downsample_ratio=1,\n overlap_mask=False,\n seed=0):\n if rect and shuffle:\n LOGGER.warning('WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False')\n shuffle = False\n with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP\n dataset = LoadImagesAndLabelsAndMasks(\n path,\n imgsz,\n batch_size,\n augment=augment, # augmentation\n hyp=hyp, # hyperparameters\n rect=rect, # rectangular batches\n cache_images=cache,\n single_cls=single_cls,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix,\n downsample_ratio=mask_downsample_ratio,\n overlap=overlap_mask)\n\n batch_size = min(batch_size, len(dataset))\n nd = torch.cuda.device_count() # number of CUDA devices\n nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates\n generator = torch.Generator()\n generator.manual_seed(6148914691236517205 + seed + RANK)\n return loader(\n dataset,\n batch_size=batch_size,\n shuffle=shuffle and sampler is None,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabelsAndMasks.collate_fn4 if quad else LoadImagesAndLabelsAndMasks.collate_fn,\n worker_init_fn=seed_worker,\n generator=generator,\n ), dataset" }, { "identifier": "mask_iou", "path": "utils/segment/general.py", "snippet": "def mask_iou(mask1, mask2, eps=1e-7):\n \"\"\"\n mask1: [N, n] m1 means number of predicted objects\n mask2: [M, n] m2 means number of gt objects\n Note: n means image_w x image_h\n\n return: masks iou, [N, M]\n \"\"\"\n intersection = torch.matmul(mask1, mask2.t()).clamp(0)\n union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection\n return intersection / (union + eps)" }, { "identifier": "process_mask", "path": "utils/segment/general.py", "snippet": "def process_mask(protos, masks_in, bboxes, shape, upsample=False):\n \"\"\"\n Crop before upsample.\n proto_out: [mask_dim, mask_h, mask_w]\n out_masks: [n, mask_dim], n is number of masks after nms\n bboxes: [n, 4], n is number of masks after nms\n shape:input_image_size, (h, w)\n\n return: h, w, n\n \"\"\"\n\n c, mh, mw = protos.shape # CHW\n ih, iw = shape\n masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw) # CHW\n\n downsampled_bboxes = bboxes.clone()\n downsampled_bboxes[:, 0] *= mw / iw\n downsampled_bboxes[:, 2] *= mw / iw\n downsampled_bboxes[:, 3] *= mh / ih\n downsampled_bboxes[:, 1] *= mh / ih\n\n masks = crop_mask(masks, downsampled_bboxes) # CHW\n if upsample:\n masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW\n return masks.gt_(0.5)" }, { "identifier": "process_mask_native", "path": "utils/segment/general.py", "snippet": "def process_mask_native(protos, masks_in, bboxes, shape):\n \"\"\"\n Crop after upsample.\n protos: [mask_dim, mask_h, mask_w]\n masks_in: [n, mask_dim], n is number of masks after nms\n bboxes: [n, 4], n is number of masks after nms\n shape: input_image_size, (h, w)\n\n return: h, w, n\n \"\"\"\n c, mh, mw = protos.shape # CHW\n masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)\n gain = min(mh / shape[0], mw / shape[1]) # gain = old / new\n pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2 # wh padding\n top, left = int(pad[1]), int(pad[0]) # y, x\n bottom, right = int(mh - pad[1]), int(mw - pad[0])\n masks = masks[:, top:bottom, left:right]\n\n masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW\n masks = crop_mask(masks, bboxes) # CHW\n return masks.gt_(0.5)" }, { "identifier": "scale_image", "path": "utils/segment/general.py", "snippet": "def scale_image(im1_shape, masks, im0_shape, ratio_pad=None):\n \"\"\"\n img1_shape: model input shape, [h, w]\n img0_shape: origin pic shape, [h, w, 3]\n masks: [h, w, num]\n \"\"\"\n # Rescale coordinates (xyxy) from im1_shape to im0_shape\n if ratio_pad is None: # calculate from im0_shape\n gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1]) # gain = old / new\n pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2 # wh padding\n else:\n pad = ratio_pad[1]\n top, left = int(pad[1]), int(pad[0]) # y, x\n bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])\n\n if len(masks.shape) < 2:\n raise ValueError(f'\"len of masks shape\" should be 2 or 3, but got {len(masks.shape)}')\n masks = masks[top:bottom, left:right]\n # masks = masks.permute(2, 0, 1).contiguous()\n # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]\n # masks = masks.permute(1, 2, 0).contiguous()\n masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))\n\n if len(masks.shape) == 2:\n masks = masks[:, :, None]\n return masks" }, { "identifier": "Metrics", "path": "utils/segment/metrics.py", "snippet": "class Metrics:\n \"\"\"Metric for boxes and masks.\"\"\"\n\n def __init__(self) -> None:\n self.metric_box = Metric()\n self.metric_mask = Metric()\n\n def update(self, results):\n \"\"\"\n Args:\n results: Dict{'boxes': Dict{}, 'masks': Dict{}}\n \"\"\"\n self.metric_box.update(list(results['boxes'].values()))\n self.metric_mask.update(list(results['masks'].values()))\n\n def mean_results(self):\n return self.metric_box.mean_results() + self.metric_mask.mean_results()\n\n def class_result(self, i):\n return self.metric_box.class_result(i) + self.metric_mask.class_result(i)\n\n def get_maps(self, nc):\n return self.metric_box.get_maps(nc) + self.metric_mask.get_maps(nc)\n\n @property\n def ap_class_index(self):\n # boxes and masks have the same ap_class_index\n return self.metric_box.ap_class_index" }, { "identifier": "ap_per_class_box_and_mask", "path": "utils/segment/metrics.py", "snippet": "def ap_per_class_box_and_mask(\n tp_m,\n tp_b,\n conf,\n pred_cls,\n target_cls,\n plot=False,\n save_dir='.',\n names=(),\n):\n \"\"\"\n Args:\n tp_b: tp of boxes.\n tp_m: tp of masks.\n other arguments see `func: ap_per_class`.\n \"\"\"\n results_boxes = ap_per_class(tp_b,\n conf,\n pred_cls,\n target_cls,\n plot=plot,\n save_dir=save_dir,\n names=names,\n prefix='Box')[2:]\n results_masks = ap_per_class(tp_m,\n conf,\n pred_cls,\n target_cls,\n plot=plot,\n save_dir=save_dir,\n names=names,\n prefix='Mask')[2:]\n\n results = {\n 'boxes': {\n 'p': results_boxes[0],\n 'r': results_boxes[1],\n 'ap': results_boxes[3],\n 'f1': results_boxes[2],\n 'ap_class': results_boxes[4]},\n 'masks': {\n 'p': results_masks[0],\n 'r': results_masks[1],\n 'ap': results_masks[3],\n 'f1': results_masks[2],\n 'ap_class': results_masks[4]}}\n return results" }, { "identifier": "plot_images_and_masks", "path": "utils/segment/plots.py", "snippet": "@threaded\ndef plot_images_and_masks(images, targets, masks, paths=None, fname='images.jpg', names=None):\n # Plot image grid with labels\n if isinstance(images, torch.Tensor):\n images = images.cpu().float().numpy()\n if isinstance(targets, torch.Tensor):\n targets = targets.cpu().numpy()\n if isinstance(masks, torch.Tensor):\n masks = masks.cpu().numpy().astype(int)\n\n max_size = 1920 # max image size\n max_subplots = 16 # max image subplots, i.e. 4x4\n bs, _, h, w = images.shape # batch size, _, height, width\n bs = min(bs, max_subplots) # limit plot images\n ns = np.ceil(bs ** 0.5) # number of subplots (square)\n if np.max(images[0]) <= 1:\n images *= 255 # de-normalise (optional)\n\n # Build Image\n mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init\n for i, im in enumerate(images):\n if i == max_subplots: # if last batch has fewer images than we expect\n break\n x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin\n im = im.transpose(1, 2, 0)\n mosaic[y:y + h, x:x + w, :] = im\n\n # Resize (optional)\n scale = max_size / ns / max(h, w)\n if scale < 1:\n h = math.ceil(scale * h)\n w = math.ceil(scale * w)\n mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n # Annotate\n fs = int((h + w) * ns * 0.01) # font size\n annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)\n for i in range(i + 1):\n x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin\n annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders\n if paths:\n annotator.text([x + 5, y + 5], text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames\n if len(targets) > 0:\n idx = targets[:, 0] == i\n ti = targets[idx] # image targets\n\n boxes = xywh2xyxy(ti[:, 2:6]).T\n classes = ti[:, 1].astype('int')\n labels = ti.shape[1] == 6 # labels if no conf column\n conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)\n\n if boxes.shape[1]:\n if boxes.max() <= 1.01: # if normalized with tolerance 0.01\n boxes[[0, 2]] *= w # scale to pixels\n boxes[[1, 3]] *= h\n elif scale < 1: # absolute coords need scale if image scales\n boxes *= scale\n boxes[[0, 2]] += x\n boxes[[1, 3]] += y\n for j, box in enumerate(boxes.T.tolist()):\n cls = classes[j]\n color = colors(cls)\n cls = names[cls] if names else cls\n if labels or conf[j] > 0.25: # 0.25 conf thresh\n label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'\n annotator.box_label(box, label, color=color)\n\n # Plot masks\n if len(masks):\n if masks.max() > 1.0: # mean that masks are overlap\n image_masks = masks[[i]] # (1, 640, 640)\n nl = len(ti)\n index = np.arange(nl).reshape(nl, 1, 1) + 1\n image_masks = np.repeat(image_masks, nl, axis=0)\n image_masks = np.where(image_masks == index, 1.0, 0.0)\n else:\n image_masks = masks[idx]\n\n im = np.asarray(annotator.im).copy()\n for j, box in enumerate(boxes.T.tolist()):\n if labels or conf[j] > 0.25: # 0.25 conf thresh\n color = colors(classes[j])\n mh, mw = image_masks[j].shape\n if mh != h or mw != w:\n mask = image_masks[j].astype(np.uint8)\n mask = cv2.resize(mask, (w, h))\n mask = mask.astype(bool)\n else:\n mask = image_masks[j].astype(bool)\n with contextlib.suppress(Exception):\n im[y:y + h, x:x + w, :][mask] = im[y:y + h, x:x + w, :][mask] * 0.4 + np.array(color) * 0.6\n annotator.fromarray(im)\n annotator.im.save(fname) # save" }, { "identifier": "de_parallel", "path": "utils/torch_utils.py", "snippet": "def de_parallel(model):\n # De-parallelize a model: returns single-GPU model if model is of type DP or DDP\n return model.module if is_parallel(model) else model" }, { "identifier": "select_device", "path": "utils/torch_utils.py", "snippet": "def select_device(device='', batch_size=0, newline=True):\n # device = None or 'cpu' or 0 or '0' or '0,1,2,3'\n s = f'YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} '\n device = str(device).strip().lower().replace('cuda:', '').replace('none', '') # to string, 'cuda:0' to '0'\n cpu = device == 'cpu'\n mps = device == 'mps' # Apple Metal Performance Shaders (MPS)\n if cpu or mps:\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False\n elif device: # non-cpu device requested\n os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available()\n assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \\\n f\"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)\"\n\n if not cpu and not mps and torch.cuda.is_available(): # prefer GPU if available\n devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7\n n = len(devices) # device count\n if n > 1 and batch_size > 0: # check batch_size is divisible by device_count\n assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'\n space = ' ' * (len(s) + 1)\n for i, d in enumerate(devices):\n p = torch.cuda.get_device_properties(i)\n s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\\n\" # bytes to MB\n arg = 'cuda:0'\n elif mps and getattr(torch, 'has_mps', False) and torch.backends.mps.is_available(): # prefer MPS if available\n s += 'MPS\\n'\n arg = 'mps'\n else: # revert to CPU\n s += 'CPU\\n'\n arg = 'cpu'\n\n if not newline:\n s = s.rstrip()\n LOGGER.info(s)\n return torch.device(arg)" }, { "identifier": "smart_inference_mode", "path": "utils/torch_utils.py", "snippet": "def smart_inference_mode(torch_1_9=check_version(torch.__version__, '1.9.0')):\n # Applies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator\n def decorate(fn):\n return (torch.inference_mode if torch_1_9 else torch.no_grad)()(fn)\n\n return decorate" } ]
import argparse import json import os import subprocess import sys import numpy as np import torch import torch.nn.functional as F from multiprocessing.pool import ThreadPool from pathlib import Path from tqdm import tqdm from models.common import DetectMultiBackend from models.yolo import SegmentationModel from utils.callbacks import Callbacks from utils.general import (LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, Profile, check_dataset, check_img_size, check_requirements, check_yaml, coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args, scale_boxes, xywh2xyxy, xyxy2xywh) from utils.metrics import ConfusionMatrix, box_iou from utils.plots import output_to_target, plot_val_study from utils.segment.dataloaders import create_dataloader from utils.segment.general import mask_iou, process_mask, process_mask_native, scale_image from utils.segment.metrics import Metrics, ap_per_class_box_and_mask from utils.segment.plots import plot_images_and_masks from utils.torch_utils import de_parallel, select_device, smart_inference_mode from pycocotools.mask import encode from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval
14,938
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Validate a trained YOLOv5 segment model on a segment dataset Usage: $ bash data/scripts/get_coco.sh --val --segments # download COCO-segments val split (1G, 5000 images) $ python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640 # validate COCO-segments Usage - formats: $ python segment/val.py --weights yolov5s-seg.pt # PyTorch yolov5s-seg.torchscript # TorchScript yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn yolov5s-seg_openvino_label # OpenVINO yolov5s-seg.engine # TensorRT yolov5s-seg.mlmodel # CoreML (macOS-only) yolov5s-seg_saved_model # TensorFlow SavedModel yolov5s-seg.pb # TensorFlow GraphDef yolov5s-seg.tflite # TensorFlow Lite yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU yolov5s-seg_paddle_model # PaddlePaddle """ FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative def save_one_txt(predn, save_conf, shape, file): # Save one txt result gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh for *xyxy, conf, cls in predn.tolist(): xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format with open(file, 'a') as f: f.write(('%g ' * len(line)).rstrip() % line + '\n') def save_one_json(predn, jdict, path, class_map, pred_masks): # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236} def single_encode(x): rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0] rle['counts'] = rle['counts'].decode('utf-8') return rle image_id = int(path.stem) if path.stem.isnumeric() else path.stem box = xyxy2xywh(predn[:, :4]) # xywh box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner pred_masks = np.transpose(pred_masks, (2, 0, 1)) with ThreadPool(NUM_THREADS) as pool: rles = pool.map(single_encode, pred_masks) for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())): jdict.append({ 'image_id': image_id, 'category_id': class_map[int(p[5])], 'bbox': [round(x, 3) for x in b], 'score': round(p[4], 5), 'segmentation': rles[i]}) def process_batch(detections, labels, iouv, pred_masks=None, gt_masks=None, overlap=False, masks=False): """ Return correct prediction matrix Arguments: detections (array[N, 6]), x1, y1, x2, y2, conf, class labels (array[M, 5]), class, x1, y1, x2, y2 Returns: correct (array[N, 10]), for 10 IoU levels """ if masks: if overlap: nl = len(labels) index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1 gt_masks = gt_masks.repeat(nl, 1, 1) # shape(1,640,640) -> (n,640,640) gt_masks = torch.where(gt_masks == index, 1.0, 0.0) if gt_masks.shape[1:] != pred_masks.shape[1:]: gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0] gt_masks = gt_masks.gt_(0.5) iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1)) else: # boxes iou = box_iou(labels[:, 1:], detections[:, :4]) correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool) correct_class = labels[:, 0:1] == detections[:, 5] for i in range(len(iouv)): x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match if x[0].shape[0]: matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou] if x[0].shape[0] > 1: matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 1], return_index=True)[1]] # matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 0], return_index=True)[1]] correct[matches[:, 1].astype(int), i] = True return torch.tensor(correct, dtype=torch.bool, device=iouv.device)
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Validate a trained YOLOv5 segment model on a segment dataset Usage: $ bash data/scripts/get_coco.sh --val --segments # download COCO-segments val split (1G, 5000 images) $ python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640 # validate COCO-segments Usage - formats: $ python segment/val.py --weights yolov5s-seg.pt # PyTorch yolov5s-seg.torchscript # TorchScript yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn yolov5s-seg_openvino_label # OpenVINO yolov5s-seg.engine # TensorRT yolov5s-seg.mlmodel # CoreML (macOS-only) yolov5s-seg_saved_model # TensorFlow SavedModel yolov5s-seg.pb # TensorFlow GraphDef yolov5s-seg.tflite # TensorFlow Lite yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU yolov5s-seg_paddle_model # PaddlePaddle """ FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative def save_one_txt(predn, save_conf, shape, file): # Save one txt result gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh for *xyxy, conf, cls in predn.tolist(): xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format with open(file, 'a') as f: f.write(('%g ' * len(line)).rstrip() % line + '\n') def save_one_json(predn, jdict, path, class_map, pred_masks): # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236} def single_encode(x): rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0] rle['counts'] = rle['counts'].decode('utf-8') return rle image_id = int(path.stem) if path.stem.isnumeric() else path.stem box = xyxy2xywh(predn[:, :4]) # xywh box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner pred_masks = np.transpose(pred_masks, (2, 0, 1)) with ThreadPool(NUM_THREADS) as pool: rles = pool.map(single_encode, pred_masks) for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())): jdict.append({ 'image_id': image_id, 'category_id': class_map[int(p[5])], 'bbox': [round(x, 3) for x in b], 'score': round(p[4], 5), 'segmentation': rles[i]}) def process_batch(detections, labels, iouv, pred_masks=None, gt_masks=None, overlap=False, masks=False): """ Return correct prediction matrix Arguments: detections (array[N, 6]), x1, y1, x2, y2, conf, class labels (array[M, 5]), class, x1, y1, x2, y2 Returns: correct (array[N, 10]), for 10 IoU levels """ if masks: if overlap: nl = len(labels) index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1 gt_masks = gt_masks.repeat(nl, 1, 1) # shape(1,640,640) -> (n,640,640) gt_masks = torch.where(gt_masks == index, 1.0, 0.0) if gt_masks.shape[1:] != pred_masks.shape[1:]: gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0] gt_masks = gt_masks.gt_(0.5) iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1)) else: # boxes iou = box_iou(labels[:, 1:], detections[:, :4]) correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool) correct_class = labels[:, 0:1] == detections[:, 5] for i in range(len(iouv)): x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match if x[0].shape[0]: matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou] if x[0].shape[0] > 1: matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 1], return_index=True)[1]] # matches = matches[matches[:, 2].argsort()[::-1]] matches = matches[np.unique(matches[:, 0], return_index=True)[1]] correct[matches[:, 1].astype(int), i] = True return torch.tensor(correct, dtype=torch.bool, device=iouv.device)
@smart_inference_mode()
18
2023-11-12 13:28:26+00:00
24k
cyberark/ark-sdk-python
ark_sdk_python/cli_services/dpa/db/ark_dpa_db_policies_editor_service.py
[ { "identifier": "ArkInquirerRender", "path": "ark_sdk_python/args/ark_args_formatter.py", "snippet": "class ArkInquirerRender(ConsoleRender):\n # pylint: disable=keyword-arg-before-vararg,protected-access\n def __init__(self, event_generator=None, *args, **kwargs):\n super().__init__(event_generator=event_generator, theme=ARK_INQUIRER_THEME, *args, **kwargs)\n\n def render(self, question, answers=None):\n question.answers = answers or {}\n\n if question.ignore:\n return question.default\n\n clazz = self.render_factory(question.kind)\n render = clazz(question, terminal=self.terminal, theme=self._theme, show_default=question.show_default)\n if isinstance(\n render, (inquirer.render.console._text.Text, inquirer.render.console._password.Password, inquirer.render.console._path.Path)\n ):\n render.current = ''\n self.clear_eos()\n\n try:\n a = self._event_loop(render)\n if not a and question.default:\n a = question.default\n elif not a and question.name in answers:\n a = answers[question.name]\n return a\n finally:\n print('')\n\n def _print_header(self, render):\n base = render.get_header()\n\n header = base[: self.width - 9] + '...' if len(base) > self.width - 6 else base\n default_value = '{normal} ({default})'.format(default=render.question.default, normal=self.terminal.normal)\n show_default = render.question.default and render.show_default\n header += default_value if show_default else ''\n msg_template = '{t.move_up}{t.clear_eol}{tq.brackets_color}{tq.mark_color}?{tq.brackets_color} {msg}{t.normal}'\n\n escaped_current_value = str(render.get_current_value()).replace('{', '{{').replace('}', '}}')\n self.print_str(\n f'\\n{msg_template} {escaped_current_value}',\n msg=header,\n lf=not render.title_inline,\n tq=self._theme.Question,\n )" }, { "identifier": "ArkISPAuth", "path": "ark_sdk_python/auth/ark_isp_auth.py", "snippet": "class ArkISPAuth(ArkAuth):\n def __perform_identity_authentication(\n self, profile: ArkProfile, auth_profile: ArkAuthProfile, secret: Optional[ArkSecret], force: bool\n ) -> ArkToken:\n try:\n method_settings = cast(IdentityArkAuthMethodSettings, auth_profile.auth_method_settings)\n identity = ArkIdentity(\n username=auth_profile.username,\n password=secret.secret.get_secret_value() if secret else None,\n identity_url=method_settings.identity_url,\n mfa_type=method_settings.identity_mfa_method,\n logger=self._logger,\n cache_authentication=self._cache_authentication,\n )\n identity.auth_identity(profile, ArkSystemConfig.is_interactive() and method_settings.identity_mfa_interactive, force)\n env = AwsEnv(os.environ.get('DEPLOY_ENV', AwsEnv.PROD.value))\n found_env = list(filter(lambda e: ROOT_DOMAIN[e] in identity.identity_url, ROOT_DOMAIN.keys()))\n if found_env:\n env = found_env[0]\n token_lifetime = identity.session_details.token_lifetime\n if not token_lifetime:\n token_lifetime = DEFAULT_TOKEN_LIFETIME\n return ArkToken(\n token=identity.session_token,\n username=auth_profile.username,\n endpoint=identity.identity_url,\n token_type=ArkTokenType.JWT,\n auth_method=ArkAuthMethod.Identity,\n expires_in=datetime.now() + timedelta(seconds=token_lifetime),\n refresh_token=identity.session_details.refresh_token,\n metadata={'env': env, 'cookies': codecs.encode(pickle.dumps(identity.session.cookies), 'base64').decode()},\n )\n except Exception as ex:\n self._logger.exception(f'Failed to authenticate to identity security platform [{str(ex)}]')\n raise ArkAuthException from ex\n\n def __perform_identity_refresh_authentication(self, profile: ArkProfile, auth_profile: ArkAuthProfile, token: ArkToken) -> ArkToken:\n try:\n method_settings = cast(IdentityArkAuthMethodSettings, auth_profile.auth_method_settings)\n identity = ArkIdentity(\n username=auth_profile.username,\n password=None,\n identity_url=method_settings.identity_url,\n mfa_type=method_settings.identity_mfa_method,\n logger=self._logger,\n cache_authentication=self._cache_authentication,\n load_cache=True,\n cache_profile=profile,\n )\n identity.refresh_auth_identity(profile, method_settings.identity_mfa_interactive, False)\n env = AwsEnv(os.environ.get('DEPLOY_ENV', AwsEnv.PROD.value))\n found_env = list(filter(lambda e: ROOT_DOMAIN[e] in identity.identity_url, ROOT_DOMAIN.keys()))\n if found_env:\n env = found_env[0]\n token_lifetime = identity.session_details.token_lifetime\n if not token_lifetime:\n token_lifetime = DEFAULT_TOKEN_LIFETIME\n return ArkToken(\n token=identity.session_token,\n username=auth_profile.username,\n endpoint=identity.identity_url,\n token_type=ArkTokenType.JWT,\n auth_method=ArkAuthMethod.Identity,\n expires_in=datetime.now() + timedelta(seconds=token_lifetime),\n refresh_token=identity.session_details.refresh_token,\n metadata={'env': env, 'cookies': codecs.encode(pickle.dumps(identity.session.cookies), 'base64').decode()},\n )\n except Exception as ex:\n raise ArkAuthException('Failed to authenticate to isp via identity') from ex\n\n def __perform_identity_service_user_authentication(\n self, profile: ArkProfile, auth_profile: ArkAuthProfile, secret: Optional[ArkSecret], force: bool\n ) -> ArkToken:\n try:\n if not secret:\n raise ArkException('Token secret is required for identity service user auth')\n method_settings = cast(IdentityServiceUserArkAuthMethodSettings, auth_profile.auth_method_settings)\n identity = ArkIdentityServiceUser(\n username=auth_profile.username,\n token=secret.secret.get_secret_value(),\n app_name=method_settings.identity_authorization_application,\n logger=self._logger,\n cache_authentication=self._cache_authentication,\n )\n identity.auth_identity(profile, force)\n env = AwsEnv(os.environ.get('DEPLOY_ENV', AwsEnv.PROD.value))\n found_env = list(filter(lambda e: ROOT_DOMAIN[e] in identity.identity_url, ROOT_DOMAIN.keys()))\n if found_env:\n env = found_env[0]\n return ArkToken(\n token=identity.session_token,\n username=auth_profile.username,\n endpoint=identity.identity_url,\n token_type=ArkTokenType.JWT,\n auth_method=ArkAuthMethod.IdentityServiceUser,\n expires_in=datetime.now() + timedelta(hours=4),\n metadata={'env': env, 'cookies': codecs.encode(pickle.dumps(identity.session.cookies), 'base64').decode()},\n )\n except Exception as ex:\n self._logger.exception(f'Failed to authenticate to identity security platform with service user [{str(ex)}]')\n raise ArkAuthException from ex\n\n @overrides\n def _perform_authentication(\n self, profile: ArkProfile, auth_profile: ArkAuthProfile, secret: Optional[ArkSecret] = None, force: bool = False\n ) -> ArkToken:\n \"\"\"\n Performs authentication to the identity security platform identity tenant\n Authentication can be done with either a service user or a normal user\n Authentication Methods:\n - Identity, Default\n - IdentityServiceUser\n\n Args:\n profile (ArkProfile): _description_\n auth_profile (ArkAuthProfile): _description_\n secret (Optional[ArkSecret], optional): _description_. Defaults to None.\n force (bool, optional): _description_. Defaults to False.\n\n Raises:\n ArkAuthException: _description_\n\n Returns:\n ArkToken: _description_\n \"\"\"\n self._logger.info('Performing authentication to ISP')\n if auth_profile.auth_method in [ArkAuthMethod.Identity, ArkAuthMethod.Default]:\n return self.__perform_identity_authentication(profile, auth_profile, secret, force)\n if auth_profile.auth_method == ArkAuthMethod.IdentityServiceUser:\n return self.__perform_identity_service_user_authentication(profile, auth_profile, secret, force)\n raise ArkAuthException('Given auth method is not supported')\n\n @overrides\n def _perform_refresh_authentication(self, profile: ArkProfile, auth_profile: ArkAuthProfile, token: ArkToken) -> ArkToken:\n \"\"\"\n Refresh for isp tenant is supported only for identity\n\n Args:\n profile (ArkProfile): _description_\n auth_profile (ArkAuthProfile): _description_\n token (ArkToken): _description_\n\n Returns:\n ArkToken: _description_\n \"\"\"\n self._logger.info('Performing refresh authentication to ISP')\n if auth_profile.auth_method in [ArkAuthMethod.Identity, ArkAuthMethod.Default]:\n return self.__perform_identity_refresh_authentication(profile, auth_profile, token)\n return token\n\n @staticmethod\n @overrides\n def authenticator_name() -> str:\n return AUTH_NAME\n\n @staticmethod\n @overrides\n def authenticator_human_readable_name() -> str:\n return AUTH_HUMAN_READABLE_NAME\n\n @staticmethod\n @overrides\n def supported_auth_methods() -> List[ArkAuthMethod]:\n return AUTH_METHODS\n\n @staticmethod\n @overrides\n def default_auth_method() -> Tuple[ArkAuthMethod, ArkAuthMethodSettings]:\n return DEFAULT_AUTH_METHOD, DEFAULT_AUTH_METHOD_SETTINGS" }, { "identifier": "ArkDPABasePoliciesEditorService", "path": "ark_sdk_python/cli_services/dpa/common/ark_dpa_base_policies_editor_service.py", "snippet": "class ArkDPABasePoliciesEditorService(\n ArkService, ABC, Generic[PolicyType, PolicyListItemType, AddPolicyType, UpdatePolicyType, GeneratePolicyType]\n):\n def __init__(\n self,\n policy_type: PolicyType,\n add_policy_type: AddPolicyType,\n update_policy_type: UpdatePolicyType,\n isp_auth: ArkISPAuth,\n policies_family: str,\n tenant_id: str,\n policies_cache_dir: Optional[str] = None,\n profile: Optional[ArkProfile] = None,\n ) -> None:\n super().__init__(isp_auth)\n profile = profile or ArkProfileLoader.load_default_profile()\n self._policies_family = policies_family\n self.__policies_cache_dir = Path(policies_cache_dir or Path.home() / '.ark_cache' / 'profiles' / profile.profile_name / tenant_id)\n if not policies_cache_dir and 'ARK_DPA_POLICIES_EDITOR_FOLDER' in os.environ:\n self.__policies_cache_dir = Path(os.environ['ARK_DPA_POLICIES_EDITOR_FOLDER'])\n self.__policies_cache_dir = self.__policies_cache_dir / policies_family\n self.__policies_cache_dir.mkdir(exist_ok=True, parents=True)\n self.__policy_type = policy_type\n self.__add_policy_type = add_policy_type\n self.__update_policy_type = update_policy_type\n\n @abstractmethod\n def _policy(self, get_policy: ArkDPAGetPolicy) -> PolicyType:\n pass\n\n @abstractmethod\n def _list_policies(self) -> List[PolicyListItemType]:\n pass\n\n @abstractmethod\n def _add_policy(self, add_policy: AddPolicyType) -> PolicyType:\n pass\n\n @abstractmethod\n def _update_policy(self, update_policy: UpdatePolicyType) -> PolicyType:\n pass\n\n @abstractmethod\n def _delete_policy(self, delete_policy: ArkDPADeletePolicy) -> None:\n pass\n\n @abstractmethod\n def _generate_policy(self, generate_policy: GeneratePolicyType, workspace_policies: List[PolicyType]) -> PolicyType:\n pass\n\n def __load_policy_diff(self, workspace_policy: PolicyType) -> Optional[Tuple[PolicyType, PolicyType]]:\n remote_policy = self._policy(ArkDPAGetPolicy(policy_id=str(workspace_policy.policy_id)))\n if remote_policy != workspace_policy:\n return (workspace_policy, remote_policy)\n return None\n\n def __load_policies_diff(self) -> Dict[str, Tuple[PolicyType, PolicyType]]:\n workspace_policies = self.__load_existing_policies_from_workspace()\n with ThreadPoolExecutor() as executor:\n remote_policies = {\n p[0].policy_name: p for p in executor.map(self.__load_policy_diff, workspace_policies.values()) if p is not None\n }\n return remote_policies\n\n def __load_policies_from_workspace_by_suffix(self, suffix: str = '') -> Dict[str, PolicyType]:\n p = Path(self.__policies_cache_dir).glob(f'*.json{suffix}')\n policies_files = [x for x in p if x.is_file() and x.suffix == suffix or '.json']\n policies = {}\n for f in policies_files:\n policy = self.__policy_type.parse_file(f)\n policies[policy.policy_name] = policy\n return policies\n\n def __load_removed_policies_from_workspace(self) -> Dict[str, PolicyType]:\n return self.__load_policies_from_workspace_by_suffix('.removed')\n\n def __load_generated_policies_from_workspace(self) -> Dict[str, PolicyType]:\n return self.__load_policies_from_workspace_by_suffix('.generated')\n\n def __load_existing_policies_from_workspace(self) -> Dict[str, PolicyType]:\n return self.__load_policies_from_workspace_by_suffix()\n\n def __load_policy_to_workspace(self, policy: PolicyListItemType, override: bool) -> Optional[PolicyType]:\n policy_data = self._policy(ArkDPAGetPolicy(policy_id=policy.policy_id))\n policy_path = Path(self.__policies_cache_dir) / (policy_data.policy_name + '.json')\n if policy_path.exists():\n existing_data = self.__policy_type.parse_raw(policy_path.read_text())\n if existing_data != policy_data:\n if not override:\n return policy_data\n if not policy_data.policy_id:\n policy_data.policy_id = policy.policy_id\n policy_path.write_text(policy_data.json(indent=4))\n (Path(self.__policies_cache_dir) / (policy_data.policy_name + '.json.removed')).unlink(missing_ok=True)\n\n def load_policies(self, load_policies: ArkDPALoadPolicies) -> ArkDPALoadedPolicies:\n \"\"\"\n Loads all remote policies into the local workspace.\n The user is asked whether to overwrite existing policies that were edited either locally or remotely.\n When default overwrite is enabled, existing policies are overwritten without prompts.\n\n Args:\n load_policies (ArkDPALoadPolicies): _description_\n\n Returns:\n ArkDPALoadedPolicies: _description_\n \"\"\"\n policies = self._list_policies()\n policies_to_query: Dict[str, PolicyType] = []\n with ThreadPoolExecutor() as executor:\n policies_to_query = {\n p.policy_name: p\n for p in executor.map(lambda p: self.__load_policy_to_workspace(p, load_policies.override), policies)\n if p is not None\n }\n # Build the query editor to ask the user\n policies_to_override = []\n if policies_to_query:\n answers = inquirer.prompt(\n [\n inquirer.Checkbox(\n 'override',\n message=f'Conflicts detected, please choose if you wish to override local {self._policies_family} policies or leave them as is',\n choices=[p.policy_name for p in policies_to_query.values()],\n )\n ],\n render=ArkInquirerRender(),\n )\n if not answers:\n return\n policies_to_override = answers['override']\n for policy_name in policies_to_override:\n policy_path = Path(self.__policies_cache_dir) / (policy_name + '.json')\n if policy_path.exists() and policy_name in policies_to_query:\n policy_path.write_text(policies_to_query[policy_name].json(indent=4))\n return ArkDPALoadedPolicies(\n loaded_path=str(self.__policies_cache_dir),\n overall_policies_count=len(policies),\n loaded_policies_count=len(policies) - len(policies_to_query),\n overriden_policies_count=len(policies_to_override),\n untouched_policies_count=len(policies_to_query) - len(policies_to_override),\n )\n\n def edit_policies(self, edit_policies: ArkDPAEditPolicies) -> None:\n \"\"\"\n Edits the set of specified policies one at a time, either via the CLI or the default OS editor.\n Edited policies are only saved locally until they are committed.\n\n Args:\n edit_policies (ArkDPAEditPolicies): _description_\n\n Raises:\n ArkServiceException: _description_\n \"\"\"\n workspace_policies = self.__load_existing_policies_from_workspace()\n workspace_policies.update(self.__load_generated_policies_from_workspace())\n if not workspace_policies:\n raise ArkServiceException(\n f'No {self._policies_family} policies to edit in the workspace, please load the policies or generate a new one'\n )\n policy_names = edit_policies.names\n if not policy_names:\n answers = inquirer.prompt(\n [\n inquirer.Checkbox(\n 'names',\n f'Which {self._policies_family} policies would you like to edit?, press space to select',\n choices=[p.policy_name for p in workspace_policies.values()],\n )\n ],\n render=ArkInquirerRender(),\n )\n if not answers:\n return\n policy_names = answers['names']\n try:\n answers = inquirer.prompt(\n [\n inquirer.Editor(f'{name}_edit', message=f'Chosen {self._policies_family} policy [{name}] is about to be edited')\n for name in policy_names\n ],\n render=ArkInquirerRender(),\n answers={f'{name}_edit': workspace_policies[name].json(indent=4) for name in policy_names},\n )\n for name in policy_names:\n policy = self.__policy_type.parse_raw(answers[f'{name}_edit'])\n for path in [\n Path(self.__policies_cache_dir) / (name + '.json'),\n Path(self.__policies_cache_dir) / (name + '.json.generated'),\n ]:\n if path.exists():\n path.write_text(policy.json(indent=4))\n break\n except EditorError as ex:\n self._logger.error(\n f'An error occurred while trying to edit {self._policies_family} policies, '\n f'you can edit the policies at [{self.__policies_cache_dir}] [{str(ex)}]'\n )\n\n def remove_policies(self, remove_policies: ArkDPARemovePolicies) -> None:\n \"\"\"\n Removes one or more policies from the local workspace.\n Until changes are committed, removing a remote policy only appends the `.deleted` indication to its name.\n After committing the changes, the policies are deleted both locally and remotely.\n New, uncommitted policies are deleted locally after the user consents.\n\n Args:\n remove_policies (ArkDPARemovePolicies): _description_\n\n Raises:\n ArkServiceException: _description_\n \"\"\"\n workspace_policies = self.__load_existing_policies_from_workspace()\n workspace_policies.update(self.__load_generated_policies_from_workspace())\n if not workspace_policies:\n raise ArkServiceException(\n f'No {self._policies_family} policies to remove in the workspace, please load the policies or generate a new one'\n )\n policy_names = remove_policies.names\n if not policy_names:\n answers = inquirer.prompt(\n [\n inquirer.Checkbox(\n 'names',\n f'Which {self._policies_family} policies would you like to remove?, press space to select',\n choices=[p.policy_name for p in workspace_policies.values()],\n )\n ],\n render=ArkInquirerRender(),\n )\n if not answers:\n return\n policy_names = answers['names']\n for policy_name in policy_names:\n for path in [\n Path(self.__policies_cache_dir) / (policy_name + '.json'),\n Path(self.__policies_cache_dir) / (policy_name + '.json.generated'),\n ]:\n if path.exists():\n if path.suffix == '.json':\n path.rename(Path(self.__policies_cache_dir) / (policy_name + '.json.removed'))\n else:\n answers = inquirer.prompt(\n [\n inquirer.Confirm(\n 'remove',\n message=f'Are you sure you want to remove local {self._policies_family} policy [{policy_name}]?, removing an uncommitted local policy cannot be reverted',\n )\n ],\n render=ArkInquirerRender(),\n )\n if not answers:\n return\n if answers['remove']:\n path.unlink(missing_ok=True)\n\n def view_policies(self, view_policies: ArkDPAViewPolicies) -> None:\n \"\"\"\n Allows the user to view one or more policies either together or individually, as defined in the CLI user prompt.\n Policies are viewed in the machine's default editor (both existing policies and newly generated policies).\n\n Args:\n view_policies (ArkDPAViewPolicies): _description_\n \"\"\"\n workspace_policies = self.__load_existing_policies_from_workspace()\n workspace_policies.update(self.__load_generated_policies_from_workspace())\n policy_names = view_policies.names\n if not policy_names:\n answers = inquirer.prompt(\n [\n inquirer.Checkbox(\n 'names',\n f'Which {self._policies_family} policies would you like to view?',\n choices=[p.policy_name for p in workspace_policies.values()],\n )\n ],\n render=ArkInquirerRender(),\n )\n if not answers:\n return\n policy_names = answers['names']\n if not policy_names:\n return\n try:\n if view_policies.unified:\n inquirer.prompt(\n [inquirer.Editor('views', f'Show all selected {self._policies_family} policies')],\n answers={\n 'views': '\\n\\n\\n'.join(\n [f'# Policy [{policy_name}]\\n{workspace_policies[policy_name].json(indent=4)}' for policy_name in policy_names]\n )\n },\n render=ArkInquirerRender(),\n )\n else:\n inquirer.prompt(\n [inquirer.Editor(f'{policy_name}_view', f'Show [{policy_name}]') for policy_name in policy_names],\n render=ArkInquirerRender(),\n answers={f'{policy_name}_view': workspace_policies[policy_name].json(indent=4) for policy_name in policy_names},\n )\n except EditorError as ex:\n self._logger.error(\n f'An error occurred while trying to view the {self._policies_family} policies, '\n f'you can view the policies at [{self.__policies_cache_dir}] [{str(ex)}]'\n )\n\n def reset_policies(self, reset_policy: ArkDPAResetPolicies) -> None:\n \"\"\"\n Resets local workspace policies.\n When all policies are reset, all local policies are overwritten and deleted policies are removed.\n Otherwise, the user can select which policies are reset.\n This function does not alter newly generated uncommitted policies.\n\n Args:\n reset_policy (ArkDPAResetPolicies): _description_\n \"\"\"\n if reset_policy.all:\n answers = inquirer.prompt(\n [inquirer.Confirm('reset', message=f'Are you sure you want to reset all edited {self._policies_family} policies?')]\n )\n if not answers:\n return\n if answers['reset']:\n self.load_policies(ArkDPALoadPolicies(override=True))\n else:\n policies_diff = self.__load_policies_diff()\n removed_policies = self.__load_removed_policies_from_workspace()\n if not policies_diff and not removed_policies:\n return\n policy_names = reset_policy.names\n if not policy_names:\n answers = inquirer.prompt(\n [\n inquirer.Checkbox(\n 'names',\n f'Which {self._policies_family} policies would you like to reset?, press space to select',\n choices=[p for p in policies_diff.keys() + removed_policies.keys()],\n )\n ],\n render=ArkInquirerRender(),\n )\n if not answers:\n return\n policy_names = answers['names']\n policy_names = [p for p in policy_names if p in policies_diff or p in removed_policies]\n for policy_name in policy_names:\n policy_path = Path(self.__policies_cache_dir) / (policy_name + '.json')\n if policy_name in policies_diff:\n policy_path.write_text(policies_diff[policy_name][1].json(indent=4))\n elif policy_name in removed_policies:\n policy_path.write_text(removed_policies[policy_name].json(indent=4))\n (Path(self.__policies_cache_dir) / (policy_name + '.json.removed')).unlink(missing_ok=True)\n\n def generate_policy(self, generate_policy: GeneratePolicyType) -> None:\n \"\"\"\n Generates a new policy from a template and the user's parameters.\n The user is prompted for the parameters when they are not specified in the CLI.\n After policy's parameters are defined, the policy is generates in memory and can bee edited.\n The new policy is saved locally until it is committed.\n\n Args:\n generate_policy (GeneratePolicyType): _description_\n \"\"\"\n workspace_policies = self.__load_existing_policies_from_workspace()\n workspace_policies.update(self.__load_generated_policies_from_workspace())\n policy = self._generate_policy(generate_policy, workspace_policies)\n policy_path = Path(self.__policies_cache_dir) / (policy.policy_name + '.json.generated')\n # Let the user edit the generated policy\n if not generate_policy.disable_edit:\n try:\n answers = inquirer.prompt(\n [\n inquirer.Editor(\n 'policy_editor',\n f'Newly {self._policies_family} policy is generated and ready to be edited, once edited, it will be saved to the local workspace',\n )\n ],\n render=ArkInquirerRender(),\n answers={'policy_editor': policy.json(indent=4, exclude_none=True)},\n )\n if not answers:\n return\n policy = self.__policy_type.parse_raw(answers['policy_editor'])\n except EditorError as ex:\n self._logger.error(\n f'An error occurred while trying to edit the {self._policies_family} policy, '\n f'the policy will be saved to [{policy_path}] and can be edited manually [{str(ex)}]'\n )\n policy_path.write_text(policy.json(indent=4))\n\n def policies_diff(self, policies_diff: ArkDPAPoliciesDiff) -> None:\n \"\"\"\n Calculates the diff between the local workspace and remote policies.\n This diff includes uncommitted removed policies. A unified or per policy diff can be displayed.\n\n Args:\n policies_diff (ArkDPAPoliciesDiff): _description_\n \"\"\"\n loaded_policies_diff = self.__load_policies_diff()\n removed_policies = self.__load_removed_policies_from_workspace()\n if not loaded_policies_diff and not removed_policies:\n return\n if policies_diff.names:\n loaded_policies_diff = {k: v for k, v in loaded_policies_diff.items() if k in policies_diff.names}\n removed_policies = {k: v for k, v in removed_policies.items() if k in policies_diff.names}\n if not loaded_policies_diff and not removed_policies:\n return\n diffs = {\n policy_name: difflib.unified_diff(\n policy_tuple[1].json(indent=4).splitlines(True),\n policy_tuple[0].json(indent=4).splitlines(True),\n fromfile=f'local policy [{policy_name}]',\n tofile=f'remote policy [{policy_name}]',\n n=MAX_LINE_DIFF,\n )\n for policy_name, policy_tuple in loaded_policies_diff.items()\n }\n diffs.update(\n {\n policy_name: difflib.unified_diff(\n policy.json(indent=4).splitlines(True),\n '',\n fromfile=f'local policy [{policy_name}]',\n tofile=f'remote policy [{policy_name}]',\n n=MAX_LINE_DIFF,\n )\n for policy_name, policy in removed_policies.items()\n }\n )\n try:\n if policies_diff.unified:\n inquirer.prompt(\n [inquirer.Editor('diffs', 'Show all diffs')],\n render=ArkInquirerRender(),\n answers={'diffs': '\\n\\n\\n'.join([''.join(d) for d in diffs.values()])},\n )\n else:\n inquirer.prompt(\n [inquirer.Editor(f'{policy_name}_diff', f'Show [{policy_name}] diff') for policy_name in diffs.keys()],\n render=ArkInquirerRender(),\n answers={f'{policy_name}_diff': ''.join(policy_diffs) for policy_name, policy_diffs in diffs.items()},\n )\n except EditorError as ex:\n self._logger.error(\n f'An error occurred while trying to show {self._policies_family} policies diff, '\n f'you can view the policies at [{self.__policies_cache_dir}] [{str(ex)}]'\n )\n\n def policies_status(self, get_policies_status: ArkDPAGetPoliciesStatus) -> ArkDPAPoliciesStatus:\n \"\"\"\n Gets the status of locally altered policies.\n\n Args:\n get_policies_status (ArkDPAGetPoliciesStatus): _description_\n\n Returns:\n ArkDPAPoliciesStatus: _description_\n \"\"\"\n loaded_policies_diff = self.__load_policies_diff()\n removed_policies = self.__load_removed_policies_from_workspace()\n generated_policies = self.__load_generated_policies_from_workspace()\n if get_policies_status.names:\n loaded_policies_diff = {k: v for k, v in loaded_policies_diff.items() if k in get_policies_status.names}\n removed_policies = {k: v for k, v in removed_policies.items() if k in get_policies_status.names}\n generated_policies = {k: v for k, v in generated_policies.items() if k in get_policies_status.names}\n return ArkDPAPoliciesStatus(\n modified_policies=list(loaded_policies_diff.keys()),\n removed_policies=list(removed_policies.keys()),\n added_policies=list(generated_policies.keys()),\n )\n\n def commit_policies(self, commit_policies: ArkDPACommitPolicies) -> None:\n \"\"\"\n Commits policies.\n The function first calculates the differences between the local and remote policies to find out which policies were edited, including\n the policies selected for deletion and new, uncommitted policies. It also\n allows selecting whether to commit all the edited policies or only specific policies by name.\n\n After all policies are committed, the workspace is reorganized accordingly.\n\n Args:\n commit_policies (ArkDPACommitPolicies): _description_\n \"\"\"\n loaded_policies_diff = self.__load_policies_diff()\n removed_policies = self.__load_removed_policies_from_workspace()\n generated_policies = self.__load_generated_policies_from_workspace()\n if not loaded_policies_diff and not removed_policies and not generated_policies:\n return\n if commit_policies.all:\n answers = inquirer.prompt(\n [inquirer.Confirm('reset', message=f'Are you sure you want to commit all edited {self._policies_family} policies?')]\n )\n if not answers or not answers['reset']:\n return\n else:\n if commit_policies.names:\n loaded_policies_diff = {k: v for k, v in loaded_policies_diff.items() if k in commit_policies.names}\n removed_policies = {k: v for k, v in removed_policies.items() if k in commit_policies.names}\n generated_policies = {k: v for k, v in generated_policies.items() if k in commit_policies.names}\n else:\n answers = inquirer.prompt(\n [\n inquirer.Checkbox(\n 'names',\n f'Which {self._policies_family} policies would you like to commit?, press space to select',\n choices=list(loaded_policies_diff.keys()) + list(removed_policies.keys()) + list(generated_policies.keys()),\n )\n ],\n render=ArkInquirerRender(),\n )\n if not answers:\n return\n loaded_policies_diff = {k: v for k, v in loaded_policies_diff.items() if k in answers['names']}\n removed_policies = {k: v for k, v in removed_policies.items() if k in answers['names']}\n generated_policies = {k: v for k, v in generated_policies.items() if k in answers['names']}\n if not loaded_policies_diff and not removed_policies and not generated_policies:\n return\n with ThreadPoolExecutor() as executor:\n added = executor.map(lambda p: self._add_policy(self.__add_policy_type(**p.dict())), generated_policies.values())\n updated = executor.map(lambda p: self._update_policy(self.__update_policy_type(**p[0].dict())), loaded_policies_diff.values())\n deleted = executor.map(\n lambda p: self._delete_policy(ArkDPADeletePolicy(policy_id=p.policy_id, policy_name=p.policy_name)),\n removed_policies.values(),\n )\n # Loop for exception checking\n added_policies = list(added)\n for _ in itertools.chain(updated, deleted):\n pass\n for policy_name in removed_policies.keys():\n (Path(self.__policies_cache_dir) / (policy_name + '.json.removed')).unlink(missing_ok=True)\n for policy_name in generated_policies.keys():\n for policy in added_policies:\n if policy.policy_name == policy_name:\n (Path(self.__policies_cache_dir) / (policy_name + '.json.generated')).rename(\n (Path(self.__policies_cache_dir) / (policy_name + '.json'))\n )\n (Path(self.__policies_cache_dir) / (policy_name + '.json')).write_text(policy.json(indent=4))" }, { "identifier": "ArkProfile", "path": "ark_sdk_python/models/ark_profile.py", "snippet": "class ArkProfile(ArkModel):\n profile_name: str = Field(default='ark', alias='Profile Name', description='Profile name for storage')\n profile_description: str = Field(default='Default Ark Profile', alias='Profile Description', description='Info about the profile')\n auth_profiles: Dict[str, ArkAuthProfile] = Field(\n description='Authentication profiles configurations, map from name of the authenticator to its profile', default_factory=dict\n )\n\n # pylint: disable=no-self-use,no-self-argument\n @validator('auth_profiles', pre=True)\n def validate_auth_profiles(cls, val):\n auth_profiles = {}\n for k, v in val.items():\n auth_profile = ArkAuthProfile.parse_obj(v)\n # Make sure that the settings are parsed with the correct class\n # Due to properties overlapping\n if 'auth_method_settings' in v:\n auth_profile.auth_method_settings = ArkAuthMethodSettingsMap[auth_profile.auth_method].parse_obj(v['auth_method_settings'])\n auth_profiles[k] = auth_profile\n return auth_profiles" }, { "identifier": "ArkDPADBGeneratePolicy", "path": "ark_sdk_python/models/cli_services/dpa/policies_editor/db/ark_dpa_db_generate_policy.py", "snippet": "class ArkDPADBGeneratePolicy(ArkDPABaseGeneratePolicy):\n providers: Optional[Set[Literal['MySQL', 'MariaDB', 'Postgres', 'MSSQL', 'Oracle']]] = Field(\n description='Providers to generate the policy for'\n )" }, { "identifier": "ArkWorkspaceType", "path": "ark_sdk_python/models/common/ark_workspace_type.py", "snippet": "class ArkWorkspaceType(str, MultiValueEnum):\n AWS = 'aws', 'AWS', 'Aws'\n AZURE = 'azure', 'AZURE', 'Azure'\n ONPREM = 'onprem', 'ON-PREMISE', 'OnPrem'\n DB = 'db', 'DATABASES', 'Databases'\n GCP = 'gcp', 'GCP'\n MYSQL = 'mysql', 'MySQL'\n MARIADB = 'mariadb', 'MariaDB'\n MSSQL = 'mssql', 'MSSQL'\n ORACLE = 'oracle', 'Oracle'\n POSTGRES = 'postgres', 'Postgres'\n FAULT = 'fault', 'FAULT'\n UNKNOWN = 'unknown', 'UNKNOWN', 'Unknown'" }, { "identifier": "ArkServiceConfig", "path": "ark_sdk_python/models/services/ark_service_config.py", "snippet": "class ArkServiceConfig(ArkModel):\n service_name: str = Field(description='Name of the service')\n required_authenticator_names: List[str] = Field(description='Required authenticators for the service to properly work')\n optional_authenticator_names: List[str] = Field(\n description='Optional authenticators for the service for extra capabilities', default_factory=list\n )" }, { "identifier": "ArkDPADeletePolicy", "path": "ark_sdk_python/models/services/dpa/policies/common/ark_dpa_delete_policy.py", "snippet": "class ArkDPADeletePolicy(ArkModel):\n policy_id: Optional[str] = Field(description='Policy id to delete')\n policy_name: Optional[str] = Field(description='Policy name to delete')\n\n # pylint: disable=no-self-use,no-self-argument\n @root_validator\n def validate_either(cls, values):\n if 'policy_id' not in values and 'policy_name' not in values:\n raise ValueError('Either policy id or policy name needs to be provided')\n return values" }, { "identifier": "ArkDPAGetPolicy", "path": "ark_sdk_python/models/services/dpa/policies/common/ark_dpa_get_policy.py", "snippet": "class ArkDPAGetPolicy(ArkModel):\n policy_id: Optional[str] = Field(description='Policy id to get')\n policy_name: Optional[str] = Field(description='Policy name to get')\n\n # pylint: disable=no-self-use,no-self-argument\n @root_validator\n def validate_either(cls, values):\n if 'policy_id' not in values and 'policy_name' not in values:\n raise ValueError('Either policy id or policy name needs to be provided')\n return values" }, { "identifier": "ArkDPARuleStatus", "path": "ark_sdk_python/models/services/dpa/policies/common/ark_dpa_rule_status.py", "snippet": "class ArkDPARuleStatus(str, Enum):\n Enabled = 'Enabled'\n Disabled = 'Disabled'\n Draft = 'Draft'\n Expired = 'Expired'" }, { "identifier": "ArkDPAUserData", "path": "ark_sdk_python/models/services/dpa/policies/common/ark_dpa_user_data.py", "snippet": "class ArkDPAUserData(ArkCamelizedModel):\n roles: Optional[List[Union[str, ArkDPAUserDataAttribute]]] = Field(description='Roles allowed for auth rule', default_factory=list)\n groups: Optional[List[Union[str, ArkDPAUserDataAttribute]]] = Field(description='Groups allowed for auth rule', default_factory=list)\n users: Optional[List[Union[str, ArkDPAUserDataAttribute]]] = Field(description='Users allowed for auth rule', default_factory=list)" }, { "identifier": "ArkDPADBAddPolicy", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_add_policy.py", "snippet": "class ArkDPADBAddPolicy(ArkDPABaseAddPolicy):\n providers_tags: List[str] = Field(description='Policy tags to use as filters for the assets in the rules', default_factory=list)\n providers_data: Optional[ArkDPADBProvidersData] = Field(\n description='Policy providers data containing database assets of different types'\n )\n user_access_rules: Optional[List[ArkDPADBAuthorizationRule]] = Field(\n description='Authorization rules of the policy describing how and who can access the assets'\n )" }, { "identifier": "ArkDPADBAuthorizationRule", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_authorization_rule.py", "snippet": "class ArkDPADBAuthorizationRule(ArkDPABaseAuthorizationRule):\n connection_information: ArkDPADBConnectionInformation = Field(description='Rule information on how access is made')" }, { "identifier": "ArkDPADBConnectionInformation", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_authorization_rule.py", "snippet": "class ArkDPADBConnectionInformation(ArkDPABaseConnectionInformation):\n connect_as: ArkDPADBConnectAs = Field(description='In which fashion the connection is made')" }, { "identifier": "ArkDPADBAppliedTo", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_connection_data.py", "snippet": "class ArkDPADBAppliedTo(ArkCamelizedModel):\n name: str = Field(description='Name of the resource to apply the auth to')\n type: ArkDPADBResourceIdentifierType = Field(description='Type of the resource')" }, { "identifier": "ArkDPADBBaseAuth", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_connection_data.py", "snippet": "class ArkDPADBBaseAuth(ArkCamelizedModel):\n pass" }, { "identifier": "ArkDPADBConnectAs", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_connection_data.py", "snippet": "class ArkDPADBConnectAs(ArkCamelizedModel):\n ldap_auth: Optional[Union[ArkDPADBLDAPAuth, List[ArkDPADBLDAPAuth]]] = Field(\n description='LDAP related authentication, only applies to MSSQL DB'\n )\n db_auth: Optional[Union[ArkDPADBLocalDBAuth, List[ArkDPADBLocalDBAuth]]] = Field(\n description='Local DB related authentication, only applies to MySQL / MariaDB / Postgres'\n )\n oracle_auth: Optional[Union[ArkDPADBOracleDBAuth, List[ArkDPADBOracleDBAuth]]] = Field(\n description='Oracle DB related authentication, only applies to Oracle'\n )" }, { "identifier": "ArkDPADBLDAPAuth", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_connection_data.py", "snippet": "class ArkDPADBLDAPAuth(ArkDPADBBaseAuth):\n assign_groups: List[str] = Field(description='LDAP groups to assign the ephemeral user to')\n applied_to: Optional[List[ArkDPADBAppliedTo]] = Field(description='Which resources to apply to')" }, { "identifier": "ArkDPADBLocalDBAuth", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_connection_data.py", "snippet": "class ArkDPADBLocalDBAuth(ArkDPADBBaseAuth):\n roles: List[str] = Field(description='Local DB roles to assign the ephemeral user to')\n applied_to: Optional[List[ArkDPADBAppliedTo]] = Field(description='Which resources to apply to')" }, { "identifier": "ArkDPADBOracleDBAuth", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_connection_data.py", "snippet": "class ArkDPADBOracleDBAuth(ArkDPADBBaseAuth):\n roles: List[str] = Field(description='Local DB roles to assign the ephemeral user to')\n applied_to: Optional[List[ArkDPADBAppliedTo]] = Field(description='Which resources to apply to')\n dba_role: bool = Field(description='Whether to apply to the ephemeral user the DBA role', default=False)\n sysdba_role: bool = Field(description='Whether to apply to the ephemeral user the SYSDBA role', default=False)\n sysoper_role: bool = Field(description='Whether to apply to the ephemeral user the SYSOPER role', default=False)" }, { "identifier": "ArkDPADBResourceIdentifierType", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_connection_data.py", "snippet": "class ArkDPADBResourceIdentifierType(str, Enum):\n RESOURCE = 'resource'\n TAG = 'tag'" }, { "identifier": "ArkDPADBPolicy", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_policy.py", "snippet": "class ArkDPADBPolicy(ArkDPABasePolicy):\n providers_tags: List[str] = Field(description='Policy tags', default_factory=list)\n providers_data: ArkDPADBProvidersData = Field(description='Policy providers data')\n user_access_rules: Optional[List[ArkDPADBAuthorizationRule]] = Field(description='Authorization rules of the policy')" }, { "identifier": "ArkDPADBPolicyListItem", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_policy_list_item.py", "snippet": "class ArkDPADBPolicyListItem(ArkDPABasePolicyListItem):\n providers: Optional[List[ArkWorkspaceType]] = Field(description='Names of the database providers of the policy')\n providers_tags: List[str] = Field(description='Tags on the policy', default_factory=list)\n\n # pylint: disable=no-self-use,no-self-argument\n @validator('providers')\n def validate_platforms(cls, val):\n if val is not None:\n for plat in val:\n if ArkWorkspaceType(plat) not in [\n ArkWorkspaceType.MYSQL,\n ArkWorkspaceType.MARIADB,\n ArkWorkspaceType.POSTGRES,\n ArkWorkspaceType.MSSQL,\n ArkWorkspaceType.ORACLE,\n ]:\n raise ValueError('Invalid Database Type')\n return val" }, { "identifier": "ArkDPADB", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADB(ArkCamelizedModel):\n pass" }, { "identifier": "ArkDPADBMariaDB", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADBMariaDB(ArkDPADBIdentifiers):\n pass" }, { "identifier": "ArkDPADBMSSQL", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADBMSSQL(ArkDPADBIdentifiers):\n pass" }, { "identifier": "ArkDPADBMySQL", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADBMySQL(ArkDPADBIdentifiers):\n pass" }, { "identifier": "ArkDPADBOracle", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADBOracle(ArkDPADB):\n resources: List[Union[str, ArkDPADBOracleResource]] = Field(description='List of oracle resources / assets for the policy')" }, { "identifier": "ArkDPADBOracleResource", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADBOracleResource(ArkCamelizedModel):\n name: str = Field(description='Name of the oracle db resource / asset')\n services: Optional[List[str]] = Field(description='Oracle services in the database')" }, { "identifier": "ArkDPADBPostgres", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADBPostgres(ArkDPADBIdentifiers):\n pass" }, { "identifier": "ArkDPADBProvidersData", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_providers.py", "snippet": "class ArkDPADBProvidersData(ArkCamelizedModel):\n mssql: Optional[ArkDPADBMSSQL] = Field(description='MSSQL related resources')\n mysql: Optional[ArkDPADBMySQL] = Field(description='MySQL related resources')\n mariadb: Optional[ArkDPADBMariaDB] = Field(description='MariaDB related resources')\n postgres: Optional[ArkDPADBPostgres] = Field(description='PostgreSQL related resources')\n oracle: Optional[ArkDPADBOracle] = Field(description='Oracle related resources')\n\n @root_validator\n @classmethod\n def validate_min_providers(cls, data: Dict) -> Dict[str, Any]:\n if isinstance(data, dict):\n if all(value is None for value in data.values()):\n raise ValueError('policy should contain at least one provider')\n return data" }, { "identifier": "ArkDPADBUpdatePolicy", "path": "ark_sdk_python/models/services/dpa/policies/db/ark_dpa_db_update_policy.py", "snippet": "class ArkDPADBUpdatePolicy(ArkDPABaseUpdatePolicy):\n providers_tags: Optional[List[str]] = Field(description='Policy tags to use as filters for the assets in the rules')\n providers_data: Optional[ArkDPADBProvidersData] = Field(\n description='Policy providers data containing database assets of different types'\n )\n user_access_rules: Optional[List[ArkDPADBAuthorizationRule]] = Field(\n description='Authorization rules of the policy describing how and who can access the assets'\n )" }, { "identifier": "ArkDPADBPoliciesService", "path": "ark_sdk_python/services/dpa/policies/db/ark_dpa_db_policies_service.py", "snippet": "class ArkDPADBPoliciesService(ArkService):\n def __init__(self, isp_auth: ArkISPAuth) -> None:\n super().__init__(isp_auth)\n self.__isp_auth = isp_auth\n self.__client: ArkISPServiceClient = ArkISPServiceClient.from_isp_auth(self.__isp_auth, 'dpa')\n\n @property\n def isp_client(self) -> ArkISPServiceClient:\n return self.__client\n\n def __policy_id_by_name(self, policy_name: str) -> str:\n policies = self.list_policies_by(ArkDPADBPoliciesFilter(name=policy_name))\n if not policies:\n raise ArkServiceException(f'Failed to find db policy id by name [{policy_name}]')\n return policies[0].policy_id\n\n def add_policy(self, add_policy: ArkDPADBAddPolicy) -> ArkDPADBPolicy:\n \"\"\"\n Adds a new DB policy with the specified information.\n\n Args:\n add_policy (ArkDPADBAddPolicy): _description_\n\n Raises:\n ArkServiceException: _description_\n\n Returns:\n ArkDPADBPolicy: _description_\n \"\"\"\n self._logger.info(f'Adding new db policy [{add_policy.policy_name}]')\n add_policy_dict = add_policy.dict(by_alias=True, exclude_none=True)\n resp: Response = self.__client.post(DB_POLICIES_API, json=add_policy_dict)\n if resp.status_code == HTTPStatus.CREATED:\n try:\n policy_id = resp.json()['policyId']\n return self.policy(ArkDPAGetPolicy(policy_id=policy_id))\n except (ValidationError, JSONDecodeError, KeyError) as ex:\n self._logger.exception(f'Failed to parse add db policy response [{str(ex)}] - [{resp.text}]')\n raise ArkServiceException(f'Failed to parse add sb policy response [{str(ex)}]') from ex\n raise ArkServiceException(f'Failed to add db policy [{resp.text}] - [{resp.status_code}]')\n\n def delete_policy(self, delete_policy: ArkDPADeletePolicy) -> None:\n \"\"\"\n Deletes the specified (ID or name) DB policy.\n\n Args:\n delete_policy (ArkDPADeletePolicy): _description_\n\n Raises:\n ArkServiceException: _description_\n \"\"\"\n if delete_policy.policy_name and not delete_policy.policy_id:\n delete_policy.policy_id = self.__policy_id_by_name(delete_policy.policy_name)\n self._logger.info(f'Deleting db policy [{delete_policy.policy_id}]')\n resp: Response = self.__client.delete(DB_POLICY_API.format(policy_id=delete_policy.policy_id))\n if resp.status_code != HTTPStatus.NO_CONTENT:\n raise ArkServiceException(f'Failed to delete db policy [{resp.text}] - [{resp.status_code}]')\n\n def update_policy(self, update_policy: ArkDPADBUpdatePolicy) -> ArkDPADBPolicy:\n \"\"\"\n Updates a DB policy.\n\n Args:\n update_policy (ArkDPADBUpdatePolicy): _description_\n\n Raises:\n ArkServiceException: _description_\n\n Returns:\n ArkDPADBPolicy: _description_\n \"\"\"\n if update_policy.policy_name and not update_policy.policy_id:\n update_policy.policy_id = self.__policy_id_by_name(update_policy.policy_name)\n self._logger.info(f'Updating db policy [{update_policy.policy_id}]')\n update_dict = json.loads(update_policy.json(by_alias=True, exclude_none=True, exclude={'new_policy_name', 'policy_name'}))\n if update_policy.new_policy_name:\n update_dict['policyName'] = update_policy.new_policy_name\n else:\n update_dict['policyName'] = update_policy.policy_name\n resp: Response = self.__client.put(DB_POLICY_API.format(policy_id=update_policy.policy_id), json=update_dict)\n if resp.status_code == HTTPStatus.OK:\n try:\n return ArkDPADBPolicy.parse_obj(resp.json())\n except (ValidationError, JSONDecodeError) as ex:\n self._logger.exception(f'Failed to parse update db policy response [{str(ex)}] - [{resp.text}]')\n raise ArkServiceException(f'Failed to parse update db policy response [{str(ex)}]') from ex\n raise ArkServiceException(f'Failed to update db policy [{resp.text}] - [{resp.status_code}]')\n\n def update_policy_status(self, update_policy_status: ArkDPAUpdatePolicyStatus) -> ArkDPADBPolicy:\n \"\"\"\n Updates the status of the specified (by ID) DB policy.\n\n Args:\n update_policy_status (ArkDPAUpdatePolicyStatus): _description_\n\n Raises:\n ArkServiceException: _description_\n\n Returns:\n ArkDPADBPolicy: _description_\n \"\"\"\n if update_policy_status.policy_name and not update_policy_status.policy_id:\n update_policy_status.policy_id = self.__policy_id_by_name(update_policy_status.policy_name)\n self._logger.info(f'Updating db policy status [{update_policy_status.policy_id}]')\n resp: Response = self.__client.put(\n DB_UPDATE_POLICY_STATUS_API.format(policy_id=update_policy_status.policy_id),\n json=update_policy_status.dict(exclude={'policy_id'}),\n )\n if resp.status_code == HTTPStatus.OK:\n return self.policy(ArkDPAGetPolicy(policy_id=update_policy_status.policy_id))\n raise ArkServiceException(f'Failed to update db policy status [{resp.text}] - [{resp.status_code}]')\n\n def list_policies(self) -> List[ArkDPADBPolicyListItem]:\n \"\"\"\n Lists all of the tenants's DB policies.\n\n Raises:\n ArkServiceException: _description_\n\n Returns:\n List[ArkDPADBPolicyListItem]: _description_\n \"\"\"\n self._logger.info('Retrieving all db policies')\n resp: Response = self.__client.get(DB_POLICIES_API)\n if resp.status_code == HTTPStatus.OK:\n try:\n return parse_obj_as(List[ArkDPADBPolicyListItem], resp.json()['items'])\n except (ValidationError, JSONDecodeError, KeyError) as ex:\n self._logger.exception(f'Failed to parse list db policies response [{str(ex)}] - [{resp.text}]')\n raise ArkServiceException(f'Failed to parse list db policies response [{str(ex)}]') from ex\n raise ArkServiceException(f'Failed to list db policies [{resp.text}] - [{resp.status_code}]')\n\n def list_policies_by(self, policies_filter: ArkDPADBPoliciesFilter) -> List[ArkDPADBPolicyListItem]:\n \"\"\"\n Lists DB policies that match the specified filters.\n\n Args:\n policies_filter (ArkDPADBPoliciesFilter): _description_\n\n Returns:\n List[ArkDPADBPolicyListItem]: _description_\n \"\"\"\n self._logger.info(f'Retrieving db policies by filter [{policies_filter}]')\n policies = self.list_policies()\n\n # Filter by statuses\n if policies_filter.statuses:\n policies = [p for p in policies if p.status in policies_filter.statuses]\n\n # Filter by name wildcard\n if policies_filter.name:\n policies = [p for p in policies if fnmatch(p.policy_name, policies_filter.name)]\n\n # Filter by cloud providers\n if policies_filter.providers:\n policies = [p for p in policies if all(cp.value in p.providers for cp in policies_filter.providers)]\n\n return policies\n\n def policy(self, get_policy: ArkDPAGetPolicy) -> ArkDPADBPolicy:\n \"\"\"\n Retrieves a DB policy by ID.\n\n Args:\n get_policy (ArkDPAGetPolicy): _description_\n\n Raises:\n ArkServiceException: _description_\n\n Returns:\n ArkDPADBPolicy: _description_\n \"\"\"\n if get_policy.policy_name and not get_policy.policy_id:\n get_policy.policy_id = self.__policy_id_by_name(get_policy.policy_name)\n self._logger.info(f'Retrieving db policy [{get_policy.policy_id}]')\n resp: Response = self.__client.get(DB_POLICY_API.format(policy_id=get_policy.policy_id))\n if resp.status_code == HTTPStatus.OK:\n try:\n return ArkDPADBPolicy.parse_obj(resp.json())\n except (ValidationError, JSONDecodeError) as ex:\n self._logger.exception(f'Failed to parse db policy response [{str(ex)}] - [{resp.text}]')\n raise ArkServiceException(f'Failed to parse db policy response [{str(ex)}]') from ex\n raise ArkServiceException(f'Failed to retrieve db policy [{get_policy.policy_id}] [{resp.text}] - [{resp.status_code}]')\n\n def policies_stats(self) -> ArkDPADBPoliciesStats:\n \"\"\"\n Calculates policy statistics.\n\n Returns:\n ArkDPADBPoliciesStats: _description_\n \"\"\"\n self._logger.info('Calculating db policies stats')\n policies = self.list_policies()\n policies_stats = ArkDPADBPoliciesStats.construct()\n policies_stats.policies_count = len(policies)\n\n # Count policies per status\n status_types: Set[ArkDPARuleStatus] = {p.status for p in policies if p.status}\n policies_stats.policies_count_per_status = {st: len([p for p in policies if p.status and p.status == st]) for st in status_types}\n\n # Count policies per platforms\n policies_stats.policies_count_per_provider = {}\n for policy in policies:\n for platform in policy.providers:\n if platform not in policies_stats.policies_count_per_provider:\n policies_stats.policies_count_per_provider[platform] = 0\n policies_stats.policies_count_per_provider[platform] += 1\n\n return policies_stats\n\n @staticmethod\n @overrides\n def service_config() -> ArkServiceConfig:\n return SERVICE_CONFIG" } ]
from datetime import date, timedelta from typing import Dict, Final, List, Optional from overrides import overrides from ark_sdk_python.args.ark_args_formatter import ArkInquirerRender from ark_sdk_python.auth.ark_isp_auth import ArkISPAuth from ark_sdk_python.cli_services.dpa.common.ark_dpa_base_policies_editor_service import ArkDPABasePoliciesEditorService from ark_sdk_python.models.ark_profile import ArkProfile from ark_sdk_python.models.cli_services.dpa.policies_editor.db import ArkDPADBGeneratePolicy from ark_sdk_python.models.common import ArkWorkspaceType from ark_sdk_python.models.services import ArkServiceConfig from ark_sdk_python.models.services.dpa.policies.common import ArkDPADeletePolicy, ArkDPAGetPolicy, ArkDPARuleStatus, ArkDPAUserData from ark_sdk_python.models.services.dpa.policies.db import ( ArkDPADB, ArkDPADBAddPolicy, ArkDPADBAppliedTo, ArkDPADBAuthorizationRule, ArkDPADBBaseAuth, ArkDPADBConnectAs, ArkDPADBConnectionInformation, ArkDPADBLDAPAuth, ArkDPADBLocalDBAuth, ArkDPADBMariaDB, ArkDPADBMSSQL, ArkDPADBMySQL, ArkDPADBOracle, ArkDPADBOracleDBAuth, ArkDPADBOracleResource, ArkDPADBPolicy, ArkDPADBPolicyListItem, ArkDPADBPostgres, ArkDPADBProvidersData, ArkDPADBResourceIdentifierType, ArkDPADBUpdatePolicy, ) from ark_sdk_python.services.dpa.policies.db.ark_dpa_db_policies_service import ArkDPADBPoliciesService import inquirer
14,727
'MySQL', 'MariaDB', 'Postgres', 'Oracle', ] DEFAULT_GENERATED_POLICY: Final[ArkDPADBPolicy] = ArkDPADBPolicy( policy_name='Default DB Policy', status=ArkDPARuleStatus.Draft, description='Auto generated db policy', providers_data=ArkDPADBProvidersData( postgres=ArkDPADBPostgres( resources=['postgres-onboarded-asset'], ), ), start_date=date.today().strftime('%Y-%m-%d'), end_date=(date.today() + timedelta(days=7)).strftime('%Y-%m-%d'), user_access_rules=[], ) DEFAULT_GENERATED_PROVIDERS: Final[Dict[ArkWorkspaceType, ArkDPADB]] = { ArkWorkspaceType.MSSQL: ArkDPADBMSSQL(resources=['mssql-onboarded-asset']), ArkWorkspaceType.MYSQL: ArkDPADBMySQL(resources=['mysql-onboarded-asset']), ArkWorkspaceType.MARIADB: ArkDPADBMariaDB(resources=['mariadb-onboarded-asset']), ArkWorkspaceType.POSTGRES: ArkDPADBPostgres(resources=['postgres-onboarded-asset']), ArkWorkspaceType.ORACLE: ArkDPADBOracle( resources=[ ArkDPADBOracleResource( name='oracle-onboarded-asset', services=['XE'], ), ], ), } DEFAULT_GENERATED_AUTH_METHODS: Final[Dict[ArkWorkspaceType, ArkDPADBBaseAuth]] = { ArkWorkspaceType.MSSQL: ArkDPADBLDAPAuth( assign_groups=['DomainSQLAdmins'], applied_to=[ ArkDPADBAppliedTo( name='mssql-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.MYSQL: ArkDPADBLocalDBAuth( roles=['db_admin'], applied_to=[ ArkDPADBAppliedTo( name='mysql-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.MARIADB: ArkDPADBLocalDBAuth( roles=['db_admin'], applied_to=[ ArkDPADBAppliedTo( name='mariadb-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.POSTGRES: ArkDPADBLocalDBAuth( roles=['rds_superuser'], applied_to=[ ArkDPADBAppliedTo( name='postgres-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.ORACLE: ArkDPADBOracleDBAuth( roles=[], dba_role=True, sysdba_role=True, sysoper_role=False, applied_to=[ ArkDPADBAppliedTo( name='oracle-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), } DEFAULT_GENERATED_AUTHORIZATION_RULE: Final[ArkDPADBAuthorizationRule] = ArkDPADBAuthorizationRule( rule_name='Default DB Rule', user_data=ArkDPAUserData(roles=['DpaAdmin'], groups=[], users=[]), connection_information=ArkDPADBConnectionInformation( grant_access=2, idle_time=10, days_of_week=[], full_days=True, hours_from='07:00', hours_to='17:00', time_zone='Asia/Jerusalem', connect_as=ArkDPADBConnectAs( db_auth=[ ArkDPADBLocalDBAuth( roles=['rds_superuser'], applied_to=[ ArkDPADBAppliedTo( name='postgres-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ], ), ), ) WORKSPACE_TO_PROVIDER_NAME: Final[Dict[ArkWorkspaceType, str]] = { ArkWorkspaceType.MSSQL: 'mssql', ArkWorkspaceType.MYSQL: 'mysql', ArkWorkspaceType.POSTGRES: 'postgres', ArkWorkspaceType.ORACLE: 'oracle', ArkWorkspaceType.MARIADB: 'mariadb', } class ArkDPADBPoliciesEditorService( ArkDPABasePoliciesEditorService[ArkDPADBPolicy, ArkDPADBPolicyListItem, ArkDPADBAddPolicy, ArkDPADBUpdatePolicy, ArkDPADBGeneratePolicy] ):
SERVICE_CONFIG: Final[ArkServiceConfig] = ArkServiceConfig( service_name='dpa-policies-db-editor', required_authenticator_names=['isp'], optional_authenticator_names=[] ) SUPPORTED_DATABASE_TYPES: Final[List[str]] = [ 'MSSQL', 'MySQL', 'MariaDB', 'Postgres', 'Oracle', ] DEFAULT_GENERATED_POLICY: Final[ArkDPADBPolicy] = ArkDPADBPolicy( policy_name='Default DB Policy', status=ArkDPARuleStatus.Draft, description='Auto generated db policy', providers_data=ArkDPADBProvidersData( postgres=ArkDPADBPostgres( resources=['postgres-onboarded-asset'], ), ), start_date=date.today().strftime('%Y-%m-%d'), end_date=(date.today() + timedelta(days=7)).strftime('%Y-%m-%d'), user_access_rules=[], ) DEFAULT_GENERATED_PROVIDERS: Final[Dict[ArkWorkspaceType, ArkDPADB]] = { ArkWorkspaceType.MSSQL: ArkDPADBMSSQL(resources=['mssql-onboarded-asset']), ArkWorkspaceType.MYSQL: ArkDPADBMySQL(resources=['mysql-onboarded-asset']), ArkWorkspaceType.MARIADB: ArkDPADBMariaDB(resources=['mariadb-onboarded-asset']), ArkWorkspaceType.POSTGRES: ArkDPADBPostgres(resources=['postgres-onboarded-asset']), ArkWorkspaceType.ORACLE: ArkDPADBOracle( resources=[ ArkDPADBOracleResource( name='oracle-onboarded-asset', services=['XE'], ), ], ), } DEFAULT_GENERATED_AUTH_METHODS: Final[Dict[ArkWorkspaceType, ArkDPADBBaseAuth]] = { ArkWorkspaceType.MSSQL: ArkDPADBLDAPAuth( assign_groups=['DomainSQLAdmins'], applied_to=[ ArkDPADBAppliedTo( name='mssql-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.MYSQL: ArkDPADBLocalDBAuth( roles=['db_admin'], applied_to=[ ArkDPADBAppliedTo( name='mysql-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.MARIADB: ArkDPADBLocalDBAuth( roles=['db_admin'], applied_to=[ ArkDPADBAppliedTo( name='mariadb-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.POSTGRES: ArkDPADBLocalDBAuth( roles=['rds_superuser'], applied_to=[ ArkDPADBAppliedTo( name='postgres-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ArkWorkspaceType.ORACLE: ArkDPADBOracleDBAuth( roles=[], dba_role=True, sysdba_role=True, sysoper_role=False, applied_to=[ ArkDPADBAppliedTo( name='oracle-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), } DEFAULT_GENERATED_AUTHORIZATION_RULE: Final[ArkDPADBAuthorizationRule] = ArkDPADBAuthorizationRule( rule_name='Default DB Rule', user_data=ArkDPAUserData(roles=['DpaAdmin'], groups=[], users=[]), connection_information=ArkDPADBConnectionInformation( grant_access=2, idle_time=10, days_of_week=[], full_days=True, hours_from='07:00', hours_to='17:00', time_zone='Asia/Jerusalem', connect_as=ArkDPADBConnectAs( db_auth=[ ArkDPADBLocalDBAuth( roles=['rds_superuser'], applied_to=[ ArkDPADBAppliedTo( name='postgres-onboarded-asset', type=ArkDPADBResourceIdentifierType.RESOURCE, ) ], ), ], ), ), ) WORKSPACE_TO_PROVIDER_NAME: Final[Dict[ArkWorkspaceType, str]] = { ArkWorkspaceType.MSSQL: 'mssql', ArkWorkspaceType.MYSQL: 'mysql', ArkWorkspaceType.POSTGRES: 'postgres', ArkWorkspaceType.ORACLE: 'oracle', ArkWorkspaceType.MARIADB: 'mariadb', } class ArkDPADBPoliciesEditorService( ArkDPABasePoliciesEditorService[ArkDPADBPolicy, ArkDPADBPolicyListItem, ArkDPADBAddPolicy, ArkDPADBUpdatePolicy, ArkDPADBGeneratePolicy] ):
def __init__(self, isp_auth: ArkISPAuth, policies_cache_dir: Optional[str] = None, profile: Optional[ArkProfile] = None) -> None:
3
2023-11-13 09:24:31+00:00
24k
kampta/asic
train.py
[ { "identifier": "Logger", "path": "commons/logger.py", "snippet": "class Logger(SummaryWriter):\n\n def __init__(self, results_path, log_to_tb=False, log_to_wandb=True):\n super().__init__(results_path)\n self.results_path = results_path\n self.log_to_tb = log_to_tb\n self.log_to_wandb = log_to_wandb\n\n def _log_image_grid(self, images, logging_name, prefix, itr, range=(-1, 1),\n scale_each=False, nrow=None, **kwargs):\n nrow = max(1, int(len(images) ** 0.5+0.5)) if nrow is None else nrow\n if type(images[0]) is torch.Tensor:\n ndarr = images2grid(images, return_as_PIL=True, nrow=nrow,\n normalize=True, value_range=range,\n scale_each=scale_each, **kwargs)\n grid = Image.fromarray(ndarr)\n grid.save(f\"{self.results_path}/{logging_name}_{str(itr).zfill(7)}.png\")\n if self.log_to_wandb:\n wandb.log({logging_name: wandb.Image(grid)}, step=itr)\n else:\n grid = concat_v(*images)\n grid.save(f\"{self.results_path}/{logging_name}_{str(itr).zfill(7)}.png\")\n if self.log_to_wandb:\n wandb.log({logging_name: [wandb.Image(im) for im in images]}, step=itr)\n\n if self.log_to_tb:\n self.add_image(f\"{prefix}/{logging_name}\", ndarr, itr,\n dataformats='HWC')\n\n def log_image_grid(self, images, logging_name, itr, imgs_to_show,\n log_mean_img=True, mean_range=None, range=(-1, 1),\n scale_each=False, num_heads=1, nrow=None, **kwargs):\n self._log_image_grid(images[:imgs_to_show], logging_name, \"grids\", itr,\n range=range, scale_each=scale_each, nrow=nrow, **kwargs)\n if log_mean_img: # Log average images:\n images = images.reshape(images.size(0) // num_heads, num_heads,\n *images.size()[1:])\n self._log_image_grid(images.mean(dim=0), f'mean_{logging_name}',\n \"means\", itr, range=mean_range,\n scale_each=True, nrow=nrow)\n\n def add_scalar(self, tag, scalar_value, global_step=None, **kwargs):\n if self.log_to_wandb:\n wandb.log({tag: scalar_value}, step=global_step)\n return super().add_scalar(tag, scalar_value, global_step, **kwargs)\n\n def add_scalars(self, main_tag, tag_scalar_dict, global_step=None, **kwargs):\n if self.log_to_wandb:\n wandb.log(tag_scalar_dict, step=global_step)\n return super().add_scalars(main_tag, tag_scalar_dict, global_step, **kwargs)" }, { "identifier": "log_visuals", "path": "commons/logger.py", "snippet": "@torch.inference_mode()\ndef log_visuals(canon, stn, dset, train_idx, writer, vis_sample=2,\n vis_denseres=32):\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n pseudo_kps = dset.pseudo_kps\n parts = dset.parts\n vis_sample = min(vis_sample, len(dset))\n res = dset.img_size\n has_gt_kp = dset.kps is not None\n has_fixed_pairs = dset.fixed_pairs is not None # SPair\n\n # Run full test dataloader (assuming small dataset)\n all_imgs = dset.imgs\n all_masks = dset.masks\n all_kps = dset.kps\n all_flows, _ = stn(all_imgs)\n\n if has_gt_kp:\n kps_cols = torch.from_numpy(get_colors(all_kps.size(1))).float()\n kps_cols = map_minmax(kps_cols, 0, 1, -1, 1).to(device).unsqueeze(0)\n\n parts_cols = torch.from_numpy(get_colors(dset.num_parts+1)).float()\n parts_cols = map_minmax(parts_cols, 0, 1, -1, 1).to(device)\n parts_cols[-1] = 0\n\n # Text logging\n text_kp, text_kp_col = load_text_points('CVPR')\n text_kp = text_kp.to(device).unsqueeze(0)\n text_kp_col = text_kp_col.to(device).unsqueeze(0)\n\n pairs = sample_tuples(len(dset), count=vis_sample, seed=0)\n src_idx, trg_idx = pairs[:, 0], pairs[:, 1]\n\n # Log only once during the training\n if train_idx == 0:\n # Log images and the mask\n writer.log_image_grid(all_imgs[:vis_sample], 'img', train_idx,\n vis_sample, nrow=vis_sample)\n writer.log_image_grid(all_imgs[:vis_sample]*all_masks[:vis_sample],\n 'img_mask', train_idx, vis_sample, nrow=vis_sample)\n\n # Log neural best buddies (sparse)\n kp1 = pseudo_kps[src_idx, trg_idx]\n kp2 = pseudo_kps[trg_idx, src_idx]\n kp_vis = kp1[..., -1] * kp2[..., -1]\n kp1, kp2 = kp1[..., :2], kp2[..., :2]\n colors = map_minmax(get_dense_colors(kp1), 0, 1, -1, 1)\n\n blend_src = splat_points(\n all_imgs[src_idx], kp1, sigma=3., opacity=1.0, colors=colors,\n alpha_channel=kp_vis.unsqueeze(-1))\n blend_trg = splat_points(\n all_imgs[trg_idx], kp2, sigma=3., opacity=1.0, colors=colors,\n alpha_channel=kp_vis.unsqueeze(-1))\n stacked = torch.stack([blend_src, blend_trg], dim=1).flatten(0, 1)\n\n writer.log_image_grid(stacked, 'kp_pseudo_gt', train_idx, 2*vis_sample,\n log_mean_img=False, nrow=2)\n\n # Log parts\n parts_img = parts_cols[parts[:vis_sample]].permute(0, 3, 1, 2)\n writer.log_image_grid(parts_img, 'parts', train_idx, vis_sample,\n nrow=vis_sample, log_mean_img=False)\n\n # Log groundtruth kp\n if has_gt_kp:\n kp1, kp2 = all_kps[src_idx], all_kps[trg_idx]\n kp_vis = kp1[..., -1] * kp2[..., -1]\n kp1, kp2 = kp1[..., :2], kp2[..., :2]\n\n colors = kps_cols.expand(vis_sample, -1, -1)\n blend_src = splat_points(\n all_imgs[src_idx], kp1, sigma=3., opacity=1.0, colors=colors,\n alpha_channel=kp_vis.unsqueeze(-1))\n blend_trg = splat_points(\n all_imgs[trg_idx], kp2, sigma=3., opacity=1.0, colors=colors,\n alpha_channel=kp_vis.unsqueeze(-1))\n stacked = torch.stack([blend_src, blend_trg], dim=1).flatten(0, 1)\n\n stacked = torch.stack([blend_src, blend_trg], dim=1).flatten(0, 1)\n writer.log_image_grid(stacked, 'kp_gt', train_idx, 2*vis_sample,\n log_mean_img=False, nrow=2)\n\n # Log kp and top predictions by STN (if kp are available)\n if has_gt_kp:\n kp1 = all_kps[src_idx][..., :2]\n kp_vis = all_kps[src_idx][..., 2]\n\n kp_pred = stn.transfer_points(\n kp1, src_idx, trg_idx, all_flows, mask=all_masks, res=res, is_flow=True)\n colors = kps_cols.expand(vis_sample, -1, -1)\n\n blend_src = splat_points(\n all_imgs[src_idx], kp1, sigma=3., opacity=1.0,\n colors=colors, alpha_channel=kp_vis.unsqueeze(-1))\n blend_trg = splat_points(\n all_imgs[trg_idx], kp_pred.float(), sigma=3., opacity=1.0,\n colors=colors, alpha_channel=kp_vis.unsqueeze(-1))\n\n stacked = torch.stack([blend_src, blend_trg], dim=1).flatten(0, 1)\n writer.log_image_grid(stacked, 'kp_pred_sparse', train_idx,\n 2*vis_sample, log_mean_img=False, nrow=2)\n\n # Log current canon image\n canon_grid = canon.get_grid(vis_sample)\n if canon_grid.size(1) > 3:\n canon_grid = canon_grid[:, :3]\n scale_factor = res / canon_grid.size(-1)\n canon_grid = F.interpolate(\n canon_grid, scale_factor=scale_factor, mode='bilinear')\n writer.log_image_grid(canon_grid, 'canon', train_idx, 1, log_mean_img=False)\n\n # Log dense correspondences\n kp, kp_vis, kp_col_dense = load_fg_points(all_masks[src_idx],\n resolution=vis_denseres)\n kp_pred, kp_canon = stn.transfer_points(\n kp, src_idx, trg_idx, all_flows, mask=all_masks, res=res,\n return_canon=True, is_flow=True)\n colors = map_minmax(kp_col_dense, 0, 1, -1, 1)\n\n blend_src = splat_points(\n all_imgs[src_idx], kp, sigma=4., opacity=0.75,\n colors=colors, alpha_channel=kp_vis.unsqueeze(-1))\n\n blend_trg = splat_points(\n all_imgs[trg_idx], kp_pred.float(), sigma=4., opacity=0.75,\n colors=colors, alpha_channel=kp_vis.unsqueeze(-1))\n\n blend_canon = splat_points(\n torch.ones_like(canon_grid) * -1, kp_canon, sigma=1.3, opacity=1.0,\n colors=colors, alpha_channel=kp_vis.unsqueeze(-1))\n stacked = torch.stack([blend_src, blend_canon, blend_trg], dim=1).\\\n flatten(0, 1)\n writer.log_image_grid(\n stacked, 'kp_pred_dense', train_idx, 3*vis_sample,\n log_mean_img=False, nrow=3)\n\n # # Log dense correspondences with text\n # text_kp = text_kp.expand(vis_sample, -1, -1)\n # text_kp_col = text_kp_col.expand(vis_sample, -1, -1)\n # kp_pred, kp_canon = stn.transfer_points(\n # text_kp, src_idx, trg_idx, all_flows, mask=all_masks, res=res,\n # return_canon=True, is_flow=True)\n\n # blend_src = splat_points(all_imgs[src_idx], text_kp, sigma=0.7, opacity=1.,\n # colors=text_kp_col)\n\n # blend_trg = splat_points(all_imgs[trg_idx], kp_pred.float(), sigma=0.7,\n # opacity=1., colors=text_kp_col)\n\n # blend_canon = splat_points(torch.ones_like(canon_grid) * -1, kp_canon,\n # sigma=0.7, opacity=1., colors=text_kp_col)\n\n # stacked = torch.stack([blend_src, blend_canon, blend_trg], dim=1).\\\n # flatten(0, 1)\n # writer.log_image_grid(\n # stacked, 'kp_pred_text', train_idx, 3*vis_sample,\n # log_mean_img=False, nrow=3)\n\n # Log dense mapping from canonical space to Image space\n wheel = color_wheel_fast_smooth(res).permute(2, 0, 1).unsqueeze(0).to(device)\n colors = wheel.expand(vis_sample, -1, -1, -1)\n flow, _ = stn(all_imgs[src_idx])\n colors = F.grid_sample(colors, flow, padding_mode='border',\n align_corners=True)\n colors = map_minmax(colors, 0, 1, -1, 1)\n alpha = 0.5\n blend_img = alpha * all_imgs[src_idx] * (1-all_masks[src_idx]) + \\\n (all_imgs[src_idx] * alpha + colors * (1-alpha)) * all_masks[src_idx]\n blend_img = torch.cat([wheel, blend_img, wheel, colors* all_masks[src_idx]])\n writer.log_image_grid(blend_img, 'canon_map', train_idx, len(blend_img),\n log_mean_img=False, nrow=len(blend_img)//2)\n\n # Log keypoints from Image space to canonical space\n if has_gt_kp:\n canon_corrs = stn.transfer_forward(all_flows, all_kps[..., :2], res, is_flow=True)\n canon_corrs = stn.unnormalize(canon_corrs, res, res)\n canon_vis = all_kps[..., -1]\n num_kp = canon_vis.size(-1)\n N = canon_vis.size(0)\n colors = kps_cols.permute(1, 0, 2).expand(-1, N, -1).to(device)\n heatmaps = splat_points(\n torch.ones(num_kp, 3, res, res, device=device) * -1,\n canon_corrs.permute(1, 0, 2), sigma=6., opacity=1.,\n colors=colors, alpha_channel=canon_vis.permute(1, 0).unsqueeze(-1))\n writer.log_image_grid(heatmaps, 'kp_heatmaps', train_idx,\n num_kp, padding=2, pad_value=1.)\n\n # Log parts from Image space to canonical space\n # Splat one part at a time to canonical\n # TODO: splat all at once\n num_parts = dset.num_parts\n part_kp_canons = []\n part_kp_vis = [] \n for part in range(num_parts):\n part_masks = (parts == part).float().unsqueeze(1)\n kp, kp_vis, _ = load_fg_points(part_masks, resolution=vis_denseres)\n kp_canon = stn.transfer_forward(all_flows, kp[..., :2], res, is_flow=True)\n kp_canon = stn.unnormalize(kp_canon, res, res)\n part_kp_canons.append(kp_canon.reshape(-1, 2))\n part_kp_vis.append(kp_vis.reshape(-1))\n\n part_kp_canons = torch.stack(part_kp_canons)\n part_kp_vis = torch.stack(part_kp_vis)\n colors = parts_cols[:-1].unsqueeze(1).expand(-1, part_kp_vis.size(1), -1)\n heatmaps = splat_points(\n torch.ones(num_parts, 3, res, res, device=device) * -1,\n part_kp_canons, sigma=2., opacity=1.,\n colors=colors, alpha_channel=part_kp_vis.unsqueeze(-1))\n writer.log_image_grid(heatmaps, 'part_heatmaps', train_idx,\n num_parts, padding=2, pad_value=1.)\n\n # Compute PCKs\n N = all_imgs.size(0)\n transfer_fn = stn.transfer_points\n pck_pairs = None\n if has_gt_kp:\n # First compute PCK for all 2-pairs\n if has_fixed_pairs:\n tuples = dset.fixed_pairs\n if dset.thresholds is not None:\n thresholds = [torch.from_numpy(dset.thresholds)[tuples[:, 1]]]\n else:\n thresholds = None\n else:\n tuples = sample_tuples(N)\n thresholds = None\n print(f\"First computing 2-point PCK for {len(tuples)} pairs\")\n gt_corrs, pred_corrs, vis = pck_loop(\n tuples, all_kps, transfer_fn, all_flows, all_masks, res,\n return_canon=False, is_flow=True)\n pck_pairs = compute_pck(pred_corrs, gt_corrs, vis, thresholds,\n img_size=res)\n\n # Compute k-cycle PCK\n pck_cycles = []\n if not has_gt_kp:\n kp, kp_vis, kp_col_dense = load_fg_points(all_masks,\n resolution=vis_denseres)\n ignore_idx = kp_vis.sum(dim=0) == 0\n all_kps = torch.cat([kp[:, ~ignore_idx], kp_vis[:, ~ignore_idx].unsqueeze(-1)], dim=2)\n ignore_interim = True\n else:\n ignore_interim = False\n\n for k in [2, 3, 4]:\n tuples = sample_tuples(N, k=k, count=200)\n if has_fixed_pairs and dset.thresholds is not None:\n thresholds = torch.from_numpy(dset.thresholds[tuples[:, 1:]])\n thresholds = thresholds.reshape(-1)\n else:\n thresholds = None\n print(f\"Next computing {k}-cycle PCK for {len(tuples)} tuples\")\n gt_corrs, pred_corrs, vis = pck_loop(\n tuples, all_kps, transfer_fn, all_flows, all_masks, res,\n return_canon=False, is_flow=True, ignore_interim=ignore_interim)\n pck = compute_pck(pred_corrs, gt_corrs, vis, thresholds, img_size=res)\n pck_cycles.append(pck)\n\n return pck_pairs, pck_cycles" }, { "identifier": "get_rank", "path": "commons/distributed.py", "snippet": "def get_rank():\n if not dist.is_available():\n return 0\n\n if not dist.is_initialized():\n return 0\n\n return dist.get_rank()" }, { "identifier": "setup_distributed", "path": "commons/distributed.py", "snippet": "def setup_distributed():\n local_rank = int(os.environ['LOCAL_RANK']) if 'LOCAL_RANK' in os.environ else 0\n n_gpu = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1\n is_distributed = n_gpu > 1\n if is_distributed:\n torch.cuda.set_device(local_rank)\n dist.init_process_group(backend=\"nccl\", init_method=\"env://\")\n synchronize()\n return is_distributed" }, { "identifier": "reduce_loss_dict", "path": "commons/distributed.py", "snippet": "def reduce_loss_dict(loss_dict):\n world_size = get_world_size()\n\n if world_size < 2:\n return loss_dict\n\n with torch.no_grad():\n keys = []\n losses = []\n\n for k in sorted(loss_dict.keys()):\n keys.append(k)\n losses.append(loss_dict[k])\n\n losses = torch.stack(losses, 0)\n dist.reduce(losses, dst=0)\n\n if dist.get_rank() == 0:\n losses /= world_size\n\n reduced_losses = {k: v for k, v in zip(keys, losses)}\n\n return reduced_losses" }, { "identifier": "get_world_size", "path": "commons/distributed.py", "snippet": "def get_world_size():\n if not dist.is_available():\n return 1\n\n if not dist.is_initialized():\n return 1\n\n return dist.get_world_size()" }, { "identifier": "primary", "path": "commons/distributed.py", "snippet": "def primary():\n if not dist.is_available():\n return True\n\n if not dist.is_initialized():\n return True\n\n return get_rank() == 0" }, { "identifier": "sample_tuples", "path": "commons/utils.py", "snippet": "def sample_tuples(N, k=1, count=None, seed=None):\n\n if seed is not None:\n np.random.seed(seed)\n\n if count is None: # return all possible (k+1) permutations\n # (N!/(N-k)!) x k array\n samples = np.array(list(permutations(range(N), k+1)))\n\n elif k == 1:\n p1 = np.random.choice(N, count)\n p2 = np.random.choice(N, count)\n return np.stack([p1, p2], axis=1)\n\n elif count == -1:\n samples = np.array(list(permutations(range(N), k)))\n samples = np.concatenate([samples, samples[:, 0].reshape(-1, 1)], axis=1)\n\n else: # sample count number of permutations\n # count x k array\n samples = np.zeros((count, k+1), dtype=int)\n for i in range(count):\n samples[i, :k] = np.random.choice(N, k, replace=False)\n # Force the last column to be same as the first column\n samples[:, k] = samples[:, 0]\n\n return samples" }, { "identifier": "CUBDataset", "path": "datasets/cub.py", "snippet": "class CUBDataset(Dataset):\n def __init__(self, data_dir, split='test', img_size=256, cls_idx=1,\n flow_dir=None, num_parts=0,\n mask_threshold=1, use_coseg_masks=False, padding_mode='border'):\n super().__init__()\n self.img_size = img_size\n self.split = split\n self.cls_idx = cls_idx\n self.flow_dir = flow_dir\n self.num_parts = num_parts\n self.mask_threshold = mask_threshold\n self.fixed_pairs = None\n self.thresholds = None\n self.border = True if padding_mode=='border' else False\n\n os.makedirs(data_dir, exist_ok=True)\n download_cub(data_dir)\n download_cub_metadata(data_dir)\n\n self.files, self.bboxes, self.kps, self.masks = load_acsm_data(\n data_dir, size=img_size, split=split, cls_idx=cls_idx)\n\n imgs = []\n for i in range(len(self.files)):\n img = Image.open(self.files[i]).convert('RGB')\n img = cub_crop(img, self.img_size, self.bboxes[i], border=self.border)\n imgs.append(torch.from_numpy(np.array(img)).permute(2, 0, 1))\n self.imgs = torch.stack(imgs) / 127.5 - 1.0 # normalize (-1, 1)\n\n # Load masks\n if flow_dir is not None:\n if use_coseg_masks:\n mask_dir = Path(flow_dir) / 'masks_coseg'\n else:\n mask_dir = Path(flow_dir) / 'masks'\n assert mask_dir.exists(), f\"{mask_dir} doesn't exist\"\n masks = []\n for i in range(0, len(self)):\n fname = mask_dir / f'{Path(self.files[i]).stem}.png'\n mask = np.array(Image.open(fname).convert('L'))\n masks.append(mask)\n self.masks = torch.from_numpy(np.stack(masks) > mask_threshold).float()\n\n self.parts = None\n if flow_dir is not None:\n parts_str = 'parts' if num_parts <=0 else f'parts_num{num_parts}'\n parts_dir = Path(flow_dir) / f'{parts_str}'\n if parts_dir.exists():\n parts = []\n for i in range(0, len(self)):\n fname = parts_dir / f'parts_s2_{Path(self.files[i]).stem}.npy'\n part = np.load(fname)\n parts.append(part)\n parts = np.stack(parts)\n num_parts = int(np.max(parts[~np.isnan(parts)])) + 1\n parts[np.isnan(parts)] = num_parts\n\n self.parts = torch.from_numpy(parts.astype(np.int64))\n else:\n print(f\"{parts_dir} doesn't exist. Parts won't load.\")\n self.num_parts = num_parts\n # self.parts = F.one_hot(parts, num_classes=num_parts+1).bool()\n\n # Load pseudo keypoints\n self.pseudo_kps = None\n if flow_dir is not None:\n nbb_dir = Path(flow_dir) / 'nbb'\n if nbb_dir.exists():\n self.pseudo_kps = load_nbb(nbb_dir, self.files, self.parts)\n max_matches = self.pseudo_kps.shape[2]\n print(f'Max #matches between an image pair: {max_matches}')\n else:\n print(f\"{nbb_dir} doesn't exist. Pseudo kps won't load.\")\n\n\n def __len__(self):\n return len(self.files)" }, { "identifier": "InMemoryDataset", "path": "datasets/in_memory.py", "snippet": "class InMemoryDataset(Dataset):\n def __init__(self, data_dir, img_size=256, flow_dir=None,\n num_parts=0, mask_threshold=1, use_coseg_masks=False,\n every_k=1):\n\n self.img_size = img_size\n self.flow_dir = flow_dir\n self.num_parts = num_parts\n self.mask_threshold = mask_threshold\n\n normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],\n std=[0.5, 0.5, 0.5])\n transform = transforms.Compose([\n transforms.Resize(img_size),\n transforms.CenterCrop(img_size),\n transforms.ToTensor(),\n normalize,\n ])\n\n files = []\n imgs = []\n for base_dir, dirnames, filenames in os.walk(data_dir):\n if len(dirnames) > 0:\n continue\n for f in sorted(filenames):\n if not f.lower().endswith(('.png', '.jpg', '.jpeg')):\n continue\n filename = Path(base_dir) / f\n files.append(filename)\n img = Image.open(filename).convert('RGB')\n imgs.append(transform(img))\n \n self.files = files[::every_k]\n self.imgs = torch.stack(imgs[::every_k])\n\n self.kps = None\n self.fixed_pairs = None\n self.thresholds = None\n self.pseudo_kps = None\n self.parts = None\n\n # Load masks\n if flow_dir is not None:\n if use_coseg_masks:\n mask_dir = Path(flow_dir) / 'masks_coseg'\n else:\n mask_dir = Path(flow_dir) / 'masks'\n assert mask_dir.exists(), f\"{mask_dir} doesn't exist\"\n masks = []\n for i in range(0, len(self)):\n fname = mask_dir / f'{self.files[i].stem}.png'\n mask = np.array(Image.open(fname).convert('L'))\n masks.append(mask)\n self.masks = torch.from_numpy(np.stack(masks) >= mask_threshold).float()\n\n # Load parts\n if flow_dir is not None:\n parts_str = 'parts' if num_parts <=0 else f'parts_num{num_parts}'\n parts_dir = Path(flow_dir) / f'{parts_str}'\n if parts_dir.exists():\n parts = []\n for i in range(0, len(self)):\n fname = parts_dir / f'parts_s2_{self.files[i].stem}.npy'\n part = np.load(fname)\n parts.append(part)\n parts = np.stack(parts)\n num_parts = int(np.max(parts[~np.isnan(parts)])) + 1\n parts[np.isnan(parts)] = num_parts\n\n self.parts = torch.from_numpy(parts.astype(np.int64))\n else:\n print(f\"{parts_dir} doesn't exist. Parts won't load.\")\n self.num_parts = num_parts\n # self.parts = F.one_hot(parts, num_classes=num_parts+1).bool()\n\n # Load pseudo keypoints\n if flow_dir is not None:\n nbb_dir = Path(flow_dir) / 'nbb'\n if nbb_dir.exists():\n self.pseudo_kps = load_nbb(nbb_dir, self.files, self.parts)\n max_matches = self.pseudo_kps.shape[2]\n print(f'Max #matches between an image pair: {max_matches}')\n else:\n print(f\"{nbb_dir} doesn't exist. Pseudo kps won't load.\")\n\n def __len__(self):\n return len(self.files)" }, { "identifier": "SpairDataset", "path": "datasets/spair.py", "snippet": "class SpairDataset(Dataset):\n def __init__(self, data_dir, split='test', img_size=256, spair_cat='cat',\n flow_dir=None, padding_mode='edge', num_parts=0,\n mask_threshold=1, use_coseg_masks=False):\n super().__init__()\n self.img_size = img_size\n self.split = split\n self.cat = spair_cat\n self.padding_mode = padding_mode\n self.flow_dir = flow_dir\n self.num_parts = num_parts\n self.mask_threshold = mask_threshold\n\n normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],\n std=[0.5, 0.5, 0.5])\n transform = transforms.Compose([\n SquarePad(padding_mode),\n transforms.Resize(img_size),\n transforms.ToTensor(),\n normalize,\n ])\n\n os.makedirs(data_dir, exist_ok=True)\n spair_dir = download_spair(data_dir)\n\n self.files, self.kps, fixed_pairs, thresholds = load_spair_data(\n spair_dir, size=img_size, split=split, category=spair_cat)\n imgs = [transform(Image.open(self.files[i]).convert('RGB'))\n for i in range(len(self))]\n self.imgs = torch.stack(imgs)\n self.fixed_pairs = np.array(fixed_pairs)\n self.thresholds = np.array(thresholds)\n\n self.masks = torch.ones(len(self), 1, img_size, img_size)\n self.pseudo_kps = None\n self.parts = None\n\n # Load masks\n if flow_dir is not None:\n if use_coseg_masks:\n mask_dir = Path(flow_dir) / 'masks_coseg'\n else:\n mask_dir = Path(flow_dir) / 'masks'\n assert mask_dir.exists(), f\"{mask_dir} doesn't exist\"\n masks = []\n for i in range(0, len(self)):\n fname = mask_dir / f'{Path(self.files[i]).stem}.png'\n mask = np.array(Image.open(fname).convert('L'))\n masks.append(mask)\n self.masks = torch.from_numpy(np.stack(masks) >= mask_threshold).float()\n\n # Load parts\n if flow_dir is not None:\n parts_str = 'parts' if num_parts <=0 else f'parts_num{num_parts}'\n parts_dir = Path(flow_dir) / f'{parts_str}'\n if parts_dir.exists():\n parts = []\n for i in range(0, len(self)):\n fname = parts_dir / f'parts_s2_{Path(self.files[i]).stem}.npy'\n part = np.load(fname)\n parts.append(part)\n parts = np.stack(parts)\n num_parts = int(np.max(parts[~np.isnan(parts)])) + 1\n parts[np.isnan(parts)] = num_parts\n\n self.parts = torch.from_numpy(parts.astype(np.int64))\n else:\n print(f\"{parts_dir} doesn't exist. Parts won't load.\")\n self.num_parts = num_parts\n # self.parts = F.one_hot(parts, num_classes=num_parts+1).bool()\n \n # Load pseudo keypoints\n if flow_dir is not None:\n nbb_dir = Path(flow_dir) / 'nbb'\n if nbb_dir.exists():\n self.pseudo_kps = load_nbb(nbb_dir, self.files, self.parts)\n max_matches = self.pseudo_kps.shape[2]\n print(f'Max #matches between an image pair: {max_matches}')\n else:\n print(f\"{nbb_dir} doesn't exist. Pseudo kps won't load.\")\n\n def __len__(self):\n return len(self.files)" }, { "identifier": "Augmentor", "path": "datasets/utils.py", "snippet": "class Augmentor(nn.Module):\n def __init__(self, jitter=[0.4, 0.4, 0.2, 0.1], jitter_prob=0.8,\n gray_prob=0.2, solar_prob=0.2, tps_scale=0.4):\n super().__init__()\n self.color_transform = K.AugmentationSequential(\n # https://github.com/facebookresearch/dino/blob/main/main_dino.py#L424\n K.ColorJitter(brightness=jitter[0], contrast=jitter[1],\n saturation=jitter[2], hue=jitter[3], p=jitter_prob),\n K.RandomGrayscale(p=gray_prob),\n K.RandomGaussianBlur((3, 3), (0.1, 2.0), p=0.1),\n K.RandomSolarize(0.1, 0.1, p=solar_prob),\n )\n\n self.perspective_transform = K.RandomPerspective(0.5, p=1.)\n self.affine_transform = K.RandomAffine(30, scale=(0.7, 1.1),\n padding_mode='border', p=1.0)\n self.elastic_transform = K.RandomElasticTransform(\n p=1.0, sigma=(16., 16.), alpha=(3, 3), padding_mode='border')\n\n # TPS doesn't support transforming points\n # Using it only for dense equivariance loss\n self.tps_transform = K.RandomThinPlateSpline(scale=tps_scale, p=1.)\n\n def forward(self, x):\n pass\n\n @torch.no_grad()\n def forward_color(self, img):\n return self.color_transform(img)\n\n @torch.no_grad()\n def forward_tps(self, img, fixed=False):\n if fixed:\n img_t = self.tps_transform(img, params=self.tps_transform._params)\n else:\n img_t = self.tps_transform(img)\n return img_t\n \n @torch.no_grad()\n def forward_geom(self, img, fixed=False):\n if fixed:\n img_t = self.elastic_transform(\n self.affine_transform(img, params=self.affine_transform._params),\n params=self.elastic_transform._params)\n else:\n img_t = self.elastic_transform(self.affine_transform(img))\n return img_t\n\n\n @torch.no_grad()\n def forward_perspective(self, img, fixed=False):\n if fixed:\n img_t = self.perspective_transform(img, params=self.perspective_transform._params)\n else:\n img_t = self.perspective_transform(img)\n return img_t\n\n @torch.no_grad()\n def forward_perspective_kp(self, kp):\n return kornia.geometry.transform_points(\n self.perspective_transform.transform_matrix, kp)" }, { "identifier": "accumulate", "path": "models/utils.py", "snippet": "def accumulate(model1, model2, decay=0.999):\n par1 = dict(model1.named_parameters())\n par2 = dict(model2.named_parameters())\n\n for k in par1.keys():\n par1[k].data.mul_(decay).add_(par2[k].data, alpha=1 - decay)" }, { "identifier": "requires_grad", "path": "models/utils.py", "snippet": "def requires_grad(model, flag=True):\n for p in model.parameters():\n p.requires_grad = flag" }, { "identifier": "Canonical", "path": "models/canonical.py", "snippet": "class Canonical(nn.Module):\n def __init__(self, size, std=0.1, clamp=True):\n super().__init__()\n mean = torch.zeros(size)\n std = torch.ones(size) * std\n self.grid = nn.Parameter(torch.normal(mean=mean, std=std),\n requires_grad=True)\n norm_class = Normalize()\n norm_class.apply(self.grid)\n if clamp:\n clamp_class = Clamp()\n clamp_class.apply(self.grid)\n\n def get_grid(self, N):\n return self.grid.expand(N, -1, -1, -1)\n\n def unwarp(self, flow, sample_res=256):\n N = flow.size(0)\n if sample_res is not None and sample_res != flow.size(1):\n scale_factor = sample_res / flow.size(1)\n sample_flow = F.interpolate(\n flow.permute(0, 3, 1, 2), scale_factor=scale_factor,\n mode='bilinear').permute(0, 2, 3, 1)\n else:\n sample_flow = flow\n warped_img = F.grid_sample(\n self.get_grid(N), sample_flow,\n padding_mode='border', align_corners=True)\n return warped_img\n\n def forward(self, x):\n return x" }, { "identifier": "CanonicalMLP", "path": "models/canonical.py", "snippet": "class CanonicalMLP(nn.Module):\n def __init__(self, input_dim=2, output_dim=3, hidden_dim=256,\n use_positional=True, positional_dim=10,\n skip_layers=[4, 7], num_layers=8, resolution=256,\n use_tanh=True, apply_softmax=False):\n super().__init__()\n self.use_tanh = use_tanh\n self.resolution = resolution\n self.apply_softmax = apply_softmax\n self.output_dim = output_dim\n if apply_softmax:\n self.softmax= nn.Softmax()\n if use_positional:\n encoding_dimensions = 2 * input_dim * positional_dim\n self.b = nn.Parameter(\n torch.tensor([(2 ** j) * np.pi\n for j in range(positional_dim)], requires_grad = False))\n else:\n encoding_dimensions = input_dim\n\n self.hidden = nn.ModuleList()\n for i in range(num_layers):\n if i == 0:\n input_dims = encoding_dimensions\n elif i in skip_layers:\n input_dims = hidden_dim + encoding_dimensions\n else:\n input_dims = hidden_dim\n\n if i == num_layers - 1:\n # last layer\n self.hidden.append(nn.Linear(input_dims, output_dim, bias=True))\n else:\n self.hidden.append(nn.Linear(input_dims, hidden_dim, bias=True))\n\n self.skip_layers = skip_layers\n self.num_layers = num_layers\n\n self.positional_dim = positional_dim\n self.use_positional = use_positional\n\n def get_grid(self, N, device='cuda'):\n resolution = self.resolution\n indsy = torch.linspace(0, resolution-1, resolution, device=device)\n indsx = torch.linspace(0, resolution-1, resolution, device=device)\n\n # Keep (x, y) indexing to make it consistent with the flow\n points = torch.stack(\n torch.meshgrid(indsx, indsy, indexing='xy'), dim=-1).reshape(-1, 2)\n\n with torch.no_grad():\n grid = self(points)\n\n grid = grid.reshape(1, resolution, resolution, self.output_dim)\n grid = grid.permute(0, 3, 1, 2)\n return grid.expand(N, -1, -1, -1)\n\n def unwarp(self, flow, sample_res=256):\n N = flow.size(0)\n # Output of flow model is usually normalized between -1 and 1\n # So we need to first scale it up to self.resolution\n flow = map_minmax(flow, -1, 1, 0, self.resolution-1)\n\n # Resize flow if computed at a lower resolution\n if sample_res is not None and sample_res != flow.size(1):\n scale_factor = sample_res / flow.size(1)\n sample_flow = F.interpolate(\n flow.permute(0, 3, 1, 2), scale_factor=scale_factor,\n mode='bilinear').permute(0, 2, 3, 1)\n else:\n sample_flow = flow\n\n # Unwarp\n warped_img = self(sample_flow.reshape(-1, 2))\n warped_img = warped_img.reshape(N, sample_res, sample_res, -1)\n warped_img = warped_img.permute(0, 3, 1, 2)\n return warped_img\n\n def forward(self, x):\n if self.use_positional:\n if self.b.device != x.device:\n self.b = self.b.to(x.device)\n pos = positionalEncoding_vec(x, self.b)\n x = pos\n\n input = x.detach().clone()\n for i, layer in enumerate(self.hidden):\n if i > 0:\n x = F.relu(x)\n if i in self.skip_layers:\n x = torch.cat((x, input), 1)\n x = layer(x)\n\n if self.use_tanh:\n x = torch.tanh(x)\n\n if self.apply_softmax:\n x = self.softmax(x)\n return x" }, { "identifier": "Asic", "path": "models/asic.py", "snippet": "class Asic(nn.Module):\n def __init__(self, in_ch, in_size, mf=1., bilinear=False,\n padding_mode='zeros', use_tanh=False):\n super().__init__()\n self.model = UNet(in_ch, 2, mf=mf, bilinear=bilinear)\n self.size = in_size\n self.register_buffer('identity_flow', self.get_identity_flow())\n self.padding_mode = padding_mode\n self.use_tanh = use_tanh\n\n def get_identity_flow(self):\n return F.affine_grid(\n torch.eye(2, 3).unsqueeze(0), (1, 1, self.size, self.size),\n align_corners=True).permute(0, 3, 1, 2).contiguous()\n\n def forward(self, x):\n if self.use_tanh:\n flow = torch.tanh(self.model(x))\n delta_flow = flow - self.identity_flow\n else:\n delta_flow = self.model(x) # (N, 2, H, W)\n flow = self.identity_flow + delta_flow\n\n flow = flow.permute(0, 2, 3, 1)\n delta_flow = delta_flow.permute(0, 2, 3, 1)\n return flow, delta_flow\n\n @torch.no_grad()\n def transfer_points(self, src_kps, src_idx, trg_idx, img, mask=None,\n res=None, return_canon=False, is_flow=False):\n # src_kps are N x P x 2 (in xy format)\n\n # Compute flow from images\n if is_flow:\n flow = img\n else:\n flow, _ = self(img)\n\n # Step 1: Map the points in src to the canonical space\n max_batch_size = 2\n if src_kps.size(0) > max_batch_size:\n N = len(src_kps)\n points_canon = []\n for start_idx in range(0, N, max_batch_size):\n end_idx = min(start_idx+max_batch_size, N)\n\n points_canon_batch = self.transfer_forward(\n flow[src_idx[start_idx:end_idx]],\n src_kps[start_idx:end_idx], res=res, is_flow=True)\n points_canon.append(points_canon_batch)\n points_canon = torch.cat(points_canon, dim=0)\n else:\n points_canon = self.transfer_forward(flow[src_idx], src_kps,\n res=res, is_flow=True)\n # points_canon = torch.clamp(points_canon, min=-1, max=1)\n\n # Step 2: Map the points in the canonical space to trg\n # This is a memory intensive step, so do a single image at a time\n # if the number of points are large\n if src_kps.size(1) > 256 or src_kps.size(0) > max_batch_size:\n N = len(src_kps)\n points_transfered = []\n for start_idx in range(0, N, max_batch_size):\n end_idx = min(start_idx+max_batch_size, N)\n points_transfered_single = self.transfer_reverse(\n flow[[trg_idx[start_idx:end_idx]]],\n points_canon[start_idx:end_idx], res=res,\n mask=mask[trg_idx[start_idx:end_idx]], is_flow=True)\n points_transfered.append(points_transfered_single)\n points_transfered = torch.cat(points_transfered, dim=0)\n else:\n points_transfered = self.transfer_reverse(\n flow[trg_idx], points_canon, res=res, mask=mask[trg_idx],\n is_flow=True)\n\n if return_canon:\n points_canon = self.unnormalize(points_canon, res, res)\n return points_transfered, points_canon\n else:\n return points_transfered\n\n def transfer_forward(self, img, points, res=None, is_flow=False):\n\n # TODO: currently points generated by load_fg_points are not\n # scaled properly. Take a look\n # TODO: Also double check normalize and unnormalize logic\n # points are N x P x 2 (in xy format)\n # assume that the flow is also xy format\n points = self.normalize(points, res, res)\n if is_flow:\n flow = img\n else:\n flow, _ = self(img)\n flow_grid = flow.permute(0, 3, 1, 2)\n points_transfered = F.grid_sample(\n flow_grid, points.unsqueeze(2).float(),\n padding_mode='border', align_corners=True)\n points_transfered = points_transfered.squeeze(3).permute(0, 2, 1)\n\n return points_transfered\n\n def transfer_reverse(self, img, points, res=None, mask=None, is_flow=False):\n N = points.size(0)\n num_points = points.size(1)\n # points are N x P x 2 (in xy format)\n points = points\n if is_flow:\n flow = img\n else:\n flow, _ = self(img)\n if flow.size(1) != res:\n scale_factor = res/flow.size(1)\n flow = F.interpolate(\n flow.permute(0, 3, 1, 2),\n scale_factor=scale_factor,\n mode='bilinear').permute(0, 2, 3, 1)\n # From (N, H, W, 2) to (N, H, W, 1, 1, 2)\n flow_reshaped = flow.unsqueeze(-2).unsqueeze(-2)\n\n # From (N, num_points, 2) to (N, 1, 1, num_points, 2, 1)\n points = points.unsqueeze(1).unsqueeze(1).unsqueeze(-1)\n\n # (N, H, W, num_points)\n similarities = (flow_reshaped @ points)[..., 0, 0]\n distances = points.pow(2).squeeze(-1).sum(dim=-1) + \\\n flow_reshaped.pow(2).sum(dim=-1).squeeze(-1) - 2 * similarities\n\n if mask is not None:\n distances[mask.squeeze(1)<0.1] = float('inf')\n\n nearest_neighbors = distances.reshape(\n N, flow_reshaped.size(1) * flow_reshaped.size(2),\n num_points).argmin(dim=1)\n points_transfered = unravel_index(\n nearest_neighbors, (flow_reshaped.size(1), flow_reshaped.size(2)))\n return points_transfered\n\n @staticmethod\n def normalize(points, res, out_res):\n return points.div(out_res - 1).add(-0.5).mul(2).mul((res - 1) / res)\n\n @staticmethod\n def unnormalize(points, res, out_res):\n return points.div((res - 1) / res).div(2).add(0.5).mul(out_res - 1)" }, { "identifier": "total_variation_loss", "path": "losses/reg_losses.py", "snippet": "def total_variation_loss(delta_flow, reduce_batch=True):\n # flow should be size (N, H, W, 2)\n reduce_dims = (0, 1, 2, 3) if reduce_batch else (1, 2, 3)\n distance_fn = lambda a: torch.where(a <= 1.0, 0.5 * a.pow(2), a - 0.5).mean(dim=reduce_dims)\n # assert delta_flow.size(-1) == 2\n diff_y = distance_fn((delta_flow[:, :-1, :, :] - delta_flow[:, 1:, :, :]).abs())\n diff_x = distance_fn((delta_flow[:, :, :-1, :] - delta_flow[:, :, 1:, :]).abs())\n loss = diff_x + diff_y\n return loss" }, { "identifier": "get_perceptual_loss", "path": "thirdparty/lpips/lpips.py", "snippet": "def get_perceptual_loss(loss_fn, device):\n if loss_fn == 'vgg_ssl':\n download_model('simclr_vgg_phase150') # Download the weights\n loss_fn_vgg = LPIPS(net='vgg', lpips=False, pnet_rand=True, pretrained_weights='pretrained/simclr_vgg_phase150.pt').to(device)\n loss_fn = lambda x,y: loss_fn_vgg(x, y) / 18.0\n elif loss_fn == 'lpips':\n download_lpips() # Download LPIPS weights\n loss_fn = LPIPS(net='vgg').to(device)\n else:\n raise NotImplementedError\n return loss_fn" }, { "identifier": "LossCorrsSparse", "path": "losses/matching_losses.py", "snippet": "class LossCorrsSparse(nn.Module):\n def __init__(self, extractor=None, flow_size=256, T=1.0):\n super().__init__()\n self.extractor = extractor\n self.flow_size = flow_size\n self.T = T\n self.dist_fn = nn.PairwiseDistance(p=2)\n self.loss_fn = nn.CrossEntropyLoss(reduction='none')\n\n def forward(self, src_flow, trg_flow, src_kp, trg_kp, kp_vis, kp_wt):\n N = src_flow.size(0)\n res = src_flow.size(1)\n top_k = kp_vis.shape[1]\n # bb1_canon - N x 2 x top_k x 1\n # bb2_canon - N x 2 x 1 x top_k\n # Sample flow values using the pseudo GT from the flow_grid\n src_kp_canon = F.grid_sample(\n src_flow.permute(0, 3, 1, 2),\n map_minmax(src_kp.unsqueeze(2), 0, res-1, -1, 1), mode='bilinear',\n padding_mode='zeros', align_corners=True).permute(0, 2, 3, 1)\n trg_kp_canon = F.grid_sample(\n trg_flow.permute(0, 3, 1, 2),\n map_minmax(trg_kp.unsqueeze(1), 0, res-1, -1, 1), mode='bilinear',\n padding_mode='zeros', align_corners=True).permute(0, 2, 3, 1)\n\n # dists - N x top_k x top_k\n dists1 = self.dist_fn(src_kp_canon, trg_kp_canon.detach()) * (-1/self.T)\n dists2 = self.dist_fn(src_kp_canon.detach(), trg_kp_canon) * (-1/self.T)\n labels = torch.arange(top_k, dtype=torch.long, device='cuda')\n labels = labels.unsqueeze(0).repeat(N, 1)\n labels[~kp_vis] = -100\n \n loss = self.loss_fn(dists1, labels) + self.loss_fn(dists2, labels)\n loss *= kp_wt\n return loss.sum() / kp_vis.sum()\n\n def forward_eq(self, src_flow, trg_flow, src_kp, trg_kp, kp_vis):\n N = src_flow.size(0)\n res = src_flow.size(1)\n top_k = kp_vis.shape[1]\n # bb1_canon - N x 2 x top_k x 1\n # bb2_canon - N x 2 x 1 x top_k\n # Sample flow values using the pseudo GT from the flow_grid\n src_kp_canon = F.grid_sample(\n src_flow.permute(0, 3, 1, 2),\n map_minmax(src_kp.unsqueeze(2), 0, res-1, -1, 1), mode='bilinear',\n padding_mode='zeros', align_corners=True).permute(0, 2, 3, 1)\n trg_kp_canon = F.grid_sample(\n trg_flow.permute(0, 3, 1, 2),\n map_minmax(trg_kp.unsqueeze(1), 0, res-1, -1, 1), mode='bilinear',\n padding_mode='zeros', align_corners=True).permute(0, 2, 3, 1)\n\n # dists - N x top_k x top_k\n dists1 = self.dist_fn(src_kp_canon, trg_kp_canon.detach()) * (-1/self.T)\n dists2 = self.dist_fn(src_kp_canon.detach(), trg_kp_canon) * (-1/self.T)\n labels = torch.arange(top_k, dtype=torch.long, device='cuda')\n labels = labels.unsqueeze(0).repeat(N, 1)\n labels[~kp_vis] = -100\n return self.loss_fn(dists1, labels).mean() + self.loss_fn(dists2, labels).mean()" }, { "identifier": "DecayingCosineAnnealingWarmRestarts", "path": "thirdparty/gangealing/annealing.py", "snippet": "class DecayingCosineAnnealingWarmRestarts(_LRScheduler):\n r\"\"\"Set the learning rate of each parameter group using a cosine annealing\n schedule, where :math:`\\eta_{max}` is set to the initial lr,\n :math:`T_{cur}` is the number of epochs since the last restart and\n :math:`T_{i}` is the number of epochs between two warm restarts in SGDR:\n .. math::\n \\eta_t = \\eta_{min} + \\frac{1}{2}(\\eta_{max} - \\eta_{min})\\left(1 +\n \\cos\\left(\\frac{T_{cur}}{T_{i}}\\pi\\right)\\right)\n When :math:`T_{cur}=T_{i}`, set :math:`\\eta_t = \\eta_{min}`.\n When :math:`T_{cur}=0` after restart, set :math:`\\eta_t=\\eta_{max}`.\n It has been proposed in\n `SGDR: Stochastic Gradient Descent with Warm Restarts`_.\n Args:\n optimizer (Optimizer): Wrapped optimizer.\n T_0 (int): Number of iterations for the first restart.\n T_mult (int, optional): A factor increases :math:`T_{i}` after a\n restart. Default: 1.\n eta_min (float, optional): Minimum learning rate. Default: 0.\n last_epoch (int, optional): The index of last epoch. Default: -1.\n .. _SGDR\\: Stochastic Gradient Descent with Warm Restarts:\n https://arxiv.org/abs/1608.03983\n \"\"\"\n\n def __init__(self, optimizer, T_0, decay=0.9, T_mult=1, eta_min=0,\n last_epoch=-1):\n if T_0 <= 0 or not isinstance(T_0, int):\n raise ValueError(f\"Expected positive integer T_0, but got {T_0}\")\n if T_mult < 1 or not isinstance(T_mult, int):\n raise ValueError(f\"Expected integer T_mult >= 1, but got {T_mult}\")\n self.T_0 = T_0\n self.T_i = T_0\n self.T_mult = T_mult\n self.eta_min = eta_min\n self.decay = decay\n self.cur_decay = 1.0\n\n super(DecayingCosineAnnealingWarmRestarts, self).__init__(optimizer,\n last_epoch)\n\n self.T_cur = self.last_epoch\n\n def get_lr(self):\n if not self._get_lr_called_within_step:\n warnings.warn(\"To get the last learning rate computed by the \"\n \"scheduler, use `get_last_lr()`.\", UserWarning)\n\n return [self.cur_decay * (self.eta_min + (base_lr - self.eta_min) *\n (1 + math.cos(math.pi * self.T_cur / self.T_i)) / 2)\n for base_lr in self.base_lrs]\n\n def step(self, epoch=None):\n \"\"\"Step could be called after every batch update\"\"\"\n\n if epoch is None and self.last_epoch < 0:\n epoch = 0\n\n if epoch is None:\n epoch = self.last_epoch + 1\n self.T_cur = self.T_cur + 1\n if self.T_cur >= self.T_i:\n self.T_cur = self.T_cur - self.T_i\n self.T_i = self.T_i * self.T_mult\n else:\n if epoch < 0:\n raise ValueError(f\"Expected non-negative epoch, got {epoch}\")\n if epoch >= self.T_0:\n if self.T_mult == 1:\n self.T_cur = epoch % self.T_0\n n = int(epoch // self.T_0)\n else:\n n = int(math.log((epoch / self.T_0 * (self.T_mult - 1)\n + 1), self.T_mult))\n self.T_cur = epoch - self.T_0 * (self.T_mult ** n - 1) / \\\n (self.T_mult - 1)\n self.T_i = self.T_0 * self.T_mult ** (n)\n else:\n self.T_i = self.T_0\n self.T_cur = epoch\n n = 0\n self.cur_decay = self.decay ** n\n self.last_epoch = math.floor(epoch)\n\n class _enable_get_lr_call:\n\n def __init__(self, o):\n self.o = o\n\n def __enter__(self):\n self.o._get_lr_called_within_step = True\n return self\n\n def __exit__(self, type, value, traceback):\n self.o._get_lr_called_within_step = False\n return self\n\n with _enable_get_lr_call(self):\n for param_group, lr in zip(self.optimizer.param_groups,\n self.get_lr()):\n param_group['lr'] = lr\n\n self._last_lr = [group['lr'] for group in self.optimizer.param_groups]" }, { "identifier": "lr_cycle_iters", "path": "thirdparty/gangealing/annealing.py", "snippet": "def lr_cycle_iters(anneal_psi, period, iter, tm):\n zero_lr_iters = [anneal_psi - 1]\n num_cycles = int(math.log((iter - anneal_psi) / period, tm))\n for n in range(num_cycles):\n step = zero_lr_iters[-1] + period * tm ** n\n zero_lr_iters.append(int(step))\n print(f'Learning Rate Cycles: {zero_lr_iters}')\n return zero_lr_iters" } ]
import argparse import torch import numpy as np import json import os import torch.nn.functional as F import wandb from torch import nn, optim from tqdm import tqdm from pathlib import Path from commons.logger import Logger, log_visuals from commons.distributed import get_rank, setup_distributed, reduce_loss_dict,\ get_world_size, primary from commons.utils import sample_tuples from datasets.cub import CUBDataset from datasets.in_memory import InMemoryDataset from datasets.spair import SpairDataset from datasets.utils import Augmentor from models.utils import accumulate, requires_grad from models.canonical import Canonical, CanonicalMLP from models.asic import Asic from losses.reg_losses import total_variation_loss from thirdparty.lpips.lpips import get_perceptual_loss from losses.matching_losses import LossCorrsSparse from thirdparty.gangealing.annealing import DecayingCosineAnnealingWarmRestarts,\ lr_cycle_iters
16,227
help='Loss weighting for equivariance') parser.add_argument("--sparse_topk", type=int, default=None, help='number of sparse correspondences for loss') parser.add_argument("--sparse_temp", type=float, default=1, help='temperature for sparse loss') parser.add_argument("--mask_weight", default=0.1, type=float, help="""Loss weighting of the mask""") parser.add_argument("--parts_weight", default=10.0, type=float, help="""Loss weighting of the Parts Mask""") parser.add_argument("--use_nbb_parts", action='store_true') # Augmentation hyperparameters parser.add_argument("--jitter", default=[0.4, 0.4, 0.2, 0.1], type=float, nargs='+', help='augmentation mode') parser.add_argument("--jitter_prob", default=0.8, type=float) parser.add_argument("--gray_prob", default=0.2, type=float) parser.add_argument("--solar_prob", default=0.2, type=float) parser.add_argument("--tps_scale", default=0.4, type=float) # Canonical space parser.add_argument("--unwarp_size", type=int, default=128, help="resolution for unwarping") # Learned Grid hyperparameters parser.add_argument("--canon_size", type=int, default=256, help="resolution of canonical space") parser.add_argument("--clamp", action='store_true', help="clamp values of canonical space (-1, 1)") # MLP Hyperparams parser.add_argument("--use_mlp", action='store_true') parser.add_argument("--mlp_hidden_dim", type=int, default=256, help="number of hidden units per layer") parser.add_argument("--mlp_num_layers", type=int, default=8, help="number of layers") parser.add_argument("--mlp_skip_layers", type=int, nargs='+', default=[4, 7], help="skip layers") # Model hyperparameters: parser.add_argument("--canon_lr", type=float, default=0.003, help="base learning rate of canonical space") parser.add_argument("--canon_ema", action='store_true', help='Enable ema for canonical space') parser.add_argument("--stn_ema", action='store_true', help='Enable ema for canonical space') parser.add_argument("--stn_lr", type=float, default=0.003, help="base learning rate of SpatialTransformer") parser.add_argument("--flow_ssl", action='store_true', help="""If specified, apply STN on SSL features)""") parser.add_argument("--channel_multiplier", default=0.5, type=float, help='channel multiplier for smaller models') parser.add_argument("--bilinear", action='store_true', help='Apply bilinear upsample/downsample') parser.add_argument("--padding_mode", default='border', choices=['border', 'zeros', 'reflection'], type=str, help="""Padding algorithm for when the STN samples beyond image boundaries""") parser.add_argument("--use_tanh", action='store_true', help='Use tanh activation at the flow output') parser.add_argument("--disable_tps", action='store_true', help='disable tps transformations') # Backbone parameters parser.add_argument("--bb", default='dino_vits8', choices=['dino_vits8', 'dino_vits16', 'dino_vitb8', 'dino_vitb16', 'vit_small_patch8_224', 'vit_small_patch16_224', 'vit_base_patch16_224'], help='backbone models') parser.add_argument('--bb_stride', default=2, type=int, help="stride.") # Visualization hyperparameters: parser.add_argument("--vis_every", type=int, default=500, help="""frequency with which visualizations are generated during training""") parser.add_argument("--vis_denseres", type=int, default=32, help='number of sparse correspondences to visualize') parser.add_argument("--ckpt_every", type=int, default=10000, help='frequency of checkpointing during training') parser.add_argument("--log_every", default=25, type=int, help='How frequently to log data to TensorBoard') parser.add_argument("--n_sample", type=int, default=4, help="""number of images (real and fake) to generate visuals for""") parser.add_argument("--disable_wandb", action='store_true', help='Disable wandb for debugging') # Learning Rate scheduler hyperparameters: parser.add_argument("--period", default=10000, type=float, help="""Period for cosine learning rate scheduler (measured in gradient steps)""") parser.add_argument("--decay", default=0.9, type=float, help="""Decay factor for the cosine learning rate scheduler""") parser.add_argument("--tm", default=2, type=int, help="""Period multiplier for the cosine learning rate scheduler""") return parser def train(args, train_dset, canon, stn, c_ema, t_ema, canon_optim, canon_sched, t_optim, t_sched, loss_fn, nbb_loss_fn, device, writer): # Record modules to make saving checkpoints easier: if args.distributed: t_module = stn.module c_module = canon.module else: t_module = stn c_module = canon # Initialize Spatial Transformation Generator (Thin Plate Spline) aug = Augmentor(jitter=args.jitter, jitter_prob=args.jitter_prob, gray_prob=args.gray_prob, solar_prob=args.solar_prob, tps_scale=args.tps_scale).to(device) # A model checkpoint will be saved whenever the learning rate is zero:
def save_state_dict(ckpt_name, c_module, t_module, c_ema, t_ema, canon_optim, canon_sched, t_optim, t_sched, args, step, add_step_to_name=False): ckpt_dict = { "canon": c_module.state_dict(), "t": t_module.state_dict(), "c_ema": c_ema.state_dict(), "t_ema": t_ema.state_dict(), "t_optim": t_optim.state_dict(), "t_sched": t_sched.state_dict(), "canon_optim": canon_optim.state_dict() if canon_optim is not None else None, "canon_sched": canon_sched.state_dict() if canon_sched is not None else None, "args": args, "iter": step } torch.save(ckpt_dict, f'{results_path}/{ckpt_name}.pt') if add_step_to_name: torch.save(ckpt_dict, f'{results_path}/{ckpt_name}_{step:07d}.pt') def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) def base_training_argparse(): parser = argparse.ArgumentParser(description="Training") # Main training arguments: parser.add_argument("--exp-name", type=str, required=True, help="Name for experiment run (used for logging)") parser.add_argument("--results", type=str, default='logs', help='path to the results directory') parser.add_argument("--seed", default=0, type=int, help='Random seed for this experiment') parser.add_argument("--dset", type=str, default='cub', choices=["cub", "spair"]) parser.add_argument("--img_dir", type=str, required=True, help="Path to real data") parser.add_argument("--flow_dir", type=str, default='processed_data', help="Path to preprocessed flows") parser.add_argument("--mask_threshold", type=int, default=1, help="Threshold for masking") parser.add_argument("--mask_bbox_pad", type=int, default=4, help="Crop with some padding") parser.add_argument("--img_size", default=256, type=int, help='resolution of real images') parser.add_argument("--iter", type=int, default=20000, help="total training iterations") parser.add_argument("--batch", type=int, default=20, help="batch size per-GPU") parser.add_argument("--num_workers", type=int, default=2, help="num workers for dataloader") # Dataset hyperparameters: parser.add_argument("--cub_idx", type=int, default=1, help="cub category") parser.add_argument("--split", default='test', choices=['test', 'val'], help='splits for training and validation') parser.add_argument("--use_coseg_masks", action='store_true') parser.add_argument("--num_parts", default=4, type=int) parser.add_argument("--spair_cat", default='cat', help="cub category") # Loss hyperparameters: parser.add_argument("--loss_fn", type=str, default='vgg_ssl', choices=['lpips', 'vgg_ssl'], help="The perceptual loss to use.") parser.add_argument("--rec_weight", type=float, default=1., help='weight for reconstruction loss') parser.add_argument("--nbb_weight", type=float, default=30., help='weight for nbb loss') parser.add_argument("--flow_tv_weight", default=15000.0, type=float, help="""Loss weighting of the Total Variation smoothness regularizer on the residual flow""") parser.add_argument("--equi_weight", default=1.0, type=float, help='Loss weighting for equivariance') parser.add_argument("--sparse_topk", type=int, default=None, help='number of sparse correspondences for loss') parser.add_argument("--sparse_temp", type=float, default=1, help='temperature for sparse loss') parser.add_argument("--mask_weight", default=0.1, type=float, help="""Loss weighting of the mask""") parser.add_argument("--parts_weight", default=10.0, type=float, help="""Loss weighting of the Parts Mask""") parser.add_argument("--use_nbb_parts", action='store_true') # Augmentation hyperparameters parser.add_argument("--jitter", default=[0.4, 0.4, 0.2, 0.1], type=float, nargs='+', help='augmentation mode') parser.add_argument("--jitter_prob", default=0.8, type=float) parser.add_argument("--gray_prob", default=0.2, type=float) parser.add_argument("--solar_prob", default=0.2, type=float) parser.add_argument("--tps_scale", default=0.4, type=float) # Canonical space parser.add_argument("--unwarp_size", type=int, default=128, help="resolution for unwarping") # Learned Grid hyperparameters parser.add_argument("--canon_size", type=int, default=256, help="resolution of canonical space") parser.add_argument("--clamp", action='store_true', help="clamp values of canonical space (-1, 1)") # MLP Hyperparams parser.add_argument("--use_mlp", action='store_true') parser.add_argument("--mlp_hidden_dim", type=int, default=256, help="number of hidden units per layer") parser.add_argument("--mlp_num_layers", type=int, default=8, help="number of layers") parser.add_argument("--mlp_skip_layers", type=int, nargs='+', default=[4, 7], help="skip layers") # Model hyperparameters: parser.add_argument("--canon_lr", type=float, default=0.003, help="base learning rate of canonical space") parser.add_argument("--canon_ema", action='store_true', help='Enable ema for canonical space') parser.add_argument("--stn_ema", action='store_true', help='Enable ema for canonical space') parser.add_argument("--stn_lr", type=float, default=0.003, help="base learning rate of SpatialTransformer") parser.add_argument("--flow_ssl", action='store_true', help="""If specified, apply STN on SSL features)""") parser.add_argument("--channel_multiplier", default=0.5, type=float, help='channel multiplier for smaller models') parser.add_argument("--bilinear", action='store_true', help='Apply bilinear upsample/downsample') parser.add_argument("--padding_mode", default='border', choices=['border', 'zeros', 'reflection'], type=str, help="""Padding algorithm for when the STN samples beyond image boundaries""") parser.add_argument("--use_tanh", action='store_true', help='Use tanh activation at the flow output') parser.add_argument("--disable_tps", action='store_true', help='disable tps transformations') # Backbone parameters parser.add_argument("--bb", default='dino_vits8', choices=['dino_vits8', 'dino_vits16', 'dino_vitb8', 'dino_vitb16', 'vit_small_patch8_224', 'vit_small_patch16_224', 'vit_base_patch16_224'], help='backbone models') parser.add_argument('--bb_stride', default=2, type=int, help="stride.") # Visualization hyperparameters: parser.add_argument("--vis_every", type=int, default=500, help="""frequency with which visualizations are generated during training""") parser.add_argument("--vis_denseres", type=int, default=32, help='number of sparse correspondences to visualize') parser.add_argument("--ckpt_every", type=int, default=10000, help='frequency of checkpointing during training') parser.add_argument("--log_every", default=25, type=int, help='How frequently to log data to TensorBoard') parser.add_argument("--n_sample", type=int, default=4, help="""number of images (real and fake) to generate visuals for""") parser.add_argument("--disable_wandb", action='store_true', help='Disable wandb for debugging') # Learning Rate scheduler hyperparameters: parser.add_argument("--period", default=10000, type=float, help="""Period for cosine learning rate scheduler (measured in gradient steps)""") parser.add_argument("--decay", default=0.9, type=float, help="""Decay factor for the cosine learning rate scheduler""") parser.add_argument("--tm", default=2, type=int, help="""Period multiplier for the cosine learning rate scheduler""") return parser def train(args, train_dset, canon, stn, c_ema, t_ema, canon_optim, canon_sched, t_optim, t_sched, loss_fn, nbb_loss_fn, device, writer): # Record modules to make saving checkpoints easier: if args.distributed: t_module = stn.module c_module = canon.module else: t_module = stn c_module = canon # Initialize Spatial Transformation Generator (Thin Plate Spline) aug = Augmentor(jitter=args.jitter, jitter_prob=args.jitter_prob, gray_prob=args.gray_prob, solar_prob=args.solar_prob, tps_scale=args.tps_scale).to(device) # A model checkpoint will be saved whenever the learning rate is zero:
zero_lr_iters = lr_cycle_iters(0, args.period, args.iter, args.tm)
21
2023-11-14 16:43:16+00:00
24k
atlantic-quantum/Shipyard
tests/passes/test_include_files.py
[ { "identifier": "Compiler", "path": "shipyard/compiler.py", "snippet": "class Compiler:\n version = \"0.1.1\"\n \"\"\"\n Compiler to compile openQASM programs to target programs for different AWG Cores.\n Currently supports compilation to ZI SEQC cores.\n\n Args:\n program_path (Path):\n Path object pointing to a qasm program file.\n setup (Setup | Path):\n Path object pointing to a experiment setup json file.\n frames_from_setup (bool, optional):\n If True, frame definitions and port declarations are generated from setup.\n If False, frame definitions and port declarations should be written\n explicitly in the qasm program.\n Defaults to False to preserve original behavior.\n \"\"\"\n\n def __init__(\n self,\n program_path: Path,\n setup: Setup | Path,\n frames_from_setup: bool = False,\n ) -> None:\n self.program_path = program_path\n self.program = CopyTransformer().visit_Program(self.load_program(program_path))\n setup = setup if isinstance(setup, Setup) else Setup.from_file(setup)\n if frames_from_setup:\n self._frames_from_setup(setup)\n self.setup = setup.to_internal()\n self.split_programs: dict[tuple[str, int, str], ast.Program] = {}\n self.split_compiled: dict[tuple[str, int, str], str] = {}\n self.core_settings: dict[tuple[str, int, str], list[tuple[str], Any]] = {}\n self.wfm_mapping: dict[tuple[str, int, str], dict[int, str]] = {}\n\n @staticmethod\n @lru_cache()\n def load_program(path: Path) -> ast.Program:\n \"\"\"\n Loads a qasm program as an AST from a file\n\n Args:\n path (Path): path to the qasm program file\n\n Returns:\n ast.Program: qasm program as an AST\n \"\"\"\n with open(path, encoding=\"utf_8\") as qasm_file:\n qasm_code = qasm_file.read()\n return parse(qasm_code)\n\n def compile(\n self,\n inputs: dict = None,\n printer_kwargs: dict = None,\n waveforms: dict[str, ndarray] | None = None,\n command_tables: dict[tuple[str, int, str], CommandTable] | None = None,\n ):\n \"\"\"\n Compile a single openQASM program into multiple programs for each\n AWG core in the setup\n\n Args:\n inputs (dict, optional):\n Dictionary of input values for the program. Defaults to None.\n Used to resolve input declarations in the program.\n printer_kwargs (dict, optional):\n Dictionary of keyword arguments to pass to the printer.\n See the printer documentation for more details.\n \"\"\"\n ResolveIODeclaration(inputs).visit(self.program)\n IncludeAnalyzer(self.program_path).visit(self.program)\n IncludeWaveforms(waveforms).visit(self.program)\n SemanticAnalyzer().visit(self.program)\n DurationTransformer().visit(self.program)\n TimingConstraints(self.setup, external_zi_function_dict()).visit(self.program)\n max_delay_obj = DetermineMaxDelay(\n self.program, self.setup, external_zi_function_dict()\n )\n extractor_obj = ShotsExtractor()\n extractor_obj.visit(self.program)\n signature = extractor_obj.create_signature()\n printer_kwargs = printer_kwargs or {}\n for instr, core_index, core_type in self.setup.cores():\n if command_tables:\n command_table = command_tables.get((instr, core_index, core_type))\n else:\n command_table = None\n ports = ports_for_core(self.setup, instr, core_index)\n split_program = CoreSplitter(ports).visit_Program(self.program)\n LOGGER.debug(\n \"Split Program before removing unused, core: (%s, %i, %s):\",\n instr,\n core_index,\n core_type,\n )\n LOGGER.debug(\"\\n%s\", LazyRepr(qasm_dumps, [split_program]))\n for repetition in [\"1st pass\", \"2nd pass\"]:\n RemoveUnused(split_program)\n LOGGER.debug(\n \"Split Program after removing unused (%s), core: (%s, %i, %s):\",\n repetition,\n instr,\n core_index,\n core_type,\n )\n LOGGER.debug(\"\\n%s\", LazyRepr(qasm_dumps, [split_program]))\n self.split_programs[(instr, core_index, core_type)] = split_program\n # todo dynamically choose printer based on instrument type\n InsertCTWaveforms(command_table).visit(split_program)\n printer = SEQCPrinter(\n io.StringIO(),\n self.setup,\n signature,\n max_delay_obj.result(),\n **printer_kwargs\n )\n printer.visit(split_program)\n compiled = printer.stream.getvalue()\n LOGGER.debug(\n \"Compiled Program, core: core: (%s, %i, %s):\",\n instr,\n core_index,\n core_type,\n )\n LOGGER.debug(\"\\n%s\", compiled)\n self.split_compiled[(instr, core_index, core_type)] = compiled\n self.core_settings[(instr, core_index, core_type)] = printer.settings()\n self.wfm_mapping[(instr, core_index, core_type)] = printer.wfm_mapping()\n\n @lru_cache()\n @staticmethod\n def cached_compile(\n program_path: Path,\n setup: Setup | Path,\n inputs: dict | None = None,\n printer_kwargs: dict | None = None,\n frames_from_setup: bool = False,\n ) -> \"Compiler\":\n \"\"\"Method to compile a program and cache the result.\n\n Args:\n program_path (Path):\n path to the qasm program file\n setup (Setup | Path):\n path to the laboratory setup file\n inputs (dict | None, optional):\n dictionary of input values for the program,\n used to resolve input declarations. Defaults to None.\n printer_kwargs (dict | None, optional):\n Dictionary of kwarg arguments to pass to the printer,\n see printer documentation for details. Defaults to None.\n frames_from_setup (bool, optional):\n If True, frame definitions and port declarations are generated from\n setup.\n If False, frame definitions and port declarations should be written\n explicitly in the qasm program.\n Defaults to False to preserve original behavior.\n\n Returns:\n Compiler: cached compiler object\n \"\"\"\n compiler = Compiler(program_path, setup, frames_from_setup)\n compiler.compile(inputs, printer_kwargs)\n return compiler\n\n def _frames_from_setup(self, setup: Setup) -> None:\n \"\"\"\n inserts a calibrationStatement after the defcalgrammar statement, the\n calibrationStatement created from the setup file\n\n Args:\n setup_path (Path): path to the setup file\n\n Raises:\n ValueError: if no calibration grammar is defined in the program\n ValueError: if the calibration grammar is not openpulse\n \"\"\"\n # make sure defcalgrammar has been define before inserting setup\n for i, statement in enumerate(self.program.statements):\n if isinstance(statement, ast.CalibrationGrammarDeclaration):\n break\n else:\n raise ValueError(\n \"No calibration grammar defined in program, cannot insert setup.\"\n )\n # make sure defcalgrammar is openpulse\n if statement.name != \"openpulse\":\n raise ValueError(\"calibration grammar be 'openpulse', \")\n # insert cal from setup after defcalgrammar statement\n self.program.statements.insert(i + 1, setup.get_qasm())" }, { "identifier": "SemanticError", "path": "shipyard/compiler_error.py", "snippet": "class SemanticError(Error):\n \"\"\"Error class for semantic errors, raised by SemanticAnalyser\"\"\"" }, { "identifier": "TransformError", "path": "shipyard/compiler_error.py", "snippet": "class TransformError(Error):\n \"\"\"Error class for Transformation Errors, raised by QASMTransformer subclasses\"\"\"" }, { "identifier": "SEQCPrinter", "path": "shipyard/printers/zi/seqcprinter.py", "snippet": "class SEQCPrinter(Printer):\n \"\"\"Internal AST-visitor for writing AST nodes out to a stream as valid ZI SEQC code.\n\n This class can be used directly to write multiple nodes to the same stream,\n potentially with some manual control fo the state between them.\n\n If subclassing, generally only the specialised ``visit_*`` methods need to be\n overridden. These are derived from the base class, and use the name of the\n relevant :mod:`AST node <.ast>` verbatim after ``visit_``.\n\n Based on the openQASM3 Printer\"\"\"\n\n def __init__(\n self,\n stream: io.TextIOBase,\n setup: SetupInternal = None,\n sig: ShotsSignature = ShotsSignature(),\n measurement_delay: float = None,\n constant_for_loops: bool = True,\n average_shots: bool = True,\n ):\n # todo docstring\n self.call_stack = CallStack()\n self.setup = setup\n self.sig = sig\n self.meas_delay = measurement_delay\n self.defcal_names = []\n self.multi_measure_bit = None\n super().__init__(\n stream, indent=\" \", chain_else_if=False, old_measurement=False\n )\n self.interpreter = Interpreter(\n setup=setup, external_funcs=external_function_dict()\n )\n self.interpreter.call_stack = self.call_stack\n self.core = None\n self.constant_for_loops = constant_for_loops\n self.interpret = True\n self.average_shots = average_shots\n self.placeholder_index = 0\n self.wfm_indices = {}\n\n def visit(self, node: ast.QASMNode, context: Optional[PrinterState] = None) -> None:\n try:\n return super().visit(node, context)\n except NotImplementedError as exception:\n LOGGER.debug(LazyRepr(self.stream.getvalue, []))\n raise exception\n\n def visit_Program(self, node: ast.Program, context: PrinterState) -> None:\n # todo compiler verions etc.\n # if node.version:\n # self._write_statement(f\"OPENQASM {node.version}\", context)\n activation_record = ActivationRecord(\n name=\"main\", ar_type=ARType.PROGRAM, nesting_level=1\n )\n for extern in self.interpreter.external_funcs:\n activation_record[extern] = \"external\"\n with self.ar_context_manager(activation_record):\n for statement in node.statements:\n self.visit(statement, context)\n\n @_maybe_annotated\n def visit_Include(self, node: ast.Include, context: PrinterState) -> None:\n raise self.compile_out(node)\n\n def visit_ExpressionStatement(\n self, node: ast.ExpressionStatement, context: PrinterState\n ) -> None:\n self.visit(node.expression, context)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_QubitDeclaration(\n self, node: ast.QubitDeclaration, context: PrinterState\n ) -> None:\n \"\"\"the concept of Qubit does not exist in SEQC code, pass for now but maybe\n replace with some combination of port / frame? or as with include statements,\n should this be resolved before writing SEQC code\"\"\"\n pass\n\n @_maybe_annotated\n def visit_QuantumGateDefinition(\n self, node: ast.QuantumGateDefinition, context: PrinterState\n ) -> None:\n raise self.compile_out(node)\n\n @_maybe_annotated\n def visit_ExternDeclaration(\n self, node: ast.ExternDeclaration, context: PrinterState\n ) -> None:\n # todo: HERE: make sure declared externals are allowed\n pass\n\n def visit_ImaginaryLiteral(\n self, node: ast.ImaginaryLiteral, context: PrinterState\n ) -> None:\n if node.value == 1.0:\n return self.interpreter.visit_ImaginaryLiteral(node)\n raise self.compile_out(node)\n # Imaginary numbers are not supported by SEQC\n\n @_visit_interpreter\n def visit_DurationLiteral(\n self, node: ast.DurationLiteral, context: PrinterState\n ) -> None:\n # todo time w/ units translate to actual time in SI or Samples?\n self.stream.write(f\"{int(node.value)}\")\n\n @_visit_interpreter\n def visit_ArrayLiteral(self, node: ast.ArrayLiteral, context: PrinterState) -> None:\n # todo compile array literals into multiple literals\n # todo what about waveforms defined from a vector?\n self._visit_sequence(\n node.values, context, start=\"vect(\", end=\")\", separator=\", \"\n )\n\n def visit_DiscreteSet(self, node: ast.DiscreteSet, context: PrinterState) -> None:\n raise self.compile_out(node)\n # seems to be intended for use in for loops e.g. for i in {1, 3, 56}: ...\n # it should be possible to compile such a statement into a traditional for loop\n # or multiple executions\n\n def visit_RangeDefinition(\n self, node: ast.RangeDefinition, context: PrinterState\n ) -> None:\n raise self.compile_out(node)\n\n @_visit_interpreter\n def visit_IndexExpression(\n self, node: ast.IndexExpression, context: PrinterState\n ) -> None:\n self.stream.write(f\"{node.collection.name}[{int(node.index[0].value)}]\")\n\n @_visit_interpreter\n def visit_IndexedIdentifier(\n self, node: ast.IndexedIdentifier, context: PrinterState\n ) -> None:\n \"\"\"\n IndexedIdentifier node visitor:\n prints openqasm indexed identifier\n\n array[float, 10] a;\n\n a[3] = 1.1;\n ^^^^\n indexed identifer\n\n openqasm supports using discreate sets as indecies\n seqc does not support this and an error gets raised upon visiting\n DiscreateSet nodes\n\n Args:\n node (ast.IndexedIdentifier): openQASM IndexedIdentifier node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n self.visit(node.name, context)\n for index in node.indices:\n self.stream.write(\"[\")\n match index:\n # todo more specific for non DiscreateSet (limit to 1D)\n # todo raise errors directly here\n case ast.DiscreteSet():\n self.visit(index, context)\n case _:\n self._visit_sequence(index, context, separator=\", \")\n self.stream.write(\"]\")\n\n @_visit_interpreter\n def visit_Concatenation(\n self, node: ast.Concatenation, context: PrinterState\n ) -> None:\n \"\"\"\n Concatenation node visitor:\n Prints openqasm concatenation statement as a SEQC join statement\n\n example:\n qasm: 'a ++ b ++ c;'\n ->\n seqc: 'join(a, b, c);'\n\n Args:\n node (ast.Concatenation): openQASM concatenation AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n\n def process_side(c_node: ast.Expression):\n match c_node:\n case ast.Concatenation():\n process_side(c_node.lhs)\n self.stream.write(\", \")\n process_side(c_node.rhs)\n case _:\n self.visit(c_node, context)\n\n self.stream.write(\"join(\")\n process_side(node)\n self.stream.write(\")\")\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_QuantumGate(self, node: ast.QuantumGate, context: PrinterState) -> None:\n \"\"\"\n QuantumGate node visitor:\n Prints quantum gate call as a mangled function name, at this point the\n gate operation should have a calibration definition (defcal)\n\n Example:\n qasm:\n defcal x90 $0 {...}\n >>x90 $0;\n -> ^^^^^^^\n seqc\n void _ZN3x90_PN0_QN1__0_R() {...}\n >>_ZNx90_PN0_QN1__0_R();\n ^^^^^^^^^^^^^^^^^^^^^^\n Args:\n node (ast.QuantumGate): openQASM QuantumGate AST node\n context (PrinterState): state of the printer (e.g. indentation)\n\n Raises:\n SEQCPrinterError: ErrorCode.COMPILE_OUT:\n if modifiers are applied to the gate, modifiers should be handled prior\n to printing to SEQC code\n \"\"\"\n # gate has to have a defcal implementation at this point\n if node.modifiers:\n raise self.compile_out(node.modifiers)\n signature = Mangler(node).signature()\n mangled_name = signature.match(self.defcal_names)[0]\n self._start_line(context)\n self.visit(ast.Identifier(self.make_string_legal(mangled_name)), context)\n self._visit_sequence(\n node.arguments, context, start=\"(\", end=\")\", separator=\", \"\n )\n self._end_statement(context)\n\n def visit_QuantumGateModifier(\n self, node: ast.QuantumGateModifier, context: PrinterState\n ) -> None:\n \"\"\"\n the concept of QuantumGateModifier does not exist in SEQC code,\n This node needs to be resolved in earlier stages of the compilation process\n \"\"\"\n raise self.compile_out(node)\n\n @_maybe_annotated\n def visit_QuantumPhase(self, node: ast.QuantumPhase, context: PrinterState) -> None:\n raise self.compile_out(node)\n\n @_visit_interpreter\n def visit_QuantumMeasurement(\n self, node: ast.QuantumMeasurement, context: PrinterState\n ) -> None:\n \"\"\"\n QuantumMeasurement node visitor:\n Prints quantum measurement call as a mangled function name,\n at this point the quantum measurement should have a calibration definition\n (defcal)\n\n Example:\n qasm:\n defcal measure $0 -> bit {...}\n >>b1 = measure $0;\n -> ^^^^^^^^^^^\n seqc\n var _ZN7measure_PN0_QN1__0_RBIT() {...}\n >>b1 = _ZN7measure_PN0_QN1__0_RBIT();\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Args:\n node (ast.QuantumMeasurement): openQASM QuantumMeasurement AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n signature = Mangler(node).signature()\n mangled_name = signature.match(self.defcal_names)[0]\n self._start_line(context)\n self.visit(ast.Identifier(self.make_string_legal(mangled_name)), context)\n self.stream.write(\"()\")\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_QuantumReset(self, node: ast.QuantumReset, context: PrinterState) -> None:\n \"\"\"\n QuantumReset node visitor:\n Prints quantum reset call as a mangled function name,\n at this point the quantum reset should have a calibration definition\n (defcal)\n\n Example:\n qasm:\n defcal reset $0 {...}\n >>reset $0;\n -> ^^^^^^^^^\n seqc\n void _ZN5reset_PN0_QN1__0_R() {...}\n >>_ZN5reset_PN0_QN1__0_R();\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n Args:\n node (ast.QuantumReset): openQASM QuantumReset AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n signature = Mangler(node).signature()\n mangled_name = signature.match(self.defcal_names)[0]\n self._start_line(context)\n self.visit(ast.Identifier(self.make_string_legal(mangled_name)), context)\n self.stream.write(\"()\")\n self._end_statement(context)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_QuantumBarrier(\n self, node: ast.QuantumBarrier, context: PrinterState\n ) -> None:\n \"\"\"\n QuantumBarrier node visitor:\n Replaces barrier statement with a waitZSyncTrigger() call for\n synchronization of channels for ZI instruments. Update documentation of\n visit_QuantumBarrier. According to OpenQASM specification, barrier invoked\n without arguments assumes all qubits are arguments. Applying the\n waitZSyncTrigger command places a barrier on all the qubits assocaited with\n a particular core.\n Note: barrier is only supported globally by the SEQCPrinter, behavior when\n placing such a barrier in a middle of a program/loop is not fully known.\n\n Example:\n qasm:\n barrier;\n seqc:\n waitZSyncTrigger();\n Args:\n node (ast.QuantumBarrier): openQASM QuantumBarrier AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n # todo write appropriate playZero/Wait instructions\n if node.qubits == []:\n self.stream.write(\"waitZSyncTrigger()\")\n self._end_statement(context)\n else:\n raise self.compile_out(node)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_QuantumMeasurementStatement(\n self, node: ast.QuantumMeasurementStatement, context: PrinterState\n ) -> None:\n \"\"\"\n QuantumMeasurementStatement node visitor:\n QuantumMeasurementStatement contains a QuantumMeasurement and 'target'\n the the result of the QuantumMeasurement is asigned to\n\n i.e.\n |----------------| <- QuantumMeasurmentStatement\n t_bit = measure $1\n target -> |---| |--------| <- QuantumMeasurement\n\n Example:\n qasm:\n defcal measure $0 -> bit {...}\n >>b1 = measure $0;\n -> ^^^^^^^^^^^^^^^^\n seqc\n var _ZN7measure_PN0_QN1__0_RBIT() {...}\n >>b1 = _ZN7measure_PN0_QN1__0_RBIT();\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Args:\n node (ast.QuantumMeasurementStatement):\n openQASM QuantumMeasurementStatement AST node\n context (PrinterState):\n state of the printer (e.g. indentation)\n \"\"\"\n self._start_line(context)\n if node.target:\n self.visit(node.target)\n self.stream.write(\" = \")\n self.visit(node.measure)\n self._end_statement(context)\n\n def visit_ClassicalArgument(\n self, node: ast.ClassicalArgument, context: PrinterState\n ) -> None:\n \"\"\"\n ClassicalArgument node visitor:\n Prints arguments in procedure/defcal/gate definitions:\n\n Example:\n qasm:\n def my_function(int i) {...}\n -> ^^^^^\n seqc:\n void my_function(var i) {...}\n ^^^^^\n Args:\n node (ast.ClassicalArgument): openQASM ClassicalArgument AST node\n context (PrinterState): state of the printer (e.g. indentation)\n\n Raises:\n NotImplementedError:\n if the argument has access control (not supported by SEQC)\n \"\"\"\n if node.access is not None:\n raise NotImplementedError\n self.stream.write(\"var \")\n self.visit(node.name, context)\n\n @_visit_interpreter\n def visit_ExternArgument(\n self, node: ast.ExternArgument, context: PrinterState\n ) -> None:\n # todo extern arguments should only be in ExternDeclarations\n # todo we may want to compile ExternDeclarations out and remove this visitor\n if node.access is not None:\n raise NotImplementedError\n self.visit(node.type, context)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_ClassicalDeclaration(\n self, node: ast.ClassicalDeclaration, context: PrinterState\n ) -> None:\n match node.type:\n case ast.PortType():\n name = node.identifier.name\n activation_record = self.call_stack.peek()\n port = self.setup.ports[name]\n activation_record[name] = port\n if not self.core:\n if port.core.type == CoreType.HD:\n self.core = HDCORE(channel=port.core.index)\n elif port.core.type == CoreType.SG:\n self.core = SHFSGCore(channel=port.core.index)\n if port.core.type == CoreType.HD:\n self.core.outputs[port.core.channels[0]] = HDCORE.Output(\n output=port.core.channels[0]\n )\n case ast.FrameType():\n match node.init_expression:\n case ast.FunctionCall(name=ast.Identifier(\"newframe\")):\n call = node.init_expression\n assert isinstance(call, ast.FunctionCall)\n assert len(call.arguments) == 3\n port = call.arguments[0].name # Identifier\n frequency = call.arguments[1].value # Literal\n phase = call.arguments[2].value # Literal\n activation_record = self.call_stack.peek()\n frame = Frame(\n name=node.identifier.name,\n port=activation_record[port],\n frequency=frequency,\n phase=phase,\n )\n self.setup.frames[frame.name] = frame\n activation_record[frame.name] = frame\n case _:\n raise SEQCPrinterError(\n ErrorCode.INVALID_ARGUMENT,\n \"Only newframe() is supported for frame initialization\",\n )\n case ast.ArrayType():\n self._start_line(context)\n self.stream.write(\"wave \")\n self.visit(node.identifier)\n if node.init_expression is None:\n self.stream.write(\" = zeros\")\n self._visit_sequence(\n node.type.dimensions,\n context,\n start=\"(\",\n end=\")\",\n separator=\", \",\n )\n else:\n self.stream.write(\" = \")\n self.visit(node.init_expression)\n self._end_statement(context)\n case ast.WaveformType():\n self._start_line(context)\n self.visit(node.type)\n self.stream.write(\" \")\n self.visit(node.identifier, context)\n if node.init_expression is not None:\n self.stream.write(\" = \")\n self.visit(node.init_expression)\n self._end_statement(context)\n match node.init_expression:\n case ast.FunctionCall(name=ast.Identifier(\"placeholder\")):\n self._start_line(context)\n self.stream.write(\"assignWaveIndex(\")\n self.visit(node.identifier, context)\n self.stream.write(f\", {self.placeholder_index})\")\n self.wfm_indices[self.placeholder_index] = node.identifier.name\n self.placeholder_index += 1\n self._end_statement(context)\n case _:\n pass\n case _:\n self._start_line(context)\n self.stream.write(\"var\")\n self.stream.write(\" \")\n self.visit(node.identifier, context)\n if node.init_expression is not None:\n self.stream.write(\" = \")\n self.visit(node.init_expression)\n self._end_statement(context)\n\n @_maybe_annotated\n def visit_IODeclaration(\n self, node: ast.IODeclaration, context: PrinterState\n ) -> None:\n raise self.compile_out(node)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_ConstantDeclaration(\n self, node: ast.ConstantDeclaration, context: PrinterState\n ) -> None:\n \"\"\"\n ConstantDeclaration node visitor:\n Prints constant declarations in correct seqc format, in seqc the datatype\n is automatically infered from the value assigned to the constant.\n\n Example:\n qasm:\n const float f = 1.1;\n ->\n seqc:\n const f = 1.1;\n\n Args:\n node (ast.ConstantDeclaration): openQASM ConstantDeclaration AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n match node:\n case ast.ConstantDeclaration(\n ast.ComplexType(), ast.Identifier(\"ii\"), ast.ImaginaryLiteral(1.0)\n ):\n return\n case _:\n self._start_line(context)\n self.stream.write(\"const \")\n self.visit(node.identifier, context)\n self.stream.write(\" = \")\n self.visit(node.init_expression, context)\n self._end_statement(context)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_CalibrationGrammarDeclaration(\n self, node: ast.CalibrationGrammarDeclaration, context: PrinterState\n ) -> None:\n \"\"\"\n CalibrationGrammarDeclaration node visitor:\n calibration grammar is not a concept in SEQC so this is omitted from the\n printed stream.\n\n ToDo: print the grammar as a comment instead\n\n Args:\n node (ast.CalibrationGrammarDeclaration):\n openQASM CalibrationGrammarDeclaration AST node\n context (PrinterState):\n state of the printer (e.g. indentation)\n \"\"\"\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_CalibrationDefinition(\n self, node: ast.CalibrationDefinition, context: PrinterState\n ) -> None:\n \"\"\"\n CalibrationDefinition (defcal) node visitor:\n Converts to openQASM calibration definitions into SEQC functions with a\n mangled name:\n\n Example 1:\n qasm: defcal x90 $1 {...}\n seqc: void _ZN3x90_PN0_QN1__1_R() {...}\n\n Some definitions (e.g. qubit state measurements) require special handling as\n multiple statements in openQASM (e.g. play followed by caputure) are\n performed by a single statment in SEQC (startQA)\n\n Example 2:\n qasm:\n defcal measure $0 {\n play(tx_frame, wfm_measure);\n return capture_v2(rx_frame, wfm_integration);\n }\n ->\n seqc:\n var _ZN7measure_PN0_QN1__0_RBIT() {\n startQA(QA_GEN_0, QA_INT_0, false, 0x0, 0b0);\n return getDIO(0x0)\n }\n\n The measure and integration waveforms are stored and uploaded to the\n appropriate waveform memories on the QA instrument during instrument\n setup <- ToDo This needs to be fully implemented\n\n Args:\n node (ast.CalibrationDefinition): defcal node to visit\n context (PrinterState): printer state (e.g. indentation)\n \"\"\"\n with self.interpret_context_manager(False):\n # here we turn off the interpreter as we don't want to interpret the\n # the contents of the defcal statement when it is defined (only when it is\n # called)\n self._start_line(context)\n self.stream.write(\"void \" if node.return_type is None else \"var \")\n mangled_name = Mangler(node).signature().mangle()\n self.defcal_names.append(mangled_name)\n self.visit(ast.Identifier(self.make_string_legal(mangled_name)), context)\n arguments = [\n ast.ClassicalArgument(ast.IntType(), ast.Identifier(f\"lit_{i}\"))\n if isinstance(argument, ast.Expression)\n else argument\n for i, argument in enumerate(node.arguments)\n ]\n self._visit_sequence(arguments, context, start=\"(\", end=\")\", separator=\", \")\n self.stream.write(\" {\")\n self._end_line(context)\n with context.increase_scope():\n LOGGER.debug(node.body)\n match node.body:\n case [\n ast.ExpressionStatement(\n ast.FunctionCall(\n name=ast.Identifier(\"play\"), arguments=play_args\n )\n ),\n # todo should ExpressionStatement be supported for v2?\n ast.ReturnStatement(\n ast.FunctionCall(\n name=ast.Identifier(\"capture_v2\"),\n arguments=capture_args,\n )\n )\n | ast.ExpressionStatement(\n ast.FunctionCall(\n name=ast.Identifier(\"capture_v1\"),\n arguments=capture_args,\n )\n ),\n ]:\n # ensure that play and caputure commands are using ports on the\n # same instrument\n is_v2 = node.body[1].expression.name.name == \"capture_v2\"\n # todo make generic for QA/QC\n # todo make a separate validation step for these assertions.\n play_frame = self.setup.frames[play_args[0].name]\n capture_frame = self.setup.frames[capture_args[0].name]\n assert (\n play_frame.port.instrument == capture_frame.port.instrument\n )\n assert play_frame.port.core.channels == [1]\n assert capture_frame.port.core.channels == [2]\n assert (\n play_frame.port.core.type\n == capture_frame.port.core.type\n == CoreType.QA\n )\n readout = SHFQACore.READOUT(\n index=-1,\n generator_wfm=self.interpreter.visit(play_args[1]).astype(\n complex\n ),\n integrator_wfm=self.interpreter.visit(\n capture_args[1]\n ).astype(complex),\n threshold=0, # todo\n )\n if self.core is None:\n readout.index = 0\n core = SHFQACore(\n channel=play_frame.port.core.index,\n readouts={readout.index: readout},\n points_to_record=prod(self.sig.steps),\n num_averages=self.sig.shots,\n readout_source=ReadoutSource.DISCRIMINATION\n if is_v2\n else ReadoutSource.INTEGRATION,\n average_shots=self.average_shots,\n )\n self.core = core\n else:\n readout.index = len(self.core.readouts.keys())\n self.core.readouts[readout.index] = readout\n # todo write correct registers\n self._start_line(context)\n self.stream.write(f\"playZero({len(readout.generator_wfm)})\")\n self._end_statement(context)\n self._start_line(context)\n self.stream.write(f\"startQA(QA_GEN_{readout.index}, \")\n self.stream.write(f\"QA_INT_{readout.index}, true, \")\n self.stream.write(f\"0x{readout.index}, 0b0)\")\n self._end_statement(context)\n if is_v2:\n self._start_line(context)\n # self.stream.write(f\"return getDIO() & 0x{readout.index}\")\n # self.stream.write(\n # f\"return getZSyncData(ZSYNC_DATA_PQSC_REGISTER)\"\n # )\n self.stream.write(\"return getZSyncData(ZSYNC_DATA_RAW)\")\n self._end_statement(context)\n case _:\n for statement in node.body:\n self.visit(statement, context)\n self._start_line(context)\n self.stream.write(\"}\")\n self._end_line(context)\n\n @_maybe_annotated\n def visit_CalibrationStatement(\n self, node: ast.CalibrationStatement, context: PrinterState\n ) -> None:\n \"\"\"\n CalibrationStatement node visitor:\n Visits all statements in the CalibrationStatement, unlike when printing\n to openQASM format this visitor omits 'cal {...}' as 'cal' is not a concept\n in the SEQC language.\n\n Example:\n qasm:\n cal {\n cal_stmt_1;\n cal_stmt_2;\n }\n ->\n seqc:\n cal_stmt_1;\n cal_stmt_2;\n\n Args:\n node (ast.CalibrationStatement): openQASM CalibrationStatement AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n for statement in node.body:\n self.visit(statement, context)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_SubroutineDefinition(\n self, node: ast.SubroutineDefinition, context: PrinterState\n ) -> None:\n \"\"\"\n SubroutineDefinition node visitor:\n Prints out subroutine definitions in SEQC format\n\n Example 1:\n qasm: def subroutine(int i) -> float {...}\n seqc: var subroutine(var i) {...}\n\n Example 2:\n qasm: def subroutine(float f) {...}\n seqc: void subroutine(var f) {...}\n\n Args:\n node (ast.SubroutineDefinition): openQASM SubroutineDefinition AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n if node.name.name == \"measure_func\":\n # The measure_func is a special case as it is defined and is not written\n # to the output stream. Later, the call of the function will mark where\n # to replace the function call with multi-qubit seqc code.\n return\n with self.interpret_context_manager(False):\n # here we turn off the interpreter as we don't want to interpret the\n # the contents of the subroutine when it is defined (only when it is\n # called)\n self._start_line(context)\n self.stream.write(\"void \" if node.return_type is None else \"var \")\n self.visit(node.name, context)\n self._visit_sequence(\n node.arguments, context, start=\"(\", end=\")\", separator=\", \"\n )\n self.stream.write(\" {\")\n self._end_line(context)\n with context.increase_scope():\n for statement in node.body:\n self.visit(statement, context)\n self._start_line(context)\n self.stream.write(\"}\")\n self._end_line(context)\n\n def visit_QuantumArgument(\n self, node: ast.QuantumArgument, context: PrinterState\n ) -> None:\n raise self.compile_out(node)\n\n @_maybe_annotated\n def visit_BreakStatement(\n self, node: ast.BreakStatement, context: PrinterState\n ) -> None:\n raise SEQCPrinterError(ErrorCode.NO_SEQC_STATEMENT, \"no 'break' statement\")\n\n @_maybe_annotated\n def visit_ContinueStatement(\n self, node: ast.ContinueStatement, context: PrinterState\n ) -> None:\n raise SEQCPrinterError(ErrorCode.NO_SEQC_STATEMENT, \"no 'continue' statement\")\n\n @_maybe_annotated\n def visit_EndStatement(self, node: ast.EndStatement, context: PrinterState) -> None:\n raise SEQCPrinterError(ErrorCode.NO_SEQC_STATEMENT, \"no 'end' statement\")\n\n @_maybe_annotated\n def visit_WhileLoop(self, node: ast.WhileLoop, context: PrinterState) -> None:\n \"\"\"\n WhileLoop node visitor:\n Prints out a while loop in SEQC format (which happens to be identical to\n openQASM format) All the statements in the block of the while loop are\n visited\n\n Example:\n qasm:\n while (int i < 10) {...; i=i+1;}\n ->\n seqc:\n while (cvar i < 10) {...; i=i+1;}\n\n Args:\n node (ast.WhileLoop): openQASM WhileLoop AST node\n context (PrinterState): state of the printer (e.g. indentation)\n \"\"\"\n self._end_line(context)\n self._start_line(context)\n self.stream.write(\"while (\")\n self.visit(node.while_condition, context)\n self.stream.write(\") {\")\n self._end_line(context)\n with context.increase_scope():\n for statement in node.block:\n self.visit(statement, context)\n self._start_line(context)\n self.stream.write(\"}\")\n self._end_line(context)\n self._end_line(context)\n\n @_maybe_annotated\n def visit_ForInLoop(self, node: ast.ForInLoop, context: PrinterState) -> None:\n \"\"\"\n ForInLoop node visitor:\n openQASM used a type of for loop called ForInLoop (think python like),\n SEQC uses a 'traditional' for loop. This node translates between the two\n in limited cases. Specifically if the SET the ForInLoop iterates over is\n defined using a RANGE. Defining the SET using a DiscreteSet is not supported\n\n Example 1 (supported):\n qasm: for int i in [0:2:10] {...}\n ->\n seqc: cvar i;\n for( i = 0; i < 10; i = i + 2 ) {...}\n\n Example 2 (not supported):\n qasm: for int j in {1, 2, 3} {...}\n ->\n SEQCPrinterError\n\n Further reading:\n\n Args:\n node (ast.ForInLoop): openQASM ForInLoop AST node\n context (PrinterState): state of the printer (e.g. indentation)\n\n Raises:\n SEQCPrinterError: ErrorCode.UNHANDLED\n If the SET iterated over by the ForInLoop is incorrectly defined or not\n created using a RangeDefinition\n \"\"\"\n\n self._end_line(context)\n self._start_line(context)\n stack_obj = StackAnalyzer(skip_calls=[\"ones\"])\n stack_obj.visit(node)\n self.constant_for_loops = stack_obj.constant_for_loops\n loop_var_type = \"cvar \" if self.constant_for_loops else \"var \"\n self.stream.write(loop_var_type)\n # todo need to distinquse between compile and runtime execution of for loop\n self.visit(node.identifier, context)\n self._end_statement(context)\n self._start_line(context)\n self.stream.write(\"for ( \")\n # self.visit(node.type)\n name = node.identifier.name\n\n curr_nesting = self.call_stack.peek().nesting_level\n activation_record = ActivationRecord(\n name=\"for loop\", ar_type=ARType.LOOP, nesting_level=curr_nesting + 1\n )\n with self.ar_context_manager(activation_record):\n match node.set_declaration:\n case ast.RangeDefinition():\n self.stream.write(f\"{name} = \")\n match node.set_declaration.start:\n case (\n ast.IntegerLiteral()\n | ast.Identifier()\n | ast.IndexExpression()\n ):\n self.visit(node.set_declaration.start)\n activation_record[name] = self.interpreter.visit(\n node.set_declaration.start\n )\n case None:\n self.stream.write(\"0\")\n activation_record[name] = 0\n case _:\n raise SEQCPrinterError(\n ErrorCode.UNHANDLED,\n f\"unsupported set declaration in for loop: \\\n {node.set_declaration}\",\n )\n self.stream.write(f\"; {name} < \")\n match node.set_declaration.end:\n case (\n ast.IntegerLiteral()\n | ast.Identifier()\n | ast.IndexExpression()\n ):\n self.visit(node.set_declaration.end)\n case _:\n raise SEQCPrinterError(\n ErrorCode.UNHANDLED,\n f\"unsupported set declaration in for loop: \\\n {node.set_declaration}\",\n )\n self.stream.write(f\"; {name} = {name} + \")\n match node.set_declaration.step:\n case (\n ast.IntegerLiteral()\n | ast.Identifier()\n | ast.IndexExpression()\n ):\n self.visit(node.set_declaration.step)\n case None:\n self.stream.write(\"1\")\n case _:\n raise SEQCPrinterError(\n ErrorCode.UNHANDLED,\n f\"unsupported set declaration in for loop: \\\n {node.set_declaration}\",\n )\n case _:\n raise SEQCPrinterError(\n ErrorCode.UNHANDLED,\n f\"unsupported set declaration in for loop: \\\n {node.set_declaration}\",\n )\n\n self.stream.write(\" ) {\")\n self._end_line(context)\n with context.increase_scope():\n with self.interpret_context_manager(False):\n # here we turn off the interpreter as interpreting the contents of\n # of the for loop can be very time consuming, while a program can\n # be written that would require this, it is not a common use case\n # and should be avoided / considered carefully.\n for statement in node.block:\n self.visit(statement, context)\n self._start_line(context)\n self.stream.write(\"}\")\n self._end_line(context)\n self._end_line(context)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_DelayInstruction(\n self, node: ast.DelayInstruction, context: PrinterState\n ) -> None:\n \"\"\"\n DelayInstruction node visitor:\n Prints delay instruction as a playZero statement\n\n Example:\n qasm: delay[10] $1;\n ->\n seqc: playZero(10);\n\n Args:\n node (ast.DelayInstruction): openQASM DelayInstruction AST node\n context (PrinterState): state of printer (e.g. indentation)\n \"\"\"\n self._start_line(context)\n self.stream.write(\"playZero(\")\n self.visit(node.duration, context)\n self.stream.write(\")\")\n self._end_statement(context)\n\n def _play_hold(self, node: ast.Expression, context: PrinterState) -> None:\n \"\"\"\n Writes a playHold statement to the stream, the node is an expression for the\n duration of the hold. the playHold statement holds the output of the\n AWG/Generator at the last value it was set to.\n\n Args:\n node (ast.Expression):\n An expression that evaluates to the duration of the hold\n context (PrinterState):\n state of the printer (e.g. indentation)\n \"\"\"\n self._start_line(context)\n self.stream.write(\"playHold(\")\n self.visit(node, context)\n self.stream.write(\")\")\n self._end_statement(context)\n\n @_maybe_annotated\n def visit_Box(self, node: ast.Box, context: PrinterState) -> None:\n \"\"\"\n Box node visitor:\n visits all the statements in the Box, (The box has special meaning in terms\n of qasm to qasm compilation but we assume that this optimisation is done\n by the time we convert the qasm code to seqc code.\n\n Example 1 (supported):\n qasm:\n box {\n cal_stmt_1;\n cal_stmt_2;\n }\n ->\n seqc:\n cal_stmt_1;\n cal_stmt_2;\n\n Currently having boxes with duration is not supported\n\n Example 2 (unsupported):\n qasm: box[100ns] {}\n ->\n SEQCPrinterError\n\n Args:\n node (ast.Box): openQASM Box AST node\n context (PrinterState): state of printer (e.g. indentation)\n\n Raises:\n SEQCPrinterError: ErrorCode.COMPILE_OUT\n Specific duration of boxes should be handled during prior compilation\n steps.\n \"\"\"\n self._start_line(context)\n if node.duration is not None:\n raise self.compile_out(node)\n for statement in node.body:\n self.visit(statement, context)\n self._end_line(context)\n\n def visit_DurationOf(self, node: ast.DurationOf, context: PrinterState) -> None:\n raise self.compile_out(node)\n\n def visit_SizeOf(self, node: ast.SizeOf, context: PrinterState) -> None:\n raise self.compile_out(node)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_AliasStatement(\n self, node: ast.AliasStatement, context: PrinterState\n ) -> None:\n # todo doctring\n match node:\n case ast.AliasStatement(\n ast.Identifier(alias),\n ast.IndexExpression(\n ast.Identifier(name),\n [\n ast.RangeDefinition(\n ast.IntegerLiteral(start), ast.IntegerLiteral(end), None\n )\n ],\n ),\n ):\n self._start_line(context)\n self.stream.write(f\"wave {alias} = cut({name}, {start}, {end})\")\n self._end_statement(context)\n case ast.AliasStatement(target=ast.Identifier(), value=ast.Concatenation()):\n self._start_line(context)\n self.stream.write(\"wave \")\n self.visit(node.target)\n self.stream.write(\" = \")\n self.visit(node.value)\n self._end_statement(context)\n case _:\n raise self.compile_out(node)\n\n @_visit_interpreter\n @_maybe_annotated\n def visit_ClassicalAssignment(\n self, node: ast.ClassicalAssignment, context: PrinterState\n ) -> None:\n \"\"\"\n ClassicalAssignment node visitor:\n prints a classical assignment\n\n Example:\n qasm: a = 1;\n seqc: a = 1;\n\n qasm: b = 2 + 3;\n seqc: b = 2 + 3;\n\n qasm: c = a - b:\n seqc: c = a - b;\n\n Args:\n node (ast.ClassicalAssignment): openQASM ClassicalAssignment AST node\n context (PrinterState): state of printer (e.g. indentation)\n \"\"\"\n match node.rvalue:\n case ast.FunctionCall(name=ast.Identifier(\"measure_func\")):\n self.multi_measure_bit = node.lvalue\n self.visit(node.rvalue, context)\n case _:\n self._start_line(context)\n self.visit(node.lvalue, context)\n self.stream.write(f\" {node.op.name} \")\n self.visit(node.rvalue, context)\n self._end_statement(context)\n\n def visit_Annotation(self, node: ast.Annotation, context: PrinterState) -> None:\n raise Warning(\"Annotations are not supported, this will not do anything\")\n\n def visit_Pragma(self, node: ast.Pragma, context: PrinterState) -> None:\n raise Warning(\"Pragmas are not supported, this will not do anything\")\n\n @_visit_interpreter\n def visit_WaveformType(self, node: ast.WaveformType, context: PrinterState) -> None:\n self.stream.write(\"wave\")\n\n @_visit_interpreter\n def visit_FunctionCall(self, node: ast.FunctionCall, context: PrinterState) -> None:\n \"\"\"\n FunctionCall node visitor:\n prints function calls to seqc code, 'play' function calls are translated\n to 'playWave' function calls\n\n Args:\n node (ast.FunctionCall): openQASM FunctionCall AST node\n context (PrinterState): state of printer (e.g. indentation)\n \"\"\"\n match node:\n case ast.FunctionCall(name=ast.Identifier(\"play\")):\n self.visit_play(node, context)\n case ast.FunctionCall(\n name=ast.Identifier(\"set_phase\"),\n arguments=[ast.Identifier(frame_name), _],\n ):\n frame: Frame = self.call_stack.get(frame_name)\n frame.port.core.obj().set_phase(node, self, context)\n case ast.FunctionCall(\n name=ast.Identifier(\"shift_phase\"),\n arguments=[ast.Identifier(frame_name), _],\n ):\n frame: Frame = self.call_stack.get(frame_name)\n frame.port.core.obj().shift_phase(node, self, context)\n case ast.FunctionCall(\n name=ast.Identifier(\"set_frequency\"),\n arguments=[ast.Identifier(frame_name), _],\n ):\n frame: Frame = self.call_stack.get(frame_name)\n frame.port.core.obj().set_frequency(node, self, context)\n case ast.FunctionCall(\n name=ast.Identifier(\"shift_frequency\"),\n arguments=[ast.Identifier(frame_name), _],\n ):\n frame: Frame = self.call_stack.get(frame_name)\n frame.port.core.obj().shift_frequency(node, self, context)\n case ast.FunctionCall(\n name=ast.Identifier(\"capture_v3\"),\n arguments=[ast.Identifier(frame_name), ast.Identifier(capture_time)],\n ):\n capture_time = self.call_stack.get(capture_time)\n frame: Frame = self.call_stack.get(frame_name)\n frame.port.core.obj().capture_v3(node, self, context)\n # todo refactor this monster\n self.core = SHFQACore(\n channel=frame.port.core.index,\n spectra={\n 1: SHFQACore.SPECTRA(\n envelope_wfm=sample_waveform(\n ast.FunctionCall(\n ast.Identifier(\"ones\"),\n arguments=[ast.IntegerLiteral(capture_time)],\n )\n ),\n integration_time=capture_time,\n )\n },\n mode=Mode.SPECTROSCOPY,\n points_to_record=prod(self.sig.steps),\n num_averages=self.sig.shots,\n enable_scope=True,\n average_shots=self.average_shots,\n )\n case ast.FunctionCall(\n name=ast.Identifier(\"capture_v1_spectrum\"),\n arguments=[ast.Identifier(frame_name), ast.Identifier(capture_time)],\n ):\n capture_time = self.call_stack.get(capture_time)\n frame: Frame = self.call_stack.get(frame_name)\n frame.port.core.obj().capture_v3(node, self, context)\n # todo refactor this monster\n self.core = SHFQACore(\n channel=frame.port.core.index,\n spectra={\n 1: SHFQACore.SPECTRA(\n envelope_wfm=sample_waveform(\n ast.FunctionCall(\n ast.Identifier(\"ones\"),\n arguments=[ast.IntegerLiteral(capture_time)],\n )\n ),\n integration_time=capture_time,\n )\n },\n mode=Mode.SPECTROSCOPY,\n points_to_record=prod(self.sig.steps),\n num_averages=self.sig.shots,\n average_shots=self.average_shots,\n )\n case ast.FunctionCall(name=ast.Identifier(\"measure_func\")):\n # TODO: AQC-216 PQSC Registers\n args = [self.interpreter.visit(arg) for arg in node.arguments]\n qubits = args[0]\n num_qubits = len(qubits)\n assert num_qubits == args[1]\n if num_qubits > 16:\n raise SEQCPrinterError(\n ErrorCode.INVALID_ARGUMENT,\n f\"Cannot simultaneously measure more than 16 qubits: {node}\",\n )\n if self.meas_delay is not None:\n self._start_line(context)\n self.stream.write(\n f\"play{'Zero' if isinstance(self.core, SHFQACore) else 'Hold'}\"\n f\"({self.meas_delay})\"\n )\n self._end_statement(context)\n if isinstance(self.core, SHFQACore):\n self._start_line(context)\n self.stream.write(\"startQA(\")\n gen_str = \" | \".join([f\"QA_GEN_{q[1]}\" for q in qubits])\n int_str = \" | \".join([f\"QA_INT_{q[1]}\" for q in qubits])\n self.stream.write(f\"{gen_str}, {int_str}, true, 0x0, 0b0)\")\n self._end_statement(context)\n if self.multi_measure_bit is not None:\n self._start_line(context)\n mbit_name = self.multi_measure_bit.name\n self.stream.write(f\"{mbit_name} = getZSyncData(ZSYNC_DATA_RAW)\")\n self._end_statement(context)\n case ast.FunctionCall(name=ast.Identifier(\"assignWaveIndex\")):\n match node.arguments[0]:\n case ast.FunctionCall(name=ast.Identifier(\"placeholder\")):\n wave_length = self.interpreter.visit(\n node.arguments[0].arguments[0]\n )\n wave_ind = self.interpreter.visit(node.arguments[1])\n self._start_line(context)\n self.stream.write(\n f\"assignWaveIndex(placeholder({wave_length}), {wave_ind})\"\n )\n self._end_statement(context)\n case _:\n super().visit_FunctionCall(node, context)\n\n def visit_play(self, node: ast.FunctionCall, context: PrinterState) -> None:\n \"\"\"\n FunctionCall node visitor. Handles 'play' calls by converting the frame\n the play function is applied to to the approprated channel(s) on an ZI AWG\n Core.\n\n If the waveform is a 'ones' waveform and its duration is greater than\n 128 samples, the play command is split into two parts\n i)\n the first part plays the 'ones' waveform for the shortest possible time\n (16 samples)\n ii)\n the second part executes a 'playHold' command for the remainder of the time\n (hold time = total time - 16 samples)\n\n # ToDo how long does it take to execute a playHold command on the ZI AWG Cores?\n # what if the total time is shorter than execution of playWave + playHold?\n\n Args:\n node (ast.FunctionCall): 'play' FunctionCall node to visit\n context (PrinterState): state of the printer stream (e.g. indentation)\n\n Raises:\n SEQCPrinterError:\n ErrorCode.UNHANDLED\n If the node does not match the expected format/structure\n \"\"\"\n\n def _play_frame(frame: Frame, wfm_node: ast.Expression) -> None:\n if frame.port.core.type == CoreType.HD:\n channel = frame.port.core.channels[0]\n frame.port.core.obj().play(wfm_node, self, context, channel)\n else:\n frame.port.core.obj().play(wfm_node, self, context)\n\n def _loop_parameters(\n duration_arg: ast.Expression,\n ) -> Optional[tuple[ActivationRecord, str, float]]:\n # get all activation records for 'for loops' in the call stack\n records = [\n record\n for record in self.call_stack._records\n if record.name == \"for loop\"\n ]\n duration = self.interpreter.visit(duration_arg)\n for record in records:\n loop_var = next(iter(record.members))\n loop_value = record[loop_var]\n # vary each loop variable by 1 and check if the duration changes\n record[loop_var] = loop_value + 1\n new_duration = self.interpreter.visit(duration_arg)\n record[loop_var] = loop_value\n if new_duration != duration:\n return record, loop_var, loop_value\n\n new_node = CopyTransformer().visit(node)\n match new_node:\n case ast.FunctionCall(\n name=ast.Identifier(\"play\"),\n arguments=[ast.Identifier(frame_name), wfm_node],\n ):\n frame: Frame = self.call_stack.get(frame_name)\n match wfm_node:\n case ast.FunctionCall(\n ast.Identifier(\"ones\"), arguments=args\n ) | ast.BinaryExpression(\n lhs=ast.FunctionCall(ast.Identifier(\"ones\"), arguments=args)\n ) | ast.BinaryExpression(\n rhs=ast.FunctionCall(ast.Identifier(\"ones\"), arguments=args)\n ):\n try:\n duration = self.interpreter.visit(args[0])\n except SemanticError:\n # if the duration is not a constant assume 64 samples\n # or longer to force the use of playHold\n duration = 64\n if duration < 64: # this parameter may need adjustment\n l_params = _loop_parameters(args[0])\n if l_params is None:\n _play_frame(frame, wfm_node)\n return\n record, loop_var, loop_value = l_params\n args[0] = ast.DurationLiteral(duration, \"dt\")\n new_statement = ast.BranchingStatement(\n condition=ast.BinaryExpression(\n op=ast.BinaryOperator[\">\"],\n lhs=ast.Identifier(loop_var),\n rhs=ast.IntegerLiteral(loop_value),\n ),\n if_block=[node],\n else_block=[new_node] if duration > 0 else [],\n )\n record[loop_var] = loop_value + 1\n self.visit(new_statement, context)\n record[loop_var] = loop_value\n else:\n hold_time = ast.BinaryExpression(\n ast.BinaryOperator[\"-\"], args[0], ast.IntegerLiteral(32)\n )\n args[0] = ast.DurationLiteral(32, \"dt\")\n _play_frame(frame, wfm_node)\n self._play_hold(hold_time, context)\n case ast.FunctionCall(\n name=ast.Identifier(name=\"executeTableEntry\"),\n arguments=[ct_index_node],\n ):\n self._start_line(context)\n self.stream.write(\"executeTableEntry(\")\n self.visit(ct_index_node)\n self.stream.write(\")\")\n self._end_statement(context)\n case _:\n _play_frame(frame, wfm_node)\n case _:\n raise SEQCPrinterError(\n ErrorCode.UNHANDLED, f\"format of play node: {node}\"\n )\n\n @_visit_interpreter\n def visit_BooleanLiteral(self, node: ast.BooleanLiteral, context: PrinterState):\n super().visit_BooleanLiteral(node, context)\n\n @_visit_interpreter\n def visit_FloatLiteral(self, node: ast.FloatLiteral, context: PrinterState):\n super().visit_FloatLiteral(node, context)\n\n @_visit_interpreter\n def visit_IntegerLiteral(self, node: ast.IntegerLiteral, context: PrinterState):\n super().visit_IntegerLiteral(node, context)\n\n @_visit_interpreter\n def visit_BinaryExpression(self, node: ast.BinaryExpression, context: PrinterState):\n super().visit_BinaryExpression(node, context)\n\n @_visit_interpreter\n def visit_UnaryExpression(self, node: ast.UnaryExpression, context: PrinterState):\n super().visit_UnaryExpression(node, context)\n\n @contextmanager\n def ar_context_manager(\n self,\n activation_record: ActivationRecord,\n ):\n \"\"\"\n Context manager for activation records / call stack,\n the activation record tracks ports and frames declared in the program\n to make sure frames can be replaced with approprate channels\n\n Args:\n activation_record (ActivationRecord): activation record to activate\n \"\"\"\n self.call_stack.push(activation_record)\n LOGGER.debug(\"ENTER: ACTIVATION RECORD %s\", activation_record.name)\n LOGGER.debug(self.call_stack)\n try:\n yield\n finally:\n LOGGER.debug(\"LEAVE: ACTIVATION RECORD %s\", activation_record.name)\n LOGGER.debug(self.call_stack)\n self.call_stack.pop()\n\n @contextmanager\n def interpret_context_manager(self, interpret: bool):\n \"\"\"\n Context manager for interpreter, used to turn on/off interpreter\n \"\"\"\n prev_interpret = self.interpret\n self.interpret = interpret\n try:\n yield\n finally:\n self.interpret = prev_interpret\n\n def compile_out(self, node: ast.QASMNode) -> SEQCPrinterError:\n \"\"\"\n Method for standartizing raising errors when SEQCPrinter is asked to visit\n nodes that should be compiled out of the AST before the SEQCPrinter is used.\n\n Args:\n node (ast.QASMNode):\n Should have been removed from the AST by prior compilation steps\n\n Returns:\n SEQCPrinterError: should be raised immediately after this method returns\n \"\"\"\n return SEQCPrinterError(ErrorCode.COMPILE_OUT, f\"{node}\")\n\n @classmethod\n def make_string_legal(cls, input_str: str) -> str:\n \"\"\"\n method for making strings 'legal' in seqc code.\n\n currenlty replaces '$' with '_'\n\n '$' are not allowed in seqc code but used in qasm code to represent physical\n qubits.\n\n Args:\n input_str (str): string to make seqc 'legal'\n\n Returns:\n str: 'legal' seqc string\n \"\"\"\n return input_str.replace(\"$\", \"_\")\n\n def settings(self) -> list[tuple[str, Any]]:\n \"\"\"\n Returns instrument settings generated by the printer while\n visiting the AST\n\n Returns:\n list[tuple[str, Any]]:\n list of instrument settings, each setting is a tuple of string and value\n where the string represents the ZI node tree path to the setting and the\n value is the value of the setting\n \"\"\"\n return self.core.settings() if self.core else None\n\n def wfm_mapping(self) -> dict:\n \"\"\"\n Returns waveform mapping generated by the printer while\n visiting the AST\n\n Returns:\n dict:\n dictionary of waveform mapping, each key maps a instrument specific\n way to assign waveforms to a waveform name\n \"\"\"\n return self.wfm_indices" }, { "identifier": "SetupInternal", "path": "shipyard/setup/internal.py", "snippet": "class SetupInternal(BaseModel):\n\n \"\"\"\n A Pydantic model containing the information required to compile an openQASM program\n to instrument level instructions.\n\n It is recommended to instanciate this object from a configuration file\n (json (future yml?))\n \"\"\"\n\n # todo validation\n\n # todo move to own module\n instruments: dict[str, Instrument]\n ports: dict[str, Port]\n frames: dict[str, Frame]\n\n @classmethod\n def from_dict(cls, setup: dict[str, dict[str, dict]]) -> \"SetupInternal\":\n \"\"\"Creates a Setup object from a dictionary\n\n Args:\n setup (dict[str, dict[str, dict]]): dictionary to create a Setup object from\n\n Returns:\n Setup: created from dictionary\n \"\"\"\n instruments = {\n k: Instrument(name=k, **v) for k, v in setup[\"Instruments\"].items()\n }\n ports = {}\n for k, val in setup[\"Ports\"].items():\n val[\"instrument\"] = instruments[val[\"instrument\"]]\n val[\"core\"] = Port.Core(**val[\"core\"])\n ports[k] = Port(name=k, **val)\n frames = {}\n for k, val in setup[\"Frames\"].items():\n val[\"port\"] = ports[val[\"port\"]]\n frames[k] = Frame(name=k, **val)\n return cls(instruments=instruments, ports=ports, frames=frames)\n\n def to_dict(self) -> dict[str, dict[str, dict]]:\n \"\"\"Creates a dictionary from a Setup object\n\n Args:\n filename (Path | str, optional):\n path to save dictionary to. Defaults to None.\n\n Returns:\n dict[str, dict[str, dict]]: dictionary created from Setup object\n \"\"\"\n setup = {\n \"Instruments\": {\n k: {\n \"type\": v.type,\n \"serial\": v.serial,\n }\n for k, v in self.instruments.items()\n },\n \"Ports\": {\n k: {\n \"instrument\": v.instrument.name,\n \"core\": {\n \"type\": v.core.type.value,\n \"index\": v.core.index,\n \"channels\": v.core.channels,\n },\n }\n for k, v in self.ports.items()\n },\n \"Frames\": {\n k: {\n \"port\": v.port.name,\n \"frequency\": v.frequency,\n \"phase\": v.phase,\n }\n for k, v in self.frames.items()\n },\n }\n return setup\n\n @classmethod\n def from_json(cls, filename: str | Path) -> \"SetupInternal\":\n \"\"\"Creates a Setup object from a json file\n\n Args:\n filename (str | Path): path to json file\n\n Returns:\n Setup: created from json file\n \"\"\"\n with open(filename, encoding=\"utf-8\") as file:\n data = json.load(file)\n return cls.from_dict(data)\n\n def to_json(self, filename: str | Path) -> Path:\n \"\"\"Writes a Setup object to a json file\n\n Args:\n filename (str | Path): path to json file to create\n\n Returns:\n Path: path to json file\n \"\"\"\n data = self.to_dict()\n with open(filename, \"w\", encoding=\"utf-8\") as file:\n json.dump(data, file, indent=4)\n return Path(filename)\n\n @classmethod\n def from_yml(cls, filename: str | Path) -> \"SetupInternal\":\n \"\"\"Creates a Setup object from a yml file\n\n Args:\n filename (str | Path): path to yml file\n\n Returns:\n Setup: created from yml file\n \"\"\"\n with open(filename, \"r\", encoding=\"utf-8\") as file:\n data = yaml.safe_load(file)\n return cls.from_dict(data)\n\n def to_yml(self, filename: str | Path) -> Path:\n \"\"\"Writes a Setup object to a yml file\n\n Args:\n filename (str | Path): path to yml file to create\n\n Returns:\n Path: path to yml file\n \"\"\"\n data = self.to_dict()\n with open(filename, \"w\", encoding=\"utf-8\") as file:\n yaml.dump(data, file)\n return Path(filename)\n\n def cores(self) -> set[tuple[str, int, str]]:\n \"\"\"Gets all the AWG Cores used in the setup\n\n Returns:\n set[tuple[str, int, str]]:\n a Set of tuples, each tuple has a string representing the instruement\n name, a integer representing the index of the awg core of the\n instrument and a string representing the type of the awg core.\n \"\"\"\n return set(\n (port.instrument.name, port.core.index, port.core.type.value)\n for port in self.ports.values()\n )" } ]
import io import pytest from pathlib import Path from openpulse import ast, parse from shipyard.compiler import Compiler from shipyard.compiler_error import SemanticError, TransformError from shipyard.printers.zi.seqcprinter import SEQCPrinter from shipyard.setup.internal import SetupInternal
16,594
@pytest.fixture(name="basic_setup") def fixture_basic_setup() -> SetupInternal: json_path = Path(__file__).parent.parent / "setups/basic.json" return SetupInternal.from_json(json_path) @pytest.fixture(name="seqc_printer")
@pytest.fixture(name="basic_setup") def fixture_basic_setup() -> SetupInternal: json_path = Path(__file__).parent.parent / "setups/basic.json" return SetupInternal.from_json(json_path) @pytest.fixture(name="seqc_printer")
def fixture_seqc_printer(basic_setup: SetupInternal) -> SEQCPrinter:
3
2023-11-16 17:37:29+00:00
24k
quantuminterface/qiclib
src/qiclib/code/qi_jobs.py
[ { "identifier": "TaskRunner", "path": "src/qiclib/hardware/taskrunner.py", "snippet": "class TaskRunner(PlatformComponent):\n \"\"\"Driver to control the Taskrunner on the Hardware Platform.\"\"\"\n\n def __init__(\n self,\n name: str,\n connection,\n controller,\n qkit_instrument=True,\n ):\n super().__init__(name, connection, controller, qkit_instrument)\n self._stub = grpc_stub.TaskRunnerServiceStub(self._conn.channel)\n\n @property\n @platform_attribute\n @ServiceHubCall(\n errormsg=\"Could not fetch the current firmware hash of the Taskrunner\"\n )\n def firmware_hash(self):\n \"\"\"The hash of the current firmware running on the realtime core.\"\"\"\n return self._stub.GetStatus(proto.Empty()).firmware_hash\n\n @property\n @platform_attribute\n @ServiceHubCall(\n errormsg=\"Could not determine the build date of the Taskrunner firmware\"\n )\n def firmware_build_date(self):\n \"\"\"Returns the build date of the Taskrunner firmware.\"\"\"\n return self._stub.GetStatus(proto.Empty()).build_date\n\n @property\n @platform_attribute\n @ServiceHubCall(\n errormsg=\"Could not determine the build commit of the Taskrunner firmware\"\n )\n def firmware_build_commit(self):\n \"\"\"Returns the build commit hash of the Taskrunner firmware.\"\"\"\n return self._stub.GetStatus(proto.Empty()).build_commit\n\n @property\n @platform_attribute\n @ServiceHubCall(errormsg=\"Could not determine the status of the taskrunner\")\n def loaded_task(self):\n \"\"\"The name of the currently loaded task.\"\"\"\n return self._stub.GetStatus(proto.Empty()).task_name\n\n @property\n @ServiceHubCall(errormsg=\"Could not determine the progress of the task\")\n def task_progress(self):\n \"\"\"Returns the progress of the task\"\"\"\n return self._stub.GetStatus(proto.Empty()).task_progress\n\n @property\n @ServiceHubCall(errormsg=\"Could not determine number of available databoxes\")\n def databoxes_available(self):\n \"\"\"Returns the number of available databoxes.\"\"\"\n return self._stub.GetStatus(proto.Empty()).databoxes_available\n\n @property\n @ServiceHubCall(errormsg=\"Could not determine state of the taskrunner\")\n def busy(self):\n \"\"\"Returns if the taskrunner is currently busy.\"\"\"\n return self._stub.GetTaskState(proto.Empty()).busy\n\n @property\n @ServiceHubCall(errormsg=\"Could not determine if task has finished\")\n def task_done(self):\n \"\"\"Returns if the task has finished.\"\"\"\n return self._stub.GetTaskState(proto.Empty()).done\n\n @property\n @ServiceHubCall(errormsg=\"Could not determine if task has error messages\")\n def task_errormsg_available(self):\n \"\"\"Returns if task has error messages.\"\"\"\n return self._stub.GetTaskState(proto.Empty()).error_msg_available\n\n @property\n @ServiceHubCall(errormsg=\"Could not determine if error message queue is full\")\n def task_errormsg_queue_full(self):\n \"\"\"Returns if if error message queue is full.\"\"\"\n return self._stub.GetTaskState(proto.Empty()).error_msg_queue_full\n\n @ServiceHubCall(errormsg=\"Failed to start task\")\n def start_task(self, loop=False, overwrite=False):\n \"\"\"Starts the execution of a previously loaded task.\n\n :param loop: bool, optional\n if the task should be executed in a loop, by default False\n :param overwrite: bool, optional\n if a current running task should be stopped, by default False\n \"\"\"\n self._stub.StartTask(\n proto.StartTaskRequest(looping=loop, stop_running=overwrite)\n )\n\n @ServiceHubCall(errormsg=\"Failed to stop task\")\n def stop_task(self):\n \"\"\"Stops the execution of running task.\"\"\"\n self._stub.StopTask(proto.StopTaskRequest())\n\n @ServiceHubCall(errormsg=\"Failed to reset task\")\n def reset_task(self):\n \"\"\"Resets (unloads) a loaded task.\"\"\"\n self._stub.StopTask(proto.StopTaskRequest(reset=True))\n\n @ServiceHubCall(errormsg=\"Failed to load task binary\")\n def load_task_binary(self, filename, taskname):\n \"\"\"Loads a task binary into the taskrunner.\n The *taskname* needs to match the name of the task to load\n in order to verify that it is indeed the desired task file.\n\n :param filename: str\n name of the file with the task\n :param taskname: str\n name of the task\n\n :raises ValueError:\n if the path of the file is not found\n \"\"\"\n if not os.path.exists(filename):\n raise ValueError(\"File not found!\")\n\n with open(filename, \"rb\") as f:\n binary = f.read()\n self._stub.ProgramTask(proto.ProgramTaskRequest(name=taskname, task=binary))\n\n @ServiceHubCall(errormsg=\"Failed to compile and load task binary\")\n def load_task_source(self, filename, taskname):\n \"\"\"Loads a task source file `filename` into the taskrunner.\n `taskname` can be freely chosen to later identify the task on the platform.\n\n :param filename:\n name of the file with the task\n :param taskname:\n name of the task\n \"\"\"\n if os.path.isfile(filename):\n # File name can be full path to a file\n filepath = filename\n else:\n # or just the file name -> pick from task repository\n filepath = get_task_source(filename)\n\n with open(filepath, \"rb\") as f:\n binary = f.read()\n\n self._stub.CompileTask(proto.ProgramTaskRequest(name=taskname, task=binary))\n\n @ServiceHubCall(errormsg=\"Failed to set parameters\")\n def set_param_list(self, param_list):\n \"\"\"Sets the parameters for the task. param_list has to be an array of 32bit values.\"\"\"\n self._stub.SetParameter(proto.ParameterRequest(parameters=param_list))\n\n class DataMode(Enum):\n INT8 = 1\n UINT8 = 2\n INT16 = 3\n UINT16 = 4\n INT32 = 5\n UINT32 = 6\n INT64 = 7\n UINT64 = 8\n\n @ServiceHubCall(errormsg=\"Failed to fetch databoxes from taskrunner\")\n def get_databoxes_with_mode(\n self, mode=DataMode.INT32, require_done=True\n ) -> List[List[Any]]:\n \"\"\"Retrieves data from a previously started task on the R5.\n Depending on the parameter mode, the data is interpreted differently.\n\n :param mode:\n DataMode of the databoxes, by default DataMode.INT32\n :param require_done:\n if the task has to be finished before fetching data, by default True\n\n :return:\n A list of databoxes, being list of values themselves, either int32 or uint32.\n\n :raises Exception:\n If require_done is True and the Task is not finished\n :raises ValueError:\n If the data mode is not known\n :raises Exception:\n If require_done and not data is available\n \"\"\"\n self.check_task_errors()\n\n if require_done and not self.task_done:\n raise RuntimeError(\"Task should be finished prior to fetching data.\")\n\n method_call = {\n TaskRunner.DataMode.INT8: self._stub.GetDataboxesINT8,\n TaskRunner.DataMode.UINT8: self._stub.GetDataboxesUINT8,\n TaskRunner.DataMode.INT16: self._stub.GetDataboxesINT16,\n TaskRunner.DataMode.UINT16: self._stub.GetDataboxesUINT16,\n TaskRunner.DataMode.INT32: self._stub.GetDataboxesINT32,\n TaskRunner.DataMode.UINT32: self._stub.GetDataboxesUINT32,\n TaskRunner.DataMode.INT64: self._stub.GetDataboxesINT64,\n TaskRunner.DataMode.UINT64: self._stub.GetDataboxesUINT64,\n }.get(mode, None)\n if method_call is None:\n raise ValueError(\"Data mode is unknown! Only use DataMode Enum values.\")\n\n databoxes: List[List[Any]] = []\n last_index = -1\n for databox_reply in method_call(proto.Empty()):\n # print databox_reply.index, databox_reply.data[:]\n if last_index != databox_reply.index:\n # Create new (empty) databox in list\n databoxes.append([])\n last_index = databox_reply.index\n # Fill the latest databox with content\n databoxes[-1].extend(databox_reply.data[:])\n\n if require_done and not databoxes:\n raise RuntimeError(\n \"No data available to fetch. Are you sure the task completed successfully?\"\n )\n\n return databoxes\n\n def get_databoxes(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 32bit signed integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.INT32, require_done)\n\n def get_databoxes_INT8(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 8bit signed integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.INT8, require_done)\n\n def get_databoxes_UINT8(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 8bit unsigned integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.UINT8, require_done)\n\n def get_databoxes_INT16(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 16bit signed integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.INT16, require_done)\n\n def get_databoxes_UINT16(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 16bit unsigned integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.UINT16, require_done)\n\n def get_databoxes_INT32(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 32bit signed integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.INT32, require_done)\n\n def get_databoxes_UINT32(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 32bit unsigned integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.UINT32, require_done)\n\n def get_databoxes_INT64(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 64bit signed integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.INT64, require_done)\n\n def get_databoxes_UINT64(self, require_done=True):\n \"\"\"Retrieves data from a previously started task on the R5.\n\n Data is interpreted as 64bit unsigned integer values which are returned as array.\n \"\"\"\n return self.get_databoxes_with_mode(TaskRunner.DataMode.UINT64, require_done)\n\n @ServiceHubCall\n def get_error_messages(self):\n \"\"\"Retrieves all error messages from the task\"\"\"\n reply = self._stub.GetTaskErrorMessages(proto.Empty())\n return reply.message[:]\n\n def check_task_errors(self):\n errors = self.get_error_messages()\n if errors:\n raise RuntimeError(\n \"The following error messages were retrieved \"\n + \"from the Taskrunner:\\n{}\".format(\"\\n\".join(errors))\n )\n\n # DEPRECATED STUFF\n @property\n def data_size(self):\n \"\"\"TODO Replace by progress in all experiments.\"\"\"\n raise DeprecationWarning(\n \"data_size is not supported anymore! Use task_progress instead!\"\n )" }, { "identifier": "DataProvider", "path": "src/qiclib/experiment/qicode/data_provider.py", "snippet": "class DataProvider(ABC):\n \"\"\"\n Provides uniform access to experiment result data.\n\n Result data is received either from the taskrunner plugin or the unit cell plugin and comes in different formats.\n This class encapsulates the format differences, to allow for further processing of the data to be handled\n independently.\n \"\"\"\n\n @classmethod\n def create(cls, result, use_taskrunner: bool):\n if use_taskrunner:\n return _TaskrunnerDataProvider(result)\n return _InternalPluginDataProvider(result)\n\n def __init__(self, result):\n self._result = result\n\n @abstractmethod\n def get_raw_i(self, cell_index: int):\n pass\n\n @abstractmethod\n def get_raw_q(self, cell_index: int):\n pass\n\n def get_default_i(self, cell_index: int, index: int):\n return self.get_raw_i(cell_index)[index]\n\n def get_default_q(self, cell_index: int, index: int):\n return self.get_raw_q(cell_index)[index]\n\n def get_amp_pha_i(self, cell_index: int, index: int):\n return self.get_default_i(cell_index, index)\n\n def get_amp_pha_q(self, cell_index: int, index: int):\n return self.get_default_q(cell_index, index)\n\n @abstractmethod\n def get_iq_cloud_i(self, cell_index: int, index: int, recording_count: int):\n pass\n\n @abstractmethod\n def get_iq_cloud_q(self, cell_index: int, index: int, recording_count: int):\n pass\n\n def get_states(self, cell_index: int):\n return self._result[cell_index]\n\n def get_counts(self):\n return self.get_states(0)" }, { "identifier": "DataHandler", "path": "src/qiclib/experiment/qicode/data_handler.py", "snippet": "class DataHandler(ABC):\n \"\"\"\n Each subclass of this one handles a different way to process result data, depending on the type of experiment run.\n This usually includes splitting it up for the different boxes.\n It takes a list of cells and the recording data provider and processes it however it sees fit.\n In order to find out the box in which to store a recording it can access the `_result_recording_order` of a cell\n which provides the correct QiResult for the n-th executed recording.\n For examples, see the subclasses.\n\n :param data_provider: to access the experiments results\n :param cell_list: to store processed results there\n \"\"\"\n\n @staticmethod\n def _data_handler_factories() -> (\n Dict[str, Callable[[DataProvider, List[\"QiCell\"], int], \"DataHandler\"]]\n ):\n \"\"\"\n This is a method instead of a static variable, because forward references to the subclasses are not possible in\n static variable assignments.\n \"\"\"\n return {\n \"average\": lambda data_provider, cell_list, averages: _DefaultDataHandler(\n data_provider, cell_list\n ),\n \"amp_pha\": lambda data_provider, cell_list, averages: _AmplitudePhaseDataHandler(\n data_provider, cell_list\n ),\n \"iqcloud\": lambda data_provider, cell_list, averages: _IQCloudDataHandler(\n data_provider, cell_list\n ),\n \"raw\": lambda data_provider, cell_list, averages: _RawDataHandler(\n data_provider, cell_list\n ),\n \"states\": _StateDataHandler,\n \"counts\": lambda data_provider, cell_list, averages: _CountDataHandler(\n data_provider, cell_list\n ),\n \"quantum_jumps\": lambda data_provider, cell_list, averages: _QuantumJumpsDataHandler(\n data_provider, cell_list\n ),\n \"custom\": lambda data_provider, cell_list, averages: _NotImplementedDataHandler(\n data_provider, cell_list\n ),\n }\n\n @staticmethod\n def names():\n return DataHandler._data_handler_factories().keys()\n\n @classmethod\n def get_factory_by_name(\n cls, name: str\n ) -> Optional[Callable[[DataProvider, List[\"QiCell\"], int], \"DataHandler\"]]:\n factories = DataHandler._data_handler_factories()\n if name not in factories:\n return None\n return factories[name]\n\n @classmethod\n def get_custom_wrapper_factory(\n cls, custom_data_handler: Callable[[List[\"QiCell\"], DataProvider], None]\n ) -> Callable[[DataProvider, List[\"QiCell\"], int], \"DataHandler\"]:\n return lambda data_provider, cell_list, averages: _CustomDataHandlerWrapper(\n data_provider, cell_list, custom_data_handler\n )\n\n def __init__(self, data_provider: DataProvider, cell_list: List[\"QiCell\"]):\n self.data_provider = data_provider\n self.cell_list = cell_list\n\n @abstractmethod\n def process_results(self):\n pass" }, { "identifier": "SequencerInstruction", "path": "src/qiclib/code/qi_seq_instructions.py", "snippet": "class SequencerInstruction:\n OPCODE_WIDTH = 7\n FUNCT3_WIDTH = 3\n FUNCT7_WIDTH = 7\n REGISTER_WIDTH = 5\n LOWER_IMMEDIATE_WIDTH = 12\n UPPER_IMMEDIATE_WIDTH = 20\n\n LOWER_IMM_MAX = (\n 2 ** (LOWER_IMMEDIATE_WIDTH - 1)\n ) - 1 # Lower immediate 12 Bits - 1Bit Signed\n LOWER_IMM_MIN = -(2 ** (LOWER_IMMEDIATE_WIDTH - 1))\n\n UPPER_IMM_MAX = (\n 2 ** (UPPER_IMMEDIATE_WIDTH - 1)\n ) - 1 # Upper immediate 20 Bits - 1Bit Signed\n UPPER_IMM_MIN = -(2 ** (UPPER_IMMEDIATE_WIDTH - 1))\n UPPER_IMM_MAX_UNSIGNED = 2**UPPER_IMMEDIATE_WIDTH\n\n imm_type = Union[int] # might include float in the future\n\n def __init__(self, OpCode: SeqOpCode) -> None:\n self.op = OpCode\n\n @staticmethod\n def is_value_in_lower_immediate(val: imm_type) -> bool:\n return (\n SequencerInstruction.LOWER_IMM_MIN\n <= val\n <= SequencerInstruction.LOWER_IMM_MAX\n )\n\n @staticmethod\n def is_value_in_unsigned_upper_immediate(val: imm_type) -> bool:\n return SequencerInstruction.UPPER_IMM_MAX_UNSIGNED >= abs(val)\n\n @abstractmethod\n def get_riscv_instruction(self) -> int:\n pass" }, { "identifier": "_QiVariableBase", "path": "src/qiclib/code/qi_var_definitions.py", "snippet": "class _QiVariableBase(QiExpression):\n \"\"\"Base class for QiVariables.\n Variables can be relevant to only a subset of QiCells, this subset is saved in _relevant_cells.\n Variables are simple expressions and, therefore, are typed.\n Variables can be compared by self.id.\"\"\"\n\n id_iter = itertools.count()\n str_id_iter = itertools.count()\n\n def __init__(\n self,\n type: QiType,\n value: Optional[Union[int, float]] = None,\n name=None,\n ):\n from .qi_jobs import QiCell\n\n assert isinstance(type, QiType)\n assert value is None or isinstance(value, (int, float))\n\n super().__init__()\n\n if type != QiType.UNKNOWN:\n self._type_info.set_type(type, _TypeDefiningUse.VARIABLE_DEFINITION)\n\n self.value = value\n\n self._value = value\n self._relevant_cells: Set[QiCell] = set()\n self.id = next(_QiVariableBase.id_iter)\n self.str_id = next(_QiVariableBase.str_id_iter)\n\n self._contained_variables.add(self)\n\n self.name = name\n\n @property\n def contained_variables(self):\n return self._contained_variables\n\n @staticmethod\n def reset_str_id():\n _QiVariableBase.str_id_iter = itertools.count()\n\n def accept(self, visitor: QiExpressionVisitor):\n visitor.visit_variable(self)\n\n def _equal_syntax(self, other: \"QiExpression\") -> bool:\n return isinstance(other, _QiVariableBase) and self.id == other.id\n\n def __hash__(self) -> int:\n return self.id\n\n def __str__(self) -> str:\n return f\"QiVariable({self.name or ''})\"" }, { "identifier": "_QiCalcBase", "path": "src/qiclib/code/qi_var_definitions.py", "snippet": "class _QiCalcBase(QiExpression):\n \"\"\"Represents binary and unary operations.\"\"\"\n\n def __init__(self, val1, op, val2) -> None:\n super().__init__()\n\n self.val1 = val1\n self.op: QiOp = op\n self.val2 = val2\n\n from .qi_types import add_qi_calc_constraints\n\n add_qi_calc_constraints(op, val1, val2, self)\n\n @property\n def contained_variables(self):\n \"\"\"Function traverses the operation tree to determine which QiVariables are used for the calculations.\n Found QiVariables are added to _contained_variables\"\"\"\n if len(self._contained_variables) == 0:\n self._variables_to_container()\n\n return self._contained_variables\n\n def accept(self, visitor: QiExpressionVisitor):\n visitor.visit_calc(self)\n\n def _equal_syntax(self, other: \"QiExpression\") -> bool:\n return (\n isinstance(other, _QiCalcBase)\n and self.op == other.op\n and self.val1._equal_syntax(other.val1)\n and self.val2._equal_syntax(other.val2)\n )\n\n def __str__(self):\n return (\n \"(\"\n + self.val1.__str__()\n + \" \"\n + self.op.value\n + \" \"\n + self.val2.__str__()\n + \")\"\n )" }, { "identifier": "_QiConstValue", "path": "src/qiclib/code/qi_var_definitions.py", "snippet": "class _QiConstValue(QiExpression):\n \"\"\"Represents QiExpression which are a constant (compiletime known) values.\n Integers can be used as either NORMAL, TIME or FREQUENCY values. It is up to the type inference to figure it out.\n If the value can be represented as a float value it has an additional attribute float_value which represents the value before\n it has been converted to the integer representation used by the sequencer.\n \"\"\"\n\n def __init__(self, value: Union[int, float]):\n super().__init__()\n\n self._given_value = value # Value given to the constructor. Is interpreted differently depending on the type.\n\n # Constant STATE values can only be 0 or 1, therefore we forbid QiType.STATE if we have a different value.\n if isinstance(self._given_value, float) or self._given_value not in [1, 0]:\n self._type_info.add_illegal_type(\n QiType.STATE, _IllegalTypeReason.INVALID_STATE_CONSTANT\n )\n\n if isinstance(self._given_value, float):\n self._type_info.add_illegal_type(\n QiType.NORMAL, _IllegalTypeReason.INVALID_NORMAL_CONSTANT\n )\n\n @property\n def float_value(self):\n assert self.type in (QiType.TIME or self.type, QiType.FREQUENCY)\n return self._given_value\n\n @property\n def value(self):\n \"\"\"\n Integer representation of the constant value.\n Since the sequencer doesn't have a floating point unit, any calculations has to be using integers.\n In practice, this means we only perform fixpoint arithmetic and need to convert any float like value\n to such an fixpoint value.\n The correct conversion depends on the type.\n \"\"\"\n if self.type in (QiType.NORMAL, QiType.STATE, QiType.UNKNOWN):\n return self._given_value\n elif self.type == QiType.TIME:\n return int(util.conv_time_to_cycles(self._given_value, \"ceil\"))\n else:\n assert self.type == QiType.FREQUENCY\n return util.conv_freq_to_nco_phase_inc(self._given_value)\n\n @property\n def contained_variables(self):\n return QiVariableSet()\n\n def accept(self, visitor: QiExpressionVisitor):\n visitor.visit_constant(self)\n\n def _equal_syntax(self, other: \"QiExpression\") -> bool:\n assert QiType.UNKNOWN not in (self.type, other.type)\n return isinstance(other, _QiConstValue) and self.value == other.value\n\n def __str__(self):\n if self.type in (QiType.TIME, QiType.FREQUENCY):\n value = self.float_value\n elif self.type in (QiType.NORMAL, QiType.STATE, QiType.UNKNOWN):\n value = self.value\n else:\n raise RuntimeError(\n \"This program point should be unreacheable. Please file a bug report.\"\n )\n return f\"{value:g}\"" }, { "identifier": "QiCellProperty", "path": "src/qiclib/code/qi_var_definitions.py", "snippet": "class QiCellProperty(QiExpression):\n \"\"\"When describing experiments, properties of cells might not yet be defined. Instead a QiCellProperty object will be generated.\n This object can be used as length definition in cQiWait commands and QiPulse\"\"\"\n\n def __init__(self, cell, name):\n super().__init__()\n from .qi_jobs import QiCell\n\n self.name: str = name\n self.cell: QiCell = cell\n self.operations = lambda val: val\n self.opcode = \"x\"\n\n @property\n def opcode_p(self):\n \"\"\"Old opcode in parantheses for building new opcode\"\"\"\n return self.opcode if self.opcode == \"x\" else f\"({self.opcode})\"\n\n def resolve_equal(self, o: object) -> bool:\n if isinstance(o, QiCellProperty):\n return self.name == o.name and self.opcode == o.opcode\n elif o is None:\n return False\n try:\n return o == self()\n except KeyError:\n return False # At time of comparison, unresolved property is not equal to o\n\n def __call__(self):\n value = self.cell._properties.get(self.name)\n\n if isinstance(value, QiCellProperty) or value is None:\n raise KeyError(\"Property could not be resolved\")\n return self.operations(value)\n\n @property\n def value(self):\n if self.type == QiType.TIME:\n return util.conv_time_to_cycles(self())\n elif self.type == QiType.FREQUENCY:\n return util.conv_freq_to_nco_phase_inc(self())\n elif self.type == QiType.NORMAL:\n return self()\n elif self.type == QiType.STATE:\n return self()\n else:\n raise RuntimeError(\n \"Mising type information to resolve value to convert to a machine value.\"\n )\n\n @property\n def float_value(self):\n assert self.type in (QiType.TIME, QiType.FREQUENCY)\n return self()\n\n @abstractmethod\n def accept(self, visitor: QiExpressionVisitor):\n visitor.visit_cell_property(self)\n\n @property\n def contained_variables(self):\n return QiVariableSet()\n\n def _equal_syntax(self, other: \"QiExpression\") -> bool:\n return isinstance(other, QiCellProperty) and self.resolve_equal(other)\n\n def move_add_op_to_property(self, x: _QiConstValue):\n if x._given_value == 0:\n return self\n old_op = self.operations # Necessary because of recursion otherwise\n self.operations = lambda val: old_op(val) + x.value\n self.opcode = f\"{self.opcode_p} + {x}\"\n return self\n\n def move_radd_op_to_property(self, x: _QiConstValue):\n if x._given_value == 0:\n return self\n old_op = self.operations\n self.operations = lambda val: x.value + old_op(val)\n self.opcode = f\"{self.opcode_p} + {x}\"\n return self\n\n def move_sub_op_to_property(self, x: _QiConstValue):\n if x._given_value == 0:\n return self\n old_op = self.operations\n self.operations = lambda val: old_op(val) - x.value\n self.opcode = f\"{self.opcode_p} - {x}\"\n return self\n\n def move_rsub_op_to_property(self, x: _QiConstValue):\n old_op = self.operations\n self.operations = lambda val: x.value - old_op(val)\n self.opcode = f\"{x} - {self.opcode_p}\"\n return self\n\n def move_mul_op_to_property(self, x: _QiConstValue):\n if x._given_value == 1:\n return self\n old_op = self.operations\n self.operations = lambda val: old_op(val) * x.value\n self.opcode = f\"{x} * {self.opcode_p}\"\n return self\n\n def move_rmul_op_to_property(self, x: _QiConstValue):\n if x._given_value == 1:\n return self\n old_op = self.operations\n self.operations = lambda val: x.value * old_op(val)\n self.opcode = f\"{x} * {self.opcode_p}\"\n return self\n\n # These operations are not implemented for general QiExpressions\n # and are, therefore, left as they are.\n\n def __truediv__(self, x):\n if (isinstance(x, _QiConstValue) and x._given_value == 1) or x == 1:\n return self\n old_op = self.operations\n self.operations = lambda val: old_op(val) / x\n self.opcode = f\"{self.opcode_p} / {x}\"\n return self\n\n def __rtruediv__(self, x):\n old_op = self.operations\n self.operations = lambda val: x / old_op(val)\n self.opcode = f\"{x} / {self.opcode_p}\"\n return self" }, { "identifier": "QiExpression", "path": "src/qiclib/code/qi_var_definitions.py", "snippet": "class QiExpression:\n \"\"\"Superclass of every possible qicode expression.\"\"\"\n\n def __init__(self):\n self._contained_variables = QiVariableSet()\n self._type_info = _TypeInformation(self)\n\n @property\n def type(self):\n return self._type_info.type\n\n @staticmethod\n def _from(x):\n \"\"\"Creates an instance of QiExpression of the provided argument if possible.\"\"\"\n if isinstance(x, (float, int)):\n return _QiConstValue(x)\n elif isinstance(x, QiExpression):\n return x\n else:\n raise RuntimeError(f\"Can not create QiExpression from type {type(x)}.\")\n\n @abstractmethod\n def accept(self, visitor: QiExpressionVisitor):\n raise NotImplementedError(\n f\"{self.__class__} has not implemented `accept`. This is a bug.\"\n )\n\n @property\n def contained_variables(self):\n \"\"\"Returns the variables used in this expression.\n QiExpression subclasses which contain variables (_QiCalcBase and _QiVariableBase) need to overwrite this.\n \"\"\"\n raise NotImplementedError(\n f\"{self.__class__} has not implemented `contained_variables`. This is a bug.\"\n )\n\n def _variables_to_container(self):\n if isinstance(self, _QiVariableBase):\n self._contained_variables.add(self)\n elif isinstance(self, _QiCalcBase):\n self._contained_variables.update(self.val1.contained_variables)\n self._contained_variables.update(self.val2.contained_variables)\n\n def _equal_syntax(self, other: \"QiExpression\") -> bool:\n raise NotImplementedError(\n f\"{self.__class__} has not implemented `_equal_syntax`. This is a bug.\"\n )\n\n # QiCellProperties are supposed to support some form of constant folding.\n # However, originally, instead of implementing this in an extra pass over\n # QiJob they were added to the QiCellProperty class.\n # In order to keep support for this limited form of constant folding\n # This logic was placed here.\n\n # (I'm not sure why we don't fold when both operands are QiCellProperty.\n # And I think the reason we don't fold tow _QiConstValue is that originally\n # They were just int/float and would \"fold\" implicitely when using any\n # math operator on them)\n\n # If anyone ever feels the need to improve this situation, I would\n # encourage them to implement a constant folding pass using the existing\n # dataflow infrastructure.\n # This pdf seems to give a nice short introduction into the topic:\n # http://openclassroom.stanford.edu/MainFolder/courses/Compilers/docs/slides/15-02-constant-propagation-annotated.pdf\n\n def __add__(self, x):\n x = QiExpression._from(x)\n if isinstance(self, QiCellProperty) and isinstance(x, _QiConstValue):\n return self.move_add_op_to_property(x)\n elif isinstance(self, _QiConstValue) and isinstance(x, QiCellProperty):\n return x.move_radd_op_to_property(self)\n else:\n return _QiCalcBase(self, QiOp.PLUS, x)\n\n def __radd__(self, x):\n x = QiExpression._from(x)\n if isinstance(self, QiCellProperty) and isinstance(x, _QiConstValue):\n return self.move_radd_op_to_property(x)\n elif isinstance(self, _QiConstValue) and isinstance(x, QiCellProperty):\n return x.move_add_op_to_property(self)\n else:\n return _QiCalcBase(x, QiOp.PLUS, self)\n\n def __sub__(self, x):\n x = QiExpression._from(x)\n if isinstance(self, QiCellProperty) and isinstance(x, _QiConstValue):\n return self.move_sub_op_to_property(x)\n elif isinstance(self, _QiConstValue) and isinstance(x, QiCellProperty):\n return x.move_rsub_op_to_property(self)\n else:\n return _QiCalcBase(self, QiOp.MINUS, x)\n\n def __rsub__(self, x):\n x = QiExpression._from(x)\n if isinstance(self, QiCellProperty) and isinstance(x, _QiConstValue):\n return self.move_rsub_op_to_property(x)\n elif isinstance(self, _QiConstValue) and isinstance(x, QiCellProperty):\n return x.move_sub_op_to_property(self)\n else:\n return _QiCalcBase(x, QiOp.MINUS, self)\n\n def __mul__(self, x):\n x = QiExpression._from(x)\n if isinstance(self, QiCellProperty) and isinstance(x, _QiConstValue):\n return self.move_mul_op_to_property(x)\n elif isinstance(self, _QiConstValue) and isinstance(x, QiCellProperty):\n return x.move_rmul_op_to_property(self)\n else:\n return _QiCalcBase(self, QiOp.MULT, x)\n\n def __rmul__(self, x):\n x = QiExpression._from(x)\n if isinstance(self, QiCellProperty) and isinstance(x, _QiConstValue):\n return self.move_rmul_op_to_property(x)\n elif isinstance(self, _QiConstValue) and isinstance(x, QiCellProperty):\n return x.move_mul_op_to_property(self)\n else:\n return _QiCalcBase(x, QiOp.MULT, self)\n\n def __lshift__(self, x):\n return _QiCalcBase(self, QiOp.LSH, QiExpression._from(x))\n\n def __rshift__(self, x):\n return _QiCalcBase(self, QiOp.RSH, QiExpression._from(x))\n\n def __and__(self, x):\n return _QiCalcBase(self, QiOp.AND, QiExpression._from(x))\n\n def __rand__(self, x):\n return _QiCalcBase(QiExpression._from(x), QiOp.AND, self)\n\n def __or__(self, x):\n return _QiCalcBase(self, QiOp.OR, QiExpression._from(x))\n\n def __ror__(self, x):\n return _QiCalcBase(QiExpression._from(x), QiOp.OR, self)\n\n def __xor__(self, x):\n return _QiCalcBase(self, QiOp.XOR, QiExpression._from(x))\n\n def __rxor__(self, x):\n return _QiCalcBase(QiExpression._from(x), QiOp.XOR, self)\n\n def __invert__(self):\n return _QiCalcBase(self, QiOp.NOT, None)\n\n def __lt__(self, x):\n return QiCondition(self, QiOpCond.LT, QiExpression._from(x))\n\n def __le__(self, x):\n return QiCondition(self, QiOpCond.LE, QiExpression._from(x))\n\n def __gt__(self, x):\n return QiCondition(self, QiOpCond.GT, QiExpression._from(x))\n\n def __ge__(self, x):\n return QiCondition(self, QiOpCond.GE, QiExpression._from(x))\n\n def __eq__(self, x):\n return QiCondition(self, QiOpCond.EQ, QiExpression._from(x))\n\n def __ne__(self, x):\n return QiCondition(self, QiOpCond.NE, QiExpression._from(x))" }, { "identifier": "QiVariableSet", "path": "src/qiclib/code/qi_var_definitions.py", "snippet": "class QiVariableSet:\n \"\"\"Class provides Set functionality for QiVariables.\n QiVariables overwrite comparison operations to build operation trees, to still allow comparisons ids are used.\n \"\"\"\n\n def __init__(self) -> None:\n self._var_list: List[\"_QiVariableBase\"] = []\n self._var_id_list: List[int] = []\n\n def __contains__(self, x):\n return x.id in self._var_id_list\n\n def add(self, x: \"_QiVariableBase\"):\n if x.id not in self._var_id_list:\n self._var_id_list.append(x.id)\n self._var_list.append(x)\n\n def update(self, var_set):\n for var in var_set:\n self.add(var)\n\n def __iter__(self):\n self.n = 0\n return self\n\n def __next__(self):\n if self.n < len(self._var_list):\n var = self._var_list[self.n]\n self.n += 1\n return var\n else:\n raise StopIteration\n\n def __len__(self):\n return len(self._var_list)" }, { "identifier": "QiCondition", "path": "src/qiclib/code/qi_var_definitions.py", "snippet": "class QiCondition:\n \"\"\"Saves conditional comparisons.\n Can only be root node\"\"\"\n\n def __init__(\n self,\n val1: QiExpression,\n op: QiOpCond = QiOpCond.GT,\n val2: QiExpression = _QiConstValue(0),\n ) -> None:\n self._contained_variables = QiVariableSet()\n\n self.val1 = val1\n self.op = op\n self.val2 = val2\n\n from .qi_types import add_qi_condition_constraints\n\n add_qi_condition_constraints(op, val1, val2)\n\n @property\n def contained_variables(self):\n if len(self._contained_variables) == 0:\n self._contained_variables.update(self.val1.contained_variables)\n self._contained_variables.update(self.val2.contained_variables)\n\n return self._contained_variables\n\n def accept(self, visitor):\n visitor.visit_condition(self)\n\n def __str__(self) -> str:\n return f\"{self.val1} {self.op.value} {self.val2}\"" }, { "identifier": "QiPulse", "path": "src/qiclib/code/qi_pulse.py", "snippet": "class QiPulse:\n \"\"\"\n Class to describe a single pulse.\n\n :param length: length of the pulse. This can also be a QiVariable for variable pulse lengths.\n :param shape: pulse shape (i.e. rect, gauss, ...)\n :param amplitude: relative amplitude of your pulse. This can also be a QiVariable for variable pulse amplitudes. NOT IMPLEMENTED\n :param phase: phase of the pulse in deg. (i.e. 90 for pulse around y-axis of the bloch sphere)\n :param frequency: Frequency of your pulse, which is loaded to the PulseGen\n \"\"\"\n\n Type = Union[float, _QiVariableBase]\n\n def __init__(\n self,\n length: Union[float, _QiVariableBase, str],\n shape: Shape = ShapeLib.rect,\n amplitude: Union[float, _QiVariableBase] = 1.0,\n phase: float = 0.0,\n frequency: Union[float, QiExpression, None] = None,\n hold=False,\n ):\n from .qi_jobs import QiCellProperty\n\n if isinstance(length, str):\n mode = length.lower()\n if not mode in [\"cw\", \"off\"]:\n raise ValueError(\"QiPulse with str length only accepts 'cw' or 'off'.\")\n length = util.conv_cycles_to_time(1)\n if mode == \"cw\":\n hold = True\n else:\n amplitude = 0\n else:\n mode = \"normal\"\n\n self.mode = mode\n self.shape = shape\n self.amplitude = amplitude\n self.phase = phase\n self._length = length\n self.frequency = (\n QiExpression._from(frequency) if frequency is not None else None\n )\n self.hold = hold\n self.shift_phase = False\n\n if self.frequency is not None:\n self.frequency._type_info.set_type(\n QiType.FREQUENCY, _TypeDefiningUse.PULSE_FREQUENCY\n )\n\n self.var_dict = {}\n\n if isinstance(length, QiExpression):\n length._type_info.set_type(QiType.TIME, _TypeDefiningUse.PULSE_LENGTH)\n\n if isinstance(length, _QiVariableBase):\n self.var_dict[\"length\"] = length\n if shape != ShapeLib.rect:\n raise NotImplementedError(\n \"Variable pulse lengths are only supported for rectangular pulses\"\n )\n elif isinstance(length, QiCellProperty):\n pass\n elif util.conv_time_to_cycles(length) >= 2**32:\n raise RuntimeError(\n f\"Pulse length exceeds possible wait time, cycles {util.conv_time_to_cycles(length)}\"\n )\n\n if isinstance(amplitude, _QiVariableBase):\n raise NotImplementedError(\"Variable Amplitude not implemented yet\")\n # self.var_dict[\"amplitude\"] = amplitude\n\n def _are_variable_length(self, other) -> bool:\n return self.is_variable_length and other.is_variable_length\n\n def _are_same_length(self, other) -> bool:\n return (\n not isinstance(self._length, _QiVariableBase)\n and not isinstance(other._length, _QiVariableBase)\n and (self._length is other._length)\n )\n\n def _are_same_amplitude(self, other) -> bool:\n return (\n not isinstance(self.amplitude, _QiVariableBase)\n and not isinstance(other.amplitude, _QiVariableBase)\n and (self.amplitude == other.amplitude)\n )\n\n def __eq__(self, o: object) -> bool:\n equal_length: bool = isinstance(o, QiPulse) and (\n self._are_variable_length(o) or self._are_same_length(o)\n )\n equal_amplitude: bool = isinstance(o, QiPulse) and self._are_same_amplitude(o)\n\n return (\n isinstance(o, QiPulse)\n and equal_length\n and equal_amplitude\n and (self.hold == o.hold)\n and (self.shape == o.shape)\n and (self.phase == o.phase)\n and (\n self.frequency._equal_syntax(o.frequency)\n if self.frequency is not None and o.frequency is not None\n else self.frequency is o.frequency\n )\n )\n\n def __call__(self, samplerate: float, **variables: Any) -> np.ndarray:\n \"\"\"\n Returns the pulse envelope for a given frequency.\n :param samplerate: sample rate for calculating the envelope\n :param variables: the variables for the length/amplitude function, if any; legacy of qup_pulses\n\n :return: envelope of the pulse as numpy array.\n \"\"\"\n from .qi_jobs import QiCellProperty\n\n if self.is_variable_length:\n # variable pulses are hold till ended by another pulse, so no need to use correct length\n return np.array([self.amplitude] * 4)\n\n length = (\n self._length() if isinstance(self._length, QiCellProperty) else self._length\n )\n\n if (\n util.conv_time_to_cycles(length) >= 2**32\n ): # check value again, QiCellproperty might be used\n raise RuntimeError(\n f\"Pulse length exceeds possible wait time, cycles {util.conv_time_to_cycles(length)}\"\n )\n\n amplitude = self.amplitude\n timestep = 1.0 / samplerate\n\n if length < timestep / 2.0:\n if length != 0:\n logging.warning(\n \"A pulse is shorter than %f ns and thus is omitted.\", length * 1e09\n )\n\n return np.zeros(0)\n\n time_fractions = np.arange(0, length, timestep) / length\n envelope = amplitude * self.shape(time_fractions)\n\n return envelope\n\n @property\n def length(self):\n return self.var_dict.get(\"length\", self._length)\n\n @property\n def variables(self):\n return list(self.var_dict.values())\n\n @property\n def is_variable_length(self):\n return isinstance(self._length, _QiVariableBase)\n\n def _stringify_args(self) -> str:\n \"\"\"Determines non-default args to explicitly stringify\"\"\"\n arg_strings = []\n defaults = self.__init__.__defaults__\n\n if self.mode == \"normal\":\n arg_strings.append(str(self.length))\n else:\n arg_strings.append(f'\"{self.mode}\"')\n\n if self.shape != defaults[0]:\n arg_strings.append(f\"shape={self.shape}\")\n if not _equal(self.amplitude, defaults[1]) and self.mode != \"off\":\n arg_strings.append(f\"amplitude={self.amplitude}\")\n if not _equal(self.phase, defaults[2]):\n arg_strings.append(f\"phase={self.phase}\")\n if not _equal(self.frequency, defaults[3]):\n arg_strings.append(f\"frequency={self.frequency}\")\n\n return \", \".join(arg_strings)\n\n def _stringify(self) -> str:\n return f\"QiPulse({self._stringify_args()})\"" }, { "identifier": "QiCMContainedCellVisitor", "path": "src/qiclib/code/qi_visitor.py", "snippet": "class QiCMContainedCellVisitor(QiCommandVisitor):\n \"\"\"Visitor to check which cells are used inside context managers.\"\"\"\n\n def __init__(self) -> None:\n self.contained_cells: Set[QiCell] = set()\n\n def visit_cell_command(self, cell_cmd):\n self.contained_cells.update(cell_cmd._relevant_cells)\n\n def visit_context_manager(self, context_manager):\n visitor = QiCMContainedCellVisitor()\n for item in context_manager.body:\n item.accept(visitor)\n\n context_manager._relevant_cells.update(visitor.contained_cells)\n\n self.contained_cells.update(visitor.contained_cells)\n\n def visit_if(self, if_cm):\n visitor = QiCMContainedCellVisitor()\n for command in if_cm.body:\n command.accept(visitor)\n\n for command in if_cm._else_body:\n command.accept(visitor)\n\n if_cm._relevant_cells.update(visitor.contained_cells)\n\n self.contained_cells.update(visitor.contained_cells)\n\n def visit_parallel(self, parallel_cm):\n visitor = QiCMContainedCellVisitor()\n for cmd_list in parallel_cm.entries:\n for cmd in cmd_list:\n cmd.accept(visitor)\n\n parallel_cm._relevant_cells.update(visitor.contained_cells)\n\n self.contained_cells.update(visitor.contained_cells)\n\n def visit_variable_command(self, variable_cmd):\n self.contained_cells.update(variable_cmd._relevant_cells)\n\n def visit_sync_command(self, sync_cmd):\n self.contained_cells.update(sync_cmd._relevant_cells)\n\n def visit_asm_command(self, asm_cmd):\n self.contained_cells.update(asm_cmd._relevant_cells)\n\n def visit_mem_store_command(self, store_cmd):\n self.contained_cells.update(store_cmd._relevant_cells)" }, { "identifier": "QiResultCollector", "path": "src/qiclib/code/qi_visitor.py", "snippet": "class QiResultCollector(QiCommandVisitor):\n def __init__(self):\n # If there are multiple QiResults used, we need to\n # simulate in which order they record.\n self.found_qi_results = set()\n # We also collect the recordings which contain the qi_results above\n self.corresponding_recordings = set()\n\n # Is a recording which saves to a QiResult within an if.\n # In these cases we can not necessarily simulate the recording order.\n self.recording_in_if = False\n\n self.if_else_depth = 0\n\n def visit_cell_command(self, cell_cmd):\n from .qi_jobs import cQiRecording, cQiPlayReadout\n\n if isinstance(cell_cmd, cQiPlayReadout) and cell_cmd.recording is not None:\n cell_cmd = cell_cmd.recording\n\n if isinstance(cell_cmd, cQiRecording):\n if self.if_else_depth > 0:\n self.recording_in_if = True\n\n self.found_qi_results.add(cell_cmd.save_to)\n self.corresponding_recordings.add(cell_cmd)\n\n def visit_if(self, if_cm):\n self.if_else_depth += 1\n\n for cmd in if_cm.body:\n cmd.accept(self)\n\n for cmd in if_cm.body:\n cmd.accept(self)\n\n self.if_else_depth -= 1\n\n def visit_parallel(self, parallel_cm):\n for cmd in parallel_cm.body:\n cmd.accept(self)\n\n def visit_for_range(self, for_range_cm):\n for cmd in for_range_cm.body:\n cmd.accept(self)" }, { "identifier": "QiVarInForRange", "path": "src/qiclib/code/qi_visitor.py", "snippet": "class QiVarInForRange(QiCommandVisitor):\n \"\"\"Visitor used to visit QiCommands inside ForRange-Contextmanager. Raises error, if variable used in ForRange-Head is target of an Assign or Store\n command inside ForRange-Body. Additionally generates UserWarning when loop-variable is used inside Parallel-CM.\n \"\"\"\n\n def __init__(self, var) -> None:\n self.var = var\n\n def raise_exception(self):\n raise RuntimeError(\n \"Variable used in ForRange must not be used in internal Assign-Commands, var: \"\n + str(self.var)\n )\n\n def visit_cell_command(self, cell_cmd):\n from .qi_jobs import cQiStore\n\n if isinstance(cell_cmd, cQiStore):\n if id(cell_cmd.store_var) == id(self.var):\n self.raise_exception()\n\n def visit_context_manager(self, context_manager):\n for item in context_manager.body:\n item.accept(self)\n\n def visit_if(self, if_cm):\n for command in if_cm.body:\n command.accept(self)\n\n for command in if_cm._else_body:\n command.accept(self)\n\n def visit_parallel(self, parallel_cm):\n if self.var in parallel_cm._associated_variable_set:\n raise RuntimeError(\n \"Loop variable inside Parallel Context Manager might result in unexpected behaviour. \"\n \"Please unroll loop or change variable.\"\n )\n\n def visit_variable_command(self, variable_cmd):\n pass\n\n def visit_assign_command(self, assign_cmd):\n if id(assign_cmd.var) == id(self.var):\n self.raise_exception()\n\n def visit_sync_command(self, sync_cmd):\n pass" }, { "identifier": "QiProgramBuilder", "path": "src/qiclib/code/qi_prog_builder.py", "snippet": "class QiProgramBuilder:\n def __init__(\n self,\n cell_list: List[Any],\n cell_map: List[Any],\n command_list: List[Any],\n skip_nco_sync: bool = False,\n nco_sync_length: float = 0,\n ) -> None:\n from .qi_sequencer import Sequencer\n\n self.cell_seq_dict: Dict[Any, Sequencer] = {}\n self.result_boxes = []\n\n for cell, index in zip(cell_list, cell_map):\n self.cell_seq_dict[cell] = Sequencer(cell_index=index)\n\n for resultbox in cell._result_container.values():\n self.result_boxes.append(resultbox)\n\n self.cell_map = cell_map\n\n self.command_list = command_list\n\n self.skip_nco = skip_nco_sync\n self.nco_length = nco_sync_length\n\n @staticmethod\n def assign_cell_to_context_manager(commands: List[Any]):\n contained_cells_visitor = QiCMContainedCellVisitor()\n for command in commands:\n command.accept(contained_cells_visitor)\n\n @staticmethod\n def assign_variables_to_cell(commands: List[Any]):\n cell_to_variable_visitor = QiCmdVariableInspection()\n for command in reversed(commands):\n command.accept(cell_to_variable_visitor)\n\n QiProgramBuilder.assign_cell_to_context_manager(\n commands\n ) # run again, to ensure all Assignment statements are considered as well\n\n def build_program(self):\n for cell, sequencer in self.cell_seq_dict.items():\n cell.reset()\n\n if self.skip_nco is False:\n sequencer.add_nco_sync(self.nco_length)\n\n self.assign_cell_to_context_manager(self.command_list)\n\n self.assign_variables_to_cell(self.command_list)\n\n prog_builder = ProgramBuilderVisitor(self.cell_seq_dict, self.cell_map)\n\n for command in self.command_list:\n command.accept(prog_builder)\n\n for sequencer in self.cell_seq_dict.values():\n sequencer.end_of_program()\n\n return self.cell_seq_dict\n\n def get_all_variables(self) -> Dict[Any, Dict[Any, int]]:\n vars: Dict[Any, Dict[Any, int]] = {}\n for cell, seq in self.cell_seq_dict.items():\n for var in cell._relevant_vars:\n if var not in vars:\n vars[var] = {}\n vars[var][cell] = seq.get_var_register(var).adr\n return vars" }, { "identifier": "QiType", "path": "src/qiclib/code/qi_types.py", "snippet": "class QiType(Enum):\n \"\"\"The type that a :class:`~qiclib.code.qi_var_definitions.QiExpression` has.\"\"\"\n\n UNKNOWN = 0\n TIME = 1\n \"\"\"Time values contain some amount of times (in cycles) that, for example, can be used in wait commands.\n They are specified using float (seconds) and are converted to cycles automatically.\n \"\"\"\n STATE = 2\n \"\"\"State values are the result of a recording.\"\"\"\n NORMAL = 3\n \"\"\"Freely usable integer values.\"\"\"\n FREQUENCY = 4\n \"\"\"\n Frequency values can be used in the Play/PlayReadout commands and, like TIME, are specified using floats.\n \"\"\"" }, { "identifier": "QiPostTypecheckVisitor", "path": "src/qiclib/code/qi_types.py", "snippet": "class QiPostTypecheckVisitor(QiJobVisitor):\n \"\"\"Checks that every variable has an assigned type.\n The start and end values of ForRanges over time values are converted to cycles, because we only know with\n certainty whether they iterate over NORMAL or TIME values after the QiTypeFallbackVisitor has run.\n \"\"\"\n\n def __init__(self):\n pass\n\n def visit_for_range(self, for_range_cm):\n from qiclib.packages.constants import CONTROLLER_CYCLE_TIME\n from .qi_var_definitions import _QiConstValue, QiType\n from .qi_jobs import ForRange\n import numpy as np\n\n for_range_cm: ForRange = for_range_cm\n\n for_range_cm.var.accept(self)\n for_range_cm.start.accept(self)\n for_range_cm.end.accept(self)\n\n super().visit_for_range(for_range_cm)\n\n if for_range_cm.var.type == QiType.TIME:\n if isinstance(for_range_cm.start, _QiConstValue):\n if for_range_cm.start.value < 0:\n raise RuntimeError(\n f\"ForRange with negative time value ({for_range_cm.start._given_value}) are not allowed\"\n )\n\n if for_range_cm.end.value == 0:\n warnings.warn(\"End value of 0 will not be included in ForRange.\")\n\n # round to 11 decimals, if result is CONTROLLER_CYCLE_TIME then float modulo probably failed\n if (\n round(np.mod(for_range_cm.step._given_value, CONTROLLER_CYCLE_TIME), 11)\n != 0\n and round(\n np.mod(for_range_cm.step._given_value, CONTROLLER_CYCLE_TIME), 11\n )\n != CONTROLLER_CYCLE_TIME\n ):\n raise RuntimeError(\n f\"When using QiTimeVariables define step size as multiple of {CONTROLLER_CYCLE_TIME*1e9:.3g} ns.\"\n f\" (It is currently off by {np.mod(for_range_cm.step._given_value, CONTROLLER_CYCLE_TIME)*1e9:.3g} ns.)\"\n )\n elif (\n for_range_cm.var.type == QiType.FREQUENCY\n and isinstance(for_range_cm.end, _QiConstValue)\n and for_range_cm.end.value == 0\n ):\n warnings.warn(\"End value of 0 will not be included in ForRange.\")\n\n def visit_assign_command(self, assign_cmd):\n assign_cmd.var.accept(self)\n super().visit_assign_command(assign_cmd)\n\n def visit_constant(self, const):\n from .qi_var_definitions import QiType\n\n if const.type == QiType.UNKNOWN:\n raise TypeError(f\"Could not infer type of {const}.\")\n\n def visit_variable(self, var):\n from .qi_var_definitions import QiType\n\n if var.type == QiType.UNKNOWN:\n raise TypeError(f\"Could not infer type of {var}.\")\n\n def visit_calc(self, calc):\n from .qi_var_definitions import QiType\n\n super().visit_calc(calc)\n if calc.type == QiType.UNKNOWN:\n raise TypeError(f\"Could not infer type of {calc}.\")\n\n def visit_cell_property(self, cell_prop):\n if cell_prop.type == QiType.UNKNOWN:\n raise TypeError(f\"Could not infer type of {cell_prop}\")" }, { "identifier": "QiTypeFallbackVisitor", "path": "src/qiclib/code/qi_types.py", "snippet": "class QiTypeFallbackVisitor(QiJobVisitor):\n \"\"\"Sets the the fallback type to NORMAL for _QiConstValue if they weren't given a type during QiJob construction.\n This is important for qicode like the following:\n\n .. code-block:: python\n\n with ForRange(x, 0, 10, 1):\n ...\n\n Here, x could theoretically be either of type TIME or NORMAL because int literals can have either type.\n However, we want this code to compile to with integer semantics which is why we need this visitor to run\n after job construction. (see QiJob __exit__ method).\n \"\"\"\n\n def visit_for_range(self, for_range_cm):\n from .qi_var_definitions import QiType\n\n if for_range_cm.var.type == QiType.UNKNOWN:\n for_range_cm.var._type_info.set_type(QiType.NORMAL, _TypeFallback.INT)\n\n super().visit_for_range(for_range_cm)\n\n def visit_constant(self, const):\n from .qi_var_definitions import QiType\n\n if const.type == QiType.UNKNOWN:\n if isinstance(const._given_value, float):\n const._type_info.set_type(QiType.TIME, _TypeFallback.FLOAT)\n else:\n assert isinstance(const._given_value, int)\n const._type_info.set_type(QiType.NORMAL, _TypeFallback.INT)" }, { "identifier": "_TypeDefiningUse", "path": "src/qiclib/code/qi_types.py", "snippet": "class _TypeDefiningUse(_TypeFact, Enum):\n VARIABLE_DEFINITION = 0\n VALUE_DEFINITION = 1\n SHIFT_EXPRESSION = 2\n PULSE_LENGTH = 3\n RECORDING_SAVE_TO = 4\n WAIT_COMMAND = 5\n RECORDING_OFFSET_EXPRESSION = 6\n PULSE_FREQUENCY = 7\n\n def to_error_message(self) -> str:\n return {\n _TypeDefiningUse.VARIABLE_DEFINITION: \"has been defined by the user as this type\",\n _TypeDefiningUse.VALUE_DEFINITION: \"has been defined by the user as this type\",\n _TypeDefiningUse.SHIFT_EXPRESSION: \"is used as right hand side of shift expression\",\n _TypeDefiningUse.PULSE_LENGTH: \"is used as length of pulse\",\n _TypeDefiningUse.RECORDING_SAVE_TO: \"is used as save_to of recording command\",\n _TypeDefiningUse.WAIT_COMMAND: \"is used as length in wait command\",\n _TypeDefiningUse.RECORDING_OFFSET_EXPRESSION: \"is used as an recording offset\",\n _TypeDefiningUse.PULSE_FREQUENCY: \"is used as pulse frequency.\",\n }[self]" } ]
import os import json import functools import warnings import numpy as np import qiclib.packages.utility as util from abc import abstractmethod from typing import Dict, List, Callable, Optional, Union, Set, Any, Type from ..hardware.taskrunner import TaskRunner from ..experiment.qicode.data_provider import DataProvider from ..experiment.qicode.data_handler import DataHandler from .qi_seq_instructions import SequencerInstruction from .qi_var_definitions import ( _QiVariableBase, _QiCalcBase, _QiConstValue, QiCellProperty, QiExpression, QiVariableSet, QiCondition, ) from .qi_pulse import QiPulse from .qi_visitor import ( QiCMContainedCellVisitor, QiResultCollector, QiVarInForRange, ) from .qi_prog_builder import QiProgramBuilder from .qi_types import ( QiType, QiPostTypecheckVisitor, QiTypeFallbackVisitor, _TypeDefiningUse, ) from .qi_types import _TypeDefiningUse from .qi_types import _TypeDefiningUse from .qi_types import ( _TypeConstraintReasonQiCommand, _IllegalTypeReason, _add_equal_constraints, ) from .qi_types import ( _TypeConstraintReasonQiCommand, _IllegalTypeReason, _add_equal_constraints, ) from .analysis.qi_insert_mem_parameters import ( insert_recording_offset_store_commands, insert_manipulation_pulse_frequency_store_commands, insert_readout_pulse_frequency_store_commands, ) from .qi_simulate import Simulator from ..experiment.qicode.base import QiCodeExperiment from qiclib.experiment.qicode.base import _TaskrunnerSettings from .qi_visitor import QiStringifyJob
17,288
isinstance(cmd, cQiPlayReadout) and isinstance(cmd.recording, cQiRecording) ): end += length + util.conv_time_to_cycles( sequencer.recording_delay, "ceil" ) else: end += length cmd_duration = self.CmdTuple(cmd, start, end) commands.append(cmd_duration) if var_pulse: # Add parallel choke command after current command, if variable length is used parallel_choke = [self.CmdTuple(cmd, end, end + 1, choke=True)] parallel_bodies.append(parallel_choke) max_end = max(end + 1, max_end) # +1 to account for choke command else: max_end = max(end, max_end) start = end parallel_bodies.append(commands) return self._create_time_slots(parallel_bodies, max_end) def accept(self, visitor, *input): return visitor.visit_parallel(self, *input) def _stringify(self) -> str: return "Parallel" class ForRange(QiContextManager): """Adds ForRange to program. If multiple cells are used inside body, a synchronisation between the cells is done before the ForRange as well as after the end of the body. If QiTimeVariable is used as var, loops starting at 0 are unrolled, to skip pulses/waits inside body using var as length. Raises exception if start, end and step are not set up properly.""" def __init__( self, var: _QiVariableBase, start: Union[_QiVariableBase, int, float], end: Union[_QiVariableBase, int, float], step: Union[int, float] = 1, ): super().__init__() if not isinstance(var, _QiVariableBase): raise RuntimeError( "Can only use QiVariables as control variable in ForRanges." ) start_expr = QiExpression._from(start) end_expr = QiExpression._from(end) step_expr = QiExpression._from(step) var._type_info.add_illegal_type(QiType.STATE, _IllegalTypeReason.FOR_RANGE) start_expr._type_info.add_illegal_type( QiType.STATE, _IllegalTypeReason.FOR_RANGE ) end_expr._type_info.add_illegal_type(QiType.STATE, _IllegalTypeReason.FOR_RANGE) step_expr._type_info.add_illegal_type( QiType.STATE, _IllegalTypeReason.FOR_RANGE ) _add_equal_constraints( QiType.TIME, _TypeConstraintReasonQiCommand(ForRange), var, start_expr, end_expr, step_expr, ) _add_equal_constraints( QiType.FREQUENCY, _TypeConstraintReasonQiCommand(ForRange), var, start_expr, end_expr, step_expr, ) _add_equal_constraints( QiType.NORMAL, _TypeConstraintReasonQiCommand(ForRange), var, start_expr, end_expr, step_expr, ) if not isinstance(start, _QiVariableBase) and not isinstance( end, _QiVariableBase ): if (start > end and step >= 0) or (start < end and step <= 0): raise ValueError("Definition of ForRange faulty") self.var = var self.start = start_expr self.end = end_expr self.step = step_expr self.add_associated_variable(var) if isinstance(start, _QiVariableBase): self.add_associated_variable(start) if start.id == var.id: raise RuntimeError("Loop variable can not be used as start value") if isinstance(end, _QiVariableBase): self.add_associated_variable(end) if end.id == var.id: raise RuntimeError("Loop variable can not be used as end value") def __exit__(self, exception_type, exception_value, traceback): super().__exit__(exception_type, exception_value, traceback)
# Copyright © 2017-2023 Quantum Interface ([email protected]) # Richard Gebauer, IPE, Karlsruhe Institute of Technology # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """ This is the main module of QiCode. Here, all important commands write QiPrograms are defined. """ class QiResult: """Result of an experiment. Can be accessed via :python:`job.cells[cell_index].data("result name")`. Where :python:`cells` denotes a :class:`QiCells` object and :python:`cell_index` an integer. The actual data can be retrieved as a numpy array using the :meth:`get` Method Example ------- .. code-block:: python qic: QiController = ... sample: QiSample = ... with QiJob() as job: q = QiCells(1) Readout(q[0], save_to="result") job.run(qic, sample, averages=1000) data = job.cells[0].data("result") :param name: The name of the variable, by default None """ def __init__(self, name: Optional[str] = None) -> None: self._cell = None self.data = None self.recording_count = 0 self.name: str = "" if name is None else name def get(self) -> np.ndarray: """gets the data of the result as a numpy array :return: The data of the experiment """ return np.array(self.data) def __str__(self) -> str: return f'QiResult("{self.name}")' class QiCommand: """Base class of every Job command. Provides _relevant_cells, containing every cell used for the execution of the command. Provides _associated_variable_set, containing every variable needed for the execution of the command. """ def __init__(self) -> None: self._associated_variable_set = QiVariableSet() self._relevant_cells: Set[QiCell] = set() @abstractmethod def accept(self, visitor, *input): raise RuntimeError( f"{self.__class__} doesn't implement `accept`. This is a bug." ) def is_variable_relevant(self, variable: _QiVariableBase) -> bool: return variable in self._associated_variable_set def add_associated_variable(self, x): if isinstance(x, _QiVariableBase): self._associated_variable_set.add(x) def __str__(self) -> str: return "cQiCommand" def _stringify(self) -> str: raise NotImplementedError(f"_stringify not implemented for {repr(self)}") _QiJobReference = None def _add_cmd_to_job(cmd: QiCommand): if _QiJobReference is None: raise RuntimeError("Can not use command outside QiJob context manager.") _QiJobReference._add_command(cmd) def _set_job_reference(job): """Used for testing purposes""" # pylint: disable=global-statement global _QiJobReference _QiJobReference = job def _delete_job_reference(): """Used for testing purposes""" # pylint: disable=global-statement global _QiJobReference _QiJobReference = None class QiCell: """A QiCell is an abstract representation of the qubit/cell the program is run on. Usually, a single :python:`QiCell` is not instantiated, but instead a :class:`QiCells` object. For a single :python:`QiCell`, use instead :python:`QiCells(1)` A :python:`QiCell` must be instantiated inside within a :class:`QiJob` context. The :python:`QiCell` object can be used to get properties that are defined on :class:`QiSamples <QiSample>`. For this, index the :python:`QiCell` object using the name of the property: .. code-block:: python q: QiCell = ... t1_time = q["t1"] The actual value for the accessed property (in the example above, the T1 time) is filled in when executing a :class:`QiJob` and providing the actual sample. **Tasks of the QiCell**: - Saves the pulses needed for program execution. - Provides a dictionary functionality to define commonly used durations/properties. - Implements a Sequencer object, which contains the assembler program after compilation. :param cellID: A unique ID :raises RuntimeError: When the :python:`QiCell` is instantiated outside a `QiJob` """ def __init__(self, cellID: int): if not isinstance(_QiJobReference, QiJob): raise RuntimeError("QiCell can't be used outside of QiJob.") self.cellID = cellID self.manipulation_pulses: List[QiPulse] = [] self.flux_pulses: List[QiPulse] = [] self.readout_pulses: List[QiPulse] = [] self._result_container: Dict[str, QiResult] = {} # The order in which recorded values are assigned to which result container self._result_recording_order: List[QiResult] = [] self._unresolved_property: Set[QiCellProperty] = set() self._job_ref = _QiJobReference self._relevant_vars: Set[_QiVariableBase] = set() # These attributes are determined by dataflow analyses self._initial_manip_freq: float = None self._initial_readout_freq: float = None self._initial_rec_offset: float = None self._rec_length: Union[int, float, QiCellProperty] = None self._properties: Dict[QiCellProperty, Any] = {} def __getitem__(self, key): if _QiJobReference != self._job_ref: raise RuntimeError( "Tried getting values for cells registered to other QiJob" ) prop = self._properties.get(key, QiCellProperty(self, key)) if isinstance(prop, QiCellProperty): self._unresolved_property.add(key) return prop def __setitem__(self, key, value): if _QiJobReference != self._job_ref: raise RuntimeError( "Tried setting values for cells registered to other QiJob" ) self._properties[key] = value def __call__(self, qic): return qic.cell[self.qic_cell] def get_properties(self): return self._properties.copy() def add_pulse(self, pulse: QiPulse): if pulse not in self.manipulation_pulses: self.manipulation_pulses.append(pulse) if len(self.manipulation_pulses) > 13: raise RuntimeError("Too many pulses in use") return self.manipulation_pulses.index(pulse) + 1 # index 0 and 15 are reserved @property def initial_manipulation_frequency(self): if self._initial_manip_freq is None: if len(self.manipulation_pulses) > 0: warnings.warn( "Manipulation pulses without frequency given, using 90 MHz." ) return 90e6 # Default frequency freq = self._initial_manip_freq return freq() if isinstance(freq, QiCellProperty) else freq def add_recording_length(self, length): if self._rec_length is None: self._rec_length = length elif ( not self._rec_length._equal_syntax(length) if isinstance(self._rec_length, QiExpression) else self._rec_length != length ): raise RuntimeError( f"Cell {self.cellID}: Multiple definitions of recording length used." ) def add_readout_pulse(self, pulse: QiPulse): if pulse not in self.readout_pulses: self.readout_pulses.append(pulse) if len(self.readout_pulses) > 13: raise RuntimeError("Too many pulses in use") return self.readout_pulses.index(pulse) + 1 # index 0 and 15 are reserved @property def initial_readout_frequency(self): if self._initial_readout_freq is None: if len(self.readout_pulses) > 0: warnings.warn("Readout pulses without frequency given, using 30 MHz.") return 30e6 # Default frequency freq = self._initial_readout_freq return freq() if isinstance(freq, QiCellProperty) else freq @property def recording_length(self): """the length of the recording pulse""" if self._rec_length is not None: return ( self._rec_length() if isinstance(self._rec_length, QiCellProperty) else self._rec_length ) return 0 @property def initial_recording_offset(self): """the recording offset in seconds""" if self._initial_rec_offset is not None: return ( self._initial_rec_offset() if isinstance(self._initial_rec_offset, QiCellProperty) else self._initial_rec_offset ) return 0 def get_result_container(self, result: str) -> QiResult: if result in self._result_container: return self._result_container[result] # was already added else: box = QiResult(result) box._cell = self self._result_container[result] = box return box def add_variable(self, var: _QiVariableBase): self._relevant_vars.add(var) def get_number_of_recordings(self): return len(self._result_recording_order) def set_default_readout(self, pulse): pass def reset(self): for container in self._result_container.values(): container.data = [] def data( self, name: Optional[str] = None ) -> Union[Dict[str, np.ndarray], np.ndarray]: """ Returns the data after running an experiment. When calling this function without a name, i.e., calling :python:`cell.data()`, returns a dictionary containing the results as numpy arrays. When calling this function with a name, i.e., calling :python:`cell.data("result_name")`, returns the whole dictionary. :param name: The name of the data :return: A single result, or a dictionary of result names mapped to results. """ if name is None: result_dict = {} for key, container in self._result_container.items(): result_dict.update({key: container.get()}) return result_dict else: return self._result_container[name].get() def _resolve_properties(self, len_dict: Dict[QiCellProperty, Any]): keys = list(self._unresolved_property) missing_keys = self._unresolved_property.difference(len_dict.keys()) if missing_keys: raise RuntimeError( f"Cell {self.cellID}: Not all properties for job could be resolved. " f"Missing properties: {missing_keys}" ) for key in keys: self._properties[key] = len_dict[key] @property def has_unresolved_properties(self): return len(self._unresolved_property) > 0 def _get_unresolved_properties(self): return [ key for key in list(self._unresolved_property) if self._properties.get(key) is None ] def __str__(self) -> str: return f"QiCell({self.cellID})" class QiCells: """ QiCells encapsulates multiple :class`QiCell` objects. It is a list-like object where the individual cells can be accessed using the index operator, i.e. .. code-block:: python cells = QiCells(5) cell0: QiCell = cells[0] cell3: QiCell = cells[3] :param num: The number of cells to create :raises RuntimeError: When the :python:`QiCells` object is instantiated outside a :python:`QiJob` """ def __init__(self, num: int) -> None: if not isinstance(_QiJobReference, QiJob): raise RuntimeError( "QiCells can only be used within QiJob description. " + "If you try to create a sample object, use the new QiSample instead." ) self.cells = [QiCell(x) for x in range(num)] _QiJobReference._register_cells(self.cells) def __getitem__(self, key): return self.cells[key] def __len__(self): return len(self.cells) class QiSampleCell: """QiSampleCell is the representation of a single qubit/cell and its properties. All necessary parameters to perform experiments can be stored here. For this purpose, the QiSampleCell can be utilized as a dictionary with user-defined keys. """ def __init__(self, cellID: int, cells_ref: "QiSample"): self.cellID = cellID self._cells_ref = cells_ref self._relevant_vars: Set[_QiVariableBase] = set() self._properties: Dict[str, Any] = {} def __getitem__(self, key): return self._properties[key] def __setitem__(self, key, value): self._properties[key] = value def __call__(self, qic): return qic.cell[self.qic_cell] @property def qic_cell(self): return self._cells_ref.cell_map[self.cellID] def get_properties(self): return self._properties.copy() def __str__(self) -> str: return f"QiSampleCell({self.cellID})" def _export(self): return {"properties": self.get_properties()} def _import(self, prop_dict, index): if prop_dict is None: warnings.warn( f"Imported JSON string does not contain 'properties' for cell[{index}]." ) return self._properties.update(prop_dict) class QiSample: """Representation of an experiment sample and its properties. Property keys can be arbitrary strings, and property values can be anything. Set the keys using :python:`sample["property_key"] = property_value` and get the values the same way, i.e., :python:`property_value = sample["property_key"]`. Note that this class **cannot** be instantiated within a :class:`QiJob`. Instead, it must be defined outside one. Accessing samples defined here within a QiJob is still possible, however, using the :class:`QiCell` object: .. code-block:: python sample: QiSample = ... qic: QiController = ... sample["t1"] = 100e-6 with QiJob() as job: q = QiCells(1) Wait(q[0], q[0]["t1"]) job.run(qic, sample) # Note that we pass the sample object here to make the value available in the job The :python:`QiSample` object is serializable to `JSON <https://www.json.org/>`_. Have a look at the :meth:`save` and :meth:`load` methods for more :param num: The number of cells/qubits this sample has. :param cell_map: On which QiController cells these are mapped, by default [0, 1, ..., num-1] :raises RuntimeError: When the Sample is used within a :class:`QiJob` """ def __init__(self, num: int, cell_map: Optional[List[int]] = None) -> None: self._cell_map = None if _QiJobReference is not None: raise RuntimeError( "QiSample can only be used outside of QiJob to define sample " "properties. Inside a QiJob, use QiCells as placeholder for the " "qubits/cells instead." ) self.cells: List[QiSampleCell] = [] for x in range(num): self.cells.append(QiSampleCell(cellID=x, cells_ref=self)) self.cell_map = cell_map or list(range(num)) def __getitem__(self, key): return self.cells[key] def __len__(self): return len(self.cells) def __str__(self): return ( f"QiSample({len(self.cells)}, cell_map=[{','.join(map(str, self.cell_map))}]):\n" + "\n".join( [ f"[{i}]: {json.dumps(props['properties'], indent=2)}" for i, props in enumerate(self._export()["cells"]) ] ) ) def _arrange_for_controller(self) -> List[Optional[QiSampleCell]]: inverse: List[Optional[QiSampleCell]] = [None] * (max(self.cell_map) + 1) for cell, qi_cell_index in enumerate(self.cell_map): inverse[qi_cell_index] = self[cell] return inverse @property def cell_map(self): return self._cell_map @cell_map.setter def cell_map(self, cell_map): if len(cell_map) != len(self): raise ValueError( "cell_map needs to have as many entries as the there are cells, but " f"{len(cell_map)} entries given and {len(self)} required!" ) if len(set(cell_map)) != len(cell_map): raise ValueError("Duplicate values not allowed in cell_map!") if any(c < 0 for c in cell_map): raise ValueError("Cell indices inside cell_map cannot be negative!") self._cell_map = cell_map def _export(self): properties = [cell._export() for cell in self.cells] return {"cells": properties, "cell_map": self.cell_map} def _import(self, jsn_string): jsn_loaded = json.loads(jsn_string) self._evaluate_import(jsn_loaded.get("cells", None)) self.cell_map = jsn_loaded.get("cell_map", self.cell_map) def save(self, file_path: Union[str, os.PathLike], overwrite: bool = False): """ Save the sample to a file denoted by the :python:`file_path` argument in JSON format. :param file_path: Where to store the file :param overwrite: When true, allow overwriting an existing file. :raise FileExistsError: When overwrite is False and the file exists. """ mode = "w" if overwrite is True else "x" with open(file_path, mode, encoding="utf-8") as file: json.dump(self._export(), file) def load(self, file_path: Union[str, os.PathLike]): """ Loads the file at :python:`file_path` and assigns all properties of the loaded file to this :class:`QiSample` object. :param file_path: Where to look for the file """ with open(file_path, "r", encoding="utf-8") as file: self._import(file.read()) def _evaluate_import(self, sample): if sample is None: warnings.warn("Imported JSON string does not contain 'cells'.") return if len(sample) != len(self): raise ValueError( f"Imported JSON contains {len(sample)} sample cells but {len(self)} " "expected." ) for i in range(0, len(self)): self.cells[i]._import(sample[i].get("properties", None), i) class _JobDescription: """Saves experiment descriptions and handles storage of commands""" def __init__(self): self._commands: List[QiCommand] = [] self._ContextStack: List[List[QiCommand]] = [] def __getitem__(self, key): return self._commands[key] def __len__(self): return len(self._commands) def add_command(self, command): """Checks current command for used cells and raises error, if cells are not defined for current QiJob""" if isinstance(command, QiCellCommand): if _QiJobReference != command.cell._job_ref: raise RuntimeError("Cell not defined for current job") self._commands.append(command) def open_new_context(self): """Saves current commands in a stack and clears command list""" self._ContextStack.append(self._commands.copy()) self._commands = [] def close_context(self) -> List[QiCommand]: """returns the current command list, and loads the commands from top of stack""" current_commands = self._commands.copy() self._commands = self._ContextStack.pop() return current_commands def reset(self): self._commands = [] self._ContextStack = [] class QiCellCommand(QiCommand): """ Cell commands are commands using only one cell, such as Play and Wait commands. :param cell: The target cell """ def __init__(self, cell: QiCell): super().__init__() self.cell = cell self._relevant_cells.add(cell) def accept(self, visitor, *input): return visitor.visit_cell_command(self, *input) class QiVariableCommand(QiCommand): """Base class of variable commands cQiDeclare and cQiAssign""" def __init__(self, var: _QiVariableBase): super().__init__() self.var = var def accept(self, visitor, *input): return visitor.visit_variable_command(self, *input) class cQiWait(QiCellCommand): """Command generated by :meth:`Wait`""" def __init__(self, cell, length: Union[QiExpression, QiCellProperty]): super().__init__(cell) self._length = length if isinstance(length, _QiVariableBase): self.add_associated_variable(length) elif isinstance(length, _QiCalcBase): for variable in length.contained_variables: self.add_associated_variable(variable) if isinstance(length, QiExpression): length._type_info.set_type(QiType.TIME, _TypeDefiningUse.WAIT_COMMAND) @property def length(self): return ( self._length() if isinstance(self._length, QiCellProperty) else self._length ) def _stringify(self) -> str: return f"Wait({self.cell}, {self._length})" class _cQiPlay_base(QiCellCommand): """Base class of Play commands. Saves pulses, trigger_index and adds pulse variables to associated variable set """ def __init__(self, cell, pulse: QiPulse): super().__init__(cell) self.pulse = pulse # default False; Set True for certain commands when unrolling a loop with TimingVariable == 1 cycle self._var_single_cycle_trigger = False for variable in self.pulse.variables: self.add_associated_variable(variable) # length of command might differ from pulse length self._length: Union[float, _QiVariableBase, QiCellProperty] = self.pulse.length self.trigger_index = 0 @property def length(self): return ( self._length if not isinstance(self._length, QiCellProperty) else self._length() ) @length.setter def length(self, value): self._length = value class cQiPlay(_cQiPlay_base): """Command generated by Play()""" def __init__(self, cell, pulse: QiPulse): super().__init__(cell, pulse) self.trigger_index = cell.add_pulse(pulse) def _stringify(self) -> str: return f"Play({self.cell}, {self.pulse._stringify()})" class cQiPlayFlux(_cQiPlay_base): pass class cQiPlayReadout(_cQiPlay_base): """Command generated by :meth:`PlayReadout`""" def __init__(self, cell, pulse) -> None: super().__init__(cell, pulse) self.recording: Union[None, cQiRecording] = None self.trigger_index = cell.add_readout_pulse(pulse) @property def length(self): length = ( self._length if not isinstance(self._length, QiCellProperty) else self._length() ) # if Recording is defined and length is not defined by variable, compare both lengths if isinstance(self.recording, cQiRecording) and not isinstance( self._length, _QiVariableBase ): return max(length, self.recording.length) return length @length.setter def length(self, value): self._length = value if isinstance(self.recording, cQiRecording): self.recording.length = value @property def uses_state(self): return self.recording is not None and self.recording.uses_state def _stringify(self) -> str: return f"PlayReadout({self.cell}, {self.pulse._stringify()})" class cQiRotateFrame(_cQiPlay_base): """Command generated by :meth:`RotateFrame`""" def __init__(self, cell, angle: float): # Negate phase because frame needs to be shifted in the opposite direction # than pulses -> want to shift the state on bloch sphere but shift the frame pulse = QiPulse(0, phase=-1 * angle) pulse.shift_phase = True # Special property to make phase offset persistant super().__init__(cell, pulse) self.trigger_index = cell.add_pulse(pulse) self.length = util.conv_cycles_to_time(1) # command needs exactly one cycle self.angle = angle def _stringify(self) -> str: return f"RotateFrame({self.cell}, {self.angle})" class cQiSync(QiCommand): """Command generated by :meth:`Sync`""" def __init__(self, cells: List[QiCell]): super().__init__() self._relevant_cells.update(cells) def accept(self, visitor, *input): return visitor.visit_sync_command(self, *input) def _stringify(self) -> str: return ( "Sync(" + ", ".join( [ f"{cell}" for cell in sorted(self._relevant_cells, key=lambda c: c.cellID) ] ) + ")" ) class cQiRecording(QiCellCommand): """Command generated by Recording()""" def __init__( self, cell: QiCell, save_to: Union[str, _QiVariableBase, None], state_to: Union[_QiVariableBase, None], length: Union[int, float, QiCellProperty], offset: Union[int, float, QiExpression], toggleContinuous: Optional[bool] = None, ): super().__init__(cell) self.result_box = None self.var = None if ( isinstance(length, QiExpression) and length.type == QiType.STATE or isinstance(offset, QiExpression) and offset.type == QiType.STATE ): raise RuntimeError("State variable can only be used at save_to parameter.") if isinstance(state_to, _QiVariableBase): state_to._type_info.set_type( QiType.STATE, _TypeDefiningUse.RECORDING_SAVE_TO ) self.add_associated_variable(state_to) self.var = state_to self.save_to = save_to assert not isinstance( save_to, QiResult ) # support for QiResult as parameter was removed. if isinstance(save_to, _QiVariableBase): # TODO This should be deprecated and turned into new result variable # to handle I/Q values instead if necessary -> consistency if self.var is not None: raise RuntimeError("Cannot pass variable to state_to and save_to.") save_to._type_info.set_type( QiType.STATE, _TypeDefiningUse.RECORDING_SAVE_TO ) self.add_associated_variable(save_to) self.var = save_to elif isinstance(save_to, str): self.result_box = cell.get_result_container( save_to ) # container might have been added to cell before self.save_to = save_to cell.add_recording_length(length) self._length = length if isinstance(self._length, QiExpression): self._length._type_info.set_type( QiType.TIME, _TypeDefiningUse.RECORDING_OFFSET_EXPRESSION ) self._offset: QiExpression = QiExpression._from(offset) self._offset._type_info.set_type( QiType.TIME, _TypeDefiningUse.RECORDING_OFFSET_EXPRESSION ) for var in self._offset.contained_variables: var._relevant_cells.add(cell) self.toggleContinuous = toggleContinuous self.follows_readout = False try: cmd = _QiJobReference.commands[-1] if ( isinstance(cmd, cQiPlayReadout) and cmd.cell == self.cell ): # Warning if previous cmd is readout but different cell self.follows_readout = True cmd.recording = self cmd._associated_variable_set.update(self._associated_variable_set) except IndexError: pass @property def uses_state(self): return len(self._associated_variable_set) > 0 @property def length(self): return ( self._length() if isinstance(self._length, QiCellProperty) else self._length ) @length.setter def length(self, value): self._length = value @property def offset(self): return ( self._offset() if isinstance(self._offset, QiCellProperty) else self._offset ) def _stringify_args(self) -> str: """Determines non-default args to explicitly stringify""" arg_strings = [str(self.cell), str(self._length)] if not ( isinstance(self._offset, _QiConstValue) and self._offset._given_value == 0 ): arg_strings.append(f"offset={self._offset}") if self.result_box is not None: arg_strings.append(f'save_to="{self.result_box.name}"') if self.var is not None: arg_strings.append(f"state_to={self.var}") if self.toggleContinuous is not None: arg_strings.append(f"toggleContinuous={self.toggleContinuous}") return ", ".join(arg_strings) def _stringify(self) -> str: return f"Recording({self._stringify_args()})" class cQiStore(QiCellCommand): """Command generated by :meth:`Store`""" def __init__(self, cell, store_var: _QiVariableBase, save_to: QiResult): super().__init__(cell) self.store_var = store_var self.save_to = save_to self.add_associated_variable(store_var) def _stringify(self) -> str: return f"Store({self.cell}, {self.store_var}, {self.save_to})" class cQiAssign(QiVariableCommand): """Command generated by :meth:`Assign`""" def __init__(self, dst: _QiVariableBase, value: Union[QiExpression, int, float]): if not isinstance(dst, _QiVariableBase): raise TypeError("Target of Assign can only be a QiVariable.") super().__init__(dst) self._value = QiExpression._from(value) dst._type_info.add_illegal_type(QiType.STATE, _IllegalTypeReason.ASSIGN) _add_equal_constraints( QiType.NORMAL, _TypeConstraintReasonQiCommand(cQiAssign), self._value, dst ) _add_equal_constraints( QiType.TIME, _TypeConstraintReasonQiCommand(cQiAssign), self._value, dst ) for variable in self.value.contained_variables: self.add_associated_variable(variable) @property def value(self): return self._value def accept(self, visitor, *input): return visitor.visit_assign_command(self, *input) def _stringify(self) -> str: return f"Assign({self.var}, {self._value})" class cQiDeclare(QiVariableCommand): """Command generated by initialization of new QiVariable""" def __init__(self, dst: _QiVariableBase) -> None: super().__init__(var=dst) def accept(self, visitor, *input): return visitor.visit_declare_command(self, *input) def _stringify(self) -> str: return f"v{self.var.str_id} = {self.var}" class cQiASM(QiCommand): def __init__(self, cells: QiCell, instr: SequencerInstruction, cycles: int): super().__init__() self._relevant_cells.add(cells) self.asm_instruction = instr self.cycles = cycles def accept(self, visitor, *input): return visitor.visit_asm_command(self, *input) def _stringify(self) -> str: return f"ASM({self.asm_instruction.get_riscv_instruction()})" class cQiMemStore(QiCommand): def __init__(self, cell: QiCell, addr: int, value): super().__init__() self._relevant_cells.add(cell) self.addr = addr self.value = value def accept(self, visitor, *input): return visitor.visit_mem_store_command(self, *input) def _stringify(self): cell_str = ", ".join(list(map(lambda x: f"{x}", self._relevant_cells))) return f"cQiMemStore({cell_str}, {self.addr}, {self.value})" class QiContextManager(QiCommand): """Base Class for If, Else, ForRange and Parallel. Defines functions for storing commands.""" def __init__(self) -> None: super().__init__() self.body: List[QiCommand] = [] def __enter__(self): _QiJobReference._open_new_context() return self def __exit__(self, exception_type, exception_value, traceback): self.body = _QiJobReference._close_context() _QiJobReference._add_command(self) def accept(self, visitor, *input): return visitor.visit_context_manager(self, *input) class If(QiContextManager): """ Add conditional logic to the program. If multiple cells are used inside the body, a synchronization between the cells takes place before the If. :param condition: The condition to check Example ------- .. code-block:: python with QiJob() as job: q = QiCells(1) x = QiIntVariable(1) with If(x > 1): ... # won't be executed The If statement is most commonly used to react to qubit states in real-time: .. code-block:: python from qiclib import jobs with QiJob() as job: q = QiCells(1) state = QiStateVariable() jobs.Readout(q[0], state_to=state) with If(state = 0): ... # Apply some conditional logic based on the qubit state """ def __init__(self, condition: Optional[QiCondition] = None): super().__init__() self._else_body: List[QiCommand] = [] if condition is None: raise RuntimeError("No QiCondition given") self.condition = condition for variable in condition.contained_variables: self.add_associated_variable(variable) def add_else_body(self, else_body): self._else_body = else_body.copy() def is_followed_by_else(self) -> bool: return len(self._else_body) != 0 def accept(self, visitor, *input): return visitor.visit_if(self, *input) def _stringify(self) -> str: return f"If({self.condition})" class Else(QiContextManager): """ Adds Conditional logic if the preceding :class:`If` command evaluates to false. :raises RuntimeError: When the preceeding command is not an :python:`If` command Example ------- .. code-block:: python from qiclib import jobs with QiJob() as job: q = QiCells(1) state = QiStateVariable() jobs.Readout(q[0], state_to=state) with If(state = 0): ... # Apply some conditional logic based on the qubit state with Else(): ... # State is 1 """ def __enter__(self): self.if_cmd = _QiJobReference.commands[-1] if not isinstance(self.if_cmd, If): raise RuntimeError("Else is not preceded by If") _QiJobReference._open_new_context() return self def __exit__(self, exception_type, exception_value, traceback): self.if_cmd.add_else_body(_QiJobReference._close_context()) class Parallel(QiContextManager): """Pulses defined in body are united in one trigger command.""" def __init__(self): super().__init__() self.entries: List[List[QiCommand]] = [] def __exit__(self, exception_type, exception_value, traceback): temp = _QiJobReference._close_context() self.body += temp # So visitors also find commands in Parallel blocks. self.entries.append(temp) containing_cells = QiCMContainedCellVisitor() for command in temp: if not isinstance( command, ( cQiPlay, cQiPlayReadout, cQiPlayFlux, cQiRotateFrame, cQiRecording, cQiWait, ), ): raise TypeError("Type not allowed inside Parallel()", command) if ( isinstance(command, (cQiRecording, cQiPlayReadout)) and command.uses_state ): raise RuntimeError("Can not save to state variable inside Parallel") try: if isinstance(command.length, _QiVariableBase): self._associated_variable_set.add(command.length) except KeyError: pass # length was QiCellProperty command.accept(containing_cells) self._relevant_cells.update(containing_cells.contained_cells) # If previous command is also parallel, combine by adding another parallel entry at previous command try: cmd = _QiJobReference.commands[-1] if isinstance(cmd, Parallel) and len(cmd.entries) < 2: cmd.entries.append(temp) cmd._associated_variable_set.update(self._associated_variable_set) else: _QiJobReference._add_command(self) except IndexError: _QiJobReference._add_command(self) class CmdTuple: def __init__(self, cmd: QiCommand, start: int, end: int, choke: bool = False): self.cmd = cmd self.start = start self.end = end self.choke_cmd = choke class TimeSlot: def __init__(self, cmd_tuples: List[Any], start, end): self.cmd_tuples: List[Parallel.CmdTuple] = cmd_tuples self.start: int = start self.end: int = end self.duration: float = 0.0 def _clear_wait_commands(self, cmd_tuples: List[CmdTuple]): """Clears cQiWait commands from cmd_tuples, if any trigger command is also in cmd_tuples""" contains_pulse = False for cmd_tuple in cmd_tuples: if isinstance(cmd_tuple.cmd, _cQiPlay_base): contains_pulse = True break return [ cmd_tuple for cmd_tuple in cmd_tuples if isinstance(cmd_tuple.cmd, _cQiPlay_base) or contains_pulse is False ] def _clear_choke_commands(self, cmd_tuples: List[CmdTuple]): """Clears choke commands, if at the same slot another Play or Readout command is present.""" contains_play = False contains_readout = False for cmd_tuple in cmd_tuples: if isinstance(cmd_tuple.cmd, cQiPlay) and cmd_tuple.choke_cmd is False: contains_play = True elif ( isinstance(cmd_tuple.cmd, cQiPlayReadout) and cmd_tuple.choke_cmd is False ): contains_readout = True if contains_play is False and contains_readout is False: return cmd_tuples cleared_tuples = [] for cmd_tuple in cmd_tuples: # if play command is present skip choke command for play if isinstance(cmd_tuple.cmd, cQiPlay): if cmd_tuple.choke_cmd is True and contains_play: continue # if PlayReadout command is present skip choke command for PlayReadout elif isinstance(cmd_tuple.cmd, cQiPlayReadout): if cmd_tuple.choke_cmd is True and contains_readout: continue cleared_tuples.append(cmd_tuple) return cleared_tuples def _create_time_slots(self, annotated_bodies: List[List[CmdTuple]], max_end: int): time_slot_list: List[Parallel.TimeSlot] = [] for start in range(0, max_end): time_slot = self.TimeSlot([], start, start) # find tuples with start time == start for cmd_list in annotated_bodies: for cmd_tuple in cmd_list: if cmd_tuple.start == start: time_slot.cmd_tuples.append(cmd_tuple) time_slot.end = max(cmd_tuple.end, time_slot.end) cmd_list.remove(cmd_tuple) break # next cmd_list # next start value, if nothing was found if len(time_slot.cmd_tuples) == 0: continue time_slot.cmd_tuples = self._clear_wait_commands(time_slot.cmd_tuples) time_slot.cmd_tuples = self._clear_choke_commands(time_slot.cmd_tuples) # Add Wait command, if previous end value < start try: prev_time_slot = time_slot_list[-1] if prev_time_slot.end < start: length = util.conv_cycles_to_time(start - prev_time_slot.end) new_wait = self.CmdTuple( cQiWait(list(self._relevant_cells)[0], length), start=prev_time_slot.end, end=start, ) time_slot_list.append( self.TimeSlot([new_wait], prev_time_slot.end, start) ) except IndexError: pass # Adjust previous end time, if previous.end > start try: prev_time_slot = time_slot_list[-1] prev_time_slot.end = min(prev_time_slot.end, start) except IndexError: pass time_slot_list.append(time_slot) # Add final wait, if previous.end != max_end try: prev_time_slot = time_slot_list[-1] if prev_time_slot.end < max_end: length = util.conv_cycles_to_time(max_end - prev_time_slot.end) new_wait = self.CmdTuple( cQiWait(list(self._relevant_cells)[0], length), start=prev_time_slot.end, end=max_end, ) time_slot_list.append( self.TimeSlot([new_wait], prev_time_slot.end, max_end) ) except IndexError: pass # calculate duration of time slot for slot in time_slot_list: slot.duration = util.conv_cycles_to_time(slot.end - slot.start) return time_slot_list def _generate_command_body(self, cell, sequencer): """Combines the parallel sequences to one command body.""" parallel_bodies: List[List[Parallel.CmdTuple]] = [] max_end = 0 # Generate annotated list of commands with start and end cycle for cmd_list in self.entries: commands: List[Parallel.CmdTuple] = [] start: int = 0 end: int = 0 for cmd in cmd_list: var_pulse = False if cell not in cmd._relevant_cells: continue # skip commands for other cells if isinstance(cmd.length, _QiVariableBase): reg = sequencer.get_var_register(cmd.length) if reg.valid is False or reg.value is None: raise RuntimeError( "Variable inside parallel not initialised or invalidated" ) length = reg.value if isinstance(cmd, (cQiPlay, cQiPlayReadout)): var_pulse = True else: length = util.conv_time_to_cycles(cmd.length, "ceil") if length == 0: continue # skip commands with length 0 if isinstance(cmd, cQiRecording) or ( isinstance(cmd, cQiPlayReadout) and isinstance(cmd.recording, cQiRecording) ): end += length + util.conv_time_to_cycles( sequencer.recording_delay, "ceil" ) else: end += length cmd_duration = self.CmdTuple(cmd, start, end) commands.append(cmd_duration) if var_pulse: # Add parallel choke command after current command, if variable length is used parallel_choke = [self.CmdTuple(cmd, end, end + 1, choke=True)] parallel_bodies.append(parallel_choke) max_end = max(end + 1, max_end) # +1 to account for choke command else: max_end = max(end, max_end) start = end parallel_bodies.append(commands) return self._create_time_slots(parallel_bodies, max_end) def accept(self, visitor, *input): return visitor.visit_parallel(self, *input) def _stringify(self) -> str: return "Parallel" class ForRange(QiContextManager): """Adds ForRange to program. If multiple cells are used inside body, a synchronisation between the cells is done before the ForRange as well as after the end of the body. If QiTimeVariable is used as var, loops starting at 0 are unrolled, to skip pulses/waits inside body using var as length. Raises exception if start, end and step are not set up properly.""" def __init__( self, var: _QiVariableBase, start: Union[_QiVariableBase, int, float], end: Union[_QiVariableBase, int, float], step: Union[int, float] = 1, ): super().__init__() if not isinstance(var, _QiVariableBase): raise RuntimeError( "Can only use QiVariables as control variable in ForRanges." ) start_expr = QiExpression._from(start) end_expr = QiExpression._from(end) step_expr = QiExpression._from(step) var._type_info.add_illegal_type(QiType.STATE, _IllegalTypeReason.FOR_RANGE) start_expr._type_info.add_illegal_type( QiType.STATE, _IllegalTypeReason.FOR_RANGE ) end_expr._type_info.add_illegal_type(QiType.STATE, _IllegalTypeReason.FOR_RANGE) step_expr._type_info.add_illegal_type( QiType.STATE, _IllegalTypeReason.FOR_RANGE ) _add_equal_constraints( QiType.TIME, _TypeConstraintReasonQiCommand(ForRange), var, start_expr, end_expr, step_expr, ) _add_equal_constraints( QiType.FREQUENCY, _TypeConstraintReasonQiCommand(ForRange), var, start_expr, end_expr, step_expr, ) _add_equal_constraints( QiType.NORMAL, _TypeConstraintReasonQiCommand(ForRange), var, start_expr, end_expr, step_expr, ) if not isinstance(start, _QiVariableBase) and not isinstance( end, _QiVariableBase ): if (start > end and step >= 0) or (start < end and step <= 0): raise ValueError("Definition of ForRange faulty") self.var = var self.start = start_expr self.end = end_expr self.step = step_expr self.add_associated_variable(var) if isinstance(start, _QiVariableBase): self.add_associated_variable(start) if start.id == var.id: raise RuntimeError("Loop variable can not be used as start value") if isinstance(end, _QiVariableBase): self.add_associated_variable(end) if end.id == var.id: raise RuntimeError("Loop variable can not be used as end value") def __exit__(self, exception_type, exception_value, traceback): super().__exit__(exception_type, exception_value, traceback)
check_variable = QiVarInForRange(self.var)
14
2023-11-10 10:26:10+00:00
24k
fg320/DEASC
examples/12C_5x1_farm_dyn_tuning_wso_grouping_looping.py
[ { "identifier": "WfModel", "path": "deasc/wf_model.py", "snippet": "class WfModel:\n \"\"\"\n Class for wind farm modelling (Interface setup but not limited to FLORIS\n framework).\n \"\"\"\n\n def __init__(self, input_file, path):\n \"\"\"\n Initialise wind farm object by pointing towards an input file.\n (FLORIS interface object).\n\n Args\n ----\n input file:(FLORIS .json input file).\n \"\"\"\n # Read and initialize input file\n self.input_file = input_file\n self.interface = floris_input_handler(self.input_file, path)\n\n # Assign wind farm model proporties\n self.D, self.H_hub, self.n_turbs = floris_properties(self)\n\n def set_aligned_layout(self, n_row, n_col, spac_x, spac_y, coordinates=False):\n \"\"\"\n Modify farm layout in aligned wind turbines with constant spacing,\n differing only from rows to columns. Flow field is also reinitialized.\n\n Args\n ----\n n_row: (float) number of turbine rows\n n_col: (float) number of turbine columns\n spac_x: (float) WT diam normalized turbines distance in x direction\n spac_y: (float) WT diam normalized turbines distance in y direction\n coordinates: (bool, opt) False if no coordinates wanted.\n Default set to False.\n\n Returns\n -------\n if coordinates is False:\n None\n if coordinates is True:\n x-coordinates: (numpy array) turbines x-coordinates\n y-coordinates: (numpy array) turbines y-coordinates\n \"\"\"\n # Input type check\n if not all(isinstance(i, int) for i in [n_row, n_col]) or \\\n not all(isinstance(j, (int, float)) for j in [spac_x, spac_y]):\n err_msg = \"Incorrect input value types\"\n raise ValueError(err_msg)\n\n # Calculate new coordinate farm layout\n layout_x = []\n layout_y = []\n for i in range(int(n_row)):\n for j in range(int(n_col)):\n layout_x.append(i * spac_x * self.D)\n layout_y.append(j * spac_y * self.D)\n\n # Reinitialize wind farm object\n floris_reinitialise_layout(self, layout_x, layout_y)\n\n if coordinates:\n return (np.array(layout_x), np.array(layout_y))\n else:\n return None\n\n def set_HR_layout(self, coordinates=False):\n \"\"\"\n Set Horns Rev wind farm layout to wind farm object and\n returns turbines' x and y coordinates if coordinates=True.\n\n Args\n ----\n coordinates: (bool, opt) False if no coordinates wanted.\n Default set to False.\n\n Returns\n -------\n if coordinates is False:\n None\n if coordinates is True:\n x-coordinates: (numpy array) turbines x-coordinates\n y-coordinates: (numpy array) turbines y-coordinates\n \"\"\"\n # Vestas V80 2 MW diameter check\n if self.D != 80:\n warning = \"Rotor diameter not from the Vestas V80 2 MW turbine\"\n warnings.warn(warning, UserWarning)\n\n n_rows = 10\n n_cols = 8\n spac_x = 7\n spac_y = 7\n angle = 6\n layout_x = []\n layout_y = []\n for i in range(int(n_rows)):\n for j in range(int(n_cols)):\n layout_x.append((i * spac_x * self.D) -\n (np.sin(np.radians(angle)) * j * spac_y * self.D))\n layout_y.append(j * spac_y * self.D * np.cos(np.radians(angle)))\n\n # Reinitialize wind farm object\n floris_reinitialise_layout(self, layout_x, layout_y)\n\n if coordinates:\n return (np.array(layout_x), np.array(layout_y))\n else:\n return None\n\n def farm_eval(self, yaw=None, ws=None, wd=None, ti=None, shear=None):\n \"\"\"\n Calculate farm flow field for given wind farm layout and input conditions.\n Return main outputs, such as yaw angles, turbines power, farm power, etc.\n\n Args\n ----\n yaw: (list, optional) turbines yaw angles (deg). Default to None.\n ws: (float, optional) input wind speeds (m/s). Default to None.\n wd: (float, optional) input wind directions (deg). Default to None.\n ti: (float, optional) input turbulence intensity. Default to None.\n shear: (float, optional) shear exponent. Default to None.\n\n Returns\n -------\n wf_pow: (float) WF power (MWatts).\n wt_pow: (np.array) WTs power (MWatts).\n wt_ti: (list) WTs turbulence intensity.\n wt_yaw: (np.array) WTs yaw angles (deg).\n \"\"\"\n # Main wind farm calculation\n wf_pow, wt_pow, wt_ti, wt_yaw, _ = floris_farm_eval(self,\n yaw,\n ws,\n wd,\n ti,\n shear)\n\n return (wf_pow, wt_pow, wt_ti, wt_yaw)\n\n def pow_yaw_sweep_1var(self, layout, var_info):\n \"\"\"\n Return wind farm power for a single yaw variable, either a\n single turbine or a single row of turbines. Sweep by row not possible\n for not aligned \"custom\" layouts.\n\n Args\n ----\n layout: (tuple)\n row: (integer) number of farm rows\n cols: (integer) number of farm columns\n or string \"custom\"\n var_info: (tuple)\n var_type: (string) \"T\" for turbine,\n \"R\" for row (not for custom layouts)\n var: (integer) turbine or row number\n var_value: (list of floats) variable values\n\n Returns\n -------\n obj_out: tuple\n obj: (list) objective values\n obj_func: (string) objective function\n var_info: (tuple) see input\n model: (string) model name\n \"\"\"\n # Extract inputs and check inputs\n var_type, var, var_value = var_info\n if layout != \"custom\":\n rows, cols = layout\n if var_type == 'R' and layout == \"custom\":\n err_msg = \"Row not allowed for custom layouts\"\n raise ValueError(err_msg)\n if var_type == 'R' and var > rows:\n err_msg = \"Row specified not in farm\"\n raise ValueError(err_msg)\n if var_type == 'T' and var > self.n_turbs:\n err_msg = \"Turbine specified not in farm\"\n raise ValueError(err_msg)\n\n # Calculations\n yaw_angles = np.array(floris_current_yaw(self))\n wf_pow = []\n\n for yaw_change in var_value:\n if layout != \"custom\":\n rows, cols = layout\n if var_type == 'T':\n yaw_angles[(var-1)] = yaw_change\n elif var_type == 'R':\n idx_1 = var*cols\n idx_0 = idx_1-cols\n yaw_angles[idx_0:idx_1] = yaw_change\n else:\n err_msg = \"var_type either 'T' or 'R'\"\n raise ValueError(err_msg)\n\n wf_pow_single, _, _, _ = self.farm_eval(yaw=yaw_angles)\n wf_pow.append(wf_pow_single)\n\n obj_out = (wf_pow, 'Farm Power')\n var_info = (var_type, var, var_value)\n print(\"Function exploration complete\")\n\n return obj_out, var_info" }, { "identifier": "WSOpt", "path": "deasc/wake_steering.py", "snippet": "class WSOpt:\n \"\"\"\n Class to perform wake steering optimization with a WfModel object, given an a-priori\n specified wind farm layout and specified atmopheric conditions. Optimization can have\n all/some turbines as variables, or rows for wind farms with equal columns. Optimizers\n available are the local SLSQP, where linear constraints can be added, and the global\n optimizer TuRBO.\n \"\"\"\n\n def __init__(self,\n wf_model,\n inflow,\n variables,\n var_bounds,\n var_initial,\n opt_method=\"SLSQP\",\n opt_options=None,\n obj_function=\"Farm Power\",\n constraints=(None, None, None),\n by_row=(False, None, None),\n tuning_dynamic=False\n ):\n \"\"\"\n Args\n ----\n wf_model: (WfModel)\n WfModel to perform wake steering optimization.\n inflow: (list) Inflow conditions for wake steering optimization.\n yaw_initial: (list) wind farm yaw angles (deg).\n (string) 'random' for random intial wind farm yaw angles.\n wd: (float) input wind directions (deg).\n ws: (float) input wind speeds (m/s).\n ti: (float) input turbulence intensity.\n shear: (float) shear exponent.\n variables: (list)\n List of turbines (or rows) to optimize. Naming convention starts from 1.\n var_bounds: (tuple)\n low_bound: (float) variable (yaw angle) lower bound.\n upp_bound: (float) variable (yaw angle) upper bound.\n var_initial:\n SLSQP: (list) list of initial variable values for each variable.\n (string) 'random' for random initial variable values.\n TURBO_1: (list of lists) list of n_init variable values lists\n (see TURBO_1 options).\n (string) 'LHS' latin hypercube sampling.\n TURBO_M: (string) 'LHS' latin hypercube sampling.\n opt_method: (string, optional) optimization method.\n 'SLSQP', 'TURBO_1 and 'TURBO_M' available.\n Default set to 'SLSQP'.\n opt_options: (dict , optional) optimization method options dictionary.\n Default set to None.\n opt_function: (string , optional) objective function. 'Farm Power' available\n Default set to 'Farm Power'.\n constraints: (tuple) Linear constraints definition. Limited to SLSQP.\n A: (matrix) linear constraint matrix.\n Default set to None.\n low_bound_constr: (float) lower non-normalized contraint bound.\n Default set to None.\n upp_bnd_constr: (float) upper non-normalized contraint bound.\n Default set to None.\n by_row : (tuple, optional) Optimization by row, requires all farm columns to have\n the same amount of rows.\n by_row_bool: (bool) True if optimization variables are wind farm rows,\n False if wind farm turbines. Default set to False.\n rows:: (int) wind farm rows. Default set to None.\n cols:: (int) wind farm columns. Default set to None.\n tuning_dynamic : (bool, optional)\n If True, include dynamic parameter tuning. See tuning_dynamic_initialize\n method. Default to False.\n \"\"\"\n # Opt Methods - Opt Options - Optimizers - Opt Functions\n self.opt_method_list = [\"SLSQP\", \"TURBO_1\", \"TURBO_M\"]\n self.opt_options_dict = {\"SLSQP\": {'maxiter': 100,\n 'disp': True,\n 'iprint': 2,\n 'ftol': 1e-6,\n 'eps': 0.01},\n \"TURBO_1\": {\"n_init\": len(variables)*2,\n \"max_evals\": 500,\n \"batch_size\": 1, # 1 = Serial\n \"verbose\": True,\n \"use_ard\": True,\n \"max_cholesky_size\": 2000,\n \"n_training_steps\": 50,\n \"min_cuda\": 1024,\n \"device\": \"cpu\",\n \"dtype\": \"float64\"},\n \"TURBO_M\": {\"n_init\": len(variables)*2,\n \"max_evals\": 500,\n \"n_trust_regions\": 2,\n \"batch_size\": 1, # 1 = Serial\n \"verbose\": True,\n \"use_ard\": True,\n \"max_cholesky_size\": 2000,\n \"n_training_steps\": 50,\n \"min_cuda\": 1024,\n \"device\": \"cpu\",\n \"dtype\": \"float64\"}}\n self.optimizer_dict = {'SLSQP': self._optimizer_scipy,\n 'TURBO_1': self._optimizer_turbo_1,\n 'TURBO_M': self._optimizer_turbo_m}\n self.obj_function_dict = {'Farm Power': self._obj_function_power}\n\n # Optimization methods and optimizer\n self.opt_method = opt_method\n self._opt_method_settler()\n self.optimizer = self.optimizer_dict[self.opt_method]\n\n # Optimizer options\n self.opt_options = opt_options\n self._opt_options_settler()\n\n # Optimization function\n self.obj_function_name = obj_function\n self._obj_function_settler()\n\n # Wind farm conditions\n self.wf_model = wf_model\n self.wf_model_dict_original = floris_extract_object_dict(self.wf_model)\n self.yaw_initial, self.wd, self.ws, self.ti, self.shear = inflow\n if not isinstance(self.yaw_initial, (list, np.ndarray)):\n if self.yaw_initial == 'random':\n self.yaw_initial = self._random_yaw_generator(self.wf_model.n_turbs,\n var_bounds)\n self._yaw_initial_input_handler()\n self.yaw_initial = np.array([float(item) for item in self.yaw_initial])\n\n # Optimization per wind turbine or per wind farm row\n self.by_row_bool = by_row[0]\n if self.by_row_bool:\n self.rows = by_row[1]\n self.cols = by_row[2]\n self._by_row_input_handler()\n\n # Variable bounds\n self.var_bounds = var_bounds\n self.low_bound, self.upp_bound = self.var_bounds\n self.low_bound_norm = norm(self.low_bound, self.low_bound, self.upp_bound)\n self.upp_bound_norm = norm(self.upp_bound, self.low_bound, self.upp_bound)\n self.var_bounds_norm = (self.low_bound_norm, self.upp_bound_norm)\n tmp = [self.var_bounds_norm for i in range(len(variables))]\n self.var_bounds_norm_list = tmp\n tmp = np.array([self.low_bound_norm for i in range(len(variables))])\n self.low_bound_norm_list = tmp\n tmp = np.array([self.upp_bound_norm for i in range(len(variables))])\n self.upp_bound_norm_list = tmp\n\n # Constraints\n self.A = constraints[0]\n self.low_bound_constr = constraints[1]\n self.upp_bound_constr = constraints[2]\n if self.A is not None:\n self._constraints_input_handler()\n self.low_bound_constr_norm = norm(self.low_bound_constr,\n self.low_bound,\n self.upp_bound)\n self.upp_bound_constr_norm = norm(self.upp_bound_constr,\n self.low_bound,\n self.upp_bound)\n\n # Yaw variables\n self.variables = variables\n self.var_initial = var_initial\n self._variables_input_handler()\n if not isinstance(self.var_initial, (list, np.ndarray)):\n if self.opt_method == 'SLSQP' and self.var_initial == 'random':\n self.var_initial = self._random_yaw_generator(len(self.variables),\n self.var_bounds)\n self._var_initial_input_handler()\n self.var_initial_norm = self._var_initial_norm()\n\n # Dynamic tuning\n self.tuning_dyn_bool = tuning_dynamic\n self._tuning_dyn_bool_check()\n self.tuning_dyn_initialization = False\n\n self.opt_run = False\n\n def tuning_dyn_initialize(self, tuning_dyn_obj_list):\n \"\"\"\n Assign list of tuning dynamic objects TuningDyn to the WSOpt object.\n\n Args\n ----\n tuning_dyn_object: (list of TuningDyn objects)\n \"\"\"\n self.tuning_dyn_obj_list = tuning_dyn_obj_list\n self._tuning_dyn_init_input_handler()\n for tuning_dyn_obj in self.tuning_dyn_obj_list:\n tuning_dyn_obj.wso_compatibility_check(self)\n self.tuning_dyn_initialization = True\n\n def optimize_yaw(self):\n \"\"\"\n Optimize the yaw angle for the given WSOpt object.\n\n Returns\n -------\n opt_yaw_angles_vars: (ndarray) optimal yaw angles for the optimization variables.\n opt_yaw_angles_all: (ndarray) optimal yaw angles for all.wind farm turbines.\n \"\"\"\n # Tuning dynamic initialization check\n self._tuning_dyn_initialization_check()\n\n # Print optimization info\n self._print_info()\n\n # Wind farm power - no yaw\n self.wf_pow_noyaw = self._get_farm_power_noyaw()\n\n # Optimize\n self._iter_details_setup()\n self.opt_yaw_angles_vars, self.opt_yaw_angles_all = self.optimizer()\n self.opt_run = True\n\n return (self.opt_yaw_angles_vars, self.opt_yaw_angles_all)\n\n def get_optimization_details(self):\n \"\"\"\n Return optimization details: optimizer iterations details and objective function\n evaluations details. The two are identical for TURBO optimizers as an objective\n function evaluation corresponds to an optimizer iteration, different for SLSQP as\n additional objective function evaluations are required to approximate gradients.\n\n Returns\n -------\n iter_details: (tuple) optimizer iterations details.\n iter_yaw_angles: (list) list of yaw angles per optimizer iteration.\n iter_obj_func: (list) list of objective function per optimizer iteration.\n iter_farm_power: (list) list of farm power values per optimizer iteration.\n eval_details: (tuple) objective fucntion evaluations details.\n eval_yaw_angles: (list) list of yaw angles per evaluation.\n eval_obj_func: (list) list of objective function per evaluation.\n eval_farm_power: (list) list of farm power values per evaluation.\n \"\"\"\n iter_details = (self.iter_yaw_angles,\n self.iter_obj_func,\n self.iter_farm_power)\n eval_details = (self.eval_yaw_angles,\n self.eval_obj_func,\n self.eval_farm_power)\n return (iter_details, eval_details)\n\n # %% Private methods\n\n def _opt_method_settler(self):\n if self.opt_method not in self.opt_method_list:\n err_msg = \"Optimization method not recognized\"\n raise Exception(err_msg)\n\n def _opt_options_settler(self):\n if self.opt_options is None:\n self.opt_options = self.opt_options_dict[self.opt_method]\n\n def _obj_function_settler(self):\n if self.obj_function_name in list(self.obj_function_dict.keys()):\n self.obj_function = self.obj_function_dict[self.obj_function_name]\n else:\n err_msg = \"Optimization function not recognized\"\n raise Exception(err_msg)\n\n def _random_yaw_generator(self, yaw_number, yaw_bounds):\n yaw_angles = []\n for i in range(yaw_number):\n x = random.choice(range(yaw_bounds[0], yaw_bounds[1]+1))\n yaw_angles.append(x)\n return yaw_angles\n\n def _yaw_initial_input_handler(self):\n if len(self.yaw_initial) != self.wf_model.n_turbs:\n err_msg = \"Initial yaw angles do not match turbine number\"\n raise Exception(err_msg)\n\n def _by_row_input_handler(self):\n if self.rows*self.cols != self.wf_model.n_turbs:\n err_msg = \"Farm rows and columns provided do not match turbine number\"\n raise Exception(err_msg)\n\n def _constraints_input_handler(self):\n if self.opt_method != 'SLSQP':\n err_msg = \"Linear constraints (on top of bounds) limited to SLSQP optimizer\"\n raise Exception(err_msg)\n\n def _variables_input_handler(self):\n if self.by_row_bool:\n for row in self.variables:\n if row > self.rows:\n err_msg = \"Row/s specified not in farm\"\n raise Exception(err_msg)\n if len(self.variables) > self.rows:\n err_msg = \"Too many rows specified\"\n raise Exception(err_msg)\n else:\n for turb in self.variables:\n if turb > self.wf_model.n_turbs:\n err_msg = \"Turbine/s specified not in the farm\"\n raise Exception(err_msg)\n if len(self.variables) > self.wf_model.n_turbs:\n err_msg = \"Too many turbines specified\"\n raise Exception(err_msg)\n if 0 in self.variables:\n err_msg = \"Turbine/row counting convention starts from 1\"\n raise Exception(err_msg)\n\n def _var_initial_input_handler(self):\n if self.opt_method == 'TURBO_1':\n if not isinstance(self.var_initial, (list, np.ndarray)):\n if self.var_initial == 'LHS':\n pass\n elif self.var_initial == 'random':\n err_msg = \"Random initial variables limited to SLSQP optimizer\"\n raise Exception(err_msg)\n else:\n if len(self.var_initial) != self.opt_options[\"n_init\"]:\n err_msg = \"n_init initial variable lists are needed (see TURBO options)\"\n raise Exception(err_msg)\n elif len(self.var_initial[0]) != len(self.variables):\n err_msg = \"var_initial sublists length not equal number of variables\"\n raise Exception(err_msg)\n elif self.opt_method == 'TURBO_M':\n if self.var_initial != 'LHS':\n err_msg = \"TURBO_M optimizer requires LHS as initial sampling\"\n elif self.opt_method == 'SLSQP':\n if not isinstance(self.var_initial, (list, np.ndarray)):\n if self.var_initial == 'LHS':\n err_msg = \"Latin Hypercube Sampling limited to TURBO optimizers\"\n raise Exception(err_msg)\n elif len(self.variables) != len(self.var_initial):\n err_msg = \"var_initial length needs to equal number of variables\"\n raise Exception(err_msg)\n\n def _var_initial_norm(self):\n if self.opt_method == \"SLSQP\":\n self.var_initial = np.array([float(item) for item in self.var_initial])\n var_initial_norm = norm(self.var_initial, self.low_bound, self.upp_bound)\n elif self.var_initial == 'LHS':\n var_initial_norm = None\n else:\n self.var_initial = np.array([np.array(x) for x in self.var_initial])\n var_initial_norm = []\n for x_list in self.var_initial:\n x_list_norm = []\n for x in x_list:\n x_norm = norm(x, self.low_bound, self.upp_bound)\n x_list_norm.append(x_norm)\n var_initial_norm.append(np.array(x_list_norm))\n return np.array(var_initial_norm)\n\n def _get_farm_power_noyaw(self):\n if (self.tuning_dyn_initialization and\n hasattr(self.tuning_dyn_obj_list[0], 'wf_pow_noyaw')):\n wf_pow_noyaw = self.tuning_dyn_obj_list[0].wf_pow_noyaw\n else:\n self.yaw_zero = np.full(shape=self.wf_model.n_turbs, fill_value=0.0)\n self.wf_model = floris_reinitialise_atmosphere(self.wf_model,\n self.ws,\n self.wd,\n self.ti,\n self.shear)\n # Tune parameters\n if self.tuning_dyn_initialization:\n for tuning_dyn_obj in self.tuning_dyn_obj_list:\n self.wf_model = tuning_dyn_obj.tune_parameter(self, self.yaw_zero)\n\n wf_pow_noyaw = floris_calculate_farm_power(self.wf_model, self.yaw_zero)\n return wf_pow_noyaw\n\n def _print_info(self):\n print(\"=====================================================\")\n print(\"Optimizing wake redirection control...\")\n print(\"Optimization method: %s\" % (self.opt_method))\n print(\"Optimization function: %s \\n\" % (self.obj_function_name))\n if self.by_row_bool:\n print(\"Rows being optimized: \")\n print(self.variables)\n else:\n print(\"Turbines being optimized: \")\n print(self.variables)\n print(\"Number of variables to optimize = \", len(self.variables))\n print(\"=====================================================\")\n\n def _iter_details_setup(self):\n # Details for each obj function evaluation\n self.eval_yaw_angles = [] # deg\n self.eval_obj_func = []\n self.eval_farm_power = [] # MW\n\n # Details for each optimizer iteration\n self.iter_yaw_angles = [] # deg\n self.iter_obj_func = []\n self.iter_farm_power = [] # MW\n\n def _variables_to_farm_yaw(self, yaw_initial, var_values):\n yaw_angles = copy.deepcopy(yaw_initial)\n if self.by_row_bool:\n for i, row_idx in enumerate(self.variables):\n idx_1 = row_idx*self.cols\n idx_0 = idx_1-self.cols\n yaw_angles[idx_0:idx_1] = var_values[i]\n else:\n for i, turb_idx in enumerate(self.variables):\n yaw_angles[turb_idx-1] = var_values[i]\n return yaw_angles.tolist()\n\n # %% Optimizers\n\n def _optimizer_scipy(self):\n # Call back function for iter details\n def callback_func(xk):\n self.iter_yaw_angles.append(self.eval_yaw_angles[-1])\n self.iter_obj_func.append(self.eval_obj_func[-1])\n self.iter_farm_power.append(self.eval_farm_power[-1])\n # Linearly constrained case\n if self.A is not None:\n self.C = LinearConstraint(self.A,\n self.low_bound_constr_norm,\n self.upp_bound_constr_norm)\n self.residual_plant = minimize(self.obj_function,\n self.var_initial_norm,\n callback=callback_func,\n method=self.opt_method,\n bounds=self.var_bounds_norm_list,\n constraints=(self.C,),\n options=self.opt_options)\n # Unconstrained case\n else:\n self.residual_plant = minimize(self.obj_function,\n self.var_initial_norm,\n callback=callback_func,\n method=self.opt_method,\n bounds=self.var_bounds_norm_list,\n options=self.opt_options)\n # Extract optimal yaw angles for variables\n opt_yaw_angles_vars = unnorm(self.residual_plant.x,\n self.low_bound,\n self.upp_bound)\n # Extract optimal yaw angles for the entire farm\n opt_yaw_angles_all = self._variables_to_farm_yaw(self.yaw_initial,\n opt_yaw_angles_vars)\n\n # Equal yaw groups if dynamic tuning with grouping is in place\n if self.tuning_dyn_initialization:\n if hasattr(self.tuning_dyn_obj_list[0], 'grouping_bool'):\n opt_yaw_angles_all = self.tuning_dyn_obj_list[0].set_yaw_groups(\n opt_yaw_angles_all)\n\n # Use best index because if total iterations reached, optimum not last evaluation\n eval_yaw_angles_lists = [x.tolist() for x in self.eval_yaw_angles]\n index_best = eval_yaw_angles_lists.index(opt_yaw_angles_all)\n opt_yaw_angles_all = np.array(opt_yaw_angles_all)\n self.obj_func_opt = self.eval_obj_func[index_best]\n self.farm_power_opt = self.eval_farm_power[index_best]\n\n # Add initial and last points to iteration details\n self.iter_yaw_angles.insert(0, self.eval_yaw_angles[0])\n self.iter_obj_func.insert(0, self.eval_obj_func[0])\n self.iter_farm_power.insert(0, self.eval_farm_power[0])\n self.iter_yaw_angles.append(self.eval_yaw_angles[-1])\n self.iter_obj_func.append(self.eval_obj_func[-1])\n self.iter_farm_power.append(self.eval_farm_power[-1])\n\n return (opt_yaw_angles_vars, opt_yaw_angles_all)\n\n def _optimizer_turbo_1(self):\n\n # TURBO initial sampling\n if not isinstance(self.var_initial, (list, np.ndarray)):\n if self.var_initial == 'LHS':\n X_init_provided = False\n X_init_same_norm = None\n else:\n X_init_provided = True\n X_init_same_norm = self.var_initial_norm\n\n # TURBO optimization\n turbo_1 = Turbo1(f=self.obj_function,\n lb=self.low_bound_norm_list,\n ub=self.upp_bound_norm_list,\n **self.opt_options,\n X_init_provided=X_init_provided,\n X_init_same=X_init_same_norm,\n )\n turbo_1.optimize()\n X = turbo_1.X # Evaluated points\n fX = turbo_1.fX # Observed values\n index_best = np.argmin(fX)\n f_best, x_best = fX[index_best], X[index_best, :]\n\n # Extract optimal yaw angles for variables and the entire farm\n opt_yaw_angles_vars = unnorm(x_best,\n self.low_bound,\n self.upp_bound)\n opt_yaw_angles_all = self._variables_to_farm_yaw(self.yaw_initial,\n opt_yaw_angles_vars)\n\n # Equal yaw groups if dynamic tuning with grouping is in place\n if self.tuning_dyn_initialization:\n if hasattr(self.tuning_dyn_obj_list[0], 'grouping_bool'):\n opt_yaw_angles_all = self.tuning_dyn_obj_list[0].set_yaw_groups(\n opt_yaw_angles_all)\n\n # Update iteration details (same as evaluation details)\n self.iter_yaw_angles = self.eval_yaw_angles\n self.iter_obj_func = self.eval_obj_func\n self.iter_farm_power = self.eval_farm_power\n\n # Use best index because last iteration might not be the optimal one\n self.obj_func_opt = f_best[0]\n self.farm_power_opt = self.iter_farm_power[index_best]\n\n return (opt_yaw_angles_vars, opt_yaw_angles_all)\n\n def _optimizer_turbo_m(self):\n\n # TURBO optimization\n turbo_m = TurboM(f=self.obj_function,\n lb=self.low_bound_norm_list,\n ub=self.upp_bound_norm_list,\n **self.opt_options,\n )\n turbo_m.optimize()\n X = turbo_m.X # Evaluated points\n fX = turbo_m.fX # Observed values\n index_best = np.argmin(fX)\n f_best, x_best = fX[index_best], X[index_best, :]\n\n # Extract optimal yaw angles for variables and the entire farm\n opt_yaw_angles_vars = unnorm(x_best,\n self.low_bound,\n self.upp_bound)\n opt_yaw_angles_all = self._variables_to_farm_yaw(self.yaw_initial,\n opt_yaw_angles_vars)\n\n # Equal yaw groups if dynamic tuning with grouping is in place\n if self.tuning_dyn_initialization:\n if hasattr(self.tuning_dyn_obj_list[0], 'grouping_bool'):\n opt_yaw_angles_all = self.tuning_dyn_obj_list[0].set_yaw_groups(\n opt_yaw_angles_all)\n\n # Update iteration details (same as evaluation details)\n self.iter_yaw_angles = self.eval_yaw_angles\n self.iter_obj_func = self.eval_obj_func\n self.iter_farm_power = self.eval_farm_power\n\n # Use best index because last iteration might not be the optimal one\n self.cost_func_opt = f_best[0]\n self.farm_power_opt = self.iter_farm_power[index_best]\n\n return (opt_yaw_angles_vars, opt_yaw_angles_all)\n\n # %% Objective functions\n\n def _obj_function_power(self, var_norm):\n\n # Extract farm yaw angles\n var_unnorm = unnorm(var_norm, self.low_bound, self.upp_bound)\n yaw_angles = self._variables_to_farm_yaw(self.yaw_initial, var_unnorm)\n yaw_angles = np.array([float(item) for item in yaw_angles])\n\n # Tune parameters dynamically\n if self.tuning_dyn_initialization:\n # Set equal yaw angles in groups\n if hasattr(self.tuning_dyn_obj_list[0], 'grouping_bool'):\n yaw_angles = self.tuning_dyn_obj_list[0].set_yaw_groups(yaw_angles)\n # Tune parameters\n for tuning_dyn_obj in self.tuning_dyn_obj_list:\n self.wf_model = tuning_dyn_obj.tune_parameter(self, yaw_angles)\n\n # Calculate negative of the farm power normalized by power for zero yaw\n self.wf_model = floris_reinitialise_atmosphere(self.wf_model,\n self.ws,\n self.wd,\n self.ti,\n self.shear)\n wf_pow = floris_calculate_farm_power(self.wf_model, yaw_angles)\n obj_function = (-1 * wf_pow / self.wf_pow_noyaw)\n\n # Update evalauation details\n self.eval_yaw_angles.append(yaw_angles)\n self.eval_obj_func.append(obj_function)\n self.eval_farm_power.append(wf_pow)\n\n return obj_function\n\n # %% Tuning Dynamic methods\n\n def _tuning_dyn_bool_check(self):\n if self.tuning_dyn_bool and self.by_row_bool:\n err_msg = \"Dynamic tuning not available for optimization by row.\"\n raise Exception(err_msg)\n\n def _tuning_dyn_init_input_handler(self):\n if isinstance(self.tuning_dyn_obj_list, (list, np.ndarray)) is False:\n err_msg = \"TuningDyn objects need to be in a list, even if only one.\"\n raise Exception(err_msg)\n # Check dynamic grouping tuning objects have the same tuning groups\n if hasattr(self.tuning_dyn_obj_list[0], 'grouping_bool'):\n tuning_groups_first = self.tuning_dyn_obj_list[0].tuning_groups\n same_groups = all(obj.tuning_groups == tuning_groups_first\n for obj in self.tuning_dyn_obj_list)\n if same_groups is False:\n err_msg = \"TuningDyn objects have different groupings.\"\n raise Exception(err_msg)\n\n def _tuning_dyn_initialization_check(self):\n if self.tuning_dyn_bool and self.tuning_dyn_initialization is False:\n err_msg = \"Tuning dynamic not initialized. See tuning_dyn_initialize method.\"\n raise Exception(err_msg)" }, { "identifier": "Tuning", "path": "deasc/tuning.py", "snippet": "class Tuning:\n \"\"\"\n Parameter tuning class for a low-fidelity model, where one or more\n parameters are tuned to higher fidelity power measurements. In particular,\n the RMSE is minimised for single turbine power measurements for a single or\n the sum of multiple atmospheric conditions. The wind farm layout is assumed fixed.\n \"\"\"\n\n def __init__(self,\n wf_model,\n variables_class_list,\n variables_names_list,\n variables_bounds_list,\n obj_func_name='RMSE',\n opt_method='SLSQP',\n opt_options=None\n ):\n \"\"\"\n Args\n ----\n wf_model : WfModel object (low-fidelity model)\n single WfModel object to tune\n variables_class_list: list of strings\n list of classes of parameters to tune, one per parameter\n variables_names_list : list of strings\n list of parameter names to tune\n variables_bounds_list : list of tuples\n list of parameter bounds, upper and lower limits for each parameter\n obj_func_name: string\n objective function. Default set to \"RMSE\"\n opt_method: string\n optimization method. Dafault set to \"SLSQP\" (\"TURBO_1\" also available)\n opt_options: dict\n optimizer options. Default set to None\n \"\"\"\n self.obj_func_dict = {'RMSE': self._tuning_rmse_function}\n self.opt_method_list = [\"SLSQP\", \"TURBO_1\"]\n self.opt_options_dict = {\"SLSQP\": {'maxiter': 100,\n 'disp': True,\n 'iprint': 2,\n 'ftol': 1e-12,\n 'eps': 0.1},\n \"TURBO_1\": {\"n_init\": 2*len(variables_names_list),\n \"max_evals\": 100,\n \"batch_size\": 1, # 1 = Serial\n \"verbose\": True,\n \"use_ard\": True,\n \"max_cholesky_size\": 2000,\n \"n_training_steps\": 50,\n \"min_cuda\": 1024,\n \"device\": \"cpu\",\n \"dtype\": \"float64\"}}\n self.tuning_optimizer_dict = {'SLSQP': self._tuning_optimizer_scipy,\n 'TURBO_1': self._tuning_optimizer_turbo_1}\n\n self.wf_model = wf_model\n self.variables_class_list = variables_class_list\n self.variables_names_list = variables_names_list\n self.variables_bounds_list = variables_bounds_list\n\n self.obj_func_name = obj_func_name\n self.obj_func = self.obj_func_dict[self.obj_func_name]\n self.opt_method = opt_method\n if opt_options == None:\n self.opt_options = self.opt_options_dict[self.opt_method]\n else:\n self.opt_options = opt_options\n self._tuning_optimizer = self.tuning_optimizer_dict[self.opt_method]\n\n self.tuning_data_received = False\n self.tuning_conditions_received = False\n\n print(\"\\nInitialised parameter tuning\")\n print(\"%i parameters to tune\" % (len(self.variables_names_list)))\n print(\"%s optimization method\" % (self.opt_method))\n\n def tuning_data(self, data_power_list):\n \"\"\"\n Provide training higher-fidelity data for parameter tuning.\n Limited to power of each turbine for each condition ('RMSE')\n\n Args\n ----\n data_power_list : list of lists\n For each condition:\n list of turbines power output ('RMSE')\n \"\"\"\n self.tuning_data_power_list = data_power_list\n self.tuning_data_received = True\n pass\n\n def tuning_conditions(self,\n yaw_angles_list,\n wind_directions_list,\n wind_speeds_list,\n turbulence_intensities_list,\n wind_shear_list):\n \"\"\"\n Define the wind farm conditions (yaw and atmospheric)\n of the higher-fidelity data.\n\n Args\n ----\n yaw_angles_list : list of lists\n For each condition, list of turbines yaw_angles\n wind_directions_list: list\n For each condtion, wind direction\n wind_speeds_list: list\n For each condtion, wind speed\n turbulence_intensities_list: list\n For each condtion, wind direction\n wind_shear_list: list\n For each condtion, wind shear\n \"\"\"\n self.yaw_angles_list = yaw_angles_list\n self.wind_directions_list = wind_directions_list\n self.wind_speeds_list = wind_speeds_list\n self.turbulence_intensities_list = turbulence_intensities_list\n self.wind_shear_list = wind_shear_list\n self.tuning_conditions_received = True\n pass\n\n def tune_parameters(self):\n \"\"\"\n Tune specified parameters of a WfModel object.\n Requires higher-fidelity tuning data and the related conditions to be\n previously specified (refer to Tuning methods: tuning_data and tuning_conditions).\n\n Returns\n -------\n wf_model_tuned: WfModel object\n WfModel object with parameters tuned\n wf_model_dict_opt: dictionary\n tuned WfModel object dictionary\n \"\"\"\n # Double check tuning data and conditions have been specified\n if self.tuning_data_received is False:\n err_msg = \"Tuning data not specified. Use tuning_data method.\"\n raise Exception(err_msg)\n if self.tuning_conditions_received is False:\n err_msg = \"Tuning conditions not specified. Use tuning_conditions method.\"\n raise Exception(err_msg)\n\n # Extract original wf_model object dictionary and print its parameters\n self.wf_model_dict_original = floris_extract_object_dict(self.wf_model)\n self.models_dict = floris_extract_models_dict(self.wf_model_dict_original)\n floris_print_params(self.wf_model_dict_original,\n self.models_dict,\n \"Original model parameters\")\n\n # Extract initial variable values and normalise them\n self.variables_init = self._wf_model_dict_to_variables(self.wf_model_dict_original,\n self.variables_class_list,\n self.variables_names_list)\n self.variables_init_norm = self._norm_variables(self.variables_init,\n self.variables_bounds_list)\n\n # Normalize variable bounds\n tmp = self.variables_bounds_list\n (self.variables_bounds_list_norm,\n self.variables_low_bound_list_norm,\n self.variables_upp_bound_list_norm) = self._norm_variables_bounds_lists(tmp)\n\n # Minimisation of error | Extract optimal variables\n self._tuning_optimizer()\n self.opt_variables = self._unnorm_variables(self.opt_variables_norm,\n self.variables_bounds_list)\n\n # Apply tuned parameters (opt_variables) to wf_model and print them\n self.wf_model_dict_opt = self._vars_to_wf_model_dict(self.wf_model_dict_original,\n self.variables_class_list,\n self.variables_names_list,\n self.opt_variables)\n self.wf_model = floris_param_change_object(self.wf_model, self.wf_model_dict_opt)\n floris_print_params(self.wf_model_dict_opt,\n self.models_dict,\n \"Optimal model parameters\")\n\n return self.wf_model, self.wf_model_dict_opt\n\n # %% Private methods\n\n def _wf_model_dict_to_variables(self, wf_model_dict, class_list, names_list):\n variables = []\n for i in range(len(names_list)):\n variable = floris_extract_parameter(wf_model_dict,\n class_list[i],\n names_list[i])\n variables.append(variable)\n return variables\n\n def _norm_variables(self, variables, variables_bounds_list):\n variables_norm = ([norm(variables[i],\n variables_bounds_list[i][0],\n variables_bounds_list[i][1])\n for i in range(len(variables))])\n return variables_norm\n\n def _norm_variables_bounds_lists(self, variables_bounds_list):\n variables_bounds_list_norm = []\n variables_low_bound_list_norm = []\n variables_upp_bound_list_norm = []\n for i, variable_bounds in enumerate(variables_bounds_list):\n lower_bound_norm = norm(variable_bounds[0],\n variable_bounds[0],\n variable_bounds[1])\n upper_bound_norm = norm(variable_bounds[1],\n variable_bounds[0],\n variable_bounds[1])\n bound_norm_tuple = (lower_bound_norm, upper_bound_norm)\n variables_bounds_list_norm.append(bound_norm_tuple)\n variables_low_bound_list_norm.append(lower_bound_norm)\n variables_upp_bound_list_norm.append(upper_bound_norm)\n return (variables_bounds_list_norm,\n np.array(variables_low_bound_list_norm),\n np.array(variables_upp_bound_list_norm))\n\n def _unnorm_variables(self, variables_norm, variables_bounds_list):\n variables = ([unnorm(variables_norm[i],\n variables_bounds_list[i][0],\n variables_bounds_list[i][1])\n for i in range(len(variables_norm))])\n return variables\n\n def _vars_to_wf_model_dict(self,\n wf_model_dict_original,\n variables_class_list,\n variables_names_list,\n variables):\n wf_model_dict_new = copy.deepcopy(wf_model_dict_original)\n for i in range(len(variables)):\n wf_model_dict_new = floris_param_change_object_dict(wf_model_dict_new,\n variables_class_list[i],\n variables_names_list[i],\n variables[i])\n return wf_model_dict_new\n\n def _tuning_optimizer_scipy(self):\n self.opt_results = minimize(self.obj_func,\n self.variables_init_norm,\n method=self.opt_method,\n bounds=self.variables_bounds_list_norm,\n options=self.opt_options)\n self.opt_variables_norm = self.opt_results.x\n\n def _tuning_optimizer_turbo_1(self):\n turbo_1 = Turbo1(f=self.obj_func,\n lb=self.variables_low_bound_list_norm,\n ub=self.variables_upp_bound_list_norm,\n **self.opt_options,\n )\n turbo_1.optimize()\n X = turbo_1.X # Evaluated points\n fX = turbo_1.fX # Observed values\n index_best = np.argmin(fX)\n f_best, x_best = fX[index_best], X[index_best, :]\n self.opt_variables_norm = x_best\n\n def _tuning_rmse_function(self, variables_norm):\n\n # Unnorm variables, create new wf_model dictionary\n variables = self._unnorm_variables(variables_norm, self.variables_bounds_list)\n wf_model_dict_new = self._vars_to_wf_model_dict(self.wf_model_dict_original,\n self.variables_class_list,\n self.variables_names_list,\n variables)\n\n # Create new wf_model object and reinitialize (atmospheric conditions set later)\n self.wf_model = floris_param_change_object(self.wf_model, wf_model_dict_new)\n\n rmse = 0\n for i in range(len(self.tuning_data_power_list)):\n\n # Calculate wind turbine power outputs with model to tune\n floris_reinitialise_atmosphere(self.wf_model,\n ws=self.wind_speeds_list[i],\n wd=self.wind_directions_list[i],\n ti=self.turbulence_intensities_list[i],\n shear=self.wind_shear_list[i])\n yaw_angles = np.array([float(item) for item in self.yaw_angles_list[i]])\n power_turbines = floris_calculate_turbine_power(self.wf_model, yaw_angles)\n\n # Calculate root mean squared error single condition\n error = 0\n for j in range(len(power_turbines)):\n error += (self.tuning_data_power_list[i][j]-power_turbines[j])**2\n rmse_single = error/len(power_turbines)\n\n # Calculate sum of root mean squared errors\n rmse += rmse_single\n\n return rmse" }, { "identifier": "GPWrap", "path": "deasc/gp.py", "snippet": "class GPWrap:\n \"\"\"\n Wrapper class to create, modify and visualise Gaussian Processes for dynamic parameter\n tuning. Currently limited to a single output GP.\n \"\"\"\n\n def __init__(self, parameter_class, parameter_name, dimensions):\n self.parameter_class = parameter_class\n self.parameter_name = parameter_name\n self.dimensions = dimensions\n \"\"\"\n Args\n ----\n parameter_class: string\n Parameter class of the optimal parameter to fit.\n parameter_name: string\n Name of the optimal parameter to fit.\n dimensions: integer\n Dimensions/inputs/variables of the GP.\n \"\"\"\n\n def GP_so(self, yaw_data, param_data, num_restarts=50, noise=0.05):\n \"\"\"\n Construct and returns a single-output (SO) GP for the given input dataset\n (optimal parameter for a given yaw configuration).\n\n Args\n ----\n yaw_data: list of lists\n list of input yaw configurations for which parameter has been tuned\n param_data: list of lists\n for each yaw configuration in yaw_data, list containing the optimal parameter\n num_restarts: int\n number of random starts of the GP hyperparameter tuning optimization\n noise: float\n noise in output prediction. Default is 0.05\n\n Returns\n -------\n m: GPy single-output Gaussian Process model\n \"\"\"\n # Sample check on argument dimension\n if len(yaw_data[0]) != self.dimensions:\n err_msg = (\"Yaw input and GP dimensions do not match\")\n raise Exception(err_msg)\n if len(param_data[0]) != 1:\n err_msg = (\"Single-output GPs only\")\n raise Exception(err_msg)\n\n # Data structure arguments\n yaw_data_GP = np.array(yaw_data)\n param_data_GP = np.array(param_data)\n\n # GP model\n kernel = GPy.kern.RBF(input_dim=self.dimensions, variance=1., lengthscale=1.)\n self.m = GPy.models.GPRegression(yaw_data_GP,\n param_data_GP,\n kernel,\n noise_var=noise)\n\n # Hyperparameter tuning\n self.m.optimize(optimizer=None, # Default lbfgsb\n start=None,\n messages=False,\n max_iters=1000)\n self.m.optimize_restarts(num_restarts=num_restarts)\n return self.m\n\n def GP_so_plot(self, parameter_range_plot, yaw_range_plot):\n \"\"\"\n Plot a single-output (SO) GP model. 1D and 2D plots are generated for each\n variable combination.\n\n Args\n ----\n parameter_range: tuple\n range of the optimal parameter to plot\n parameter_range: tuple\n range of the yaw variables to plot\n \"\"\"\n # Plotting library choice and defaults values\n GPy.plotting.change_plotting_library('matplotlib')\n GPy.plotting.matplot_dep.defaults.data_2d = {'s': 0,\n 'edgecolors': 'none',\n 'linewidth': 0.0,\n 'cmap': cm.get_cmap('hot'),\n 'alpha': 0.5}\n\n # 1D Plots\n if self.dimensions == 1:\n figure = GPy.plotting.plotting_library().figure(1, 1, figsize=(5, 2.5))\n title = 'GP %s' % (self.parameter_name)\n xlabel = '$\\gamma_{1}$ [deg]'\n ylabel = '$%s_{opt}$' % (self.parameter_name)\n fig = self.m.plot(figure=figure,\n col=1,\n row=1,\n title=title,\n xlabel=xlabel,\n ylabel=ylabel,\n ylim=list(parameter_range_plot),\n legend=False,\n plot_data=True)\n else:\n n_cuts = 3\n slices = np.linspace(yaw_range_plot[0], yaw_range_plot[1], n_cuts)\n figsize = (5*n_cuts, 2.5*self.dimensions)\n figure = GPy.plotting.plotting_library().figure(self.dimensions,\n n_cuts,\n figsize=figsize)\n\n for dim_idx in range(self.dimensions):\n for i, slice_single in zip(range(n_cuts), slices):\n title = \"GP %s - $\\gamma_{others}$\" \\\n \"%.1f $^{\\circ}$\" % (self.parameter_name, slice_single)\n xlabel = '$\\gamma_{%i}$ [deg]' % (dim_idx+1)\n ylabel = '$%s_{opt}$' % (self.parameter_name)\n inputs = []\n for j in range(self.dimensions):\n if j == dim_idx:\n pass\n else:\n inputs.append((j, slice_single))\n fig = self.m.plot(figure=figure,\n col=(i+1),\n row=(dim_idx+1),\n fixed_inputs=inputs,\n title=title,\n xlabel=xlabel,\n ylabel=ylabel,\n ylim=list(parameter_range_plot),\n legend=False,\n plot_data=False)\n\n # 2D Plots\n # Countours are fine ##\n # Data points (training) plotted are off ##\n # double checked with GP and training database ##\n if self.dimensions == 1:\n pass\n elif self.dimensions == 2:\n figure = GPy.plotting.plotting_library().figure(1, 1, figsize=(3, 2.5))\n\n title = 'GP %s' % (self.parameter_name)\n xlabel = '$\\gamma_{1}$ [deg]'\n ylabel = '$\\gamma_{2}$ [deg]'\n\n fig = self.m.plot(figure=figure,\n title=title,\n xlabel=xlabel,\n ylabel=ylabel,\n legend=False,\n plot_data=True)\n\n ax = plt.gca()\n mappable = ax.collections[0]\n cbar = plt.colorbar(mappable)\n # cbar.set_label('$%s_{opt}$'%(self.parameter_name))\n else:\n n_cuts = 3\n slices = np.linspace(yaw_range_plot[0], yaw_range_plot[1], n_cuts)\n plot_rows = self.dimensions-1\n plot_cols = self.dimensions-1\n combinations = list(itertools.combinations(\n list(range(0, self.dimensions)), 2))\n\n figsize = (3*plot_cols*len(slices), 2.5*plot_rows)\n figure = GPy.plotting.plotting_library().figure(plot_rows,\n plot_cols*len(slices),\n figsize=figsize)\n for i, slice_single in zip(range(n_cuts), slices):\n for comb_idx, comb in enumerate(combinations):\n title = 'GP %s - $\\gamma_{others}$' \\\n '%.1f $^{\\circ}$' % (self.parameter_name, slice_single)\n xlabel = '$\\gamma_{%i}$ [deg]' % (comb[0]+1)\n ylabel = '$\\gamma_{%i}$ [deg]' % (comb[1]+1)\n inputs = []\n for j in range(self.dimensions):\n if j in comb:\n pass\n else:\n inputs.append((j, slice_single))\n\n fig = self.m.plot(figure=figure,\n col=(comb[0]+1+plot_cols*i),\n row=(comb[1]),\n fixed_inputs=inputs,\n title=title,\n xlabel=xlabel,\n ylabel=ylabel,\n legend=False,\n plot_data=True)\n\n ax = plt.gca()\n mappable = ax.collections[0]\n cbar = plt.colorbar(mappable)\n # cbar.set_label('$%s_{opt}$'%(self.parameter_name))" }, { "identifier": "TuningDyn_Grouping", "path": "deasc/tuning_dynamic.py", "snippet": "class TuningDyn_Grouping(TuningDyn, TuningDyn_SharedMethods):\n \"\"\"Class for dynamic parameter tuning with grouping of turbines within a wind farm.\"\"\"\n\n def __init__(self, param_class, param_name, tuning_groups, GP_model):\n \"\"\"\n Args\n ----\n param_class: (string) tuning parameter class.\n param_name: (string) tuning parameter name.\n tuning_groups: (list of lists) list of turbine groups included in the tuning. In\n each list, specify the turbines in the group.\n GP_model: (GPy object) GP model with len(tuning_groups) input dimensions.\n \"\"\"\n super().__init__(param_class, param_name)\n # Tuning info\n self.tuning_variables = tuning_groups\n self.tuning_dimensions = len(self.tuning_variables)\n self.GP_model = GP_model\n # GP dimension check\n self._GP_dimension_check(self.tuning_dimensions, self.GP_model)\n # Grouping info\n self.tuning_groups = tuning_groups\n self.grouping_bool = True\n\n @property\n def tuning_turbines(self):\n \"\"\"List of the tuning turbines in the wind farm.\"\"\"\n return [x for sublist in self.tuning_variables for x in sublist]\n\n def wso_compatibility_check(self, wso_obj):\n \"\"\"\n Check compatibility with a WSOpt object.\n\n Args\n ----\n wso_obj: (WSOpt) WSOpt object to which dynamic parameter tuning is added.\n \"\"\"\n self._tuning_turbines_check(wso_obj, self.tuning_turbines)\n self._tuning_groups_check(wso_obj)\n\n def tune_parameter(self, wso_obj, yaw_angles):\n \"\"\"\n Perform parameter tuning in a WSOpt object.\n\n Args\n ----\n wso_obj: (WSOpt) WSOpt object.\n yaw_angles: (np.ndarray) yaw angles of all turbines in the wind farm.\n\n Returns\n -------\n wf-model_tuned: (WfModel) tuned WfModel to use in the current iteration of the\n wake steering optimisation.\n \"\"\"\n # Extract WSOpt WfModel dictionary\n wf_model_dict = floris_extract_object_dict(wso_obj.wf_model)\n\n # Create and apply tuned WfModel dictionary\n GP_input = self._get_GP_input_groups(self.tuning_groups, yaw_angles)\n mu, var, = self.GP_model.predict_noiseless(np.array([GP_input]))\n optimal_parameter = mu[0][0]\n wf_model_dict_tuned = floris_param_change_object_dict(wf_model_dict,\n self.param_class,\n self.param_name,\n optimal_parameter)\n wf_model_tuned = floris_param_change_object(wso_obj.wf_model,\n wf_model_dict_tuned)\n return wf_model_tuned\n\n def set_yaw_groups(self, yaw_angles):\n \"\"\"\n Force yaw angles of turbines in tuning groups to be equal in the wake\n steering optimisation.\n\n Args\n ----\n yaw_angles: (np.ndarray) yaw angles of all turbines in the wind farm.\n\n Returns\n -------\n yaw_angles_grouped: (np.ndarray) yaw angles of all turbines in the wind farm with\n equal yaw angles in each turbine group.\n \"\"\"\n return self._set_yaw_groups(yaw_angles)" }, { "identifier": "TuningDyn_Looping_Turbine", "path": "deasc/tuning_dynamic.py", "snippet": "class TuningDyn_Looping_Turbine(TuningDyn, TuningDyn_SharedMethods):\n \"\"\"\n Class for dynamic parameter tuning with the looping approach of turbines within\n a wind farm.\n \"\"\"\n\n def __init__(self, param_class, param_name, tuning_turbine, GP_model, wf_pow_noyaw):\n \"\"\"\n Args\n ----\n param_class: (string) tuning parameter class.\n param_name: (string) tuning parameter name.\n tuning_turbines: (list) list of single turbine included in the tuning.\n GP_model: (GPy object) GP model with a single input dimension.\n wf_pow_noyaw: (float) value of the wind farm power without any yaw applied,\n usually extracted from the previous grouping optimisation to refine.\n \"\"\"\n super().__init__(param_class, param_name)\n # Tuning info\n self.tuning_variables = tuning_turbine\n self.tuning_dimensions = len(self.tuning_variables)\n self.GP_model = GP_model\n self._GP_dimension_check(self.tuning_dimensions, self.GP_model)\n # Looping info\n self.wf_pow_noyaw = wf_pow_noyaw\n self.tuning_bool = True\n\n @property\n def tuning_turbines(self):\n \"\"\"List of the tuning turbines in the wind farm.\"\"\"\n return self.tuning_variables\n\n def wso_compatibility_check(self, wso_obj):\n \"\"\"\n Check compatibility with a WSOpt object.\n\n Args\n ----\n wso_obj: (WSOpt) WSOpt object to which dynamic parameter tuning is added.\n \"\"\"\n self._tuning_turbines_check(wso_obj, self.tuning_turbines)\n self._looping_check(wso_obj)\n\n def tune_parameter(self, wso_obj, yaw_angles):\n \"\"\"\n Perform parameter tuning in a WSOpt object.\n\n Args\n ----\n wso_obj: (WSOpt) WSOpt object.\n yaw_angles: (np.ndarray) yaw angles of all turbines in the wind farm.\n\n Returns\n -------\n wf-model_tuned: (WfModel) tuned WfModel to use in the current iteration of the\n wake steering optimisation.\n \"\"\"\n # Extract WSOpt WfModel dictionary\n wf_model_dict = floris_extract_object_dict(wso_obj.wf_model)\n\n # Create and apply tuned WfModel dictionary\n GP_input = self._get_GP_input_turbines(self.tuning_turbines, yaw_angles)\n mu, var, = self.GP_model.predict_noiseless(np.array([GP_input]))\n optimal_parameter = mu[0][0]\n wf_model_dict_tuned = floris_param_change_object_dict(wf_model_dict,\n self.param_class,\n self.param_name,\n optimal_parameter)\n wf_model_tuned = floris_param_change_object(wso_obj.wf_model,\n wf_model_dict_tuned)\n return wf_model_tuned\n\n def _looping_check(self, wso_obj):\n if len(self.tuning_variables) != 1:\n err_msg = \"While looping, only a single turbine can be tuned.\"\n raise Exception(err_msg)\n if len(wso_obj.variables) != 1:\n err_msg = \"While looping, only a single turbine can be optimised.\"\n raise Exception(err_msg)" }, { "identifier": "floris_extract_object_dict", "path": "deasc/utils_floris.py", "snippet": "def floris_extract_object_dict(wf_model):\n \"\"\"Extract and return the current FLORIS object dictionary.\"\"\"\n return wf_model.interface.floris.as_dict()" }, { "identifier": "floris_extract_parameter", "path": "deasc/utils_floris.py", "snippet": "def floris_extract_parameter(wf_model_dict, param_class, param_name):\n \"\"\"Extract and return the current parameter value of a FLORIS object parameter.\"\"\"\n models_dict = floris_extract_models_dict(wf_model_dict)\n return wf_model_dict['wake'][param_class][models_dict[param_class]][param_name]" }, { "identifier": "floris_param_change_object_dict", "path": "deasc/utils_floris.py", "snippet": "def floris_param_change_object_dict(wf_model_dict, param_class, param_name, param_value):\n \"\"\"\n Change FLORIS object with a new model parameter, return new FLORIS object dictionary.\n FLORIS object is not reinitialised (see function floris_parameter_change_object).\n \"\"\"\n wf_model_dict_new = copy.deepcopy(wf_model_dict)\n models_dict = floris_extract_models_dict(wf_model_dict_new)\n (wf_model_dict_new['wake'][param_class]\n [models_dict[param_class]][param_name]) = param_value\n return wf_model_dict_new" }, { "identifier": "floris_param_change_object", "path": "deasc/utils_floris.py", "snippet": "def floris_param_change_object(wf_model, wf_model_dict_new):\n \"\"\"Change FLORIS object with new object dictionary. Also reinitialise farm layout.\"\"\"\n x_reinit, y_reinit = wf_model.interface.get_turbine_layout()\n wf_model.interface = FI(wf_model_dict_new)\n wf_model.interface.reinitialize(layout_x=x_reinit, layout_y=y_reinit)\n return wf_model" } ]
import numpy as np from deasc import WfModel from deasc import WSOpt from deasc import Tuning from deasc import GPWrap from deasc import TuningDyn_Grouping from deasc import TuningDyn_Looping_Turbine from deasc.utils_floris import ( floris_extract_object_dict, floris_extract_parameter, floris_param_change_object_dict, floris_param_change_object )
15,122
""" This example shows wake steering optimisation on a 5x1 wind farm of NREL 5 MW turbines. Dynamic parameter tuning with the looping approach is implemented to refine the results achieved with grouping. Tuning is introduced in the optimisation for the wake expansion parameter k of the Jensen wake model. The tuning variables are the yaw angles of all wind turbines in the farm, excluding the most downstream one. """ # %% Initial wake steering optimisation - Grouping approach for dynamic parameter tuning # Initialise and set layout for wind farm model path = "./inputs/" input_file = "jensen.yaml"
""" This example shows wake steering optimisation on a 5x1 wind farm of NREL 5 MW turbines. Dynamic parameter tuning with the looping approach is implemented to refine the results achieved with grouping. Tuning is introduced in the optimisation for the wake expansion parameter k of the Jensen wake model. The tuning variables are the yaw angles of all wind turbines in the farm, excluding the most downstream one. """ # %% Initial wake steering optimisation - Grouping approach for dynamic parameter tuning # Initialise and set layout for wind farm model path = "./inputs/" input_file = "jensen.yaml"
wf_model = WfModel(input_file, path)
0
2023-11-10 18:13:27+00:00
24k
PlaxtonFlarion/NexaFlow
nexaflow/skills/alynex.py
[ { "identifier": "toolbox", "path": "nexaflow/toolbox.py", "snippet": "def video_capture(video_path: str):\ndef video_jump(video_cap: cv2.VideoCapture, frame_id: int):\ndef compare_ssim(pic1: np.ndarray, pic2: np.ndarray) -> float:\ndef multi_compare_ssim(\n pic1_list: typing.List, pic2_list: typing.List, hooks: typing.List = None\n) -> typing.List[float]:\ndef get_current_frame_id(video_cap: cv2.VideoCapture) -> int:\ndef get_current_frame_time(video_cap: cv2.VideoCapture) -> float:\ndef imread(img_path: str, *_, **__) -> np.ndarray:\ndef get_frame_time(\n video_cap: cv2.VideoCapture, frame_id: int, recover: bool = None\n) -> float:\ndef get_frame_count(video_cap: cv2.VideoCapture) -> int:\ndef get_frame_size(video_cap: cv2.VideoCapture) -> typing.Tuple[int, int]:\ndef get_frame(\n video_cap: cv2.VideoCapture, frame_id: int, recover: bool = None\n) -> np.ndarray:\ndef turn_grey(old: np.ndarray) -> np.ndarray:\ndef turn_binary(old: np.ndarray) -> np.ndarray:\ndef turn_hog_desc(old: np.ndarray) -> np.ndarray:\ndef turn_lbp_desc(old: np.ndarray, radius: int = None) -> np.ndarray:\ndef turn_blur(old: np.ndarray) -> np.ndarray:\ndef sharpen_frame(old: np.ndarray) -> np.ndarray:\ndef calc_mse(pic1: np.ndarray, pic2: np.ndarray) -> float:\ndef calc_psnr(pic1: np.ndarray, pic2: np.ndarray) -> float:\ndef compress_frame(\n old: np.ndarray,\n compress_rate: float = None,\n target_size: typing.Tuple[int, int] = None,\n not_grey: bool = None,\n interpolation: int = None,\n *_,\n **__,\n) -> np.ndarray:\ndef get_timestamp_str() -> str:\ndef np2b64str(frame: np.ndarray) -> str:\ndef fps_convert(\n target_fps: int, source_path: str, target_path: str, ffmpeg_exe: str = None\n) -> int:\ndef match_template_with_object(\n template: np.ndarray,\n target: np.ndarray,\n engine_template_cv_method_name: str = None,\n **kwargs,\n) -> typing.Dict[str, typing.Any]:\ndef match_template_with_path(\n template: str, target: np.ndarray, **kwargs\n) -> typing.Dict[str, typing.Any]:\ndef show_progress(total: int, color: int, title: str) -> tqdm:\ndef draw_line(image_path: str, save_path: str = None):" }, { "identifier": "Report", "path": "nexaflow/skills/report.py", "snippet": "class Report(object):\n\n __lock: threading.Lock = threading.Lock()\n __initialized: bool = False\n __instance = None\n __init_var = None\n\n def __new__(cls, *args, **kwargs):\n if cls.__instance is None:\n with cls.__lock:\n if cls.__instance is None:\n cls.__instance = super(Report, cls).__new__(cls)\n cls.__init_var = (args, kwargs)\n return cls.__instance\n\n def __init__(self, total_path: str):\n if not self.__initialized:\n self.__initialized = True\n\n self.clock: Any = lambda: time.strftime(\"%Y%m%d%H%M%S\")\n\n self.__title: str = \"\"\n self.__query: str = \"\"\n self.query_path: str = \"\"\n self.video_path: str = \"\"\n self.frame_path: str = \"\"\n self.extra_path: str = \"\"\n\n self.range_list: list[dict] = []\n self.total_list: list[dict] = []\n\n self.total_path = os.path.join(total_path, f\"Nexa_{self.clock()}_{os.getpid()}\", \"Nexa_Collection\")\n # self.total_path = \"/Users/acekeppel/PycharmProjects/NexaFlow/report/Nexa_20230822223025/Nexa_Collection\"\n os.makedirs(self.total_path, exist_ok=True)\n\n self.reset_path = os.path.join(os.path.dirname(self.total_path), \"Nexa_Recovery\")\n os.makedirs(self.reset_path, exist_ok=True)\n log_papers = os.path.join(self.reset_path, \"nexaflow.log\")\n logger.add(log_papers, format=FORMAT, level=\"DEBUG\")\n\n @property\n def proto_path(self) -> str:\n return os.path.join(self.query_path, self.query)\n\n @property\n def title(self):\n return self.__title\n\n @title.setter\n def title(self, title: str):\n self.__title = title\n self.query_path = os.path.join(self.total_path, self.title)\n os.makedirs(self.query_path, exist_ok=True)\n logger.info(f\"✪✪✪✪✪✪✪✪✪✪ {self.title} ✪✪✪✪✪✪✪✪✪✪\\n\")\n\n @title.deleter\n def title(self):\n del self.__title\n\n @property\n def query(self):\n return self.__query\n\n @query.setter\n def query(self, query: str):\n self.__query = query\n self.video_path = os.path.join(self.query_path, self.query, \"video\")\n self.frame_path = os.path.join(self.query_path, self.query, \"frame\")\n self.extra_path = os.path.join(self.query_path, self.query, \"extra\")\n os.makedirs(self.video_path, exist_ok=True)\n os.makedirs(self.frame_path, exist_ok=True)\n os.makedirs(self.extra_path, exist_ok=True)\n logger.info(f\"Start -> {self.query}\")\n\n @query.deleter\n def query(self):\n del self.__query\n\n def load(self, inform: Optional[Dict[str, Union[str | Dict]]]) -> None:\n if inform:\n self.range_list.append(inform)\n logger.info(f\"End -> {self.query}\\n\")\n\n def create_report(self) -> None:\n\n def start_create(result):\n handler_list = []\n query = result.get(\"query\", \"TimeCost\")\n stage = result.get(\"stage\", {\"start\": 1, \"end\": 2, \"cost\": \"0.00000\"})\n frame = result.get(\"frame\", \"\")\n extra = result.get(\"extra\", \"\")\n proto = result.get(\"proto\", \"\")\n\n image_list = []\n for image in os.listdir(frame):\n image_src = os.path.join(query, \"frame\", image)\n image_ids = re.search(r\"\\d+(?=_)\", image).group()\n timestamp = float(re.search(r\"(?<=_).+(?=\\.)\", image).group())\n image_list.append(\n {\n \"src\": image_src,\n \"frames_id\": image_ids,\n \"timestamp\": f\"{timestamp:.5f}\"\n }\n )\n image_list.sort(key=lambda x: int(x[\"frames_id\"]))\n\n extra_list = []\n for ex in os.listdir(extra):\n extra_src = os.path.join(query, \"extra\", ex)\n extra_idx = ex.split(\"(\")[0]\n extra_list.append(\n {\n \"src\": extra_src,\n \"idx\": extra_idx\n }\n )\n extra_list.sort(key=lambda x: int(x[\"idx\"].split(\"(\")[0]))\n\n handler_list.append(\n {\n \"query\": query,\n \"stage\": stage,\n \"image_list\": image_list,\n \"extra_list\": extra_list,\n \"proto\": os.path.join(query, os.path.basename(proto))\n }\n )\n\n return handler_list\n\n if len(self.range_list) > 0:\n if len(self.range_list) == 1:\n images_list = start_create(self.range_list[0])\n else:\n with ThreadPoolExecutor() as executor:\n future = executor.map(start_create, self.range_list)\n images_list = [i for f in future for i in f]\n\n loader = FileSystemLoader(os.path.join(Constants.NEXA, \"template\"))\n environment = Environment(loader=loader)\n template = environment.get_template(\"template_main.html\")\n\n html = template.render(title=self.title, images_list=images_list)\n report_html = os.path.join(self.query_path, f\"{self.title}.html\")\n with open(file=report_html, mode=\"w\", encoding=\"utf-8\") as f:\n f.write(html)\n logger.info(f\"生成聚合报告: {os.path.basename(report_html)}\")\n\n cost_list = [cost['stage']['cost'] for cost in images_list]\n href_path = os.path.join(\n os.path.basename(self.total_path),\n self.title,\n os.path.basename(report_html)\n )\n single = {\n \"case\": self.title,\n \"cost_list\": cost_list,\n \"avg\": f\"{sum(map(float, cost_list)) / len(cost_list):.5f}\",\n \"href\": href_path\n }\n logger.debug(\"Recovery: \" + json.dumps(single, ensure_ascii=False))\n self.total_list.append(single)\n self.range_list.clear()\n else:\n logger.info(\"没有可以聚合的报告 ...\")\n\n logger.info(f\"✪✪✪✪✪✪✪✪✪✪ {self.title} ✪✪✪✪✪✪✪✪✪✪\\n\\n\")\n\n def create_total_report(self) -> None:\n if len(self.total_list) > 0:\n loader = FileSystemLoader(os.path.join(Constants.NEXA, \"template\"))\n environment = Environment(loader=loader)\n template = environment.get_template(\"template_information.html\")\n report_time = time.strftime('%Y.%m.%d %H:%M:%S')\n html = template.render(report_time=report_time, total_list=self.total_list)\n\n total_html_path = os.path.join(os.path.dirname(self.total_path), \"NexaFlow.html\")\n with open(file=total_html_path, mode=\"w\", encoding=\"utf-8\") as f:\n f.write(html)\n logger.info(f\"生成汇总报告: {total_html_path}\\n\\n\")\n self.total_list.clear()\n else:\n logger.info(\"没有可以汇总的报告 ...\")\n\n @staticmethod\n def reset_report(file_name: str) -> None:\n loader = FileSystemLoader(os.path.join(Constants.NEXA, \"template\"))\n environment = Environment(loader=loader)\n template = environment.get_template(\"template_information.html\")\n report_time = time.strftime('%Y.%m.%d %H:%M:%S')\n\n with open(\n file=os.path.join(file_name, \"Nexa_Recovery\", \"nexaflow.log\"),\n mode=\"r\", encoding=\"utf-8\"\n ) as f:\n log_restore = re.findall(r\"(?<=Recovery: ).*}\", f.read())\n total_list = [json.loads(file) for file in log_restore]\n html = template.render(report_time=report_time, total_list=total_list)\n\n total_html_path = os.path.join(file_name, \"NexaFlow.html\")\n with open(file=total_html_path, mode=\"w\", encoding=\"utf-8\") as f:\n f.write(html)\n logger.info(f\"生成汇总报告: {total_html_path}\\n\\n\")\n\n @staticmethod\n def merge_report(merge_list: List[str], loader_merge_loc: str) -> None:\n merge_path = os.path.join(\n os.path.dirname(os.path.dirname(merge_list[0])),\n \"Merge_Nexa_\" + time.strftime(\"%Y%m%d%H%M%S\"),\n \"Nexa_Collection\"\n )\n os.makedirs(merge_path, exist_ok=True)\n log_restore = []\n for merge in merge_list:\n logs = os.path.join(os.path.dirname(merge), \"Nexa_Recovery\", \"nexaflow.log\")\n with open(file=logs, mode=\"r\", encoding=\"utf-8\") as f:\n log_restore.extend(re.findall(r\"(?<=Recovery: ).*}\", f.read()))\n shutil.copytree(\n merge, merge_path, dirs_exist_ok=True,\n ignore=shutil.ignore_patterns(\"NexaFlow.html\", \"nexaflow.log\")\n )\n\n loader = FileSystemLoader(loader_merge_loc)\n environment = Environment(loader=loader)\n template = environment.get_template(\"template_information.html\")\n report_time = time.strftime('%Y.%m.%d %H:%M:%S')\n total_list = [json.loads(file) for file in log_restore]\n html = template.render(report_time=report_time, total_list=total_list)\n\n total_html_path = os.path.join(os.path.dirname(merge_path), \"NexaFlow.html\")\n with open(file=total_html_path, mode=\"w\", encoding=\"utf-8\") as f:\n f.write(html)\n logger.info(f\"合并汇总报告: {total_html_path}\\n\\n\")\n\n @staticmethod\n async def ask_create_report(major_loc, title, total_path, query_path, range_list):\n\n async def handler_inform(result):\n handler_list = []\n query = result.get(\"query\", \"TimeCost\")\n stage = result.get(\"stage\", {\"start\": 1, \"end\": 2, \"cost\": \"0.00000\"})\n frame = result.get(\"frame\", \"\")\n extra = result.get(\"extra\", \"\")\n proto = result.get(\"proto\", \"\")\n\n async def handler_frame():\n handler_image_list = []\n for image in os.listdir(\n os.path.join(\n query_path, query, os.path.basename(frame)\n )\n ):\n image_src = os.path.join(query, \"frame\", image)\n image_ids = re.search(r\"\\d+(?=_)\", image).group()\n timestamp = float(re.search(r\"(?<=_).+(?=\\.)\", image).group())\n handler_image_list.append(\n {\n \"src\": image_src,\n \"frames_id\": image_ids,\n \"timestamp\": f\"{timestamp:.5f}\"\n }\n )\n handler_image_list.sort(key=lambda x: int(x[\"frames_id\"]))\n return handler_image_list\n\n async def handler_extra():\n handler_extra_list = []\n for ex in os.listdir(\n os.path.join(\n query_path, query, os.path.basename(extra)\n )\n ):\n extra_src = os.path.join(query, \"extra\", ex)\n extra_idx = ex.split(\"(\")[0]\n handler_extra_list.append(\n {\n \"src\": extra_src,\n \"idx\": extra_idx\n }\n )\n handler_extra_list.sort(key=lambda x: int(x[\"idx\"].split(\"(\")[0]))\n return handler_extra_list\n\n image_list, extra_list = await asyncio.gather(\n handler_frame(), handler_extra()\n )\n\n handler_list.append(\n {\n \"query\": query,\n \"stage\": stage,\n \"image_list\": image_list,\n \"extra_list\": extra_list,\n \"proto\": os.path.join(query, os.path.basename(proto))\n }\n )\n return handler_list\n\n async def handler_start():\n single = {}\n if len(range_list) > 0:\n tasks = [handler_inform(result) for result in range_list]\n results = await asyncio.gather(*tasks)\n images_list = [ele for res in results for ele in res]\n\n major_loader = FileSystemLoader(major_loc)\n major_environment = Environment(loader=major_loader)\n major_template = major_environment.get_template(\"template_main.html\")\n\n html = major_template.render(title=title, images_list=images_list)\n report_html = os.path.join(query_path, f\"{title}.html\")\n with open(file=report_html, mode=\"w\", encoding=\"utf-8\") as f:\n f.write(html)\n logger.info(f\"生成聚合报告: {os.path.basename(report_html)}\")\n\n cost_list = [cost['stage']['cost'] for cost in images_list]\n href_path = os.path.join(\n os.path.basename(total_path),\n title,\n os.path.basename(report_html)\n )\n single = {\n \"case\": title,\n \"cost_list\": cost_list,\n \"avg\": f\"{sum(map(float, cost_list)) / len(cost_list):.5f}\",\n \"href\": href_path\n }\n logger.debug(\"Recovery: \" + json.dumps(single, ensure_ascii=False))\n else:\n logger.info(\"没有可以聚合的报告 ...\")\n\n logger.info(f\"✪✪✪✪✪✪✪✪✪✪ {title} ✪✪✪✪✪✪✪✪✪✪\\n\\n\")\n return single\n\n return await handler_start()\n\n @staticmethod\n async def ask_create_total_report(file_name: str, major_loc: str, loader_total_loc: str):\n report_time = time.strftime('%Y.%m.%d %H:%M:%S')\n try:\n with open(file=os.path.join(file_name, \"Nexa_Recovery\", \"nexaflow.log\"), mode=\"r\", encoding=\"utf-8\") as f:\n open_file = f.read()\n except FileNotFoundError as e:\n return e\n else:\n match_list = re.findall(r\"(?<=Restore: ).*}\", open_file)\n range_list = [json.loads(file.replace(\"'\", '\"')) for file in match_list if file]\n grouped_dict = defaultdict(list)\n for part in range_list:\n parts = part.pop(\"title\"), part.pop(\"total_path\"), part.pop(\"query_path\")\n grouped_dict[parts].append(part)\n\n tasks = [\n Report.ask_create_report(\n major_loc,\n title,\n os.path.join(file_name, os.path.basename(total_path)),\n os.path.join(file_name, os.path.basename(total_path), title),\n range_list\n )\n for (title, total_path, query_path), range_list in grouped_dict.items()\n ]\n merge_result = await asyncio.gather(*tasks)\n total_list = [merge for merge in merge_result]\n\n if len(total_list) > 0:\n total_loader = FileSystemLoader(loader_total_loc)\n total_environment = Environment(loader=total_loader)\n total_template = total_environment.get_template(\"template_information.html\")\n\n html = total_template.render(report_time=report_time, total_list=total_list)\n total_html = os.path.join(file_name, \"NexaFlow.html\")\n with open(file=total_html, mode=\"w\", encoding=\"utf-8\") as f:\n f.write(html)\n logger.info(f\"生成汇总报告: {total_html}\")\n else:\n logger.info(\"没有可以汇总的报告 ...\")\n\n @staticmethod\n def draw(\n classifier_result,\n proto_path: str,\n compress_rate: float = None,\n target_size: Tuple[int, int] = None,\n boost_mode: bool = False,\n framix_template: str = None\n ) -> str:\n\n label_stable: str = \"稳定阶段\"\n label_unstable: str = \"不稳定阶段\"\n label_unspecific: str = \"不明阶段\"\n\n thumbnail_list: List[Dict[str, str]] = list()\n extra_dict: Dict[str, str] = dict()\n\n if not compress_rate:\n compress_rate = 0.2\n\n try:\n stage_range = classifier_result.get_stage_range()\n except AssertionError:\n stage_range = [classifier_result.data]\n\n if boost_mode:\n for cur_index in range(len(stage_range)):\n each = stage_range[cur_index]\n middle = each[len(each) // 2]\n image_list = []\n if middle.is_stable():\n label = label_stable\n image = toolbox.compress_frame(\n middle.get_data(), compress_rate=compress_rate, target_size=target_size\n )\n frame = {\n \"frame_id\": middle.frame_id,\n \"timestamp\": f\"{middle.timestamp:.5f}\",\n \"image\": toolbox.np2b64str(image)\n }\n image_list.append(frame)\n else:\n if middle.stage == constants.UNKNOWN_STAGE_FLAG:\n label = label_unspecific\n else:\n label = label_unstable\n\n if cur_index + 1 < len(stage_range):\n new_each = [*each, stage_range[cur_index + 1][0]]\n else:\n new_each = each\n\n for i in new_each:\n image = toolbox.compress_frame(\n i.get_data(), compress_rate=compress_rate, target_size=target_size\n )\n frame = {\n \"frame_id\": i.frame_id,\n \"timestamp\": f\"{i.timestamp:.5f}\",\n \"image\": toolbox.np2b64str(image)\n }\n image_list.append(frame)\n\n first, last = each[0], each[-1]\n title = (f\"{label} \"\n f\"区间: {first.frame_id}({first.timestamp:.5f}) - {last.frame_id}({last.timestamp:.5f}) \"\n f\"耗时: {last.timestamp - first.timestamp:.5f} \"\n f\"分类: {first.stage}\")\n thumbnail_list.append({title: image_list})\n else:\n for cur_index in range(len(stage_range)):\n each_range = stage_range[cur_index]\n middle = each_range[len(each_range) // 2]\n\n if middle.is_stable():\n label = label_stable\n elif middle.stage == constants.UNKNOWN_STAGE_FLAG:\n label = label_unspecific\n else:\n label = label_unstable\n\n if cur_index + 1 < len(stage_range):\n range_for_display = [*each_range, stage_range[cur_index + 1][0]]\n else:\n range_for_display = each_range\n\n image_list = []\n for i in range_for_display:\n image = toolbox.compress_frame(\n i.get_data(), compress_rate=compress_rate, target_size=target_size\n )\n frame = {\n \"frame_id\": i.frame_id,\n \"timestamp\": f\"{i.timestamp:.5f}\",\n \"image\": toolbox.np2b64str(image)\n }\n image_list.append(frame)\n\n first, last = each_range[0], each_range[-1]\n title = (f\"{label} \"\n f\"区间: {first.frame_id}({first.timestamp:.5f}) - {last.frame_id}({last.timestamp:.5f}) \"\n f\"耗时: {last.timestamp - first.timestamp:.5f} \"\n f\"分类: {first.stage}\")\n thumbnail_list.append({title: image_list})\n\n cost_dict = classifier_result.calc_changing_cost()\n timestamp = toolbox.get_timestamp_str()\n\n extra_dict[\"视频路径\"] = classifier_result.video_path\n extra_dict[\"总计帧数\"] = str(classifier_result.get_length())\n extra_dict[\"每帧间隔\"] = str(classifier_result.get_offset())\n\n def get_template() -> str:\n template_dirs = os.path.join(Constants.NEXA, \"template\")\n template_path = os.path.join(template_dirs, \"template_extra.html\")\n with open(template_path, encoding=constants.CHARSET) as t:\n template_file = t.read()\n return template_file\n\n if framix_template:\n template = Template(framix_template)\n else:\n template = Template(get_template())\n\n template_content = template.render(\n thumbnail_list=thumbnail_list,\n extras=extra_dict,\n background_color=constants.BACKGROUND_COLOR,\n cost_dict=cost_dict,\n timestamp=timestamp,\n version_code=\"1.0.0\"\n )\n\n default_name = f\"{timestamp}.html\"\n if os.path.isdir(proto_path):\n report_path = os.path.join(proto_path, default_name)\n else:\n report_path = proto_path\n\n with open(report_path, \"w\", encoding=constants.CHARSET) as fh:\n fh.write(template_content)\n logger.info(f\"生成单次报告: {os.path.basename(report_path)}\")\n\n return report_path" }, { "identifier": "Record", "path": "nexaflow/skills/record.py", "snippet": "class Record(object):\n\n def __init__(self):\n self.__connection: Optional[Popen] = None\n self.__record_event: threading.Event = threading.Event()\n self.__initial: str = \"scrcpy\"\n\n def start_record(self, video_path: str, serial: str = None) -> None:\n cmd = [\n self.__initial, \"--no-audio\", \"--video-bit-rate\", \"8M\", \"--max-fps\", \"60\", \"-Nr\",\n f\"{os.path.join(video_path, 'screen')}.mkv\"\n ]\n if serial:\n cmd.insert(1, \"-s\")\n cmd.insert(2, serial)\n self.__connection = Terminal.cmd_connect(cmd)\n\n def stream(flow: Union[int, IO[str]]) -> None:\n for line in iter(flow.readline, \"\"):\n logger.info(\" \".join(line.strip().split()))\n flow.close()\n\n if self.__connection:\n self.__record_event.set()\n threading.Thread(target=stream, args=(self.__connection.stdout, )).start()\n threading.Thread(target=stream, args=(self.__connection.stderr, )).start()\n time.sleep(1)\n\n def stop_record(self) -> None:\n self.__connection.send_signal(signal.CTRL_C_EVENT)\n self.__record_event.clear()\n self.__connection = None\n\n try:\n Terminal.cmd_oneshot([\"taskkill\", \"/im\", \"scrcpy.exe\"])\n except KeyboardInterrupt:\n logger.info(\"Stop with Ctrl_C_Event ...\")" }, { "identifier": "Player", "path": "nexaflow/skills/player.py", "snippet": "class Player(object):\n\n def __init__(self):\n pygame.mixer.init()\n\n @staticmethod\n def load_all_audio(audio_dirs: str) -> List[Tuple[str, str]]:\n audio_list = []\n for audio_file in os.listdir(audio_dirs):\n if \".mp3\" in audio_file or \".wav\" in audio_file:\n if match := re.search(r\".*?(?=\\.)\", audio_file):\n audio_list.append(\n (match.group(), os.path.join(audio_dirs, audio_file))\n )\n return audio_list\n\n @staticmethod\n def load_audio(audio_dirs: str, audio_name: str) -> Tuple[str, str]:\n query, audio = \"\", \"\"\n for audio_file in os.listdir(audio_dirs):\n if audio_name in audio_file:\n if match := re.search(r\".*?(?=\\.)\", audio_file):\n query = match.group()\n audio = os.path.join(audio_dirs, audio_file)\n return query, audio\n\n @staticmethod\n def play_audio(audio_file: str, volume: float = 1.0):\n if os.path.isfile(audio_file):\n pygame.mixer.music.load(audio_file)\n pygame.mixer.music.set_volume(volume)\n pygame.mixer.music.play()\n logger.info(f\"INFO: Playing audio {audio_file}\")\n while pygame.mixer.music.get_busy():\n pygame.time.Clock().tick(10)\n else:\n logger.error(f\"{audio_file} 不是一个音频文件 ...\")" }, { "identifier": "Switch", "path": "nexaflow/skills/switch.py", "snippet": "class Switch(object):\n\n def __init__(self):\n self.__ffmpeg = \"ffmpeg\"\n self.__ffprobe = \"ffprobe\"\n\n async def audio_reform(self, src: str, dst: str) -> None:\n \"\"\"\n 调整mp3编码格式为标准mp3\n :param src: 原音频路径\n :param dst: 新音频路径\n \"\"\"\n cmd = [self.__ffmpeg, \"-i\", src, \"-ar\", \"44100\", \"-b:a\", \"128k\", dst]\n await Terminal.cmd_line(*cmd)\n\n async def video_reform(self, src: str, dst: str) -> None:\n \"\"\"\n 转换视频格式\n :param src: 原始视频路径\n :param dst: 新视频路径\n \"\"\"\n cmd = [self.__ffmpeg, \"-i\", src, \"-r\", \"60\", dst]\n await Terminal.cmd_line(*cmd)\n\n async def video_change(self, src: str, dst: str) -> None:\n \"\"\"\n 调整视频\n :param src: 原视频路径\n :param dst: 新视频路径\n \"\"\"\n cmd = [\n self.__ffmpeg, \"-i\", src, \"-vf\", \"fps=60\", \"-c:v\",\n \"libx264\", \"-crf\", \"18\", \"-c:a\", \"copy\", dst\n ]\n await Terminal.cmd_line(*cmd)\n\n async def video_tailor(self, src: str, dst: str, start: str = \"00:00:00\", end: str = \"00:00:05\") -> None:\n \"\"\"\n 截取视频\n :param src: 原视频路径\n :param dst: 新视频路径\n :param start: 开始\n :param end: 结束\n \"\"\"\n before = os.path.basename(src).split(\".\")[0]\n after = os.path.basename(src).split(\".\")[-1]\n target = os.path.join(\n dst,\n f\"{before}_{time.strftime('%Y%m%d%H%M%S')}_{random.randint(100, 999)}.{after}\"\n )\n cmd = [self.__ffmpeg, \"-i\", src, \"-ss\", start, \"-t\", end, \"-c\", \"copy\", target]\n await Terminal.cmd_line(*cmd)\n\n async def video_cutter(self, src: str, dst: str, start: str = \"00:00:00\", end: str = \"00:00:05\") -> None:\n \"\"\"\n 流式截取视频\n :param src: 原视频路径\n :param dst: 新视频路径\n :param start: 开始\n :param end: 结束\n \"\"\"\n before = os.path.basename(src).split(\".\")[0]\n after = os.path.basename(src).split(\".\")[-1]\n target = os.path.join(\n dst,\n f\"{before}_{time.strftime('%Y%m%d%H%M%S')}_{random.randint(100, 999)}.{after}\"\n )\n cmd = [\n self.__ffmpeg, \"-i\", src, \"-ss\", start, \"-t\", end, \"-vf\", \"fps=60\",\n \"-c:v\", \"libx264\", \"-crf\", \"18\", \"-c:a\", \"copy\", target\n ]\n await Terminal.cmd_line(*cmd)\n\n async def video_length(self, src: str) -> float:\n \"\"\"\n 查看视频的时间长度\n :param src: 原视频路径\n :return: 视频时间长度\n \"\"\"\n cmd = [\n self.__ffprobe, \"-v\", \"error\", \"-show_entries\", \"format=duration\",\n \"-of\", \"default=noprint_wrappers=1:nokey=1\", \"-i\", src\n ]\n result = await Terminal.cmd_line(*cmd)\n return float(result.strip())" }, { "identifier": "VideoCutter", "path": "nexaflow/cutter/cutter.py", "snippet": "class VideoCutter(object):\n\n def __init__(\n self,\n step: int = None,\n compress_rate: float = None,\n target_size: typing.Tuple[int, int] = None,\n ):\n\n self.step = step or 1\n\n if (not compress_rate) and (not target_size):\n # logger.debug(\n # f\"no compress rate or target size received. set compress rate to 0.2\"\n # )\n compress_rate = 0.2\n\n self._hook_list: typing.List[BaseHook] = list()\n compress_hook = CompressHook(\n overwrite=True, compress_rate=compress_rate, target_size=target_size\n )\n grey_hook = GreyHook(overwrite=True)\n self.add_hook(compress_hook)\n self.add_hook(grey_hook)\n\n def add_hook(self, new_hook: BaseHook):\n self._hook_list.append(new_hook)\n # logger.debug(f\"add hook: {new_hook.__class__.__name__}\")\n\n @staticmethod\n def pic_split(origin: np.ndarray, block: int) -> typing.List[np.ndarray]:\n result: typing.List[np.ndarray] = list()\n for each_block in np.array_split(origin, block, axis=0):\n sub_block = np.array_split(each_block, block, axis=1)\n result += sub_block\n return result\n\n def _apply_hook(self, frame: VideoFrame, *args, **kwargs) -> VideoFrame:\n for each_hook in self._hook_list:\n frame = each_hook.do(frame, *args, **kwargs)\n return frame\n\n @staticmethod\n def compare_frame_list(\n src: typing.List[np.ndarray], target: typing.List[np.ndarray]\n ) -> typing.List[float]:\n\n ssim = 1.0\n mse = 0.0\n psnr = 0.0\n\n for part_index, (each_start, each_end) in enumerate(zip(src, target)):\n part_ssim = toolbox.compare_ssim(each_start, each_end)\n if part_ssim < ssim:\n ssim = part_ssim\n\n part_mse = toolbox.calc_mse(each_start, each_end)\n if part_mse > mse:\n mse = part_mse\n\n part_psnr = toolbox.calc_psnr(each_start, each_end)\n if part_psnr > psnr:\n psnr = part_psnr\n # logger.debug(\n # f\"part {part_index}: ssim={part_ssim}; mse={part_mse}; psnr={part_psnr}\"\n # )\n return [ssim, mse, psnr]\n\n @staticmethod\n def split_into_parts(value: int, parts: int) -> List[Tuple[int, int, int]]:\n division, remainder = value // parts, value % parts\n result, current_start = [], 1\n\n for i in range(parts):\n current_end = current_start + division - 1\n if i == parts - 1: # 处理最后一部分,加上余数\n current_end += remainder\n result.append((current_start, current_end, current_end - current_start))\n\n if i < parts - 1: # 不是最后一部分时,添加断开部分\n gap_start = current_end\n gap_end = current_end + 1\n result.append((gap_start, gap_end, gap_end - gap_start))\n current_start = current_end + 1\n\n return result\n\n def handler_frames(self, window: Window) -> typing.List[VideoCutRange]:\n range_list_part = []\n\n def technique():\n frame_list = window.load_data()\n frame_list = [self._apply_hook(each) for each in frame_list]\n\n ssim_list, mse_list, psnr_list = [], [], []\n\n cur_frame = frame_list[0]\n first_target_frame = frame_list[1]\n cur_frame_list = self.pic_split(cur_frame.data, window.block)\n for each in frame_list[1:]:\n each_frame_list = self.pic_split(each.data, window.block)\n ssim, mse, psnr = self.compare_frame_list(\n cur_frame_list, each_frame_list\n )\n ssim_list.append(ssim)\n mse_list.append(mse)\n psnr_list.append(psnr)\n\n ssim = window.float_merge(ssim_list)\n mse = window.float_merge(mse_list)\n psnr = window.float_merge(psnr_list)\n\n range_list_part.append(\n VideoCutRange(\n window.video,\n start=cur_frame.frame_id, end=first_target_frame.frame_id,\n ssim=[ssim], mse=[mse], psnr=[psnr],\n start_time=cur_frame.timestamp, end_time=first_target_frame.timestamp,\n )\n )\n\n pbar = toolbox.show_progress(window.frame_total, 174, \"Cutter\")\n while True:\n technique()\n pbar.update(1)\n\n continue_flag = window.shift()\n if not continue_flag:\n pbar.close()\n break\n\n return range_list_part\n\n def _convert_video_into_range_list(\n self, video: VideoObject, block: int, window_size: int, window_coefficient: int\n ) -> typing.List[VideoCutRange]:\n\n step = self.step\n video_length = video.frame_count\n range_list: typing.List[VideoCutRange] = list()\n logger.info(f\"总帧数: {video_length} 片段数: {video_length - 1} 分辨率: {video.frame_size}\")\n\n window_list: List[\"Window\"] = []\n for index, parts in enumerate(self.split_into_parts(video_length, 2)):\n start, end, size = parts\n logger.info(f\"帧片段: {index + 1:02} Start: {start:03} End: {end:03} Length: {size:03}\")\n window = Window(video, step, block, window_size, window_coefficient, start, end, size)\n window_list.append(window)\n\n with ThreadPoolExecutor() as executor:\n futures = [executor.submit(self.handler_frames, w) for w in window_list]\n for future in futures:\n range_list.extend(future.result())\n\n return range_list\n\n def cut(\n self,\n video: typing.Union[str, VideoObject],\n block: int = None,\n window_size: int = None,\n window_coefficient: int = None,\n *_,\n **kwargs,\n ) -> VideoCutResult:\n\n if not block:\n block = 3\n if not window_size:\n window_size = 1\n if not window_coefficient:\n window_coefficient = 2\n\n start_time = time.time()\n if isinstance(video, str):\n video = VideoObject(video)\n\n logger.info(f\"开始压缩视频: {os.path.basename(video.path)}\")\n range_list = self._convert_video_into_range_list(\n video, block, window_size, window_coefficient\n )\n logger.info(f\"视频压缩完成: {os.path.basename(video.path)}\")\n logger.info(f\"视频压缩耗时: {(time.time() - start_time):.2f}秒\")\n\n return VideoCutResult(video, range_list, cut_kwargs=kwargs)" }, { "identifier": "VideoObject", "path": "nexaflow/video.py", "snippet": "class VideoObject(object):\n\n def __init__(\n self,\n path: typing.Union[str, os.PathLike],\n fps: int = None,\n ):\n \"\"\"\n 初始化,检查文件路径是否有效,执行其他一些初始化操作\n \"\"\"\n assert os.path.isfile(path), f\"video {path} not existed\"\n self.path: str = str(path)\n self.grey_data: typing.Optional[typing.Tuple[\"VideoFrame\"]] = tuple() # 灰度帧\n self.hued_data: typing.Optional[typing.Tuple[\"ColorFrame\"]] = tuple() # 彩色帧\n\n if fps:\n video_path = os.path.join(tempfile.mkdtemp(), f\"tmp_{fps}.mp4\")\n logger.debug(f\"convert video, and bind path to {video_path}\")\n logger.info(f\"转换视频: {video_path}\")\n toolbox.fps_convert(\n fps, self.path, video_path, imageio_ffmpeg.get_ffmpeg_exe()\n )\n self.path = video_path\n\n with toolbox.video_capture(self.path) as cap:\n self.frame_count = toolbox.get_frame_count(cap)\n self.frame_size = toolbox.get_frame_size(cap)\n\n logger.info(f\"视频已生成,视频帧长度: {self.frame_count} 分辨率: {self.frame_size}\")\n\n def __str__(self):\n return f\"<VideoObject path={self.path}>\"\n\n __repr__ = __str__\n\n def sync_timestamp(self, frame_data: tuple[VideoFrame]) -> None:\n assert frame_data, \"load_frames() first\"\n vid = mpy.VideoFileClip(self.path)\n\n vid_count = vid.reader.nframes\n pbar = toolbox.show_progress(vid_count, 153, \"Synzer\")\n for frame_id, (timestamp, _) in enumerate(vid.iter_frames(with_times=True)):\n if frame_id >= len(frame_data):\n break\n # frame_id_real = frame_id + 1\n if not frame_data[frame_id].timestamp:\n # logger.debug(f\"fix frame {frame_id_real}'s timestamp: {timestamp}\")\n frame_data[frame_id].timestamp = timestamp\n pbar.update(1)\n pbar.close()\n\n def sync_backstage(self, frame_data: tuple[ColorFrame]) -> None:\n assert frame_data, \"load_frames() first\"\n vid = mpy.VideoFileClip(self.path)\n\n for frame_id, (timestamp, _) in enumerate(vid.iter_frames(with_times=True)):\n if frame_id >= len(frame_data):\n break\n # frame_id_real = frame_id + 1\n if not frame_data[frame_id].timestamp:\n # logger.debug(f\"fix frame {frame_id_real}'s timestamp: {timestamp}\")\n frame_data[frame_id].timestamp = timestamp\n\n def clean_frames(self):\n \"\"\"\n 清除所有帧数据\n \"\"\"\n self.grey_data = tuple()\n self.hued_data = tuple()\n\n @staticmethod\n def frame_details(frame_type):\n each_cost = frame_type[0].data.nbytes / (1024 ** 2)\n total_cost = each_cost * len(frame_type)\n frame_size = frame_type[0].data.shape[::-1]\n return f\"{frame_type[0].__class__.__name__}: [{each_cost:.2f} MB] [{total_cost:.2f} MB] {frame_size}\"\n\n def load_frames(self, color: bool = False):\n \"\"\"\n 从文件中加载所有帧到内存\n \"\"\"\n logger.info(f\"加载视频帧到内存: {os.path.basename(self.path)}\")\n\n def load_stream(frames: type[VideoFrame]):\n pbar = toolbox.show_progress(self.frame_count, 180, \"Loader\")\n data: list[VideoFrame] = []\n with toolbox.video_capture(self.path) as cap:\n for success, frame in iter(lambda: cap.read(), (False, None)):\n if success:\n data.append(frames.initial(cap, frame))\n pbar.update(1)\n pbar.close()\n return data\n\n def back_ground(frames: type[ColorFrame]):\n data: list[ColorFrame] = []\n with toolbox.video_capture(self.path) as cap:\n for success, frame in iter(lambda: cap.read(), (False, None)):\n if success:\n data.append(frames.initial(cap, frame))\n return data\n\n def load_stream_sync(brand):\n self.sync_timestamp(tuple(frame_data := load_stream(brand)))\n return frame_data\n\n def back_ground_sync(brand):\n self.sync_backstage(tuple(frame_data := back_ground(brand)))\n return frame_data\n\n start_time, task, hued = time.time(), None, None\n if color:\n task = ThreadPoolExecutor()\n hued = task.submit(back_ground_sync, ColorFrame)\n\n grey = load_stream_sync(VideoFrame)\n self.grey_data = tuple(grey)\n logger.info(f\"灰度帧已加载: {self.frame_details(self.grey_data)}\")\n logger.info(f\"视频加载耗时: {time.time() - start_time:.2f} 秒\")\n return task, hued\n\n def _read_from_file(self) -> typing.Generator[\"VideoFrame\", None, None]:\n \"\"\"\n 从文件中读取帧\n \"\"\"\n with toolbox.video_capture(self.path) as cap:\n success, frame = cap.read()\n while success:\n yield VideoFrame.initial(cap, frame)\n success, frame = cap.read()\n\n def _read_from_mem(self) -> typing.Generator[\"VideoFrame\", None, None]:\n \"\"\"\n 从内存中读取帧\n \"\"\"\n for each_frame in self.grey_data:\n yield each_frame\n\n def _read(self) -> typing.Generator[\"VideoFrame\", None, None]:\n \"\"\"\n 选择从文件还是从内存中读取帧\n \"\"\"\n if self.grey_data:\n yield from self._read_from_mem()\n else:\n yield from self._read_from_file()\n\n def get_iterator(self) -> typing.Generator[\"VideoFrame\", None, None]:\n \"\"\"\n 获取帧的迭代器\n \"\"\"\n return self._read()\n\n def get_operator(self) -> _BaseFrameOperator:\n \"\"\"\n 根据是否已经加载帧,返回相应的FrameOperator(`MemFrameOperator`或`FileFrameOperator`)\n \"\"\"\n if self.grey_data:\n return MemFrameOperator(self)\n return FileFrameOperator(self)\n\n def __iter__(self):\n \"\"\"\n 返回一个用于迭代帧的迭代器\n \"\"\"\n return self.get_iterator()" }, { "identifier": "Frame", "path": "nexaflow/video.py", "snippet": "class Frame(object):\n\n def __init__(self, frame_id: int, timestamp: float, data: np.ndarray):\n self.frame_id: int = frame_id\n self.timestamp: float = timestamp\n self.data: np.ndarray = data\n\n @staticmethod\n def initial(cap: cv2.VideoCapture, frame: np.ndarray) -> \"Frame\":\n raise NotImplementedError\n\n def copy(self) -> \"Frame\":\n raise NotImplementedError" }, { "identifier": "KerasClassifier", "path": "nexaflow/classifier/keras_classifier.py", "snippet": "class KerasClassifier(BaseModelClassifier):\n\n UNKNOWN_STAGE_NAME = constants.UNKNOWN_STAGE_FLAG\n MODEL_DENSE = 6\n\n def __init__(\n self,\n score_threshold: float = None,\n data_size: typing.Sequence[int] = None,\n nb_train_samples: int = None,\n nb_validation_samples: int = None,\n epochs: int = None,\n batch_size: int = None,\n *_,\n **__,\n ):\n super(KerasClassifier, self).__init__(*_, **__)\n\n # 模型\n self._model: typing.Optional[keras.Sequential] = None\n # 配置\n self.score_threshold: float = score_threshold or 0.0\n self.data_size: typing.Sequence[int] = data_size or (200, 200)\n self.nb_train_samples: int = nb_train_samples or 64\n self.nb_validation_samples: int = nb_validation_samples or 64\n self.epochs: int = epochs or 20\n self.batch_size: int = batch_size or 4\n\n # logger.debug(f\"score threshold: {self.score_threshold}\")\n # logger.debug(f\"data size: {self.data_size}\")\n # logger.debug(f\"nb train samples: {self.nb_train_samples}\")\n # logger.debug(f\"nb validation samples: {self.nb_validation_samples}\")\n # logger.debug(f\"epochs: {self.epochs}\")\n # logger.debug(f\"batch size: {self.batch_size}\")\n\n @property\n def follow_keras_size(self):\n return self.data_size[1], self.data_size[0]\n\n @property\n def follow_cv_size(self):\n return self.data_size[0], self.data_size[1]\n\n def clean_model(self):\n self._model = None\n\n def save_model(self, model_path: str, overwrite: bool = None):\n logger.debug(f\"save model to {model_path}\")\n # assert model file\n if os.path.isfile(model_path) and not overwrite:\n raise FileExistsError(\n f\"model file {model_path} already existed, you can set `overwrite` True to cover it\"\n )\n # assert model data is not empty\n assert self._model, \"model is empty\"\n print(self._model.summary())\n self._model.save_weights(model_path)\n\n def load_model(self, model_path: str, overwrite: bool = None):\n # logger.debug(f\"load model from {model_path}\")\n logger.info(f\"加载Keras神经网络引擎 ...\")\n # assert model file\n assert os.path.isfile(model_path), f\"model file {model_path} not existed\"\n # assert model data is empty\n if self._model and not overwrite:\n raise RuntimeError(\n f\"model is not empty, you can set `overwrite` True to cover it\"\n )\n self._model = self.create_model()\n self._model.load_weights(model_path)\n\n def create_model(self) -> keras.Sequential:\n # logger.info(f\"creating Keras sequential model\")\n logger.info(\"Keras神经网络引擎创建图像分析模型 ...\")\n if keras.backend.image_data_format() == \"channels_first\":\n input_shape = (1, *self.follow_keras_size)\n else:\n input_shape = (*self.follow_keras_size, 1)\n\n model = keras.Sequential()\n\n model.add(keras.layers.Conv2D(32, (3, 3), padding=\"same\", input_shape=input_shape))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(keras.layers.Dropout(0.25))\n\n model.add(keras.layers.Conv2D(64, (3, 3), padding=\"same\"))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(keras.layers.Dropout(0.25))\n\n model.add(keras.layers.Conv2D(128, (3, 3), padding=\"same\"))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(keras.layers.Dropout(0.25))\n\n model.add(keras.layers.Flatten())\n model.add(keras.layers.Dense(256, activation=\"relu\"))\n model.add(keras.layers.Dropout(0.5))\n model.add(keras.layers.Dense(self.MODEL_DENSE, activation=\"softmax\"))\n\n model.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"])\n\n # logger.info(\"Keras model created\")\n logger.info(\"Keras神经网络引擎加载完成,开始分析图像 ...\")\n return model\n\n def train(self, data_path: str = None, *_, **__):\n\n def _data_verify(p: str):\n p = pathlib.Path(p)\n assert p.is_dir(), f\"{p} is not a valid directory\"\n\n number_of_dir = len([each for each in os.listdir(p) if (p / each).is_dir()])\n assert (\n number_of_dir > 1\n ), f\"dataset only contains one class. maybe some path errors happened: {p}?\"\n\n assert number_of_dir <= self.MODEL_DENSE, (\n f\"dataset has {number_of_dir} classes (more than \" + str(self.MODEL_DENSE) + \")\"\n )\n\n _data_verify(data_path)\n\n if not self._model:\n self._model = self.create_model()\n\n datagen = keras.preprocessing.image.ImageDataGenerator(\n rescale=1.0 / 16,\n shear_range=0.2,\n zoom_range=0.2,\n validation_split=0.33,\n horizontal_flip=True # 水平翻转增强\n )\n\n train_generator = datagen.flow_from_directory(\n data_path,\n target_size=self.follow_keras_size,\n batch_size=self.batch_size,\n color_mode=\"grayscale\",\n class_mode=\"sparse\",\n subset=\"training\",\n )\n\n validation_generator = datagen.flow_from_directory(\n data_path,\n target_size=self.follow_keras_size,\n batch_size=self.batch_size,\n color_mode=\"grayscale\",\n class_mode=\"sparse\",\n subset=\"validation\",\n )\n\n self._model.fit(\n train_generator,\n epochs=self.epochs,\n validation_data=validation_generator,\n )\n\n logger.debug(\"train finished\")\n\n def predict(self, pic_path: str, *args, **kwargs) -> str:\n pic_object = toolbox.imread(pic_path)\n # fake VideoFrame for apply_hook\n fake_frame = VideoFrame(0, 0.0, pic_object)\n fake_frame = self._apply_hook(fake_frame, *args, **kwargs)\n return self.predict_with_object(fake_frame.data)\n\n def predict_with_object(self, frame: np.ndarray) -> str:\n # resize for model\n frame = cv2.resize(frame, dsize=self.follow_cv_size)\n frame = np.expand_dims(frame, axis=[0, -1])\n # verbose = 0, 静默Keras分类显示\n result = self._model.predict(frame, verbose=0)\n tag = str(np.argmax(result, axis=1)[0])\n confidence = result.max()\n # logger.debug(f\"confidence: {confidence}\")\n if confidence < self.score_threshold:\n logger.warning(\n f\"max score is lower than {self.score_threshold}, unknown class\"\n )\n return self.UNKNOWN_STAGE_NAME\n return tag\n\n def _classify_frame(self, frame: VideoFrame, *_, **__) -> str:\n return self.predict_with_object(frame.data)" }, { "identifier": "BaseHook", "path": "nexaflow/hook.py", "snippet": "class BaseHook(object):\n\n def __init__(self, *_, **__):\n # logger.debug(f\"start initialing: {self.__class__.__name__} ...\")\n logger.info(f\"加载视频帧处理单元: Frame Processor {self.__class__.__name__} ...\")\n self.result = dict()\n\n def do(self, frame: VideoFrame, *_, **__) -> typing.Optional[VideoFrame]:\n # info = f\"execute hook: {self.__class__.__name__}\"\n\n frame_id = frame.frame_id\n if frame_id != -1:\n # logger.debug(f\"{info}, frame id: {frame_id}\")\n pass\n return frame" }, { "identifier": "CropHook", "path": "nexaflow/hook.py", "snippet": "class CropHook(_AreaBaseHook):\n\n def do(self, frame: VideoFrame, *_, **__) -> typing.Optional[VideoFrame]:\n super().do(frame, *_, **__)\n\n height_range, width_range = self.convert_size_and_offset(*frame.data.shape)\n frame.data[: height_range[0], :] = 0\n frame.data[height_range[1]:, :] = 0\n frame.data[:, : width_range[0]] = 0\n frame.data[:, width_range[1]:] = 0\n return frame" }, { "identifier": "OmitHook", "path": "nexaflow/hook.py", "snippet": "class OmitHook(_AreaBaseHook):\n\n def do(self, frame: VideoFrame, *_, **__) -> typing.Optional[VideoFrame]:\n super().do(frame, *_, **__)\n\n height_range, width_range = self.convert_size_and_offset(*frame.data.shape)\n frame.data[\n height_range[0]: height_range[1], width_range[0]: width_range[1]\n ] = 0\n return frame" }, { "identifier": "FrameSaveHook", "path": "nexaflow/hook.py", "snippet": "class FrameSaveHook(BaseHook):\n\n def __init__(self, target_dir: str, *_, **__):\n super().__init__(*_, **__)\n\n self.target_dir = target_dir\n os.makedirs(target_dir, exist_ok=True)\n # logger.debug(f\"target dir: {target_dir}\")\n\n def do(self, frame: VideoFrame, *_, **__) -> typing.Optional[VideoFrame]:\n super().do(frame, *_, **__)\n\n safe_timestamp = str(frame.timestamp).replace(\".\", \"_\")\n frame_name = f\"{frame.frame_id}({safe_timestamp}).png\"\n target_path = os.path.join(self.target_dir, frame_name)\n\n # 不能保存中文路径\n # cv2.imwrite(target_path, frame.data)\n # logger.debug(f\"frame saved to {target_path}\")\n\n # 保存中文路径\n cv2.imencode(\".png\", frame.data)[1].tofile(target_path)\n\n return frame" }, { "identifier": "ClassifierResult", "path": "nexaflow/classifier/base.py", "snippet": "class ClassifierResult(object):\n\n LABEL_DATA: str = \"data\"\n LABEL_VIDEO_PATH: str = \"video_path\"\n\n def __init__(self, data: typing.List[SingleClassifierResult]):\n self.video_path: str = data[0].video_path\n self.data: typing.List[SingleClassifierResult] = data\n\n def get_timestamp_list(self) -> typing.List[float]:\n return [each.timestamp for each in self.data]\n\n def get_stage_list(self) -> typing.List[str]:\n return [each.stage for each in self.data]\n\n def get_length(self) -> int:\n return len(self.data)\n\n def get_offset(self) -> float:\n return self.data[1].timestamp - self.data[0].timestamp\n\n def get_ordered_stage_set(self) -> typing.List[str]:\n ret = list()\n for each in self.get_stage_list():\n if not ret:\n ret.append(each)\n continue\n if each == ret[-1]:\n continue\n ret.append(each)\n return ret\n\n def get_stage_set(self) -> typing.Set[str]:\n return set(self.get_stage_list())\n\n def to_dict(\n self,\n ) -> typing.Dict[str, typing.List[typing.List[SingleClassifierResult]]]:\n stage_list = list(self.get_stage_set())\n try:\n int(stage_list[0])\n except ValueError:\n stage_list.sort()\n else:\n stage_list.sort(key=lambda o: int(o))\n\n d = OrderedDict()\n for each_stage in stage_list:\n d[each_stage] = self.get_specific_stage_range(each_stage)\n return d\n\n def contain(self, stage_name: str) -> bool:\n return stage_name in self.get_stage_set()\n\n def first(self, stage_name: str) -> SingleClassifierResult:\n for each in self.data:\n if each.stage == stage_name:\n # logger.debug(f\"first frame of {stage_name}: {each}\")\n return each\n logger.warning(f\"no stage named {stage_name} found\")\n\n def last(self, stage_name: str) -> SingleClassifierResult:\n for each in self.data[::-1]:\n if each.stage == stage_name:\n # logger.debug(f\"last frame of {stage_name}: {each}\")\n return each\n logger.warning(f\"no stage named {stage_name} found\")\n\n def get_stage_range(self) -> typing.List[typing.List[SingleClassifierResult]]:\n result: typing.List[typing.List[SingleClassifierResult]] = []\n\n cur = self.data[0]\n cur_index = cur.frame_id - 1\n ptr = cur_index\n length = self.get_length()\n while ptr < length:\n next_one = self.data[ptr]\n if cur.stage == next_one.stage:\n ptr += 1\n continue\n\n result.append(self.data[cur_index: ptr + 1 - 1] or [self.data[cur_index]])\n cur = next_one\n cur_index = next_one.frame_id - 1\n\n assert len(result) > 0, \"video seems to only contain one stage\"\n\n last_data = self.data[-1]\n last_result = result[-1][-1]\n if last_result != last_data:\n result.append(\n self.data[last_result.frame_id - 1 + 1: last_data.frame_id - 1 + 1]\n or [self.data[last_result.frame_id - 1]]\n )\n # logger.debug(f\"get stage range: {result}\")\n return result\n\n def get_specific_stage_range(\n self, stage_name: str\n ) -> typing.List[typing.List[SingleClassifierResult]]:\n ret = list()\n for each_range in self.get_stage_range():\n cur = each_range[0]\n if cur.stage == stage_name:\n ret.append(each_range)\n return ret\n\n def get_not_stable_stage_range(\n self,\n ) -> typing.List[typing.List[SingleClassifierResult]]:\n unstable = self.get_specific_stage_range(constants.UNSTABLE_FLAG)\n ignore = self.get_specific_stage_range(constants.IGNORE_FLAG)\n return sorted(unstable + ignore, key=lambda x: x[0].stage)\n\n def mark_range(self, start: int, end: int, target_stage: str):\n for each in self.data[start:end]:\n each.stage = target_stage\n # logger.debug(f\"range {start} to {end} has been marked as {target_stage}\")\n\n def mark_range_unstable(self, start: int, end: int):\n self.mark_range(start, end, constants.UNSTABLE_FLAG)\n\n def mark_range_ignore(self, start: int, end: int):\n self.mark_range(start, end, constants.IGNORE_FLAG)\n\n def time_cost_between(self, start_stage: str, end_stage: str) -> float:\n return self.first(end_stage).timestamp - self.last(start_stage).timestamp\n\n def get_important_frame_list(self) -> typing.List[SingleClassifierResult]:\n result = [self.data[0]]\n\n prev = self.data[0]\n for cur in self.data[1:]:\n if cur.stage != prev.stage:\n result.append(prev)\n result.append(cur)\n prev = cur\n\n if result[-1] != self.data[-1]:\n result.append(self.data[-1])\n return result\n\n def calc_changing_cost(\n self,\n ) -> typing.Dict[str, typing.Tuple[SingleClassifierResult, SingleClassifierResult]]:\n\n cost_dict: typing.Dict[\n str, typing.Tuple[SingleClassifierResult, SingleClassifierResult]\n ] = {}\n i = 0\n while i < len(self.data) - 1:\n cur = self.data[i]\n next_one = self.data[i + 1]\n\n if not next_one.is_stable():\n for j in range(i + 1, len(self.data)):\n i = j\n next_one = self.data[j]\n if next_one.is_stable():\n break\n\n changing_name = f\"from {cur.stage} to {next_one.stage}\"\n cost_dict[changing_name] = (cur, next_one)\n else:\n i += 1\n return cost_dict\n\n def dumps(self) -> str:\n\n def _handler(obj: object):\n if isinstance(obj, np.ndarray):\n return \"<np.ndarray object>\"\n return obj.__dict__\n\n return json.dumps(self, sort_keys=True, default=_handler)\n\n def dump(self, json_path: str, **kwargs):\n logger.debug(f\"dump result to {json_path}\")\n assert not os.path.isfile(json_path), f\"{json_path} already existed\"\n with open(json_path, \"w+\", **kwargs) as f:\n f.write(self.dumps())\n\n @classmethod\n def load(cls, from_file: str) -> \"ClassifierResult\":\n assert os.path.isfile(from_file), f\"file {from_file} not existed\"\n with open(from_file, encoding=constants.CHARSET) as f:\n content = json.load(f)\n\n data = content[cls.LABEL_DATA]\n return ClassifierResult([SingleClassifierResult(**each) for each in data])\n\n def diff(self, another: \"ClassifierResult\") -> DiffResult:\n return DiffResult(self, another)\n\n def is_order_correct(self, should_be: typing.List[str]) -> bool:\n cur = self.get_ordered_stage_set()\n len_cur, len_should_be = len(cur), len(should_be)\n if len_cur == len_should_be:\n return cur == should_be\n if len_cur < len_should_be:\n return False\n\n ptr_should, ptr_cur = 0, 0\n while ptr_cur < len_cur:\n if cur[ptr_cur] == should_be[ptr_should]:\n ptr_should += 1\n ptr_cur += 1\n if ptr_should == len_should_be:\n return True\n return False\n\n get_frame_length = get_offset" }, { "identifier": "SingleClassifierResult", "path": "nexaflow/classifier/base.py", "snippet": "class SingleClassifierResult(object):\n\n def __init__(\n self,\n video_path: str,\n frame_id: int,\n timestamp: float,\n stage: str,\n data: np.ndarray = None,\n ):\n self.video_path: str = video_path\n self.frame_id: int = frame_id\n self.timestamp: float = timestamp\n self.stage: str = stage\n self.data: np.ndarray = data\n\n def to_video_frame(self, *args, **kwargs) -> VideoFrame:\n if self.data is not None:\n return VideoFrame(self.frame_id, self.timestamp, self.data)\n\n with toolbox.video_capture(self.video_path) as cap:\n frame = toolbox.get_frame(cap, self.frame_id)\n compressed = toolbox.compress_frame(frame, *args, **kwargs)\n return VideoFrame(self.frame_id, self.timestamp, compressed)\n\n def get_data(self) -> np.ndarray:\n return self.to_video_frame().data\n\n def is_stable(self) -> bool:\n return self.stage not in (\n constants.UNSTABLE_FLAG,\n constants.IGNORE_FLAG,\n constants.UNKNOWN_STAGE_FLAG,\n )\n\n def contain_image(\n self, *, image_path: str = None, image_object: np.ndarray = None, **kwargs\n ) -> typing.Dict[str, typing.Any]:\n return self.to_video_frame().contain_image(\n image_path=image_path, image_object=image_object, **kwargs\n )\n\n def to_dict(self) -> typing.Dict:\n return self.__dict__\n\n def __str__(self):\n return f\"<ClassifierResult stage={self.stage} frame_id={self.frame_id} timestamp={self.timestamp}>\"\n\n __repr__ = __str__" } ]
import os import cv2 import time import random import asyncio from loguru import logger from typing import List, Union, Optional from concurrent.futures import ThreadPoolExecutor from nexaflow import toolbox from nexaflow.skills.report import Report from nexaflow.skills.record import Record from nexaflow.skills.player import Player from nexaflow.skills.switch import Switch from nexaflow.cutter.cutter import VideoCutter from nexaflow.video import VideoObject, Frame from nexaflow.classifier.keras_classifier import KerasClassifier from nexaflow.hook import BaseHook, CropHook, OmitHook, FrameSaveHook from nexaflow.classifier.base import ClassifierResult, SingleClassifierResult
17,415
def filmer(self) -> "Alynex._Filmer": return self.__filmer @property def framix(self) -> "Alynex._Framix": assert self.__framix, f"{self.activate.__name__} first ..." return self.__framix @staticmethod def only_video(folder: str) -> List: class Entry(object): def __init__(self, title: str, place: str, sheet: list): self.title = title self.place = place self.sheet = sheet return [ Entry( os.path.basename(root), root, [os.path.join(root, f) for f in sorted(file)] ) for root, _, file in os.walk(folder) if file ] def activate(self, models: str, total_path: str): if not self.__report: self.__report = Report(total_path) self.__framix = Alynex._Framix(self.report) Alynex.kc.load_model(models) class _Filmer(object): @staticmethod def train_model(video_file: str) -> None: model_path = os.path.join( os.path.dirname(video_file), f"Model_{time.strftime('%Y%m%d%H%M%S')}_{os.getpid()}" ) if not os.path.exists(model_path): os.makedirs(model_path, exist_ok=True) # 将视频切分成帧 video = VideoObject(video_file, fps=Alynex.fps) # 新建帧,计算视频总共有多少帧,每帧多少ms video.load_frames() # 压缩视频 cutter = VideoCutter( target_size=Alynex.target_size ) # 计算每一帧视频的每一个block的ssim和峰值信噪比 res = cutter.cut( video=video, block=Alynex.block, window_size=Alynex.window_size, window_coefficient=Alynex.window_coefficient ) # 计算出判断A帧到B帧之间是稳定还是不稳定 stable, unstable = res.get_range( threshold=Alynex.threshold, offset=Alynex.offset ) # 保存分类后的图片 res.pick_and_save( range_list=stable, frame_count=20, to_dir=model_path, meaningful_name=True ) @staticmethod def build_model(src: str) -> None: new_model_path = os.path.join(src, f"Create_Model_{time.strftime('%Y%m%d%H%M%S')}") new_model_name = f"Keras_Model_{random.randint(10000, 99999)}.h5" final_model = os.path.join(new_model_path, new_model_name) if not os.path.exists(new_model_path): os.makedirs(new_model_path, exist_ok=True) Alynex.kc.train(src) Alynex.kc.save_model(final_model, overwrite=True) class _Framix(object): def __init__(self, report: "Report"): self.__framix_list: List["BaseHook"] = [] self.__reporter = report @property def framix_list(self) -> List["BaseHook"]: return self.__framix_list def crop_hook( self, x: Union[int | float], y: Union[int | float], x_size: Union[int | float], y_size: Union[int | float] ) -> None: """获取区域""" hook = CropHook((y_size, x_size), (y, x)) self.framix_list.append(hook) def omit_hook( self, x: Union[int | float], y: Union[int | float], x_size: Union[int | float], y_size: Union[int | float] ) -> None: """忽略区域""" hook = OmitHook((y_size, x_size), (y, x)) self.framix_list.append(hook) def pixel_wizard(self, video: "VideoObject") -> "ClassifierResult": cutter = VideoCutter( target_size=Alynex.target_size ) # 应用视频帧处理单元 for mix in self.framix_list: cutter.add_hook(mix)
class Alynex(object): target_size: tuple = (350, 700) fps: int = 60 step: int = 1 block: int = 6 threshold: Union[int | float] = 0.97 offset: int = 3 compress_rate: float = 0.5 window_size: int = 1 window_coefficient: int = 2 kc: KerasClassifier = KerasClassifier( target_size=target_size, data_size=target_size ) def __init__(self): self.__report: Optional[Report] = None self.__record: Optional[Record] = Record() self.__player: Optional[Player] = Player() self.__ffmpeg: Optional[Switch] = Switch() self.__filmer: Optional[Alynex._Filmer] = Alynex._Filmer() self.__framix: Optional[Alynex._Framix] = None def __str__(self): return (f""" <Alynex for NexaFlow Target Size: {self.target_size} Fps: {self.fps} Step: {self.step} Block: {self.block} Threshold: {self.threshold} Offset: {self.offset} Compress Rate: {self.compress_rate} Window Size: {self.window_size} Window Coefficient: {self.window_coefficient} > """) __repr__ = __str__ def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): pass @property def report(self) -> "Report": assert self.__report, f"{self.activate.__name__} first ..." return self.__report @property def record(self) -> "Record": return self.__record @property def player(self) -> "Player": return self.__player @property def ffmpeg(self) -> "Switch": return self.__ffmpeg @property def filmer(self) -> "Alynex._Filmer": return self.__filmer @property def framix(self) -> "Alynex._Framix": assert self.__framix, f"{self.activate.__name__} first ..." return self.__framix @staticmethod def only_video(folder: str) -> List: class Entry(object): def __init__(self, title: str, place: str, sheet: list): self.title = title self.place = place self.sheet = sheet return [ Entry( os.path.basename(root), root, [os.path.join(root, f) for f in sorted(file)] ) for root, _, file in os.walk(folder) if file ] def activate(self, models: str, total_path: str): if not self.__report: self.__report = Report(total_path) self.__framix = Alynex._Framix(self.report) Alynex.kc.load_model(models) class _Filmer(object): @staticmethod def train_model(video_file: str) -> None: model_path = os.path.join( os.path.dirname(video_file), f"Model_{time.strftime('%Y%m%d%H%M%S')}_{os.getpid()}" ) if not os.path.exists(model_path): os.makedirs(model_path, exist_ok=True) # 将视频切分成帧 video = VideoObject(video_file, fps=Alynex.fps) # 新建帧,计算视频总共有多少帧,每帧多少ms video.load_frames() # 压缩视频 cutter = VideoCutter( target_size=Alynex.target_size ) # 计算每一帧视频的每一个block的ssim和峰值信噪比 res = cutter.cut( video=video, block=Alynex.block, window_size=Alynex.window_size, window_coefficient=Alynex.window_coefficient ) # 计算出判断A帧到B帧之间是稳定还是不稳定 stable, unstable = res.get_range( threshold=Alynex.threshold, offset=Alynex.offset ) # 保存分类后的图片 res.pick_and_save( range_list=stable, frame_count=20, to_dir=model_path, meaningful_name=True ) @staticmethod def build_model(src: str) -> None: new_model_path = os.path.join(src, f"Create_Model_{time.strftime('%Y%m%d%H%M%S')}") new_model_name = f"Keras_Model_{random.randint(10000, 99999)}.h5" final_model = os.path.join(new_model_path, new_model_name) if not os.path.exists(new_model_path): os.makedirs(new_model_path, exist_ok=True) Alynex.kc.train(src) Alynex.kc.save_model(final_model, overwrite=True) class _Framix(object): def __init__(self, report: "Report"): self.__framix_list: List["BaseHook"] = [] self.__reporter = report @property def framix_list(self) -> List["BaseHook"]: return self.__framix_list def crop_hook( self, x: Union[int | float], y: Union[int | float], x_size: Union[int | float], y_size: Union[int | float] ) -> None: """获取区域""" hook = CropHook((y_size, x_size), (y, x)) self.framix_list.append(hook) def omit_hook( self, x: Union[int | float], y: Union[int | float], x_size: Union[int | float], y_size: Union[int | float] ) -> None: """忽略区域""" hook = OmitHook((y_size, x_size), (y, x)) self.framix_list.append(hook) def pixel_wizard(self, video: "VideoObject") -> "ClassifierResult": cutter = VideoCutter( target_size=Alynex.target_size ) # 应用视频帧处理单元 for mix in self.framix_list: cutter.add_hook(mix)
save_hook = FrameSaveHook(self.__reporter.extra_path)
12
2023-11-13 05:27:34+00:00
24k
microsoft/SoM
demo_gpt4v_som.py
[ { "identifier": "interactive_seem_m2m_auto", "path": "task_adapter/seem/tasks/interactive_seem_m2m_auto.py", "snippet": "def interactive_seem_m2m_auto(model, image, text_size, label_mode='1', alpha=0.1, anno_mode=['Mask']):\n t = []\n t.append(transforms.Resize(int(text_size), interpolation=Image.BICUBIC))\n transform1 = transforms.Compose(t)\n image_ori = transform1(image)\n\n image_ori = np.asarray(image_ori)\n images = torch.from_numpy(image_ori.copy()).permute(2,0,1).cuda()\n\n mask_generator = SeemAutomaticMaskGenerator(model)\n outputs = mask_generator.generate(images)\n\n from task_adapter.utils.visualizer import Visualizer\n visual = Visualizer(image_ori, metadata=metadata)\n sorted_anns = sorted(outputs, key=(lambda x: x['area']), reverse=True)\n label = 1\n for ann in sorted_anns:\n mask = ann['segmentation']\n color_mask = np.random.random((1, 3)).tolist()[0]\n # color_mask = [int(c*255) for c in color_mask]\n demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n label += 1\n im = demo.get_image()\n\n # fig=plt.figure(figsize=(10, 10))\n # plt.imshow(image_ori)\n # show_anns(outputs)\n # fig.canvas.draw()\n # im=Image.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())\n return im" }, { "identifier": "inference_seem_pano", "path": "task_adapter/seem/tasks/inference_seem_pano.py", "snippet": "def inference_seem_pano(model, image, text_size, label_mode='1', alpha=0.1, anno_mode=['Mask']):\n t = []\n t.append(transforms.Resize(int(text_size), interpolation=Image.BICUBIC))\n transform1 = transforms.Compose(t)\n image_ori = transform1(image)\n\n image_ori = np.asarray(image_ori)\n images = torch.from_numpy(image_ori.copy()).permute(2,0,1).cuda()\n\n orig_size = images.shape[-2:]\n orig_h, orig_w = orig_size\n crop_box = [0,0,orig_w,orig_h]\n\n data = {\"image\": images, \"height\": orig_h, \"width\": orig_w}\n batch_inputs = [data]\n\n model.model.metadata = metadata\n outputs = model.model.evaluate(batch_inputs)\n\n pano_mask = outputs[0]['panoptic_seg'][0]\n pano_info = outputs[0]['panoptic_seg'][1]\n\n masks = []\n for seg_info in pano_info:\n masks += [pano_mask == seg_info['id']]\n masks = torch.stack(masks, dim=0)\n iou_preds = torch.ones(masks.shape[0], dtype=torch.float32)\n points = torch.zeros((masks.shape[0], 2), dtype=torch.float32)\n\n mask_data = MaskData(\n masks=masks,\n iou_preds=iou_preds,\n points=points,\n )\n mask_data[\"stability_score\"] = torch.ones(masks.shape[0], dtype=torch.float32)\n del masks\n\n mask_data[\"boxes\"] = batched_mask_to_box(mask_data[\"masks\"])\n mask_data[\"crop_boxes\"] = torch.tensor([crop_box for _ in range(len(mask_data[\"boxes\"]))])\n\n # Compress to RLE\n mask_data[\"masks\"] = uncrop_masks(mask_data[\"masks\"], crop_box, orig_h, orig_w)\n mask_data[\"rles\"] = mask_to_rle_pytorch(mask_data[\"masks\"])\n del mask_data[\"masks\"]\n mask_data[\"segmentations\"] = [rle_to_mask(rle) for rle in mask_data[\"rles\"]]\n\n # Write mask records\n outputs = []\n for idx in range(len(mask_data[\"segmentations\"])):\n ann = {\n \"segmentation\": mask_data[\"segmentations\"][idx],\n \"area\": area_from_rle(mask_data[\"rles\"][idx]),\n \"bbox\": box_xyxy_to_xywh(mask_data[\"boxes\"][idx]).tolist(),\n \"predicted_iou\": mask_data[\"iou_preds\"][idx].item(),\n \"point_coords\": [mask_data[\"points\"][idx].tolist()],\n \"stability_score\": mask_data[\"stability_score\"][idx].item(),\n \"crop_box\": box_xyxy_to_xywh(mask_data[\"crop_boxes\"][idx]).tolist(),\n }\n outputs.append(ann)\n\n from task_adapter.utils.visualizer import Visualizer\n visual = Visualizer(image_ori, metadata=metadata)\n # create a full zero image as the image_orig\n sorted_anns = sorted(outputs, key=(lambda x: x['area']), reverse=True)\n label = 1\n mask_map = np.zeros(image_ori.shape, dtype=np.uint8) \n for i, ann in enumerate(sorted_anns):\n mask = ann['segmentation']\n color_mask = np.random.random((1, 3)).tolist()[0]\n # color_mask = [int(c*255) for c in color_mask]\n demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # assign the mask to the mask_map\n mask_map[mask == 1] = label\n label += 1\n im = demo.get_image()\n # fig=plt.figure(figsize=(10, 10))\n # plt.imshow(image_ori)\n # show_anns(outputs)\n # fig.canvas.draw()\n # im=Image.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())\n return im, sorted_anns" }, { "identifier": "inference_seem_interactive", "path": "task_adapter/seem/tasks/inference_seem_interactive.py", "snippet": "def inference_seem_interactive(model, image, spatial_masks, text_size, label_mode='1', alpha=0.1, anno_mode=['Mask']):\n t = []\n t.append(transforms.Resize(int(text_size), interpolation=Image.BICUBIC))\n transform1 = transforms.Compose(t)\n image_ori = transform1(image)\n\n image_ori = np.asarray(image_ori)\n images = torch.from_numpy(image_ori.copy()).permute(2,0,1).cuda()\n\n orig_size = images.shape[-2:]\n orig_h, orig_w = orig_size\n crop_box = [0,0,orig_w,orig_h]\n\n data = {\"image\": images, \"height\": orig_h, \"width\": orig_w}\n\n spatial_masks = spatial_masks[:, None].float().cuda()\n spatial_masks = F.interpolate(spatial_masks, size=(orig_h, orig_w), mode='bicubic', align_corners=False) > 0\n data['spatial_query'] = {'rand_shape': spatial_masks}\n\n model.model.metadata = metadata\n masks, _ = model.model.evaluate_demo([data])\n masks = masks > 0.0\n iou_preds = torch.ones(masks.shape[0], dtype=torch.float32)\n points = torch.zeros((masks.shape[0], 2), dtype=torch.float32)\n\n mask_data = MaskData(\n masks=masks,\n iou_preds=iou_preds,\n points=points,\n )\n\n mask_data[\"stability_score\"] = torch.ones(masks.shape[0], dtype=torch.float32)\n del masks\n\n mask_data[\"boxes\"] = batched_mask_to_box(mask_data[\"masks\"])\n mask_data[\"crop_boxes\"] = torch.tensor([crop_box for _ in range(len(mask_data[\"boxes\"]))])\n\n # Compress to RLE\n mask_data[\"masks\"] = uncrop_masks(mask_data[\"masks\"], crop_box, orig_h, orig_w)\n mask_data[\"rles\"] = mask_to_rle_pytorch(mask_data[\"masks\"])\n del mask_data[\"masks\"]\n mask_data[\"segmentations\"] = [rle_to_mask(rle) for rle in mask_data[\"rles\"]]\n\n # Write mask records\n outputs = []\n for idx in range(len(mask_data[\"segmentations\"])):\n ann = {\n \"segmentation\": mask_data[\"segmentations\"][idx],\n \"area\": area_from_rle(mask_data[\"rles\"][idx]),\n \"bbox\": box_xyxy_to_xywh(mask_data[\"boxes\"][idx]).tolist(),\n \"predicted_iou\": mask_data[\"iou_preds\"][idx].item(),\n \"point_coords\": [mask_data[\"points\"][idx].tolist()],\n \"stability_score\": mask_data[\"stability_score\"][idx].item(),\n \"crop_box\": box_xyxy_to_xywh(mask_data[\"crop_boxes\"][idx]).tolist(),\n }\n outputs.append(ann)\n\n from task_adapter.utils.visualizer import Visualizer\n visual = Visualizer(image_ori, metadata=metadata)\n sorted_anns = sorted(outputs, key=(lambda x: x['area']), reverse=True)\n label = 1\n # for ann in sorted_anns:\n # mask = ann['segmentation']\n # color_mask = np.random.random((1, 3)).tolist()[0]\n # # color_mask = [int(c*255) for c in color_mask]\n # demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # label += 1\n # im = demo.get_image()\n\n mask_map = np.zeros(image_ori.shape, dtype=np.uint8) \n for i, ann in enumerate(sorted_anns):\n mask = ann['segmentation']\n color_mask = np.random.random((1, 3)).tolist()[0]\n # color_mask = [int(c*255) for c in color_mask]\n demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # assign the mask to the mask_map\n mask_map[mask == 1] = label\n label += 1\n im = demo.get_image()\n # fig=plt.figure(figsize=(10, 10))\n # plt.imshow(image_ori)\n # show_anns(outputs)\n # fig.canvas.draw()\n # im=Image.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())\n return im, sorted_anns" }, { "identifier": "inference_semsam_m2m_auto", "path": "task_adapter/semantic_sam/tasks/inference_semsam_m2m_auto.py", "snippet": "def inference_semsam_m2m_auto(model, image, level, all_classes, all_parts, thresh, text_size, hole_scale, island_scale, semantic, refimg=None, reftxt=None, audio_pth=None, video_pth=None, label_mode='1', alpha=0.1, anno_mode=['Mask']):\n t = []\n t.append(transforms.Resize(int(text_size), interpolation=Image.BICUBIC))\n transform1 = transforms.Compose(t)\n image_ori = transform1(image)\n\n image_ori = np.asarray(image_ori)\n images = torch.from_numpy(image_ori.copy()).permute(2,0,1).cuda()\n\n mask_generator = SemanticSamAutomaticMaskGenerator(model,points_per_side=32,\n pred_iou_thresh=0.88,\n stability_score_thresh=0.92,\n min_mask_region_area=10,\n level=level,\n )\n outputs = mask_generator.generate(images)\n\n from task_adapter.utils.visualizer import Visualizer\n visual = Visualizer(image_ori, metadata=metadata)\n sorted_anns = sorted(outputs, key=(lambda x: x['area']), reverse=True)\n label = 1\n # for ann in sorted_anns:\n # mask = ann['segmentation']\n # color_mask = np.random.random((1, 3)).tolist()[0]\n # # color_mask = [int(c*255) for c in color_mask]\n # demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # label += 1\n # im = demo.get_image()\n\n mask_map = np.zeros(image_ori.shape, dtype=np.uint8) \n for i, ann in enumerate(sorted_anns):\n mask = ann['segmentation']\n color_mask = np.random.random((1, 3)).tolist()[0]\n # color_mask = [int(c*255) for c in color_mask]\n demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # assign the mask to the mask_map\n mask_map[mask == 1] = label\n label += 1\n im = demo.get_image() \n # fig=plt.figure(figsize=(10, 10))\n # plt.imshow(image_ori)\n # show_anns(outputs)\n # fig.canvas.draw()\n # im=Image.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())\n return im, sorted_anns" }, { "identifier": "prompt_switch", "path": "task_adapter/semantic_sam/tasks/automatic_mask_generator.py", "snippet": "def prompt_switch(p):\n p = int(p)\n if p == 1:\n return 3\n if p == 2:\n return 2\n if p == 3:\n return 0\n if p == 4:\n return 4\n if p == 5:\n return 1\n if p == 6:\n return 5\n else:\n raise NotImplementedError" }, { "identifier": "inference_sam_m2m_auto", "path": "task_adapter/sam/tasks/inference_sam_m2m_auto.py", "snippet": "def inference_sam_m2m_auto(model, image, text_size, label_mode='1', alpha=0.1, anno_mode=['Mask']):\n t = []\n t.append(transforms.Resize(int(text_size), interpolation=Image.BICUBIC))\n transform1 = transforms.Compose(t)\n image_ori = transform1(image)\n image_ori = np.asarray(image_ori)\n\n mask_generator = SamAutomaticMaskGenerator(model)\n outputs = mask_generator.generate(image_ori)\n\n from task_adapter.utils.visualizer import Visualizer\n visual = Visualizer(image_ori, metadata=metadata)\n sorted_anns = sorted(outputs, key=(lambda x: x['area']), reverse=True)\n label = 1\n # for ann in sorted_anns:\n # mask = ann['segmentation']\n # color_mask = np.random.random((1, 3)).tolist()[0]\n # # color_mask = [int(c*255) for c in color_mask]\n # demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # label += 1\n # im = demo.get_image()\n\n mask_map = np.zeros(image_ori.shape, dtype=np.uint8) \n for i, ann in enumerate(sorted_anns):\n mask = ann['segmentation']\n color_mask = np.random.random((1, 3)).tolist()[0]\n # color_mask = [int(c*255) for c in color_mask]\n demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # assign the mask to the mask_map\n mask_map[mask == 1] = label\n label += 1\n im = demo.get_image() \n # fig=plt.figure(figsize=(10, 10))\n # plt.imshow(image_ori)\n # show_anns(outputs)\n # fig.canvas.draw()\n # im=Image.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())\n return im, sorted_anns" }, { "identifier": "inference_sam_m2m_interactive", "path": "task_adapter/sam/tasks/inference_sam_m2m_interactive.py", "snippet": "def inference_sam_m2m_interactive(model, image, spatial_masks, text_size, label_mode='1', alpha=0.1, anno_mode=['Mask']):\n t = []\n t.append(transforms.Resize(int(text_size), interpolation=Image.BICUBIC))\n transform1 = transforms.Compose(t)\n image_ori = transform1(image)\n\n image_ori = np.asarray(image_ori)\n images = torch.from_numpy(image_ori.copy()).permute(2,0,1).cuda()\n\n orig_size = images.shape[-2:]\n orig_h, orig_w = orig_size\n crop_box = [0,0,orig_w,orig_h]\n\n spatial_masks = spatial_masks[:, None].float().cuda()\n spatial_masks = F.interpolate(spatial_masks, size=(orig_h, orig_w), mode='bicubic', align_corners=False) > 0\n\n # generate single center point\n # n,_,h,w = spatial_masks.shape\n # mask_dt = (distance_transform((~F.pad(spatial_masks, pad=(1, 1, 1, 1), mode='constant', value=0)).float())[:,:,1:-1,1:-1]).reshape(n,-1)\n # max_xy_idx = torch.stack([torch.arange(n), mask_dt.max(dim=-1)[1].cpu()]).tolist()\n # next_mask = torch.zeros(spatial_masks.shape, device=torch.cuda.current_device()).bool()\n # next_mask = next_mask.view(n,-1)\n # next_mask[max_xy_idx] = True\n # next_mask = next_mask.reshape((n,1,h,w))\n # points = next_mask.nonzero()[:,2:].flip(dims=[1]).cpu().numpy()\n\n # stack sampled points\n acc_points = []\n for i in range(len(spatial_masks)):\n points = spatial_masks[i:i+1].nonzero()[:,2:].flip(dims=[1]).cpu().numpy()\n rand_ids = np.random.choice(points.shape[0], size=40, replace=True)\n points = points[rand_ids]\n acc_points.append(points)\n _np = len(acc_points)\n points = np.concatenate(acc_points)\n\n mask_generator = SamAutomaticMaskGenerator(model)\n mask_generator.predictor.set_image(image_ori)\n im_size = image_ori.shape[:-1]\n\n transformed_points = mask_generator.predictor.transform.apply_coords(points, im_size)\n in_points = torch.as_tensor(transformed_points, device=mask_generator.predictor.device).reshape(_np,-1,2).transpose(0,1)\n in_labels = torch.ones((in_points.shape[0], _np), dtype=torch.int, device=mask_generator.predictor.device)\n\n masks = sam_interactive_mask(mask_generator, points, in_points.transpose(0,1), in_labels.transpose(0,1), None)\n\n masks = masks > 0.0\n iou_preds = torch.ones(masks.shape[0], dtype=torch.float32)\n points = torch.zeros((masks.shape[0], 2), dtype=torch.float32)\n\n mask_data = MaskData(\n masks=masks,\n iou_preds=iou_preds,\n points=points,\n )\n\n mask_data[\"stability_score\"] = torch.ones(masks.shape[0], dtype=torch.float32)\n del masks\n\n mask_data[\"boxes\"] = batched_mask_to_box(mask_data[\"masks\"])\n mask_data[\"crop_boxes\"] = torch.tensor([crop_box for _ in range(len(mask_data[\"boxes\"]))])\n\n # Compress to RLE\n mask_data[\"masks\"] = uncrop_masks(mask_data[\"masks\"], crop_box, orig_h, orig_w)\n mask_data[\"rles\"] = mask_to_rle_pytorch(mask_data[\"masks\"])\n del mask_data[\"masks\"]\n mask_data[\"segmentations\"] = [rle_to_mask(rle) for rle in mask_data[\"rles\"]]\n\n # Write mask records\n outputs = []\n for idx in range(len(mask_data[\"segmentations\"])):\n ann = {\n \"segmentation\": mask_data[\"segmentations\"][idx],\n \"area\": area_from_rle(mask_data[\"rles\"][idx]),\n \"bbox\": box_xyxy_to_xywh(mask_data[\"boxes\"][idx]).tolist(),\n \"predicted_iou\": mask_data[\"iou_preds\"][idx].item(),\n \"point_coords\": [mask_data[\"points\"][idx].tolist()],\n \"stability_score\": mask_data[\"stability_score\"][idx].item(),\n \"crop_box\": box_xyxy_to_xywh(mask_data[\"crop_boxes\"][idx]).tolist(),\n }\n outputs.append(ann)\n\n from task_adapter.utils.visualizer import Visualizer\n visual = Visualizer(image_ori, metadata=metadata)\n sorted_anns = sorted(outputs, key=(lambda x: x['area']), reverse=True)\n label = 1\n # for ann in sorted_anns:\n # mask = ann['segmentation']\n # demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # label += 1\n # im = demo.get_image()\n\n mask_map = np.zeros(image_ori.shape, dtype=np.uint8) \n for i, ann in enumerate(sorted_anns):\n mask = ann['segmentation']\n color_mask = np.random.random((1, 3)).tolist()[0]\n # color_mask = [int(c*255) for c in color_mask]\n demo = visual.draw_binary_mask_with_number(mask, text=str(label), label_mode=label_mode, alpha=alpha, anno_mode=anno_mode)\n # assign the mask to the mask_map\n mask_map[mask == 1] = label\n label += 1\n im = demo.get_image() \n # fig=plt.figure(figsize=(10, 10))\n # plt.imshow(image_ori)\n # show_anns(outputs)\n # fig.canvas.draw()\n # im=Image.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())\n return im, sorted_anns" }, { "identifier": "Visualizer", "path": "task_adapter/utils/visualizer.py", "snippet": "class Visualizer:\n \"\"\"\n Visualizer that draws data about detection/segmentation on images.\n\n It contains methods like `draw_{text,box,circle,line,binary_mask,polygon}`\n that draw primitive objects to images, as well as high-level wrappers like\n `draw_{instance_predictions,sem_seg,panoptic_seg_predictions,dataset_dict}`\n that draw composite data in some pre-defined style.\n\n Note that the exact visualization style for the high-level wrappers are subject to change.\n Style such as color, opacity, label contents, visibility of labels, or even the visibility\n of objects themselves (e.g. when the object is too small) may change according\n to different heuristics, as long as the results still look visually reasonable.\n\n To obtain a consistent style, you can implement custom drawing functions with the\n abovementioned primitive methods instead. If you need more customized visualization\n styles, you can process the data yourself following their format documented in\n tutorials (:doc:`/tutorials/models`, :doc:`/tutorials/datasets`). This class does not\n intend to satisfy everyone's preference on drawing styles.\n\n This visualizer focuses on high rendering quality rather than performance. It is not\n designed to be used for real-time applications.\n \"\"\"\n\n # TODO implement a fast, rasterized version using OpenCV\n\n def __init__(self, img_rgb, metadata=None, scale=1.0, instance_mode=ColorMode.IMAGE):\n \"\"\"\n Args:\n img_rgb: a numpy array of shape (H, W, C), where H and W correspond to\n the height and width of the image respectively. C is the number of\n color channels. The image is required to be in RGB format since that\n is a requirement of the Matplotlib library. The image is also expected\n to be in the range [0, 255].\n metadata (Metadata): dataset metadata (e.g. class names and colors)\n instance_mode (ColorMode): defines one of the pre-defined style for drawing\n instances on an image.\n \"\"\"\n self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)\n if metadata is None:\n metadata = MetadataCatalog.get(\"__nonexist__\")\n self.metadata = metadata\n self.output = VisImage(self.img, scale=scale)\n self.cpu_device = torch.device(\"cpu\")\n\n # too small texts are useless, therefore clamp to 9\n self._default_font_size = max(\n np.sqrt(self.output.height * self.output.width) // 90, 10 // scale\n )\n self._default_font_size = 18\n self._instance_mode = instance_mode\n self.keypoint_threshold = _KEYPOINT_THRESHOLD\n\n import matplotlib.colors as mcolors\n css4_colors = mcolors.CSS4_COLORS\n self.color_proposals = [list(mcolors.hex2color(color)) for color in css4_colors.values()]\n\n def draw_instance_predictions(self, predictions):\n \"\"\"\n Draw instance-level prediction results on an image.\n\n Args:\n predictions (Instances): the output of an instance detection/segmentation\n model. Following fields will be used to draw:\n \"pred_boxes\", \"pred_classes\", \"scores\", \"pred_masks\" (or \"pred_masks_rle\").\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n boxes = predictions.pred_boxes if predictions.has(\"pred_boxes\") else None\n scores = predictions.scores if predictions.has(\"scores\") else None\n classes = predictions.pred_classes.tolist() if predictions.has(\"pred_classes\") else None\n labels = _create_text_labels(classes, scores, self.metadata.get(\"thing_classes\", None))\n keypoints = predictions.pred_keypoints if predictions.has(\"pred_keypoints\") else None\n\n keep = (scores > 0.5).cpu()\n boxes = boxes[keep]\n scores = scores[keep]\n classes = np.array(classes)\n classes = classes[np.array(keep)]\n labels = np.array(labels)\n labels = labels[np.array(keep)]\n\n if predictions.has(\"pred_masks\"):\n masks = np.asarray(predictions.pred_masks)\n masks = masks[np.array(keep)]\n masks = [GenericMask(x, self.output.height, self.output.width) for x in masks]\n else:\n masks = None\n\n if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get(\"thing_colors\"):\n # if self.metadata.get(\"thing_colors\"):\n colors = [\n self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in classes\n ]\n alpha = 0.4\n else:\n colors = None\n alpha = 0.4\n\n if self._instance_mode == ColorMode.IMAGE_BW:\n self.output.reset_image(\n self._create_grayscale_image(\n (predictions.pred_masks.any(dim=0) > 0).numpy()\n if predictions.has(\"pred_masks\")\n else None\n )\n )\n alpha = 0.3\n \n self.overlay_instances(\n masks=masks,\n boxes=boxes,\n labels=labels,\n keypoints=keypoints,\n assigned_colors=colors,\n alpha=alpha,\n )\n return self.output\n\n def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.7):\n \"\"\"\n Draw semantic segmentation predictions/labels.\n\n Args:\n sem_seg (Tensor or ndarray): the segmentation of shape (H, W).\n Each value is the integer label of the pixel.\n area_threshold (int): segments with less than `area_threshold` are not drawn.\n alpha (float): the larger it is, the more opaque the segmentations are.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n if isinstance(sem_seg, torch.Tensor):\n sem_seg = sem_seg.numpy()\n labels, areas = np.unique(sem_seg, return_counts=True)\n sorted_idxs = np.argsort(-areas).tolist()\n labels = labels[sorted_idxs]\n for label in filter(lambda l: l < len(self.metadata.stuff_classes), labels):\n try:\n mask_color = [x / 255 for x in self.metadata.stuff_colors[label]]\n except (AttributeError, IndexError):\n mask_color = None\n\n binary_mask = (sem_seg == label).astype(np.uint8)\n text = self.metadata.stuff_classes[label]\n self.draw_binary_mask(\n binary_mask,\n color=mask_color,\n edge_color=_OFF_WHITE,\n text=text,\n alpha=alpha,\n area_threshold=area_threshold,\n )\n return self.output\n\n def draw_panoptic_seg(self, panoptic_seg, segments_info, area_threshold=None, alpha=0.7):\n \"\"\"\n Draw panoptic prediction annotations or results.\n\n Args:\n panoptic_seg (Tensor): of shape (height, width) where the values are ids for each\n segment.\n segments_info (list[dict] or None): Describe each segment in `panoptic_seg`.\n If it is a ``list[dict]``, each dict contains keys \"id\", \"category_id\".\n If None, category id of each pixel is computed by\n ``pixel // metadata.label_divisor``.\n area_threshold (int): stuff segments with less than `area_threshold` are not drawn.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n pred = _PanopticPrediction(panoptic_seg, segments_info, self.metadata)\n\n if self._instance_mode == ColorMode.IMAGE_BW:\n self.output.reset_image(self._create_grayscale_image(pred.non_empty_mask()))\n\n # draw mask for all semantic segments first i.e. \"stuff\"\n for mask, sinfo in pred.semantic_masks():\n category_idx = sinfo[\"category_id\"]\n try:\n mask_color = [x / 255 for x in self.metadata.stuff_colors[category_idx]]\n except AttributeError:\n mask_color = None\n\n text = self.metadata.stuff_classes[category_idx].replace('-other','').replace('-merged','')\n self.draw_binary_mask(\n mask,\n color=mask_color,\n edge_color=_OFF_WHITE,\n text=text,\n alpha=alpha,\n area_threshold=area_threshold,\n )\n\n # draw mask for all instances second\n all_instances = list(pred.instance_masks())\n if len(all_instances) == 0:\n return self.output\n masks, sinfo = list(zip(*all_instances))\n category_ids = [x[\"category_id\"] for x in sinfo]\n\n try:\n scores = [x[\"score\"] for x in sinfo]\n except KeyError:\n scores = None\n class_names = [name.replace('-other','').replace('-merged','') for name in self.metadata.thing_classes]\n labels = _create_text_labels(\n category_ids, scores, class_names, [x.get(\"iscrowd\", 0) for x in sinfo]\n )\n\n try:\n colors = [\n self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in category_ids\n ]\n except AttributeError:\n colors = None\n self.overlay_instances(masks=masks, labels=labels, assigned_colors=colors, alpha=alpha)\n\n return self.output\n\n draw_panoptic_seg_predictions = draw_panoptic_seg # backward compatibility\n\n def draw_dataset_dict(self, dic):\n \"\"\"\n Draw annotations/segmentaions in Detectron2 Dataset format.\n\n Args:\n dic (dict): annotation/segmentation data of one image, in Detectron2 Dataset format.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n annos = dic.get(\"annotations\", None)\n if annos:\n if \"segmentation\" in annos[0]:\n masks = [x[\"segmentation\"] for x in annos]\n else:\n masks = None\n if \"keypoints\" in annos[0]:\n keypts = [x[\"keypoints\"] for x in annos]\n keypts = np.array(keypts).reshape(len(annos), -1, 3)\n else:\n keypts = None\n\n boxes = [\n BoxMode.convert(x[\"bbox\"], x[\"bbox_mode\"], BoxMode.XYXY_ABS)\n if len(x[\"bbox\"]) == 4\n else x[\"bbox\"]\n for x in annos\n ]\n\n colors = None\n category_ids = [x[\"category_id\"] for x in annos]\n if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get(\"thing_colors\"):\n colors = [\n self._jitter([x / 255 for x in self.metadata.thing_colors[c]])\n for c in category_ids\n ]\n names = self.metadata.get(\"thing_classes\", None)\n labels = _create_text_labels(\n category_ids,\n scores=None,\n class_names=names,\n is_crowd=[x.get(\"iscrowd\", 0) for x in annos],\n )\n self.overlay_instances(\n labels=labels, boxes=boxes, masks=masks, keypoints=keypts, assigned_colors=colors\n )\n\n sem_seg = dic.get(\"sem_seg\", None)\n if sem_seg is None and \"sem_seg_file_name\" in dic:\n with PathManager.open(dic[\"sem_seg_file_name\"], \"rb\") as f:\n sem_seg = Image.open(f)\n sem_seg = np.asarray(sem_seg, dtype=\"uint8\")\n if sem_seg is not None:\n self.draw_sem_seg(sem_seg, area_threshold=0, alpha=0.4)\n\n pan_seg = dic.get(\"pan_seg\", None)\n if pan_seg is None and \"pan_seg_file_name\" in dic:\n with PathManager.open(dic[\"pan_seg_file_name\"], \"rb\") as f:\n pan_seg = Image.open(f)\n pan_seg = np.asarray(pan_seg)\n from panopticapi.utils import rgb2id\n\n pan_seg = rgb2id(pan_seg)\n if pan_seg is not None:\n segments_info = dic[\"segments_info\"]\n pan_seg = torch.tensor(pan_seg)\n self.draw_panoptic_seg(pan_seg, segments_info, area_threshold=0, alpha=0.7)\n return self.output\n\n def overlay_instances(\n self,\n *,\n boxes=None,\n labels=None,\n masks=None,\n keypoints=None,\n assigned_colors=None,\n alpha=0.5,\n ):\n \"\"\"\n Args:\n boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,\n or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image,\n or a :class:`RotatedBoxes`,\n or an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format\n for the N objects in a single image,\n labels (list[str]): the text to be displayed for each instance.\n masks (masks-like object): Supported types are:\n\n * :class:`detectron2.structures.PolygonMasks`,\n :class:`detectron2.structures.BitMasks`.\n * list[list[ndarray]]: contains the segmentation masks for all objects in one image.\n The first level of the list corresponds to individual instances. The second\n level to all the polygon that compose the instance, and the third level\n to the polygon coordinates. The third level should have the format of\n [x0, y0, x1, y1, ..., xn, yn] (n >= 3).\n * list[ndarray]: each ndarray is a binary mask of shape (H, W).\n * list[dict]: each dict is a COCO-style RLE.\n keypoints (Keypoint or array like): an array-like object of shape (N, K, 3),\n where the N is the number of instances and K is the number of keypoints.\n The last dimension corresponds to (x, y, visibility or score).\n assigned_colors (list[matplotlib.colors]): a list of colors, where each color\n corresponds to each mask or box in the image. Refer to 'matplotlib.colors'\n for full list of formats that the colors are accepted in.\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n num_instances = 0\n if boxes is not None:\n boxes = self._convert_boxes(boxes)\n num_instances = len(boxes)\n if masks is not None:\n masks = self._convert_masks(masks)\n if num_instances:\n assert len(masks) == num_instances\n else:\n num_instances = len(masks)\n if keypoints is not None:\n if num_instances:\n assert len(keypoints) == num_instances\n else:\n num_instances = len(keypoints)\n keypoints = self._convert_keypoints(keypoints)\n if labels is not None:\n assert len(labels) == num_instances\n if assigned_colors is None:\n assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]\n if num_instances == 0:\n return self.output\n if boxes is not None and boxes.shape[1] == 5:\n return self.overlay_rotated_instances(\n boxes=boxes, labels=labels, assigned_colors=assigned_colors\n )\n\n # Display in largest to smallest order to reduce occlusion.\n areas = None\n if boxes is not None:\n areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1)\n elif masks is not None:\n areas = np.asarray([x.area() for x in masks])\n\n if areas is not None:\n sorted_idxs = np.argsort(-areas).tolist()\n # Re-order overlapped instances in descending order.\n boxes = boxes[sorted_idxs] if boxes is not None else None\n labels = [labels[k] for k in sorted_idxs] if labels is not None else None\n masks = [masks[idx] for idx in sorted_idxs] if masks is not None else None\n assigned_colors = [assigned_colors[idx] for idx in sorted_idxs]\n keypoints = keypoints[sorted_idxs] if keypoints is not None else None\n\n for i in range(num_instances):\n color = assigned_colors[i]\n if boxes is not None:\n self.draw_box(boxes[i], edge_color=color)\n\n if masks is not None:\n for segment in masks[i].polygons:\n self.draw_polygon(segment.reshape(-1, 2), color, alpha=alpha)\n\n if labels is not None:\n # first get a box\n if boxes is not None:\n x0, y0, x1, y1 = boxes[i]\n text_pos = (x0, y0) # if drawing boxes, put text on the box corner.\n horiz_align = \"left\"\n elif masks is not None:\n # skip small mask without polygon\n if len(masks[i].polygons) == 0:\n continue\n\n x0, y0, x1, y1 = masks[i].bbox()\n\n # draw text in the center (defined by median) when box is not drawn\n # median is less sensitive to outliers.\n text_pos = np.median(masks[i].mask.nonzero(), axis=1)[::-1]\n horiz_align = \"center\"\n else:\n continue # drawing the box confidence for keypoints isn't very useful.\n # for small objects, draw text at the side to avoid occlusion\n instance_area = (y1 - y0) * (x1 - x0)\n if (\n instance_area < _SMALL_OBJECT_AREA_THRESH * self.output.scale\n or y1 - y0 < 40 * self.output.scale\n ):\n if y1 >= self.output.height - 5:\n text_pos = (x1, y0)\n else:\n text_pos = (x0, y1)\n\n height_ratio = (y1 - y0) / np.sqrt(self.output.height * self.output.width)\n lighter_color = self._change_color_brightness(color, brightness_factor=0.7)\n font_size = (\n np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2)\n * 0.5\n * self._default_font_size\n )\n self.draw_text(\n labels[i],\n text_pos,\n color=lighter_color,\n horizontal_alignment=horiz_align,\n font_size=font_size,\n )\n\n # draw keypoints\n if keypoints is not None:\n for keypoints_per_instance in keypoints:\n self.draw_and_connect_keypoints(keypoints_per_instance)\n\n return self.output\n\n def overlay_rotated_instances(self, boxes=None, labels=None, assigned_colors=None):\n \"\"\"\n Args:\n boxes (ndarray): an Nx5 numpy array of\n (x_center, y_center, width, height, angle_degrees) format\n for the N objects in a single image.\n labels (list[str]): the text to be displayed for each instance.\n assigned_colors (list[matplotlib.colors]): a list of colors, where each color\n corresponds to each mask or box in the image. Refer to 'matplotlib.colors'\n for full list of formats that the colors are accepted in.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n num_instances = len(boxes)\n\n if assigned_colors is None:\n assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]\n if num_instances == 0:\n return self.output\n\n # Display in largest to smallest order to reduce occlusion.\n if boxes is not None:\n areas = boxes[:, 2] * boxes[:, 3]\n\n sorted_idxs = np.argsort(-areas).tolist()\n # Re-order overlapped instances in descending order.\n boxes = boxes[sorted_idxs]\n labels = [labels[k] for k in sorted_idxs] if labels is not None else None\n colors = [assigned_colors[idx] for idx in sorted_idxs]\n\n for i in range(num_instances):\n self.draw_rotated_box_with_label(\n boxes[i], edge_color=colors[i], label=labels[i] if labels is not None else None\n )\n\n return self.output\n\n def draw_and_connect_keypoints(self, keypoints):\n \"\"\"\n Draws keypoints of an instance and follows the rules for keypoint connections\n to draw lines between appropriate keypoints. This follows color heuristics for\n line color.\n\n Args:\n keypoints (Tensor): a tensor of shape (K, 3), where K is the number of keypoints\n and the last dimension corresponds to (x, y, probability).\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n visible = {}\n keypoint_names = self.metadata.get(\"keypoint_names\")\n for idx, keypoint in enumerate(keypoints):\n\n # draw keypoint\n x, y, prob = keypoint\n if prob > self.keypoint_threshold:\n self.draw_circle((x, y), color=_RED)\n if keypoint_names:\n keypoint_name = keypoint_names[idx]\n visible[keypoint_name] = (x, y)\n\n if self.metadata.get(\"keypoint_connection_rules\"):\n for kp0, kp1, color in self.metadata.keypoint_connection_rules:\n if kp0 in visible and kp1 in visible:\n x0, y0 = visible[kp0]\n x1, y1 = visible[kp1]\n color = tuple(x / 255.0 for x in color)\n self.draw_line([x0, x1], [y0, y1], color=color)\n\n # draw lines from nose to mid-shoulder and mid-shoulder to mid-hip\n # Note that this strategy is specific to person keypoints.\n # For other keypoints, it should just do nothing\n try:\n ls_x, ls_y = visible[\"left_shoulder\"]\n rs_x, rs_y = visible[\"right_shoulder\"]\n mid_shoulder_x, mid_shoulder_y = (ls_x + rs_x) / 2, (ls_y + rs_y) / 2\n except KeyError:\n pass\n else:\n # draw line from nose to mid-shoulder\n nose_x, nose_y = visible.get(\"nose\", (None, None))\n if nose_x is not None:\n self.draw_line([nose_x, mid_shoulder_x], [nose_y, mid_shoulder_y], color=_RED)\n\n try:\n # draw line from mid-shoulder to mid-hip\n lh_x, lh_y = visible[\"left_hip\"]\n rh_x, rh_y = visible[\"right_hip\"]\n except KeyError:\n pass\n else:\n mid_hip_x, mid_hip_y = (lh_x + rh_x) / 2, (lh_y + rh_y) / 2\n self.draw_line([mid_hip_x, mid_shoulder_x], [mid_hip_y, mid_shoulder_y], color=_RED)\n return self.output\n\n \"\"\"\n Primitive drawing functions:\n \"\"\"\n\n def draw_text(\n self,\n text,\n position,\n *,\n font_size=None,\n color=\"g\",\n horizontal_alignment=\"center\",\n rotation=0,\n ):\n \"\"\"\n Args:\n text (str): class label\n position (tuple): a tuple of the x and y coordinates to place text on image.\n font_size (int, optional): font of the text. If not provided, a font size\n proportional to the image width is calculated and used.\n color: color of the text. Refer to `matplotlib.colors` for full list\n of formats that are accepted.\n horizontal_alignment (str): see `matplotlib.text.Text`\n rotation: rotation angle in degrees CCW\n\n Returns:\n output (VisImage): image object with text drawn.\n \"\"\"\n if not font_size:\n font_size = self._default_font_size\n\n # since the text background is dark, we don't want the text to be dark\n color = np.maximum(list(mplc.to_rgb(color)), 0.15)\n color[np.argmax(color)] = max(0.8, np.max(color))\n\n def contrasting_color(rgb):\n \"\"\"Returns 'white' or 'black' depending on which color contrasts more with the given RGB value.\"\"\"\n \n # Decompose the RGB tuple\n R, G, B = rgb\n\n # Calculate the Y value\n Y = 0.299 * R + 0.587 * G + 0.114 * B\n\n # If Y value is greater than 128, it's closer to white so return black. Otherwise, return white.\n return 'black' if Y > 128 else 'white'\n\n bbox_background = contrasting_color(color*255)\n\n x, y = position\n self.output.ax.text(\n x,\n y,\n text,\n size=font_size * self.output.scale,\n family=\"sans-serif\",\n bbox={\"facecolor\": bbox_background, \"alpha\": 0.8, \"pad\": 0.7, \"edgecolor\": \"none\"},\n verticalalignment=\"top\",\n horizontalalignment=horizontal_alignment,\n color=color,\n zorder=10,\n rotation=rotation,\n )\n return self.output\n\n def draw_box(self, box_coord, alpha=0.5, edge_color=\"g\", line_style=\"-\"):\n \"\"\"\n Args:\n box_coord (tuple): a tuple containing x0, y0, x1, y1 coordinates, where x0 and y0\n are the coordinates of the image's top left corner. x1 and y1 are the\n coordinates of the image's bottom right corner.\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n edge_color: color of the outline of the box. Refer to `matplotlib.colors`\n for full list of formats that are accepted.\n line_style (string): the string to use to create the outline of the boxes.\n\n Returns:\n output (VisImage): image object with box drawn.\n \"\"\"\n x0, y0, x1, y1 = box_coord\n width = x1 - x0\n height = y1 - y0\n\n linewidth = max(self._default_font_size / 12, 1)\n\n self.output.ax.add_patch(\n mpl.patches.Rectangle(\n (x0, y0),\n width,\n height,\n fill=False,\n edgecolor=edge_color,\n linewidth=linewidth * self.output.scale,\n alpha=alpha,\n linestyle=line_style,\n )\n )\n return self.output\n\n def draw_rotated_box_with_label(\n self, rotated_box, alpha=0.5, edge_color=\"g\", line_style=\"-\", label=None\n ):\n \"\"\"\n Draw a rotated box with label on its top-left corner.\n\n Args:\n rotated_box (tuple): a tuple containing (cnt_x, cnt_y, w, h, angle),\n where cnt_x and cnt_y are the center coordinates of the box.\n w and h are the width and height of the box. angle represents how\n many degrees the box is rotated CCW with regard to the 0-degree box.\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n edge_color: color of the outline of the box. Refer to `matplotlib.colors`\n for full list of formats that are accepted.\n line_style (string): the string to use to create the outline of the boxes.\n label (string): label for rotated box. It will not be rendered when set to None.\n\n Returns:\n output (VisImage): image object with box drawn.\n \"\"\"\n cnt_x, cnt_y, w, h, angle = rotated_box\n area = w * h\n # use thinner lines when the box is small\n linewidth = self._default_font_size / (\n 6 if area < _SMALL_OBJECT_AREA_THRESH * self.output.scale else 3\n )\n\n theta = angle * math.pi / 180.0\n c = math.cos(theta)\n s = math.sin(theta)\n rect = [(-w / 2, h / 2), (-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2)]\n # x: left->right ; y: top->down\n rotated_rect = [(s * yy + c * xx + cnt_x, c * yy - s * xx + cnt_y) for (xx, yy) in rect]\n for k in range(4):\n j = (k + 1) % 4\n self.draw_line(\n [rotated_rect[k][0], rotated_rect[j][0]],\n [rotated_rect[k][1], rotated_rect[j][1]],\n color=edge_color,\n linestyle=\"--\" if k == 1 else line_style,\n linewidth=linewidth,\n )\n\n if label is not None:\n text_pos = rotated_rect[1] # topleft corner\n\n height_ratio = h / np.sqrt(self.output.height * self.output.width)\n label_color = self._change_color_brightness(edge_color, brightness_factor=0.7)\n font_size = (\n np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 * self._default_font_size\n )\n self.draw_text(label, text_pos, color=label_color, font_size=font_size, rotation=angle)\n\n return self.output\n\n def draw_circle(self, circle_coord, color, radius=3):\n \"\"\"\n Args:\n circle_coord (list(int) or tuple(int)): contains the x and y coordinates\n of the center of the circle.\n color: color of the polygon. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n radius (int): radius of the circle.\n\n Returns:\n output (VisImage): image object with box drawn.\n \"\"\"\n x, y = circle_coord\n self.output.ax.add_patch(\n mpl.patches.Circle(circle_coord, radius=radius, fill=True, color=color)\n )\n return self.output\n\n def draw_line(self, x_data, y_data, color, linestyle=\"-\", linewidth=None):\n \"\"\"\n Args:\n x_data (list[int]): a list containing x values of all the points being drawn.\n Length of list should match the length of y_data.\n y_data (list[int]): a list containing y values of all the points being drawn.\n Length of list should match the length of x_data.\n color: color of the line. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n linestyle: style of the line. Refer to `matplotlib.lines.Line2D`\n for a full list of formats that are accepted.\n linewidth (float or None): width of the line. When it's None,\n a default value will be computed and used.\n\n Returns:\n output (VisImage): image object with line drawn.\n \"\"\"\n if linewidth is None:\n linewidth = self._default_font_size / 3\n linewidth = max(linewidth, 1)\n self.output.ax.add_line(\n mpl.lines.Line2D(\n x_data,\n y_data,\n linewidth=linewidth * self.output.scale,\n color=color,\n linestyle=linestyle,\n )\n )\n return self.output\n\n def draw_binary_mask(\n self, binary_mask, color=None, *, edge_color=None, text=None, alpha=0.7, area_threshold=10\n ):\n \"\"\"\n Args:\n binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and\n W is the image width. Each value in the array is either a 0 or 1 value of uint8\n type.\n color: color of the mask. Refer to `matplotlib.colors` for a full list of\n formats that are accepted. If None, will pick a random color.\n edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a\n full list of formats that are accepted.\n text (str): if None, will be drawn on the object\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n area_threshold (float): a connected component smaller than this area will not be shown.\n\n Returns:\n output (VisImage): image object with mask drawn.\n \"\"\"\n if color is None:\n color = random_color(rgb=True, maximum=1)\n color = mplc.to_rgb(color)\n\n has_valid_segment = False\n binary_mask = binary_mask.astype(\"uint8\") # opencv needs uint8\n mask = GenericMask(binary_mask, self.output.height, self.output.width)\n shape2d = (binary_mask.shape[0], binary_mask.shape[1])\n\n if not mask.has_holes:\n # draw polygons for regular masks\n for segment in mask.polygons:\n area = mask_util.area(mask_util.frPyObjects([segment], shape2d[0], shape2d[1]))\n if area < (area_threshold or 0):\n continue\n has_valid_segment = True\n segment = segment.reshape(-1, 2)\n self.draw_polygon(segment, color=color, edge_color=edge_color, alpha=alpha)\n else:\n # TODO: Use Path/PathPatch to draw vector graphics:\n # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon\n rgba = np.zeros(shape2d + (4,), dtype=\"float32\")\n rgba[:, :, :3] = color\n rgba[:, :, 3] = (mask.mask == 1).astype(\"float32\") * alpha\n has_valid_segment = True\n self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))\n\n if text is not None and has_valid_segment:\n lighter_color = self._change_color_brightness(color, brightness_factor=0.7)\n self._draw_text_in_mask(binary_mask, text, lighter_color)\n return self.output\n \n def draw_binary_mask_with_number(\n self, binary_mask, color=None, *, edge_color=None, text=None, label_mode='1', alpha=0.1, anno_mode=['Mask'], area_threshold=10\n ):\n \"\"\"\n Args:\n binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and\n W is the image width. Each value in the array is either a 0 or 1 value of uint8\n type.\n color: color of the mask. Refer to `matplotlib.colors` for a full list of\n formats that are accepted. If None, will pick a random color.\n edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a\n full list of formats that are accepted.\n text (str): if None, will be drawn on the object\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n area_threshold (float): a connected component smaller than this area will not be shown.\n\n Returns:\n output (VisImage): image object with mask drawn.\n \"\"\"\n if color is None:\n randint = random.randint(0, len(self.color_proposals)-1)\n color = self.color_proposals[randint]\n color = mplc.to_rgb(color)\n\n has_valid_segment = True\n binary_mask = binary_mask.astype(\"uint8\") # opencv needs uint8\n mask = GenericMask(binary_mask, self.output.height, self.output.width)\n shape2d = (binary_mask.shape[0], binary_mask.shape[1])\n bbox = mask.bbox()\n\n if 'Mask' in anno_mode:\n if not mask.has_holes:\n # draw polygons for regular masks\n for segment in mask.polygons:\n area = mask_util.area(mask_util.frPyObjects([segment], shape2d[0], shape2d[1]))\n if area < (area_threshold or 0):\n continue\n has_valid_segment = True\n segment = segment.reshape(-1, 2)\n self.draw_polygon(segment, color=color, edge_color=edge_color, alpha=alpha)\n else:\n # TODO: Use Path/PathPatch to draw vector graphics:\n # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon\n rgba = np.zeros(shape2d + (4,), dtype=\"float32\")\n rgba[:, :, :3] = color\n rgba[:, :, 3] = (mask.mask == 1).astype(\"float32\") * alpha\n has_valid_segment = True\n self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))\n\n if 'Box' in anno_mode:\n self.draw_box(bbox, edge_color=color, alpha=0.75)\n\n if 'Mark' in anno_mode:\n has_valid_segment = True\n else:\n has_valid_segment = False\n\n if text is not None and has_valid_segment:\n # lighter_color = tuple([x*0.2 for x in color])\n lighter_color = [1,1,1] # self._change_color_brightness(color, brightness_factor=0.7)\n self._draw_number_in_mask(binary_mask, text, lighter_color, label_mode)\n return self.output\n\n def draw_soft_mask(self, soft_mask, color=None, *, text=None, alpha=0.5):\n \"\"\"\n Args:\n soft_mask (ndarray): float array of shape (H, W), each value in [0, 1].\n color: color of the mask. Refer to `matplotlib.colors` for a full list of\n formats that are accepted. If None, will pick a random color.\n text (str): if None, will be drawn on the object\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n\n Returns:\n output (VisImage): image object with mask drawn.\n \"\"\"\n if color is None:\n color = random_color(rgb=True, maximum=1)\n color = mplc.to_rgb(color)\n\n shape2d = (soft_mask.shape[0], soft_mask.shape[1])\n rgba = np.zeros(shape2d + (4,), dtype=\"float32\")\n rgba[:, :, :3] = color\n rgba[:, :, 3] = soft_mask * alpha\n self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))\n\n if text is not None:\n lighter_color = self._change_color_brightness(color, brightness_factor=0.7)\n binary_mask = (soft_mask > 0.5).astype(\"uint8\")\n self._draw_text_in_mask(binary_mask, text, lighter_color)\n return self.output\n\n def draw_polygon(self, segment, color, edge_color=None, alpha=0.5):\n \"\"\"\n Args:\n segment: numpy array of shape Nx2, containing all the points in the polygon.\n color: color of the polygon. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a\n full list of formats that are accepted. If not provided, a darker shade\n of the polygon color will be used instead.\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n\n Returns:\n output (VisImage): image object with polygon drawn.\n \"\"\"\n if edge_color is None:\n # make edge color darker than the polygon color\n if alpha > 0.8:\n edge_color = self._change_color_brightness(color, brightness_factor=-0.7)\n else:\n edge_color = color\n edge_color = mplc.to_rgb(edge_color) + (1,)\n\n polygon = mpl.patches.Polygon(\n segment,\n fill=True,\n facecolor=mplc.to_rgb(color) + (alpha,),\n edgecolor=edge_color,\n linewidth=max(self._default_font_size // 15 * self.output.scale, 1),\n )\n self.output.ax.add_patch(polygon)\n return self.output\n\n \"\"\"\n Internal methods:\n \"\"\"\n\n def _jitter(self, color):\n \"\"\"\n Randomly modifies given color to produce a slightly different color than the color given.\n\n Args:\n color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color\n picked. The values in the list are in the [0.0, 1.0] range.\n\n Returns:\n jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the\n color after being jittered. The values in the list are in the [0.0, 1.0] range.\n \"\"\"\n color = mplc.to_rgb(color)\n # np.random.seed(0)\n vec = np.random.rand(3)\n # better to do it in another color space\n vec = vec / np.linalg.norm(vec) * 0.5\n res = np.clip(vec + color, 0, 1)\n return tuple(res)\n\n def _create_grayscale_image(self, mask=None):\n \"\"\"\n Create a grayscale version of the original image.\n The colors in masked area, if given, will be kept.\n \"\"\"\n img_bw = self.img.astype(\"f4\").mean(axis=2)\n img_bw = np.stack([img_bw] * 3, axis=2)\n if mask is not None:\n img_bw[mask] = self.img[mask]\n return img_bw\n\n def _change_color_brightness(self, color, brightness_factor):\n \"\"\"\n Depending on the brightness_factor, gives a lighter or darker color i.e. a color with\n less or more saturation than the original color.\n\n Args:\n color: color of the polygon. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of\n 0 will correspond to no change, a factor in [-1.0, 0) range will result in\n a darker color and a factor in (0, 1.0] range will result in a lighter color.\n\n Returns:\n modified_color (tuple[double]): a tuple containing the RGB values of the\n modified color. Each value in the tuple is in the [0.0, 1.0] range.\n \"\"\"\n assert brightness_factor >= -1.0 and brightness_factor <= 1.0\n color = mplc.to_rgb(color)\n polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))\n modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1])\n modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness\n modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness\n modified_color = colorsys.hls_to_rgb(polygon_color[0], modified_lightness, polygon_color[2])\n return modified_color\n\n def _convert_boxes(self, boxes):\n \"\"\"\n Convert different format of boxes to an NxB array, where B = 4 or 5 is the box dimension.\n \"\"\"\n if isinstance(boxes, Boxes) or isinstance(boxes, RotatedBoxes):\n return boxes.tensor.detach().numpy()\n else:\n return np.asarray(boxes)\n\n def _convert_masks(self, masks_or_polygons):\n \"\"\"\n Convert different format of masks or polygons to a tuple of masks and polygons.\n\n Returns:\n list[GenericMask]:\n \"\"\"\n\n m = masks_or_polygons\n if isinstance(m, PolygonMasks):\n m = m.polygons\n if isinstance(m, BitMasks):\n m = m.tensor.numpy()\n if isinstance(m, torch.Tensor):\n m = m.numpy()\n ret = []\n for x in m:\n if isinstance(x, GenericMask):\n ret.append(x)\n else:\n ret.append(GenericMask(x, self.output.height, self.output.width))\n return ret\n\n def _draw_number_in_mask(self, binary_mask, text, color, label_mode='1'):\n \"\"\"\n Find proper places to draw text given a binary mask.\n \"\"\"\n\n def number_to_string(n):\n chars = []\n while n:\n n, remainder = divmod(n-1, 26)\n chars.append(chr(97 + remainder))\n return ''.join(reversed(chars))\n\n binary_mask = np.pad(binary_mask, ((1, 1), (1, 1)), 'constant')\n mask_dt = cv2.distanceTransform(binary_mask, cv2.DIST_L2, 0)\n mask_dt = mask_dt[1:-1, 1:-1]\n max_dist = np.max(mask_dt)\n coords_y, coords_x = np.where(mask_dt == max_dist) # coords is [y, x]\n\n if label_mode == 'a':\n text = number_to_string(int(text))\n else:\n text = text\n\n self.draw_text(text, (coords_x[len(coords_x)//2] + 2, coords_y[len(coords_y)//2] - 6), color=color)\n\n # TODO sometimes drawn on wrong objects. the heuristics here can improve.\n # _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8)\n # if stats[1:, -1].size == 0:\n # return\n # largest_component_id = np.argmax(stats[1:, -1]) + 1\n\n # # draw text on the largest component, as well as other very large components.\n # for cid in range(1, _num_cc):\n # if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:\n # # median is more stable than centroid\n # # center = centroids[largest_component_id]\n # center = np.median((cc_labels == cid).nonzero(), axis=1)[::-1]\n # # bottom=np.max((cc_labels == cid).nonzero(), axis=1)[::-1]\n # # center[1]=bottom[1]+2\n # self.draw_text(text, center, color=color)\n \n def _draw_text_in_mask(self, binary_mask, text, color):\n \"\"\"\n Find proper places to draw text given a binary mask.\n \"\"\"\n # TODO sometimes drawn on wrong objects. the heuristics here can improve.\n _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8)\n if stats[1:, -1].size == 0:\n return\n largest_component_id = np.argmax(stats[1:, -1]) + 1\n\n # draw text on the largest component, as well as other very large components.\n for cid in range(1, _num_cc):\n if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:\n # median is more stable than centroid\n # center = centroids[largest_component_id]\n center = np.median((cc_labels == cid).nonzero(), axis=1)[::-1]\n bottom=np.max((cc_labels == cid).nonzero(), axis=1)[::-1]\n center[1]=bottom[1]+2\n self.draw_text(text, center, color=color)\n\n def _convert_keypoints(self, keypoints):\n if isinstance(keypoints, Keypoints):\n keypoints = keypoints.tensor\n keypoints = np.asarray(keypoints)\n return keypoints\n\n def get_output(self):\n \"\"\"\n Returns:\n output (VisImage): the image output containing the visualizations added\n to the image.\n \"\"\"\n return self.output" }, { "identifier": "request_gpt4v", "path": "gpt4v.py", "snippet": "def request_gpt4v(message, image):\n payload = prepare_inputs(message, image)\n response = requests.post(\"https://api.openai.com/v1/chat/completions\", headers=headers, json=payload)\n res = response.json()['choices'][0]['message']['content']\n return res" } ]
import io import gradio as gr import torch import argparse import numpy as np import matplotlib.colors as mcolors from PIL import Image from seem.modeling.BaseModel import BaseModel as BaseModel_Seem from seem.utils.distributed import init_distributed as init_distributed_seem from seem.modeling import build_model as build_model_seem from task_adapter.seem.tasks import interactive_seem_m2m_auto, inference_seem_pano, inference_seem_interactive from semantic_sam.BaseModel import BaseModel from semantic_sam import build_model from semantic_sam.utils.dist import init_distributed_mode from semantic_sam.utils.arguments import load_opt_from_config_file from semantic_sam.utils.constants import COCO_PANOPTIC_CLASSES from task_adapter.semantic_sam.tasks import inference_semsam_m2m_auto, prompt_switch from segment_anything import sam_model_registry from task_adapter.sam.tasks.inference_sam_m2m_auto import inference_sam_m2m_auto from task_adapter.sam.tasks.inference_sam_m2m_interactive import inference_sam_m2m_interactive from task_adapter.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog from scipy.ndimage import label from gpt4v import request_gpt4v from openai import OpenAI from pydub import AudioSegment from pydub.playback import play
17,770
# -------------------------------------------------------- # Set-of-Mark (SoM) Prompting for Visual Grounding in GPT-4V # Copyright (c) 2023 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by: # Jianwei Yang ([email protected]) # Xueyan Zou ([email protected]) # Hao Zhang ([email protected]) # -------------------------------------------------------- # seem # semantic sam # sam metadata = MetadataCatalog.get('coco_2017_train_panoptic') css4_colors = mcolors.CSS4_COLORS color_proposals = [list(mcolors.hex2color(color)) for color in css4_colors.values()] client = OpenAI() ''' build args ''' semsam_cfg = "configs/semantic_sam_only_sa-1b_swinL.yaml" seem_cfg = "configs/seem_focall_unicl_lang_v1.yaml" semsam_ckpt = "./swinl_only_sam_many2many.pth" sam_ckpt = "./sam_vit_h_4b8939.pth" seem_ckpt = "./seem_focall_v1.pt" opt_semsam = load_opt_from_config_file(semsam_cfg) opt_seem = load_opt_from_config_file(seem_cfg) opt_seem = init_distributed_seem(opt_seem) ''' build model ''' model_semsam = BaseModel(opt_semsam, build_model(opt_semsam)).from_pretrained(semsam_ckpt).eval().cuda() model_sam = sam_model_registry["vit_h"](checkpoint=sam_ckpt).eval().cuda() model_seem = BaseModel_Seem(opt_seem, build_model_seem(opt_seem)).from_pretrained(seem_ckpt).eval().cuda() with torch.no_grad(): with torch.autocast(device_type='cuda', dtype=torch.float16): model_seem.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(COCO_PANOPTIC_CLASSES + ["background"], is_eval=True) history_images = [] history_masks = [] history_texts = [] @torch.no_grad() def inference(image, slider, mode, alpha, label_mode, anno_mode, *args, **kwargs): global history_images; history_images = [] global history_masks; history_masks = [] if slider < 1.5: model_name = 'seem' elif slider > 2.5: model_name = 'sam' else: if mode == 'Automatic': model_name = 'semantic-sam' if slider < 1.5 + 0.14: level = [1] elif slider < 1.5 + 0.28: level = [2] elif slider < 1.5 + 0.42: level = [3] elif slider < 1.5 + 0.56: level = [4] elif slider < 1.5 + 0.70: level = [5] elif slider < 1.5 + 0.84: level = [6] else: level = [6, 1, 2, 3, 4, 5] else: model_name = 'sam' if label_mode == 'Alphabet': label_mode = 'a' else: label_mode = '1' text_size, hole_scale, island_scale=640,100,100 text, text_part, text_thresh = '','','0.0' with torch.autocast(device_type='cuda', dtype=torch.float16): semantic=False if mode == "Interactive": labeled_array, num_features = label(np.asarray(image['mask'].convert('L'))) spatial_masks = torch.stack([torch.from_numpy(labeled_array == i+1) for i in range(num_features)]) if model_name == 'semantic-sam': model = model_semsam
# -------------------------------------------------------- # Set-of-Mark (SoM) Prompting for Visual Grounding in GPT-4V # Copyright (c) 2023 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by: # Jianwei Yang ([email protected]) # Xueyan Zou ([email protected]) # Hao Zhang ([email protected]) # -------------------------------------------------------- # seem # semantic sam # sam metadata = MetadataCatalog.get('coco_2017_train_panoptic') css4_colors = mcolors.CSS4_COLORS color_proposals = [list(mcolors.hex2color(color)) for color in css4_colors.values()] client = OpenAI() ''' build args ''' semsam_cfg = "configs/semantic_sam_only_sa-1b_swinL.yaml" seem_cfg = "configs/seem_focall_unicl_lang_v1.yaml" semsam_ckpt = "./swinl_only_sam_many2many.pth" sam_ckpt = "./sam_vit_h_4b8939.pth" seem_ckpt = "./seem_focall_v1.pt" opt_semsam = load_opt_from_config_file(semsam_cfg) opt_seem = load_opt_from_config_file(seem_cfg) opt_seem = init_distributed_seem(opt_seem) ''' build model ''' model_semsam = BaseModel(opt_semsam, build_model(opt_semsam)).from_pretrained(semsam_ckpt).eval().cuda() model_sam = sam_model_registry["vit_h"](checkpoint=sam_ckpt).eval().cuda() model_seem = BaseModel_Seem(opt_seem, build_model_seem(opt_seem)).from_pretrained(seem_ckpt).eval().cuda() with torch.no_grad(): with torch.autocast(device_type='cuda', dtype=torch.float16): model_seem.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(COCO_PANOPTIC_CLASSES + ["background"], is_eval=True) history_images = [] history_masks = [] history_texts = [] @torch.no_grad() def inference(image, slider, mode, alpha, label_mode, anno_mode, *args, **kwargs): global history_images; history_images = [] global history_masks; history_masks = [] if slider < 1.5: model_name = 'seem' elif slider > 2.5: model_name = 'sam' else: if mode == 'Automatic': model_name = 'semantic-sam' if slider < 1.5 + 0.14: level = [1] elif slider < 1.5 + 0.28: level = [2] elif slider < 1.5 + 0.42: level = [3] elif slider < 1.5 + 0.56: level = [4] elif slider < 1.5 + 0.70: level = [5] elif slider < 1.5 + 0.84: level = [6] else: level = [6, 1, 2, 3, 4, 5] else: model_name = 'sam' if label_mode == 'Alphabet': label_mode = 'a' else: label_mode = '1' text_size, hole_scale, island_scale=640,100,100 text, text_part, text_thresh = '','','0.0' with torch.autocast(device_type='cuda', dtype=torch.float16): semantic=False if mode == "Interactive": labeled_array, num_features = label(np.asarray(image['mask'].convert('L'))) spatial_masks = torch.stack([torch.from_numpy(labeled_array == i+1) for i in range(num_features)]) if model_name == 'semantic-sam': model = model_semsam
output, mask = inference_semsam_m2m_auto(model, image['image'], level, text, text_part, text_thresh, text_size, hole_scale, island_scale, semantic, label_mode=label_mode, alpha=alpha, anno_mode=anno_mode, *args, **kwargs)
3
2023-10-16 03:39:26+00:00
24k
hkchengrex/Cutie
gui/main_controller.py
[ { "identifier": "CUTIE", "path": "cutie/model/cutie.py", "snippet": "class CUTIE(nn.Module):\n def __init__(self, cfg: DictConfig, *, single_object=False):\n super().__init__()\n model_cfg = cfg.model\n self.ms_dims = model_cfg.pixel_encoder.ms_dims\n self.key_dim = model_cfg.key_dim\n self.value_dim = model_cfg.value_dim\n self.sensory_dim = model_cfg.sensory_dim\n self.pixel_dim = model_cfg.pixel_dim\n self.embed_dim = model_cfg.embed_dim\n self.single_object = single_object\n\n log.info(f'Single object: {self.single_object}')\n\n self.pixel_encoder = PixelEncoder(model_cfg)\n self.pix_feat_proj = nn.Conv2d(self.ms_dims[0], self.pixel_dim, kernel_size=1)\n self.key_proj = KeyProjection(model_cfg)\n self.mask_encoder = MaskEncoder(model_cfg, single_object=single_object)\n self.mask_decoder = MaskDecoder(model_cfg)\n self.pixel_fuser = PixelFeatureFuser(model_cfg, single_object=single_object)\n self.object_transformer = QueryTransformer(model_cfg)\n self.object_summarizer = ObjectSummarizer(model_cfg)\n self.aux_computer = AuxComputer(cfg)\n\n self.register_buffer(\"pixel_mean\", torch.Tensor(model_cfg.pixel_mean).view(-1, 1, 1), False)\n self.register_buffer(\"pixel_std\", torch.Tensor(model_cfg.pixel_std).view(-1, 1, 1), False)\n\n def _get_others(self, masks: torch.Tensor) -> torch.Tensor:\n # for each object, return the sum of masks of all other objects\n if self.single_object:\n return None\n\n num_objects = masks.shape[1]\n if num_objects >= 1:\n others = (masks.sum(dim=1, keepdim=True) - masks).clamp(0, 1)\n else:\n others = torch.zeros_like(masks)\n return others\n\n def encode_image(self, image: torch.Tensor) -> (Iterable[torch.Tensor], torch.Tensor):\n image = (image - self.pixel_mean) / self.pixel_std\n ms_image_feat = self.pixel_encoder(image)\n return ms_image_feat, self.pix_feat_proj(ms_image_feat[0])\n\n def encode_mask(\n self,\n image: torch.Tensor,\n ms_features: List[torch.Tensor],\n sensory: torch.Tensor,\n masks: torch.Tensor,\n *,\n deep_update: bool = True,\n chunk_size: int = -1,\n need_weights: bool = False) -> (torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor):\n image = (image - self.pixel_mean) / self.pixel_std\n others = self._get_others(masks)\n mask_value, new_sensory = self.mask_encoder(image,\n ms_features,\n sensory,\n masks,\n others,\n deep_update=deep_update,\n chunk_size=chunk_size)\n object_summaries, object_logits = self.object_summarizer(masks, mask_value, need_weights)\n return mask_value, new_sensory, object_summaries, object_logits\n\n def transform_key(self,\n final_pix_feat: torch.Tensor,\n *,\n need_sk: bool = True,\n need_ek: bool = True) -> (torch.Tensor, torch.Tensor, torch.Tensor):\n key, shrinkage, selection = self.key_proj(final_pix_feat, need_s=need_sk, need_e=need_ek)\n return key, shrinkage, selection\n\n # Used in training only.\n # This step is replaced by MemoryManager in test time\n def read_memory(self, query_key: torch.Tensor, query_selection: torch.Tensor,\n memory_key: torch.Tensor, memory_shrinkage: torch.Tensor,\n msk_value: torch.Tensor, obj_memory: torch.Tensor, pix_feat: torch.Tensor,\n sensory: torch.Tensor, last_mask: torch.Tensor,\n selector: torch.Tensor) -> (torch.Tensor, Dict[str, torch.Tensor]):\n \"\"\"\n query_key : B * CK * H * W\n query_selection : B * CK * H * W\n memory_key : B * CK * T * H * W\n memory_shrinkage: B * 1 * T * H * W\n msk_value : B * num_objects * CV * T * H * W\n obj_memory : B * num_objects * T * num_summaries * C\n pixel_feature : B * C * H * W\n \"\"\"\n batch_size, num_objects = msk_value.shape[:2]\n\n # read using visual attention\n with torch.cuda.amp.autocast(enabled=False):\n affinity = get_affinity(memory_key.float(), memory_shrinkage.float(), query_key.float(),\n query_selection.float())\n\n msk_value = msk_value.flatten(start_dim=1, end_dim=2).float()\n\n # B * (num_objects*CV) * H * W\n pixel_readout = readout(affinity, msk_value)\n pixel_readout = pixel_readout.view(batch_size, num_objects, self.value_dim,\n *pixel_readout.shape[-2:])\n pixel_readout = self.pixel_fusion(pix_feat, pixel_readout, sensory, last_mask)\n\n # read from query transformer\n mem_readout, aux_features = self.readout_query(pixel_readout, obj_memory, selector=selector)\n\n aux_output = {\n 'sensory': sensory,\n 'q_logits': aux_features['logits'] if aux_features else None,\n 'attn_mask': aux_features['attn_mask'] if aux_features else None,\n }\n\n return mem_readout, aux_output\n\n def pixel_fusion(self,\n pix_feat: torch.Tensor,\n pixel: torch.Tensor,\n sensory: torch.Tensor,\n last_mask: torch.Tensor,\n *,\n chunk_size: int = -1) -> torch.Tensor:\n last_mask = F.interpolate(last_mask, size=sensory.shape[-2:], mode='area')\n last_others = self._get_others(last_mask)\n fused = self.pixel_fuser(pix_feat,\n pixel,\n sensory,\n last_mask,\n last_others,\n chunk_size=chunk_size)\n return fused\n\n def readout_query(self,\n pixel_readout,\n obj_memory,\n *,\n selector=None,\n need_weights=False) -> (torch.Tensor, Dict[str, torch.Tensor]):\n return self.object_transformer(pixel_readout,\n obj_memory,\n selector=selector,\n need_weights=need_weights)\n\n def segment(self,\n ms_image_feat: List[torch.Tensor],\n memory_readout: torch.Tensor,\n sensory: torch.Tensor,\n *,\n selector: bool = None,\n chunk_size: int = -1,\n update_sensory: bool = True) -> (torch.Tensor, torch.Tensor, torch.Tensor):\n \"\"\"\n multi_scale_features is from the key encoder for skip-connection\n memory_readout is from working/long-term memory\n sensory is the sensory memory\n last_mask is the mask from the last frame, supplementing sensory memory\n selector is 1 if an object exists, and 0 otherwise. We use it to filter padded objects\n during training.\n \"\"\"\n sensory, logits = self.mask_decoder(ms_image_feat,\n memory_readout,\n sensory,\n chunk_size=chunk_size,\n update_sensory=update_sensory)\n\n prob = torch.sigmoid(logits)\n if selector is not None:\n prob = prob * selector\n\n # Softmax over all objects[]\n logits = aggregate(prob, dim=1)\n logits = F.interpolate(logits, scale_factor=4, mode='bilinear', align_corners=False)\n prob = F.softmax(logits, dim=1)\n\n return sensory, logits, prob\n\n def compute_aux(self, pix_feat: torch.Tensor, aux_inputs: Dict[str, torch.Tensor],\n selector: torch.Tensor) -> Dict[str, torch.Tensor]:\n return self.aux_computer(pix_feat, aux_inputs, selector)\n\n def forward(self, *args, **kwargs):\n raise NotImplementedError\n\n def load_weights(self, src_dict, init_as_zero_if_needed=False) -> None:\n if not self.single_object:\n # Map single-object weight to multi-object weight (4->5 out channels in conv1)\n for k in list(src_dict.keys()):\n if k == 'mask_encoder.conv1.weight':\n if src_dict[k].shape[1] == 4:\n log.info(f'Converting {k} from single object to multiple objects.')\n pads = torch.zeros((64, 1, 7, 7), device=src_dict[k].device)\n if not init_as_zero_if_needed:\n nn.init.orthogonal_(pads)\n log.info(f'Randomly initialized padding for {k}.')\n else:\n log.info(f'Zero-initialized padding for {k}.')\n src_dict[k] = torch.cat([src_dict[k], pads], 1)\n elif k == 'pixel_fuser.sensory_compress.weight':\n if src_dict[k].shape[1] == self.sensory_dim + 1:\n log.info(f'Converting {k} from single object to multiple objects.')\n pads = torch.zeros((self.value_dim, 1, 1, 1), device=src_dict[k].device)\n if not init_as_zero_if_needed:\n nn.init.orthogonal_(pads)\n log.info(f'Randomly initialized padding for {k}.')\n else:\n log.info(f'Zero-initialized padding for {k}.')\n src_dict[k] = torch.cat([src_dict[k], pads], 1)\n elif self.single_object:\n \"\"\"\n If the model is multiple-object and we are training in single-object, \n we strip the last channel of conv1.\n This is not supposed to happen in standard training except when users are trying to\n finetune a trained model with single object datasets.\n \"\"\"\n if src_dict['mask_encoder.conv1.weight'].shape[1] == 5:\n log.warning(f'Converting {k} from multiple objects to single object.'\n 'This is not supposed to happen in standard training.')\n src_dict[k] = src_dict[k][:, :-1]\n\n for k in src_dict:\n if k not in self.state_dict():\n log.info(f'Key {k} found in src_dict but not in self.state_dict()!!!')\n for k in self.state_dict():\n if k not in src_dict:\n log.info(f'Key {k} found in self.state_dict() but not in src_dict!!!')\n\n self.load_state_dict(src_dict, strict=False)\n\n @property\n def device(self) -> torch.device:\n return self.pixel_mean.device" }, { "identifier": "InferenceCore", "path": "cutie/inference/inference_core.py", "snippet": "class InferenceCore:\n def __init__(self,\n network: CUTIE,\n cfg: DictConfig,\n *,\n image_feature_store: ImageFeatureStore = None):\n self.network = network\n self.cfg = cfg\n self.mem_every = cfg.mem_every\n stagger_updates = cfg.stagger_updates\n self.chunk_size = cfg.chunk_size\n self.save_aux = cfg.save_aux\n self.max_internal_size = cfg.max_internal_size\n self.flip_aug = cfg.flip_aug\n\n self.curr_ti = -1\n self.last_mem_ti = 0\n # at which time indices should we update the sensory memory\n if stagger_updates >= self.mem_every:\n self.stagger_ti = set(range(1, self.mem_every + 1))\n else:\n self.stagger_ti = set(\n np.round(np.linspace(1, self.mem_every, stagger_updates)).astype(int))\n self.object_manager = ObjectManager()\n self.memory = MemoryManager(cfg=cfg, object_manager=self.object_manager)\n\n if image_feature_store is None:\n self.image_feature_store = ImageFeatureStore(self.network)\n else:\n self.image_feature_store = image_feature_store\n\n self.last_mask = None\n\n def clear_memory(self):\n self.curr_ti = -1\n self.last_mem_ti = 0\n self.memory = MemoryManager(cfg=self.cfg, object_manager=self.object_manager)\n\n def clear_non_permanent_memory(self):\n self.curr_ti = -1\n self.last_mem_ti = 0\n self.memory.clear_non_permanent_memory()\n\n def clear_sensory_memory(self):\n self.curr_ti = -1\n self.last_mem_ti = 0\n self.memory.clear_sensory_memory()\n\n def update_config(self, cfg):\n self.mem_every = cfg['mem_every']\n self.memory.update_config(cfg)\n\n def _add_memory(self,\n image: torch.Tensor,\n pix_feat: torch.Tensor,\n prob: torch.Tensor,\n key: torch.Tensor,\n shrinkage: torch.Tensor,\n selection: torch.Tensor,\n *,\n is_deep_update: bool = True,\n force_permanent: bool = False) -> None:\n \"\"\"\n Memorize the given segmentation in all memory stores.\n\n The batch dimension is 1 if flip augmentation is not used.\n image: RGB image, (1/2)*3*H*W\n pix_feat: from the key encoder, (1/2)*_*H*W\n prob: (1/2)*num_objects*H*W, in [0, 1]\n key/shrinkage/selection: for anisotropic l2, (1/2)*_*H*W\n selection can be None if not using long-term memory\n is_deep_update: whether to use deep update (e.g. with the mask encoder)\n force_permanent: whether to force the memory to be permanent\n \"\"\"\n if prob.shape[1] == 0:\n # nothing to add\n log.warn('Trying to add an empty object mask to memory!')\n return\n\n if force_permanent:\n as_permanent = 'all'\n else:\n as_permanent = 'first'\n\n self.memory.initialize_sensory_if_needed(key, self.object_manager.all_obj_ids)\n msk_value, sensory, obj_value, self.obj_logits = self.network.encode_mask(\n image,\n pix_feat,\n self.memory.get_sensory(self.object_manager.all_obj_ids),\n prob,\n deep_update=is_deep_update,\n chunk_size=self.chunk_size,\n need_weights=self.save_aux)\n self.memory.add_memory(key,\n shrinkage,\n msk_value,\n obj_value,\n self.object_manager.all_obj_ids,\n selection=selection,\n as_permanent=as_permanent)\n self.last_mem_ti = self.curr_ti\n if is_deep_update:\n self.memory.update_sensory(sensory, self.object_manager.all_obj_ids)\n\n def _segment(self,\n key: torch.Tensor,\n selection: torch.Tensor,\n pix_feat: torch.Tensor,\n ms_features: Iterable[torch.Tensor],\n update_sensory: bool = True) -> torch.Tensor:\n \"\"\"\n Produce a segmentation using the given features and the memory\n\n The batch dimension is 1 if flip augmentation is not used.\n key/selection: for anisotropic l2: (1/2) * _ * H * W\n pix_feat: from the key encoder, (1/2) * _ * H * W\n ms_features: an iterable of multiscale features from the encoder, each is (1/2)*_*H*W\n with strides 16, 8, and 4 respectively\n update_sensory: whether to update the sensory memory\n\n Returns: (num_objects+1)*H*W normalized probability; the first channel is the background\n \"\"\"\n bs = key.shape[0]\n if self.flip_aug:\n assert bs == 2\n else:\n assert bs == 1\n\n if not self.memory.engaged:\n log.warn('Trying to segment without any memory!')\n return torch.zeros((1, key.shape[-2] * 16, key.shape[-1] * 16),\n device=key.device,\n dtype=key.dtype)\n\n memory_readout = self.memory.read(pix_feat, key, selection, self.last_mask, self.network)\n memory_readout = self.object_manager.realize_dict(memory_readout)\n sensory, _, pred_prob_with_bg = self.network.segment(ms_features,\n memory_readout,\n self.memory.get_sensory(\n self.object_manager.all_obj_ids),\n chunk_size=self.chunk_size,\n update_sensory=update_sensory)\n # remove batch dim\n if self.flip_aug:\n # average predictions of the non-flipped and flipped version\n pred_prob_with_bg = (pred_prob_with_bg[0] +\n torch.flip(pred_prob_with_bg[1], dims=[-1])) / 2\n else:\n pred_prob_with_bg = pred_prob_with_bg[0]\n if update_sensory:\n self.memory.update_sensory(sensory, self.object_manager.all_obj_ids)\n return pred_prob_with_bg\n\n def step(self,\n image: torch.Tensor,\n mask: Optional[torch.Tensor] = None,\n objects: Optional[List[int]] = None,\n *,\n idx_mask: bool = True,\n end: bool = False,\n delete_buffer: bool = True,\n force_permanent: bool = False) -> torch.Tensor:\n \"\"\"\n Take a step with a new incoming image.\n If there is an incoming mask with new objects, we will memorize them.\n If there is no incoming mask, we will segment the image using the memory.\n In both cases, we will update the memory and return a segmentation.\n\n image: 3*H*W\n mask: H*W (if idx mask) or len(objects)*H*W or None\n objects: list of object ids that are valid in the mask Tensor.\n The ids themselves do not need to be consecutive/in order, but they need to be \n in the same position in the list as the corresponding mask\n in the tensor in non-idx-mask mode.\n objects is ignored if the mask is None. \n If idx_mask is False and objects is None, we sequentially infer the object ids.\n idx_mask: if True, mask is expected to contain an object id at every pixel.\n If False, mask should have multiple channels with each channel representing one object.\n end: if we are at the end of the sequence, we do not need to update memory\n if unsure just set it to False \n delete_buffer: whether to delete the image feature buffer after this step\n force_permanent: the memory recorded this frame will be added to the permanent memory\n \"\"\"\n if objects is None and mask is not None:\n assert not idx_mask\n objects = list(range(1, mask.shape[0] + 1))\n\n # resize input if needed -- currently only used for the GUI\n resize_needed = False\n if self.max_internal_size > 0:\n h, w = image.shape[-2:]\n min_side = min(h, w)\n if min_side > self.max_internal_size:\n resize_needed = True\n new_h = int(h / min_side * self.max_internal_size)\n new_w = int(w / min_side * self.max_internal_size)\n image = F.interpolate(image.unsqueeze(0),\n size=(new_h, new_w),\n mode='bilinear',\n align_corners=False)[0]\n if mask is not None:\n if idx_mask:\n mask = F.interpolate(mask.unsqueeze(0).unsqueeze(0).float(),\n size=(new_h, new_w),\n mode='nearest',\n align_corners=False)[0, 0].round().long()\n else:\n mask = F.interpolate(mask.unsqueeze(0),\n size=(new_h, new_w),\n mode='bilinear',\n align_corners=False)[0]\n\n self.curr_ti += 1\n\n image, self.pad = pad_divide_by(image, 16)\n image = image.unsqueeze(0) # add the batch dimension\n if self.flip_aug:\n image = torch.cat([image, torch.flip(image, dims=[-1])], dim=0)\n\n # whether to update the working memory\n is_mem_frame = ((self.curr_ti - self.last_mem_ti >= self.mem_every) or\n (mask is not None)) and (not end)\n # segment when there is no input mask or when the input mask is incomplete\n need_segment = (mask is None) or (self.object_manager.num_obj > 0\n and not self.object_manager.has_all(objects))\n update_sensory = ((self.curr_ti - self.last_mem_ti) in self.stagger_ti) and (not end)\n\n # encoding the image\n ms_feat, pix_feat = self.image_feature_store.get_features(self.curr_ti, image)\n key, shrinkage, selection = self.image_feature_store.get_key(self.curr_ti, image)\n\n # segmentation from memory if needed\n if need_segment:\n pred_prob_with_bg = self._segment(key,\n selection,\n pix_feat,\n ms_feat,\n update_sensory=update_sensory)\n\n # use the input mask if provided\n if mask is not None:\n # inform the manager of the new objects, and get a list of temporary id\n # temporary ids -- indicates the position of objects in the tensor\n # (starts with 1 due to the background channel)\n corresponding_tmp_ids, _ = self.object_manager.add_new_objects(objects)\n\n mask, _ = pad_divide_by(mask, 16)\n if need_segment:\n # merge predicted mask with the incomplete input mask\n pred_prob_no_bg = pred_prob_with_bg[1:]\n # use the mutual exclusivity of segmentation\n if idx_mask:\n pred_prob_no_bg[:, mask > 0] = 0\n else:\n pred_prob_no_bg[:, mask.max(0) > 0.5] = 0\n\n new_masks = []\n for mask_id, tmp_id in enumerate(corresponding_tmp_ids):\n if idx_mask:\n this_mask = (mask == objects[mask_id]).type_as(pred_prob_no_bg)\n else:\n this_mask = mask[tmp_id]\n if tmp_id > pred_prob_no_bg.shape[0]:\n new_masks.append(this_mask.unsqueeze(0))\n else:\n # +1 for padding the background channel\n pred_prob_no_bg[tmp_id - 1] = this_mask\n # new_masks are always in the order of tmp_id\n mask = torch.cat([pred_prob_no_bg, *new_masks], dim=0)\n elif idx_mask:\n # simply convert cls to one-hot representation\n if len(objects) == 0:\n if delete_buffer:\n self.image_feature_store.delete(self.curr_ti)\n log.warn('Trying to insert an empty mask as memory!')\n return torch.zeros((1, key.shape[-2] * 16, key.shape[-1] * 16),\n device=key.device,\n dtype=key.dtype)\n mask = torch.stack(\n [mask == objects[mask_id] for mask_id, _ in enumerate(corresponding_tmp_ids)],\n dim=0)\n pred_prob_with_bg = aggregate(mask, dim=0)\n pred_prob_with_bg = torch.softmax(pred_prob_with_bg, dim=0)\n\n self.last_mask = pred_prob_with_bg[1:].unsqueeze(0)\n if self.flip_aug:\n self.last_mask = torch.cat(\n [self.last_mask, torch.flip(self.last_mask, dims=[-1])], dim=0)\n\n # save as memory if needed\n if is_mem_frame or force_permanent:\n self._add_memory(image,\n pix_feat,\n self.last_mask,\n key,\n shrinkage,\n selection,\n force_permanent=force_permanent)\n\n if delete_buffer:\n self.image_feature_store.delete(self.curr_ti)\n\n output_prob = unpad(pred_prob_with_bg, self.pad)\n if resize_needed:\n # restore output to the original size\n output_prob = F.interpolate(output_prob.unsqueeze(0),\n size=(h, w),\n mode='bilinear',\n align_corners=False)[0]\n\n return output_prob\n\n def get_aux_outputs(self, image: torch.Tensor) -> Dict[str, torch.Tensor]:\n image, pads = pad_divide_by(image, 16)\n image = image.unsqueeze(0) # add the batch dimension\n _, pix_feat = self.image_feature_store.get_features(self.curr_ti, image)\n\n aux_inputs = self.memory.aux\n aux_outputs = self.network.compute_aux(pix_feat, aux_inputs, selector=None)\n aux_outputs['q_weights'] = aux_inputs['q_weights']\n aux_outputs['p_weights'] = aux_inputs['p_weights']\n\n for k, v in aux_outputs.items():\n if len(v.shape) == 5:\n aux_outputs[k] = F.interpolate(v[0],\n size=image.shape[-2:],\n mode='bilinear',\n align_corners=False)\n elif 'weights' in k:\n b, num_objects, num_heads, num_queries, h, w = v.shape\n v = v.view(num_objects * num_heads, num_queries, h, w)\n v = F.interpolate(v, size=image.shape[-2:], mode='bilinear', align_corners=False)\n aux_outputs[k] = v.view(num_objects, num_heads, num_queries, *image.shape[-2:])\n else:\n aux_outputs[k] = F.interpolate(v,\n size=image.shape[-2:],\n mode='bilinear',\n align_corners=False)[0]\n aux_outputs[k] = unpad(aux_outputs[k], pads)\n if 'weights' in k:\n weights = aux_outputs[k]\n weights = weights / (weights.max(-1, keepdim=True)[0].max(-2, keepdim=True)[0] +\n 1e-8)\n aux_outputs[k] = (weights * 255).cpu().numpy()\n else:\n aux_outputs[k] = (aux_outputs[k].softmax(dim=0) * 255).cpu().numpy()\n\n self.image_feature_store.delete(self.curr_ti)\n return aux_outputs\n\n def get_aux_object_weights(self, image: torch.Tensor) -> np.ndarray:\n image, pads = pad_divide_by(image, 16)\n # B*num_objects*H*W*num_queries -> num_objects*num_queries*H*W\n # weights = F.softmax(self.obj_logits, dim=-1)[0]\n weights = F.sigmoid(self.obj_logits)[0]\n weights = weights.permute(0, 3, 1, 2).contiguous()\n weights = F.interpolate(weights,\n size=image.shape[-2:],\n mode='bilinear',\n align_corners=False)\n # weights = weights / (weights.max(-1, keepdim=True)[0].max(-2, keepdim=True)[0])\n weights = unpad(weights, pads)\n weights = (weights * 255).cpu().numpy()\n return weights" }, { "identifier": "ResourceManager", "path": "gui/resource_manager.py", "snippet": "class ResourceManager:\n def __init__(self, cfg: DictConfig):\n # determine inputs\n images = cfg['images']\n video = cfg['video']\n self.workspace = cfg['workspace']\n self.max_size = cfg['max_overall_size']\n self.palette = davis_palette\n\n # create temporary workspace if not specified\n if self.workspace is None:\n if images is not None:\n basename = path.basename(images)\n elif video is not None:\n basename = path.basename(video)[:-4]\n else:\n raise NotImplementedError('Either images, video, or workspace has to be specified')\n\n self.workspace = path.join('./workspace', basename)\n\n print(f'Workspace is in: {self.workspace}')\n with open_dict(cfg):\n cfg['workspace'] = self.workspace\n\n # determine the location of input images\n need_decoding = False\n need_resizing = False\n if path.exists(path.join(self.workspace, 'images')):\n pass\n elif images is not None:\n need_resizing = True\n elif video is not None:\n # will decode video into frames later\n need_decoding = True\n\n # create workspace subdirectories\n self.image_dir = path.join(self.workspace, 'images')\n self.mask_dir = path.join(self.workspace, 'masks')\n self.visualization_dir = path.join(self.workspace, 'visualization')\n self.soft_mask_dir = path.join(self.workspace, 'soft_masks')\n os.makedirs(self.image_dir, exist_ok=True)\n os.makedirs(self.mask_dir, exist_ok=True)\n os.makedirs(self.visualization_dir, exist_ok=True)\n os.makedirs(self.soft_mask_dir, exist_ok=True)\n\n # create all soft mask sub-directories\n for i in range(1, cfg['num_objects'] + 1):\n os.makedirs(path.join(self.soft_mask_dir, f'{i}'), exist_ok=True)\n\n # convert read functions to be buffered\n self.get_image = LRU(self._get_image_unbuffered, maxsize=cfg['buffer_size'])\n self.get_mask = LRU(self._get_mask_unbuffered, maxsize=cfg['buffer_size'])\n\n # extract frames from video\n if need_decoding:\n self._extract_frames(video)\n\n # copy/resize existing images to the workspace\n if need_resizing:\n self._copy_resize_frames(images)\n\n # read all frame names\n self.names = sorted(os.listdir(self.image_dir))\n self.names = [f[:-4] for f in self.names] # remove extensions\n self.length = len(self.names)\n\n assert self.length > 0, f'No images found! Check {self.workspace}/images. Remove folder if necessary.'\n\n print(f'{self.length} images found.')\n\n self.height, self.width = self.get_image(0).shape[:2]\n\n # create the saver threads for saving the masks/visualizations\n self.save_queue = Queue(maxsize=cfg['save_queue_size'])\n self.num_save_threads = cfg['num_save_threads']\n self.save_threads = [\n Thread(target=self.save_thread, args=(self.save_queue, ))\n for _ in range(self.num_save_threads)\n ]\n for t in self.save_threads:\n t.daemon = True\n t.start()\n\n def __del__(self):\n for _ in range(self.num_save_threads):\n self.save_queue.put(None)\n self.save_queue.join()\n for t in self.save_threads:\n t.join()\n\n def save_thread(self, queue: Queue):\n while True:\n args: SaveItem = queue.get()\n if args is None:\n queue.task_done()\n break\n if args.type == 'mask':\n # PIL image\n args.data.save(path.join(self.mask_dir, args.name + '.png'))\n elif args.type.startswith('visualization'):\n # numpy array, save with cv2\n vis_mode = args.type.split('_')[-1]\n data = cv2.cvtColor(args.data, cv2.COLOR_RGB2BGR)\n os.makedirs(path.join(self.visualization_dir, vis_mode), exist_ok=True)\n cv2.imwrite(path.join(self.visualization_dir, vis_mode, args.name + '.jpg'), data)\n elif args.type == 'soft_mask':\n # numpy array, save each channel with cv2\n num_channels = args.data.shape[0]\n # first channel is background -- ignore\n for i in range(1, num_channels):\n data = args.data[i]\n data = (data * 255).astype(np.uint8)\n cv2.imwrite(path.join(self.soft_mask_dir, f'{i}', args.name + '.png'), data)\n else:\n raise NotImplementedError\n queue.task_done()\n\n def _extract_frames(self, video: str):\n cap = cv2.VideoCapture(video)\n frame_index = 0\n print(f'Extracting frames from {video} into {self.image_dir}...')\n with tqdm() as bar:\n while (cap.isOpened()):\n _, frame = cap.read()\n if frame is None:\n break\n h, w = frame.shape[:2]\n if self.max_size > 0 and min(h, w) > self.max_size:\n new_w = (w * self.max_size // min(w, h))\n new_h = (h * self.max_size // min(w, h))\n frame = cv2.resize(frame, dsize=(new_w, new_h), interpolation=cv2.INTER_AREA)\n cv2.imwrite(path.join(self.image_dir, f'{frame_index:07d}.jpg'), frame)\n frame_index += 1\n bar.update()\n print('Done!')\n\n def _copy_resize_frames(self, images: str):\n image_list = os.listdir(images)\n print(f'Copying/resizing frames into {self.image_dir}...')\n for image_name in tqdm(image_list):\n if self.max_size < 0:\n # just copy\n shutil.copy2(path.join(images, image_name), self.image_dir)\n else:\n frame = cv2.imread(path.join(images, image_name))\n h, w = frame.shape[:2]\n if self.max_size > 0 and min(h, w) > self.max_size:\n new_w = (w * self.max_size // min(w, h))\n new_h = (h * self.max_size // min(w, h))\n frame = cv2.resize(frame, dsize=(new_w, new_h), interpolation=cv2.INTER_AREA)\n cv2.imwrite(path.join(self.image_dir, image_name), frame)\n print('Done!')\n\n def add_to_queue_with_warning(self, item: SaveItem):\n if self.save_queue.full():\n print(\n 'The save queue is full! You need more threads or faster IO. Program might pause.')\n self.save_queue.put(item)\n\n def save_mask(self, ti: int, mask: np.ndarray):\n # mask should be uint8 H*W without channels\n assert 0 <= ti < self.length\n assert isinstance(mask, np.ndarray)\n\n mask = Image.fromarray(mask)\n mask.putpalette(self.palette)\n self.invalidate(ti)\n self.add_to_queue_with_warning(SaveItem('mask', mask, self.names[ti]))\n\n def save_visualization(self, ti: int, vis_mode: str, image: np.ndarray):\n # image should be uint8 3*H*W\n assert 0 <= ti < self.length\n assert isinstance(image, np.ndarray)\n\n self.add_to_queue_with_warning(SaveItem(f'visualization_{vis_mode}', image, self.names[ti]))\n\n def save_soft_mask(self, ti: int, prob: np.ndarray):\n # mask should be float (num_objects+1)*H*W np array\n assert 0 <= ti < self.length\n assert isinstance(prob, np.ndarray)\n\n self.add_to_queue_with_warning(SaveItem('soft_mask', prob, self.names[ti]))\n\n def _get_image_unbuffered(self, ti: int):\n # returns H*W*3 uint8 array\n assert 0 <= ti < self.length\n\n image = Image.open(path.join(self.image_dir, self.names[ti] + '.jpg')).convert('RGB')\n image = np.array(image)\n return image\n\n def _get_mask_unbuffered(self, ti: int):\n # returns H*W uint8 array\n assert 0 <= ti < self.length\n\n mask_path = path.join(self.mask_dir, self.names[ti] + '.png')\n if path.exists(mask_path):\n mask = Image.open(mask_path)\n mask = np.array(mask)\n return mask\n else:\n return None\n\n def import_mask(self, file_name: str, size: Optional[Tuple[int, int]] = None):\n # read an mask file and resize it to exactly match the canvas size\n image = Image.open(file_name)\n if size is not None:\n # PIL uses (width, height)\n image = image.resize((size[1], size[0]), resample=Image.Resampling.NEAREST)\n image = np.array(image)\n return image\n\n def import_layer(self, file_name: str, size: Tuple[int, int]):\n # read a RGBA/RGB file and resize it such that the entire layer is visible in the canvas\n # and then pad it to the canvas size (h, w)\n image = Image.open(file_name).convert('RGBA')\n im_w, im_h = image.size\n im_ratio = im_w / im_h\n canvas_ratio = size[1] / size[0]\n if im_ratio < canvas_ratio:\n # fit height\n new_h = size[0]\n new_w = int(new_h * im_ratio)\n else:\n # fit width\n new_w = size[1]\n new_h = int(new_w / im_ratio)\n image = image.resize((new_w, new_h), resample=Image.Resampling.BILINEAR)\n image = np.array(image)\n # padding\n pad_h = (size[0] - new_h) // 2\n pad_w = (size[1] - new_w) // 2\n image = np.pad(image,\n ((pad_h, size[0] - new_h - pad_h), (pad_w, size[1] - new_w - pad_w), (0, 0)),\n mode='constant',\n constant_values=0)\n\n return image\n\n def invalidate(self, ti: int):\n # the image buffer is never invalidated\n self.get_mask.invalidate((ti, ))\n\n def __len__(self):\n return self.length\n\n @property\n def T(self) -> int:\n return self.length\n\n @property\n def h(self) -> int:\n return self.height\n\n @property\n def w(self) -> int:\n return self.width" }, { "identifier": "GUI", "path": "gui/gui.py", "snippet": "class GUI(QWidget):\n def __init__(self, controller, cfg: DictConfig) -> None:\n super().__init__()\n\n # callbacks to be set by the controller\n self.on_mouse_motion_xy = None\n self.click_fn = None\n\n self.controller = controller\n self.cfg = cfg\n self.h = controller.h\n self.w = controller.w\n self.T = controller.T\n\n # set up the window\n self.setWindowTitle(f'Cutie demo: {cfg[\"workspace\"]}')\n self.setGeometry(100, 100, self.w + 200, self.h + 200)\n self.setWindowIcon(QIcon('docs/icon.png'))\n\n # set up some buttons\n self.play_button = QPushButton('Play video')\n self.play_button.clicked.connect(self.on_play_video)\n self.commit_button = QPushButton('Commit to permanent memory')\n self.commit_button.clicked.connect(controller.on_commit)\n self.export_video_button = QPushButton('Export as video')\n self.export_video_button.clicked.connect(controller.on_export_visualization)\n self.export_binary_button = QPushButton('Export binary masks')\n self.export_binary_button.clicked.connect(controller.on_export_binary)\n\n self.forward_run_button = QPushButton('Propagate forward')\n self.forward_run_button.clicked.connect(controller.on_forward_propagation)\n self.forward_run_button.setMinimumWidth(150)\n\n self.backward_run_button = QPushButton('Propagate backward')\n self.backward_run_button.clicked.connect(controller.on_backward_propagation)\n self.backward_run_button.setMinimumWidth(150)\n\n # universal progressbar\n self.progressbar = QProgressBar()\n self.progressbar.setMinimum(0)\n self.progressbar.setMaximum(100)\n self.progressbar.setValue(0)\n self.progressbar.setMinimumWidth(200)\n\n self.reset_frame_button = QPushButton('Reset frame')\n self.reset_frame_button.clicked.connect(controller.on_reset_mask)\n self.reset_object_button = QPushButton('Reset object')\n self.reset_object_button.clicked.connect(controller.on_reset_object)\n\n # set up the LCD\n self.lcd = QTextEdit()\n self.lcd.setReadOnly(True)\n self.lcd.setMaximumHeight(28)\n self.lcd.setMaximumWidth(150)\n self.lcd.setText('{: 5d} / {: 5d}'.format(0, controller.T - 1))\n\n # current object id\n self.object_dial = QSpinBox()\n self.object_dial.setReadOnly(False)\n self.object_dial.setMinimumSize(50, 30)\n self.object_dial.setMinimum(1)\n self.object_dial.setMaximum(controller.num_objects)\n self.object_dial.editingFinished.connect(controller.on_object_dial_change)\n\n self.object_color = QLabel()\n self.object_color.setMinimumSize(100, 30)\n self.object_color.setAlignment(Qt.AlignmentFlag.AlignCenter)\n\n self.frame_name = QLabel()\n self.frame_name.setMinimumSize(100, 30)\n self.frame_name.setAlignment(Qt.AlignmentFlag.AlignLeft)\n\n # timeline slider\n self.tl_slider = QSlider(Qt.Orientation.Horizontal)\n self.tl_slider.valueChanged.connect(controller.on_slider_update)\n self.tl_slider.setMinimum(0)\n self.tl_slider.setMaximum(controller.T - 1)\n self.tl_slider.setValue(0)\n self.tl_slider.setTickPosition(QSlider.TickPosition.TicksBelow)\n self.tl_slider.setTickInterval(1)\n\n # combobox\n self.combo = QComboBox(self)\n self.combo.addItem(\"mask\")\n self.combo.addItem(\"davis\")\n self.combo.addItem(\"fade\")\n self.combo.addItem(\"light\")\n self.combo.addItem(\"popup\")\n self.combo.addItem(\"layer\")\n self.combo.setCurrentText('davis')\n self.combo.currentTextChanged.connect(controller.set_vis_mode)\n\n self.save_visualization_checkbox = QCheckBox(self)\n self.save_visualization_checkbox.toggled.connect(controller.on_save_visualization_toggle)\n self.save_visualization_checkbox.setChecked(False)\n\n self.save_soft_mask_checkbox = QCheckBox(self)\n self.save_soft_mask_checkbox.toggled.connect(controller.on_save_soft_mask_toggle)\n self.save_soft_mask_checkbox.setChecked(False)\n\n # controls for output FPS and bitrate\n self.fps_dial = QSpinBox()\n self.fps_dial.setReadOnly(False)\n self.fps_dial.setMinimumSize(40, 30)\n self.fps_dial.setMinimum(1)\n self.fps_dial.setMaximum(60)\n self.fps_dial.setValue(cfg['output_fps'])\n self.fps_dial.editingFinished.connect(controller.on_fps_dial_change)\n\n self.bitrate_dial = QSpinBox()\n self.bitrate_dial.setReadOnly(False)\n self.bitrate_dial.setMinimumSize(40, 30)\n self.bitrate_dial.setMinimum(1)\n self.bitrate_dial.setMaximum(100)\n self.bitrate_dial.setValue(cfg['output_bitrate'])\n self.bitrate_dial.editingFinished.connect(controller.on_bitrate_dial_change)\n\n # Main canvas -> QLabel\n self.main_canvas = QLabel()\n self.main_canvas.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)\n self.main_canvas.setAlignment(Qt.AlignmentFlag.AlignCenter)\n self.main_canvas.setMinimumSize(100, 100)\n\n self.main_canvas.mousePressEvent = self.on_mouse_press\n self.main_canvas.mouseMoveEvent = self.on_mouse_motion\n self.main_canvas.setMouseTracking(True) # Required for all-time tracking\n self.main_canvas.mouseReleaseEvent = self.on_mouse_release\n\n # clearing memory\n self.clear_all_mem_button = QPushButton('Reset all memory')\n self.clear_all_mem_button.clicked.connect(controller.on_clear_memory)\n self.clear_non_perm_mem_button = QPushButton('Reset non-permanent memory')\n self.clear_non_perm_mem_button.clicked.connect(controller.on_clear_non_permanent_memory)\n\n # displaying memory usage\n self.perm_mem_gauge, self.perm_mem_gauge_layout = create_gauge('Permanent memory size')\n self.work_mem_gauge, self.work_mem_gauge_layout = create_gauge('Working memory size')\n self.long_mem_gauge, self.long_mem_gauge_layout = create_gauge('Long-term memory size')\n self.gpu_mem_gauge, self.gpu_mem_gauge_layout = create_gauge(\n 'GPU mem. (all proc, w/ caching)')\n self.torch_mem_gauge, self.torch_mem_gauge_layout = create_gauge(\n 'GPU mem. (torch, w/o caching)')\n\n # Parameters setting\n self.work_mem_min, self.work_mem_min_layout = create_parameter_box(\n 1, 100, 'Min. working memory frames', callback=controller.on_work_min_change)\n self.work_mem_max, self.work_mem_max_layout = create_parameter_box(\n 2, 100, 'Max. working memory frames', callback=controller.on_work_max_change)\n self.long_mem_max, self.long_mem_max_layout = create_parameter_box(\n 1000,\n 100000,\n 'Max. long-term memory size',\n step=1000,\n callback=controller.update_config)\n self.mem_every_box, self.mem_every_box_layout = create_parameter_box(\n 1, 100, 'Memory frame every (r)', callback=controller.update_config)\n\n # import mask/layer\n self.import_mask_button = QPushButton('Import mask')\n self.import_mask_button.clicked.connect(controller.on_import_mask)\n self.import_layer_button = QPushButton('Import layer')\n self.import_layer_button.clicked.connect(controller.on_import_layer)\n\n # Console on the GUI\n self.console = QPlainTextEdit()\n self.console.setReadOnly(True)\n self.console.setMinimumHeight(100)\n self.console.setMaximumHeight(100)\n\n # Tips for the users\n self.tips = QTextEdit()\n self.tips.setReadOnly(True)\n self.tips.setTextInteractionFlags(Qt.NoTextInteraction)\n self.tips.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)\n with open('./gui/TIPS.md') as f:\n self.tips.setMarkdown(f.read())\n\n # navigator\n navi = QHBoxLayout()\n\n interact_subbox = QVBoxLayout()\n interact_topbox = QHBoxLayout()\n interact_botbox = QHBoxLayout()\n interact_topbox.setAlignment(Qt.AlignmentFlag.AlignCenter)\n interact_topbox.addWidget(self.lcd)\n interact_topbox.addWidget(self.play_button)\n interact_topbox.addWidget(self.reset_frame_button)\n interact_topbox.addWidget(self.reset_object_button)\n interact_botbox.addWidget(QLabel('Current object ID:'))\n interact_botbox.addWidget(self.object_dial)\n interact_botbox.addWidget(self.object_color)\n interact_botbox.addWidget(self.frame_name)\n interact_subbox.addLayout(interact_topbox)\n interact_subbox.addLayout(interact_botbox)\n interact_botbox.setAlignment(Qt.AlignmentFlag.AlignLeft)\n navi.addLayout(interact_subbox)\n\n apply_fixed_size_policy = lambda x: x.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.\n Policy.Fixed)\n apply_to_all_children_widget(interact_topbox, apply_fixed_size_policy)\n apply_to_all_children_widget(interact_botbox, apply_fixed_size_policy)\n\n navi.addStretch(1)\n navi.addStretch(1)\n overlay_subbox = QVBoxLayout()\n overlay_topbox = QHBoxLayout()\n overlay_botbox = QHBoxLayout()\n overlay_topbox.setAlignment(Qt.AlignmentFlag.AlignLeft)\n overlay_botbox.setAlignment(Qt.AlignmentFlag.AlignLeft)\n overlay_topbox.addWidget(QLabel('Overlay mode'))\n overlay_topbox.addWidget(self.combo)\n overlay_topbox.addWidget(QLabel('Save soft mask during propagation'))\n overlay_topbox.addWidget(self.save_soft_mask_checkbox)\n overlay_topbox.addWidget(self.export_binary_button)\n overlay_botbox.addWidget(QLabel('Save overlay'))\n overlay_botbox.addWidget(self.save_visualization_checkbox)\n overlay_botbox.addWidget(self.export_video_button)\n overlay_botbox.addWidget(QLabel('Output FPS: '))\n overlay_botbox.addWidget(self.fps_dial)\n overlay_botbox.addWidget(QLabel('Output bitrate (Mbps): '))\n overlay_botbox.addWidget(self.bitrate_dial)\n overlay_subbox.addLayout(overlay_topbox)\n overlay_subbox.addLayout(overlay_botbox)\n navi.addLayout(overlay_subbox)\n apply_to_all_children_widget(overlay_topbox, apply_fixed_size_policy)\n apply_to_all_children_widget(overlay_botbox, apply_fixed_size_policy)\n\n navi.addStretch(1)\n control_subbox = QVBoxLayout()\n control_topbox = QHBoxLayout()\n control_botbox = QHBoxLayout()\n control_topbox.addWidget(self.commit_button)\n control_topbox.addWidget(self.forward_run_button)\n control_topbox.addWidget(self.backward_run_button)\n control_botbox.addWidget(self.progressbar)\n control_subbox.addLayout(control_topbox)\n control_subbox.addLayout(control_botbox)\n navi.addLayout(control_subbox)\n\n # Drawing area main canvas\n draw_area = QHBoxLayout()\n draw_area.addWidget(self.main_canvas, 4)\n\n # right area\n right_area = QVBoxLayout()\n right_area.setAlignment(Qt.AlignmentFlag.AlignBottom)\n right_area.addWidget(self.tips)\n # right_area.addStretch(1)\n\n # Parameters\n right_area.addLayout(self.perm_mem_gauge_layout)\n right_area.addLayout(self.work_mem_gauge_layout)\n right_area.addLayout(self.long_mem_gauge_layout)\n right_area.addLayout(self.gpu_mem_gauge_layout)\n right_area.addLayout(self.torch_mem_gauge_layout)\n right_area.addWidget(self.clear_all_mem_button)\n right_area.addWidget(self.clear_non_perm_mem_button)\n right_area.addLayout(self.work_mem_min_layout)\n right_area.addLayout(self.work_mem_max_layout)\n right_area.addLayout(self.long_mem_max_layout)\n right_area.addLayout(self.mem_every_box_layout)\n\n # import mask/layer\n import_area = QHBoxLayout()\n import_area.setAlignment(Qt.AlignmentFlag.AlignBottom)\n import_area.addWidget(self.import_mask_button)\n import_area.addWidget(self.import_layer_button)\n right_area.addLayout(import_area)\n\n # console\n right_area.addWidget(self.console)\n\n draw_area.addLayout(right_area, 1)\n\n layout = QVBoxLayout()\n layout.addLayout(draw_area)\n layout.addWidget(self.tl_slider)\n layout.addLayout(navi)\n self.setLayout(layout)\n\n # timer to play video\n self.timer = QTimer()\n self.timer.setSingleShot(False)\n self.timer.timeout.connect(controller.on_play_video_timer)\n\n # timer to update GPU usage\n self.gpu_timer = QTimer()\n self.gpu_timer.setSingleShot(False)\n self.gpu_timer.timeout.connect(controller.on_gpu_timer)\n self.gpu_timer.setInterval(2000)\n self.gpu_timer.start()\n\n # Objects shortcuts\n for i in range(1, controller.num_objects + 1):\n QShortcut(QKeySequence(str(i)),\n self).activated.connect(functools.partial(controller.hit_number_key, i))\n QShortcut(QKeySequence(f\"Ctrl+{i}\"),\n self).activated.connect(functools.partial(controller.hit_number_key, i))\n\n # <- and -> shortcuts\n QShortcut(QKeySequence(Qt.Key.Key_Left), self).activated.connect(controller.on_prev_frame)\n QShortcut(QKeySequence(Qt.Key.Key_Right), self).activated.connect(controller.on_next_frame)\n\n def resizeEvent(self, event):\n self.controller.show_current_frame()\n\n def text(self, text):\n self.console.moveCursor(QTextCursor.MoveOperation.End)\n self.console.insertPlainText(text + '\\n')\n\n def set_canvas(self, image):\n height, width, channel = image.shape\n bytesPerLine = 3 * width\n\n qImg = QImage(image.data, width, height, bytesPerLine, QImage.Format.Format_RGB888)\n self.main_canvas.setPixmap(\n QPixmap(\n qImg.scaled(self.main_canvas.size(), Qt.AspectRatioMode.KeepAspectRatio,\n Qt.TransformationMode.FastTransformation)))\n\n self.main_canvas_size = self.main_canvas.size()\n self.image_size = qImg.size()\n\n def update_slider(self, value):\n self.lcd.setText('{: 3d} / {: 3d}'.format(value, self.controller.T - 1))\n self.tl_slider.setValue(value)\n\n def pixel_pos_to_image_pos(self, x, y):\n # Un-scale and un-pad the label coordinates into image coordinates\n oh, ow = self.image_size.height(), self.image_size.width()\n nh, nw = self.main_canvas_size.height(), self.main_canvas_size.width()\n\n h_ratio = nh / oh\n w_ratio = nw / ow\n dominate_ratio = min(h_ratio, w_ratio)\n\n # Solve scale\n x /= dominate_ratio\n y /= dominate_ratio\n\n # Solve padding\n fh, fw = nh / dominate_ratio, nw / dominate_ratio\n x -= (fw - ow) / 2\n y -= (fh - oh) / 2\n\n return x, y\n\n def is_pos_out_of_bound(self, x, y):\n x, y = self.pixel_pos_to_image_pos(x, y)\n\n out_of_bound = ((x < 0) or (y < 0) or (x > self.w - 1) or (y > self.h - 1))\n\n return out_of_bound\n\n def get_scaled_pos(self, x, y):\n x, y = self.pixel_pos_to_image_pos(x, y)\n\n x = max(0, min(self.w - 1, x))\n y = max(0, min(self.h - 1, y))\n\n return x, y\n\n def forward_propagation_start(self):\n self.backward_run_button.setEnabled(False)\n self.forward_run_button.setText('Pause propagation')\n\n def backward_propagation_start(self):\n self.forward_run_button.setEnabled(False)\n self.backward_run_button.setText('Pause propagation')\n\n def pause_propagation(self):\n self.forward_run_button.setEnabled(True)\n self.backward_run_button.setEnabled(True)\n self.clear_all_mem_button.setEnabled(True)\n self.clear_non_perm_mem_button.setEnabled(True)\n self.forward_run_button.setText('Propagate forward')\n self.backward_run_button.setText('propagate backward')\n self.tl_slider.setEnabled(True)\n\n def process_events(self):\n QApplication.processEvents()\n\n def on_mouse_press(self, event):\n if self.is_pos_out_of_bound(event.position().x(), event.position().y()):\n return\n\n ex, ey = self.get_scaled_pos(event.position().x(), event.position().y())\n if event.button() == Qt.MouseButton.LeftButton:\n action = 'left'\n elif event.button() == Qt.MouseButton.RightButton:\n action = 'right'\n elif event.button() == Qt.MouseButton.MiddleButton:\n action = 'middle'\n\n self.click_fn(action, ex, ey)\n\n def on_mouse_motion(self, event):\n ex, ey = self.get_scaled_pos(event.position().x(), event.position().y())\n self.on_mouse_motion_xy(ex, ey)\n\n def on_mouse_release(self, event):\n pass\n\n def on_play_video(self):\n if self.timer.isActive():\n self.timer.stop()\n self.play_button.setText('Play video')\n else:\n self.timer.start(1000 // 30)\n self.play_button.setText('Stop video')\n\n def open_file(self, prompt):\n options = QFileDialog.Options()\n file_name, _ = QFileDialog.getOpenFileName(self,\n prompt,\n \"\",\n \"Image files (*)\",\n options=options)\n return file_name\n\n def set_object_color(self, object_id: int):\n r, g, b = davis_palette_np[object_id]\n rgb = f'rgb({r},{g},{b})'\n self.object_color.setStyleSheet('QLabel {background: ' + rgb + ';}')\n self.object_color.setText(f'{object_id}')\n\n def progressbar_update(self, progress: float):\n self.progressbar.setValue(int(progress * 100))\n self.process_events()" }, { "identifier": "ClickController", "path": "gui/click_controller.py", "snippet": "class ClickController:\n def __init__(self, checkpoint_path: str, device: str = 'cuda', max_size: int = 800):\n model = utils.load_is_model(checkpoint_path, device, cpu_dist_maps=True)\n\n # Predictor params\n zoomin_params = {\n 'skip_clicks': 1,\n 'target_size': 480,\n 'expansion_ratio': 1.4,\n }\n\n predictor_params = {\n 'brs_mode': 'f-BRS-B',\n # 'brs_mode': 'NoBRS',\n 'prob_thresh': 0.5,\n 'zoom_in_params': zoomin_params,\n 'predictor_params': {\n 'net_clicks_limit': 8,\n 'max_size': max_size,\n },\n 'brs_opt_func_params': {\n 'min_iou_diff': 1e-3\n },\n 'lbfgs_params': {\n 'maxfun': 20\n },\n 'with_flip': True,\n }\n\n self.controller = InteractiveController(model, device, predictor_params)\n self.anchored = False\n self.device = device\n\n def unanchor(self):\n self.anchored = False\n\n def interact(self, image: torch.Tensor, x: int, y: int, is_positive: bool,\n prev_mask: torch.Tensor):\n if not self.anchored:\n image = image.to(self.device, non_blocking=True)\n self.controller.set_image(image)\n self.controller.reset_predictor()\n self.anchored = True\n\n self.controller.add_click(x, y, is_positive, prev_mask=prev_mask)\n # return self.controller.result_mask\n return self.controller.probs_history[-1][1]\n # return (self.controller.probs_history[-1][1] > 0.5).float()\n\n def undo(self):\n self.controller.undo_click()\n if len(self.controller.probs_history) == 0:\n return None\n else:\n return (self.controller.probs_history[-1][1] > 0.5).float()" }, { "identifier": "PropagationReader", "path": "gui/reader.py", "snippet": "class PropagationReader(Dataset):\n def __init__(self, res_man: ResourceManager, start_ti: int, direction: Literal['forward',\n 'backward']):\n self.res_man = res_man\n self.start_ti = start_ti\n self.direction = direction\n\n # skip the first frame\n if self.direction == 'forward':\n self.start_ti += 1\n self.length = self.res_man.T - self.start_ti\n elif self.direction == 'backward':\n self.start_ti -= 1\n self.length = self.start_ti + 1\n else:\n raise NotImplementedError\n\n self.to_tensor = ToTensor()\n\n def __getitem__(self, index: int):\n if self.direction == 'forward':\n ti = self.start_ti + index\n elif self.direction == 'backward':\n ti = self.start_ti - index\n else:\n raise NotImplementedError\n\n assert 0 <= ti < self.res_man.T\n\n image = self.res_man.get_image(ti)\n image_torch = self.to_tensor(image)\n\n return image, image_torch\n\n def __len__(self):\n return self.length" }, { "identifier": "get_data_loader", "path": "gui/reader.py", "snippet": "def get_data_loader(dataset: Dataset, num_workers: int):\n if 'linux' in sys.platform:\n loader = DataLoader(dataset,\n batch_size=None,\n shuffle=False,\n num_workers=num_workers,\n collate_fn=lambda x: x)\n else:\n print(f'Non-linux platform {sys.platform} detected, using single-threaded dataloader')\n loader = DataLoader(dataset,\n batch_size=None,\n shuffle=False,\n num_workers=0,\n collate_fn=lambda x: x)\n return loader" }, { "identifier": "convert_frames_to_video", "path": "gui/exporter.py", "snippet": "def convert_frames_to_video(\n image_folder: str,\n output_path: str,\n fps: int = 24,\n bitrate: int = 1, # in Mbps\n progress_callback=None) -> None:\n images = [img for img in sorted(os.listdir(image_folder)) if img.endswith(\".jpg\")]\n frame = cv2.imread(os.path.join(image_folder, images[0]))\n height, width, layers = frame.shape\n\n output = av.open(output_path, mode=\"w\")\n\n stream = output.add_stream(\"h264\", rate=fps)\n stream.width = width\n stream.height = height\n stream.pix_fmt = \"yuv420p\"\n stream.bit_rate = bitrate * (10**7)\n\n for i, img_path in enumerate(images):\n img = cv2.imread(os.path.join(image_folder, img_path))\n frame = av.VideoFrame.from_ndarray(img, format='bgr24')\n packet = stream.encode(frame)\n output.mux(packet)\n\n if progress_callback is not None and i % 10 == 0:\n progress_callback(i / len(images))\n\n # flush\n packet = stream.encode(None)\n output.mux(packet)\n\n output.close()" }, { "identifier": "convert_mask_to_binary", "path": "gui/exporter.py", "snippet": "def convert_mask_to_binary(mask_folder: str,\n output_path: str,\n target_objects: List[int],\n progress_callback=None) -> None:\n masks = [img for img in sorted(os.listdir(mask_folder)) if img.endswith(\".png\")]\n\n for i, mask_path in enumerate(masks):\n mask = Image.open(os.path.join(mask_folder, mask_path))\n mask = np.array(mask)\n mask = np.where(np.isin(mask, target_objects), 255, 0)\n cv2.imwrite(os.path.join(output_path, mask_path), mask)\n\n if progress_callback is not None and i % 10 == 0:\n progress_callback(i / len(masks))" }, { "identifier": "download_models_if_needed", "path": "scripts/download_models.py", "snippet": "def download_models_if_needed():\n os.makedirs('weights', exist_ok=True)\n for link, md5 in _links:\n # download file if not exists with a progressbar\n filename = link.split('/')[-1]\n if not os.path.exists(os.path.join('weights', filename)) or hashlib.md5(open(os.path.join('weights', filename), 'rb').read()).hexdigest() != md5:\n print(f'Downloading {filename}...')\n r = requests.get(link, stream=True)\n total_size = int(r.headers.get('content-length', 0))\n block_size = 1024\n t = tqdm(total=total_size, unit='iB', unit_scale=True)\n with open(os.path.join('weights', filename), 'wb') as f:\n for data in r.iter_content(block_size):\n t.update(len(data))\n f.write(data)\n t.close()\n if total_size != 0 and t.n != total_size:\n raise RuntimeError('Error while downloading %s' % filename)" } ]
import os import logging import cv2 import torch import numpy as np from os import path from typing import Literal from torch import mps from torch import autocast from torchvision.transforms.functional import to_tensor from omegaconf import DictConfig, open_dict from cutie.model.cutie import CUTIE from cutie.inference.inference_core import InferenceCore from gui.interaction import * from gui.interactive_utils import * from gui.resource_manager import ResourceManager from gui.gui import GUI from gui.click_controller import ClickController from gui.reader import PropagationReader, get_data_loader from gui.exporter import convert_frames_to_video, convert_mask_to_binary from scripts.download_models import download_models_if_needed
17,461
if self.propagating: # acts as a pause button self.propagating = False self.propagate_direction = 'none' else: self.propagate_fn = self.on_prev_frame self.gui.backward_propagation_start() self.propagate_direction = 'backward' self.on_propagate() def on_pause(self): self.propagating = False self.gui.text(f'Propagation stopped at t={self.curr_ti}.') self.gui.pause_propagation() def on_propagate(self): # start to propagate with autocast(self.device, enabled=(self.amp and self.device == 'cuda')): self.convert_current_image_mask_torch() self.gui.text(f'Propagation started at t={self.curr_ti}.') self.processor.clear_sensory_memory() self.curr_prob = self.processor.step(self.curr_image_torch, self.curr_prob[1:], idx_mask=False) self.curr_mask = torch_prob_to_numpy_mask(self.curr_prob) # clear self.interacted_prob = None self.reset_this_interaction() self.show_current_frame(fast=True) self.propagating = True self.gui.clear_all_mem_button.setEnabled(False) self.gui.clear_non_perm_mem_button.setEnabled(False) self.gui.tl_slider.setEnabled(False) dataset = PropagationReader(self.res_man, self.curr_ti, self.propagate_direction) loader = get_data_loader(dataset, self.cfg.num_read_workers) # propagate till the end for data in loader: if not self.propagating: break self.curr_image_np, self.curr_image_torch = data self.curr_image_torch = self.curr_image_torch.to(self.device, non_blocking=True) self.propagate_fn() self.curr_prob = self.processor.step(self.curr_image_torch) self.curr_mask = torch_prob_to_numpy_mask(self.curr_prob) self.save_current_mask() self.show_current_frame(fast=True) self.update_memory_gauges() self.gui.process_events() if self.curr_ti == 0 or self.curr_ti == self.T - 1: break self.propagating = False self.curr_frame_dirty = False self.on_pause() self.on_slider_update() self.gui.process_events() def pause_propagation(self): self.propagating = False def on_commit(self): if self.interacted_prob is None: # get mask from disk self.load_current_image_mask() else: # get mask from interaction self.complete_interaction() self.update_interacted_mask() with autocast(self.device, enabled=(self.amp and self.device == 'cuda')): self.convert_current_image_mask_torch() self.gui.text(f'Permanent memory saved at {self.curr_ti}.') self.curr_prob = self.processor.step(self.curr_image_torch, self.curr_prob[1:], idx_mask=False, force_permanent=True) self.update_memory_gauges() self.update_gpu_gauges() def on_play_video_timer(self): self.curr_ti += 1 if self.curr_ti > self.T - 1: self.curr_ti = 0 self.gui.tl_slider.setValue(self.curr_ti) def on_export_visualization(self): # NOTE: Save visualization at the end of propagation image_folder = path.join(self.cfg['workspace'], 'visualization', self.vis_mode) save_folder = self.cfg['workspace'] if path.exists(image_folder): # Sorted so frames will be in order output_path = path.join(save_folder, f'visualization_{self.vis_mode}.mp4') self.gui.text(f'Exporting visualization -- please wait') self.gui.process_events() convert_frames_to_video(image_folder, output_path, fps=self.output_fps, bitrate=self.output_bitrate, progress_callback=self.gui.progressbar_update) self.gui.text(f'Visualization exported to {output_path}') self.gui.progressbar_update(0) else: self.gui.text(f'No visualization images found in {image_folder}') def on_export_binary(self): # export masks in binary format for other applications, e.g., ProPainter mask_folder = path.join(self.cfg['workspace'], 'masks') save_folder = path.join(self.cfg['workspace'], 'binary_masks') if path.exists(mask_folder): os.makedirs(save_folder, exist_ok=True) self.gui.text(f'Exporting binary masks -- please wait') self.gui.process_events()
# fix conflicts between qt5 and cv2 os.environ.pop("QT_QPA_PLATFORM_PLUGIN_PATH") try: except: print('torch.MPS not available.') log = logging.getLogger() class MainController(): def __init__(self, cfg: DictConfig) -> None: super().__init__() self.initialized = False # setting up the workspace if cfg["workspace"] is None: if cfg["images"] is not None: basename = path.basename(cfg["images"]) elif cfg["video"] is not None: basename = path.basename(cfg["video"])[:-4] else: raise NotImplementedError('Either images, video, or workspace has to be specified') cfg["workspace"] = path.join(cfg['workspace_root'], basename) # reading arguments self.cfg = cfg self.num_objects = cfg['num_objects'] self.device = cfg['device'] self.amp = cfg['amp'] # initializing the network(s) self.initialize_networks() # main components self.res_man = ResourceManager(cfg) self.processor = InferenceCore(self.cutie, self.cfg) self.gui = GUI(self, self.cfg) # initialize control info self.length: int = self.res_man.length self.interaction: Interaction = None self.interaction_type: str = 'Click' self.curr_ti: int = 0 self.curr_object: int = 1 self.propagating: bool = False self.propagate_direction: Literal['forward', 'backward', 'none'] = 'none' self.last_ex = self.last_ey = 0 # current frame info self.curr_frame_dirty: bool = False self.curr_image_np: np.ndarray = np.zeros((self.h, self.w, 3), dtype=np.uint8) self.curr_image_torch: torch.Tensor = None self.curr_mask: np.ndarray = np.zeros((self.h, self.w), dtype=np.uint8) self.curr_prob: torch.Tensor = torch.zeros((self.num_objects + 1, self.h, self.w), dtype=torch.float).to(self.device) self.curr_prob[0] = 1 # visualization info self.vis_mode: str = 'davis' self.vis_image: np.ndarray = None self.save_visualization: bool = False self.save_soft_mask: bool = False self.interacted_prob: torch.Tensor = None self.overlay_layer: np.ndarray = None self.overlay_layer_torch: torch.Tensor = None # the object id used for popup/layer overlay self.vis_target_objects = list(range(1, self.num_objects + 1)) self.load_current_image_mask() self.show_current_frame() # initialize stuff self.update_memory_gauges() self.update_gpu_gauges() self.gui.work_mem_min.setValue(self.processor.memory.min_mem_frames) self.gui.work_mem_max.setValue(self.processor.memory.max_mem_frames) self.gui.long_mem_max.setValue(self.processor.memory.max_long_tokens) self.gui.mem_every_box.setValue(self.processor.mem_every) # for exporting videos self.output_fps = cfg['output_fps'] self.output_bitrate = cfg['output_bitrate'] # set callbacks self.gui.on_mouse_motion_xy = self.on_mouse_motion_xy self.gui.click_fn = self.click_fn self.gui.show() self.gui.text('Initialized.') self.initialized = True # try to load the default overlay self._try_load_layer('./docs/uiuc.png') self.gui.set_object_color(self.curr_object) self.update_config() def initialize_networks(self) -> None: download_models_if_needed() self.cutie = CUTIE(self.cfg).eval().to(self.device) model_weights = torch.load(self.cfg.weights, map_location=self.device) self.cutie.load_weights(model_weights) self.click_ctrl = ClickController(self.cfg.ritm_weights, device=self.device) def hit_number_key(self, number: int): if number == self.curr_object: return self.curr_object = number self.gui.object_dial.setValue(number) if self.click_ctrl is not None: self.click_ctrl.unanchor() self.gui.text(f'Current object changed to {number}.') self.gui.set_object_color(number) self.show_current_frame() def click_fn(self, action: Literal['left', 'right', 'middle'], x: int, y: int): if self.propagating: return last_interaction = self.interaction new_interaction = None with autocast(self.device, enabled=(self.amp and self.device == 'cuda')): if action in ['left', 'right']: # left: positive click # right: negative click self.convert_current_image_mask_torch() image = self.curr_image_torch if (last_interaction is None or last_interaction.tar_obj != self.curr_object): # create new interaction is needed self.complete_interaction() self.click_ctrl.unanchor() new_interaction = ClickInteraction(image, self.curr_prob, (self.h, self.w), self.click_ctrl, self.curr_object) if new_interaction is not None: self.interaction = new_interaction self.interaction.push_point(x, y, is_neg=(action == 'right')) self.interacted_prob = self.interaction.predict().to(self.device, non_blocking=True) self.update_interacted_mask() self.update_gpu_gauges() elif action == 'middle': # middle: select a new visualization object target_object = self.curr_mask[int(y), int(x)] if target_object in self.vis_target_objects: self.vis_target_objects.remove(target_object) else: self.vis_target_objects.append(target_object) self.gui.text(f'Overlay target(s) changed to {self.vis_target_objects}') self.show_current_frame() return else: raise NotImplementedError def load_current_image_mask(self, no_mask: bool = False): self.curr_image_np = self.res_man.get_image(self.curr_ti) self.curr_image_torch = None if not no_mask: loaded_mask = self.res_man.get_mask(self.curr_ti) if loaded_mask is None: self.curr_mask.fill(0) else: self.curr_mask = loaded_mask.copy() self.curr_prob = None def convert_current_image_mask_torch(self, no_mask: bool = False): if self.curr_image_torch is None: self.curr_image_torch = to_tensor(self.curr_image_np).to(self.device, non_blocking=True) if self.curr_prob is None and not no_mask: self.curr_prob = index_numpy_to_one_hot_torch(self.curr_mask, self.num_objects + 1).to( self.device, non_blocking=True) def compose_current_im(self): self.vis_image = get_visualization(self.vis_mode, self.curr_image_np, self.curr_mask, self.overlay_layer, self.vis_target_objects) def update_canvas(self): self.gui.set_canvas(self.vis_image) def update_current_image_fast(self): # fast path, uses gpu. Changes the image in-place to avoid copying # thus current_image_torch must be voided afterwards self.vis_image = get_visualization_torch(self.vis_mode, self.curr_image_torch, self.curr_prob, self.overlay_layer_torch, self.vis_target_objects) self.curr_image_torch = None self.vis_image = np.ascontiguousarray(self.vis_image) if self.save_visualization: self.res_man.save_visualization(self.curr_ti, self.vis_mode, self.vis_image) if self.save_soft_mask: self.res_man.save_soft_mask(self.curr_ti, self.curr_prob.cpu().numpy()) self.gui.set_canvas(self.vis_image) def show_current_frame(self, fast: bool = False): # Re-compute overlay and show the image if fast: self.update_current_image_fast() else: self.compose_current_im() if self.save_visualization: self.res_man.save_visualization(self.curr_ti, self.vis_mode, self.vis_image) self.update_canvas() self.gui.update_slider(self.curr_ti) self.gui.frame_name.setText(self.res_man.names[self.curr_ti] + '.jpg') def set_vis_mode(self): self.vis_mode = self.gui.combo.currentText() self.show_current_frame() def save_current_mask(self): # save mask to hard disk self.res_man.save_mask(self.curr_ti, self.curr_mask) def on_slider_update(self): # if we are propagating, the on_run function will take care of everything # don't do duplicate work here self.curr_ti = self.gui.tl_slider.value() if not self.propagating: # with self.vis_cond: # self.vis_cond.notify() if self.curr_frame_dirty: self.save_current_mask() self.curr_frame_dirty = False self.reset_this_interaction() self.curr_ti = self.gui.tl_slider.value() self.load_current_image_mask() self.show_current_frame() def on_forward_propagation(self): if self.propagating: # acts as a pause button self.propagating = False self.propagate_direction = 'none' else: self.propagate_fn = self.on_next_frame self.gui.forward_propagation_start() self.propagate_direction = 'forward' self.on_propagate() def on_backward_propagation(self): if self.propagating: # acts as a pause button self.propagating = False self.propagate_direction = 'none' else: self.propagate_fn = self.on_prev_frame self.gui.backward_propagation_start() self.propagate_direction = 'backward' self.on_propagate() def on_pause(self): self.propagating = False self.gui.text(f'Propagation stopped at t={self.curr_ti}.') self.gui.pause_propagation() def on_propagate(self): # start to propagate with autocast(self.device, enabled=(self.amp and self.device == 'cuda')): self.convert_current_image_mask_torch() self.gui.text(f'Propagation started at t={self.curr_ti}.') self.processor.clear_sensory_memory() self.curr_prob = self.processor.step(self.curr_image_torch, self.curr_prob[1:], idx_mask=False) self.curr_mask = torch_prob_to_numpy_mask(self.curr_prob) # clear self.interacted_prob = None self.reset_this_interaction() self.show_current_frame(fast=True) self.propagating = True self.gui.clear_all_mem_button.setEnabled(False) self.gui.clear_non_perm_mem_button.setEnabled(False) self.gui.tl_slider.setEnabled(False) dataset = PropagationReader(self.res_man, self.curr_ti, self.propagate_direction) loader = get_data_loader(dataset, self.cfg.num_read_workers) # propagate till the end for data in loader: if not self.propagating: break self.curr_image_np, self.curr_image_torch = data self.curr_image_torch = self.curr_image_torch.to(self.device, non_blocking=True) self.propagate_fn() self.curr_prob = self.processor.step(self.curr_image_torch) self.curr_mask = torch_prob_to_numpy_mask(self.curr_prob) self.save_current_mask() self.show_current_frame(fast=True) self.update_memory_gauges() self.gui.process_events() if self.curr_ti == 0 or self.curr_ti == self.T - 1: break self.propagating = False self.curr_frame_dirty = False self.on_pause() self.on_slider_update() self.gui.process_events() def pause_propagation(self): self.propagating = False def on_commit(self): if self.interacted_prob is None: # get mask from disk self.load_current_image_mask() else: # get mask from interaction self.complete_interaction() self.update_interacted_mask() with autocast(self.device, enabled=(self.amp and self.device == 'cuda')): self.convert_current_image_mask_torch() self.gui.text(f'Permanent memory saved at {self.curr_ti}.') self.curr_prob = self.processor.step(self.curr_image_torch, self.curr_prob[1:], idx_mask=False, force_permanent=True) self.update_memory_gauges() self.update_gpu_gauges() def on_play_video_timer(self): self.curr_ti += 1 if self.curr_ti > self.T - 1: self.curr_ti = 0 self.gui.tl_slider.setValue(self.curr_ti) def on_export_visualization(self): # NOTE: Save visualization at the end of propagation image_folder = path.join(self.cfg['workspace'], 'visualization', self.vis_mode) save_folder = self.cfg['workspace'] if path.exists(image_folder): # Sorted so frames will be in order output_path = path.join(save_folder, f'visualization_{self.vis_mode}.mp4') self.gui.text(f'Exporting visualization -- please wait') self.gui.process_events() convert_frames_to_video(image_folder, output_path, fps=self.output_fps, bitrate=self.output_bitrate, progress_callback=self.gui.progressbar_update) self.gui.text(f'Visualization exported to {output_path}') self.gui.progressbar_update(0) else: self.gui.text(f'No visualization images found in {image_folder}') def on_export_binary(self): # export masks in binary format for other applications, e.g., ProPainter mask_folder = path.join(self.cfg['workspace'], 'masks') save_folder = path.join(self.cfg['workspace'], 'binary_masks') if path.exists(mask_folder): os.makedirs(save_folder, exist_ok=True) self.gui.text(f'Exporting binary masks -- please wait') self.gui.process_events()
convert_mask_to_binary(mask_folder,
8
2023-10-19 17:49:24+00:00
24k
ZhengyiLuo/PerpetualHumanoidControl
scripts/vis/vis_motion.py
[ { "identifier": "MotionLibSMPL", "path": "phc/utils/motion_lib_smpl.py", "snippet": "class MotionLibSMPL(MotionLibBase):\n\n def __init__(self, motion_file, device, fix_height=FixHeightMode.full_fix, masterfoot_conifg=None, min_length=-1, im_eval=False, multi_thread=True):\n super().__init__(motion_file=motion_file, device=device, fix_height=fix_height, masterfoot_conifg=masterfoot_conifg, min_length=min_length, im_eval=im_eval, multi_thread=multi_thread)\n \n data_dir = \"data/smpl\"\n if osp.exists(data_dir):\n smpl_parser_n = SMPL_Parser(model_path=data_dir, gender=\"neutral\")\n smpl_parser_m = SMPL_Parser(model_path=data_dir, gender=\"male\")\n smpl_parser_f = SMPL_Parser(model_path=data_dir, gender=\"female\")\n self.mesh_parsers = {0: smpl_parser_n, 1: smpl_parser_m, 2: smpl_parser_f}\n else:\n self.mesh_parsers = None\n \n return\n \n @staticmethod\n def fix_trans_height(pose_aa, trans, curr_gender_betas, mesh_parsers, fix_height_mode):\n if fix_height_mode == FixHeightMode.no_fix:\n return trans, 0\n \n with torch.no_grad():\n frame_check = 30\n gender = curr_gender_betas[0]\n betas = curr_gender_betas[1:]\n mesh_parser = mesh_parsers[gender.item()]\n height_tolorance = 0.0\n vertices_curr, joints_curr = mesh_parser.get_joints_verts(pose_aa[:frame_check], betas[None,], trans[:frame_check])\n offset = joints_curr[:, 0] - trans[:frame_check] # account for SMPL root offset. since the root trans we pass in has been processed, we have to \"add it back\".\n \n if fix_height_mode == FixHeightMode.ankle_fix:\n assignment_indexes = mesh_parser.lbs_weights.argmax(axis=1)\n pick = (((assignment_indexes != mesh_parser.joint_names.index(\"L_Toe\")).int() + (assignment_indexes != mesh_parser.joint_names.index(\"R_Toe\")).int() \n + (assignment_indexes != mesh_parser.joint_names.index(\"R_Hand\")).int() + + (assignment_indexes != mesh_parser.joint_names.index(\"L_Hand\")).int()) == 4).nonzero().squeeze()\n diff_fix = ((vertices_curr[:, pick] - offset[:, None])[:frame_check, ..., -1].min(dim=-1).values - height_tolorance).min() # Only acount the first 30 frames, which usually is a calibration phase.\n elif fix_height_mode == FixHeightMode.full_fix:\n \n diff_fix = ((vertices_curr - offset[:, None])[:frame_check, ..., -1].min(dim=-1).values - height_tolorance).min() # Only acount the first 30 frames, which usually is a calibration phase.\n \n \n \n trans[..., -1] -= diff_fix\n return trans, diff_fix\n\n @staticmethod\n def load_motion_with_skeleton(ids, motion_data_list, skeleton_trees, gender_betas, fix_height, mesh_parsers, masterfoot_config, max_len, queue, pid):\n # ZL: loading motion with the specified skeleton. Perfoming forward kinematics to get the joint positions\n np.random.seed(np.random.randint(5000)* pid)\n res = {}\n assert (len(ids) == len(motion_data_list))\n for f in range(len(motion_data_list)):\n curr_id = ids[f] # id for this datasample\n curr_file = motion_data_list[f]\n if not isinstance(curr_file, dict) and osp.isfile(curr_file):\n key = motion_data_list[f].split(\"/\")[-1].split(\".\")[0]\n curr_file = joblib.load(curr_file)[key]\n curr_gender_beta = gender_betas[f]\n\n seq_len = curr_file['root_trans_offset'].shape[0]\n if max_len == -1 or seq_len < max_len:\n start, end = 0, seq_len\n else:\n start = random.randint(0, seq_len - max_len)\n end = start + max_len\n\n trans = curr_file['root_trans_offset'].clone()[start:end]\n pose_aa = to_torch(curr_file['pose_aa'][start:end])\n pose_quat_global = curr_file['pose_quat_global'][start:end]\n\n B, J, N = pose_quat_global.shape\n\n ##### ZL: randomize the heading ######\n if (not flags.im_eval) and (not flags.test):\n # if True:\n random_rot = np.zeros(3)\n random_rot[2] = np.pi * (2 * np.random.random() - 1.0)\n random_heading_rot = sRot.from_euler(\"xyz\", random_rot)\n pose_aa[:, :3] = torch.tensor((random_heading_rot * sRot.from_rotvec(pose_aa[:, :3])).as_rotvec())\n pose_quat_global = (random_heading_rot * sRot.from_quat(pose_quat_global.reshape(-1, 4))).as_quat().reshape(B, J, N)\n trans = torch.matmul(trans, torch.from_numpy(random_heading_rot.as_matrix().T))\n ##### ZL: randomize the heading ######\n\n if not mesh_parsers is None:\n trans, trans_fix = MotionLibSMPL.fix_trans_height(pose_aa, trans, curr_gender_beta, mesh_parsers, fix_height_mode = fix_height)\n else:\n trans_fix = 0\n \n\n if not masterfoot_config is None:\n num_bodies = len(masterfoot_config['body_names'])\n pose_quat_holder = np.zeros([B, num_bodies, N])\n pose_quat_holder[..., -1] = 1\n pose_quat_holder[...,masterfoot_config['body_to_orig_without_toe'], :] \\\n = pose_quat_global[..., masterfoot_config['orig_to_orig_without_toe'], :]\n\n pose_quat_holder[..., [masterfoot_config['body_names'].index(name) for name in [\"L_Toe\", \"L_Toe_1\", \"L_Toe_1_1\", \"L_Toe_2\"]], :] = pose_quat_holder[..., [masterfoot_config['body_names'].index(name) for name in [\"L_Ankle\"]], :]\n pose_quat_holder[..., [masterfoot_config['body_names'].index(name) for name in [\"R_Toe\", \"R_Toe_1\", \"R_Toe_1_1\", \"R_Toe_2\"]], :] = pose_quat_holder[..., [masterfoot_config['body_names'].index(name) for name in [\"R_Ankle\"]], :]\n\n pose_quat_global = pose_quat_holder\n\n pose_quat_global = to_torch(pose_quat_global)\n sk_state = SkeletonState.from_rotation_and_root_translation(skeleton_trees[f], pose_quat_global, trans, is_local=False)\n\n curr_motion = SkeletonMotion.from_skeleton_state(sk_state, curr_file.get(\"fps\", 30))\n curr_dof_vels = compute_motion_dof_vels(curr_motion)\n \n if flags.real_traj:\n quest_sensor_data = to_torch(curr_file['quest_sensor_data'])\n quest_trans = quest_sensor_data[..., :3]\n quest_rot = quest_sensor_data[..., 3:]\n \n quest_trans[..., -1] -= trans_fix # Fix trans\n \n global_angular_vel = SkeletonMotion._compute_angular_velocity(quest_rot, time_delta=1 / curr_file['fps'])\n linear_vel = SkeletonMotion._compute_velocity(quest_trans, time_delta=1 / curr_file['fps'])\n quest_motion = {\"global_angular_vel\": global_angular_vel, \"linear_vel\": linear_vel, \"quest_trans\": quest_trans, \"quest_rot\": quest_rot}\n curr_motion.quest_motion = quest_motion\n\n curr_motion.dof_vels = curr_dof_vels\n curr_motion.gender_beta = curr_gender_beta\n res[curr_id] = (curr_file, curr_motion)\n \n \n\n if not queue is None:\n queue.put(res)\n else:\n return res" }, { "identifier": "SMPL_Robot", "path": "uhc/smpllib/smpl_local_robot.py", "snippet": "class SMPL_Robot:\n def __init__(self, cfg, data_dir=\"data/smpl\"):\n self.bodies = []\n self.weight = 0\n self.height = 0\n self.cfg = cfg\n self.model_dirs = []\n self.param_mapping = cfg.get(\"param_mapping\", \"clip\")\n self.smpl_model = cfg.get(\"model\", \"smpl\")\n self.mesh = cfg.get(\"mesh\", False)\n self.replace_feet = cfg.get(\"replace_feet\", True)\n self.gender = cfg.get(\"gender\", \"neutral\")\n self.flatfoot = cfg.get(\"flatfoot\", True)\n self.upright_start = cfg.get(\"upright_start\", True)\n if self.upright_start:\n print(\"!!!! Using modified SMPL starting pose !!!!\")\n self.remove_toe = cfg.get(\"remove_toe\", False)\n self.freeze_hand = cfg.get(\"freeze_hand\", True)\n self.big_ankle = cfg.get(\"big_ankle\", False)\n self.box_body = cfg.get(\"box_body\", False)\n self.real_weight = cfg.get(\"real_weight\", False)\n self.real_weight_porpotion_capsules = cfg.get(\"real_weight_porpotion_capsules\", False)\n self.real_weight_porpotion_boxes = cfg.get(\"real_weight_porpotion_boxes\", False)\n self.rel_joint_lm = cfg.get(\"rel_joint_lm\", True) # Rolling this out worldwide!!\n \n os.makedirs(\"/tmp/smpl/\", exist_ok=True)\n self.masterfoot = cfg.get(\"masterfoot\", False)\n self.param_specs = self.cfg.get(\"body_params\", {})\n self.hull_dict = {}\n self.beta = (torch.zeros(\n (1, 10)).float() if self.smpl_model == \"smpl\" else torch.zeros(\n (1, 16)).float())\n\n if self.smpl_model == \"smpl\":\n self.smpl_parser_n = SMPL_Parser(model_path=data_dir,\n gender=\"neutral\")\n self.smpl_parser_m = SMPL_Parser(model_path=data_dir,\n gender=\"male\")\n self.smpl_parser_f = SMPL_Parser(model_path=data_dir,\n gender=\"female\")\n elif self.smpl_model == \"smplh\":\n self.smpl_parser_n = SMPLH_Parser(\n model_path=data_dir,\n gender=\"neutral\",\n use_pca=False,\n create_transl=False,\n )\n self.smpl_parser_m = SMPLH_Parser(model_path=data_dir,\n gender=\"male\",\n use_pca=False,\n create_transl=False)\n self.smpl_parser_f = SMPLH_Parser(model_path=data_dir,\n gender=\"female\",\n use_pca=False,\n create_transl=False)\n elif self.smpl_model == \"smplx\":\n self.smpl_parser_n = SMPLX_Parser(\n model_path=data_dir,\n gender=\"neutral\",\n use_pca=False,\n create_transl=False,\n )\n self.smpl_parser_m = SMPLX_Parser(model_path=data_dir,\n gender=\"male\",\n use_pca=False,\n create_transl=False)\n self.smpl_parser_f = SMPLX_Parser(model_path=data_dir,\n gender=\"female\",\n use_pca=False,\n create_transl=False)\n\n self.load_from_skeleton()\n\n atexit.register(self.remove_geoms)\n\n def remove_geoms(self):\n while len(self.model_dirs) > 0:\n geom_dir = self.model_dirs.pop(0)\n if osp.isdir(geom_dir):\n shutil.rmtree(geom_dir, ignore_errors=True)\n\n def get_joint_vertices(self,\n pose_aa,\n th_betas=None,\n th_trans=None,\n gender=[0]):\n if gender[0] == 0:\n smpl_parser = self.smpl_parser_n\n elif gender[0] == 1:\n smpl_parser = self.smpl_parser_m\n elif gender[0] == 2:\n smpl_parser = self.smpl_parser_f\n else:\n print(gender)\n raise Exception(\"Gender Not Supported!!\")\n vertices, joints = smpl_parser.get_joints_verts(pose=pose_aa,\n th_betas=th_betas,\n th_trans=th_trans)\n return vertices, joints\n\n def load_from_skeleton(\n self,\n betas=None,\n v_template=None,\n gender=[0],\n objs_info=None,\n obj_pose=None,\n params=None,\n ):\n\n self.tree = None # xml tree\n\n if gender[0] == 0:\n self.smpl_parser = smpl_parser = self.smpl_parser_n\n elif gender[0] == 1:\n self.smpl_parser = smpl_parser = self.smpl_parser_m\n elif gender[0] == 2:\n self.smpl_parser = smpl_parser = self.smpl_parser_f\n else:\n print(gender)\n raise Exception(\"Gender Not Supported!!\")\n\n if betas is None and self.beta is None:\n betas = (torch.zeros(\n (1, 10)).float() if self.smpl_model == \"smpl\" else torch.zeros(\n (1, 16)).float())\n else:\n if params is None:\n self.beta = betas if not betas is None else self.beta\n else:\n # If params is not none, we need to set the beta first\n betas = self.map_params(betas)\n self.beta = torch.from_numpy(\n denormalize_range(\n betas.numpy().squeeze(),\n self.param_specs[\"beta\"][\"lb\"],\n self.param_specs[\"beta\"][\"ub\"],\n )[None, ])\n if flags.debug:\n print(self.beta)\n\n ## Clear up beta for smpl and smplh\n if self.smpl_model == \"smpl\" and self.beta.shape[1] == 16:\n self.beta = self.beta[:, :10]\n # print(f\"Incorrect shape size for {self.model}!!!\")\n elif self.smpl_model == \"smplh\" and self.beta.shape[1] == 10:\n self.beta = torch.hstack([self.beta, torch.zeros((1, 6)).float()])\n # print(f\"Incorrect shape size for {self.model}!!!\")\n\n # self.remove_geoms()\n size_dict = {}\n if self.mesh:\n self.model_dirs.append(f\"/tmp/smpl/{uuid.uuid4()}\")\n # self.model_dirs.append(f\"phc/data/assets/mesh/smpl/{uuid.uuid4()}\")\n\n self.skeleton = SkeletonMesh(self.model_dirs[-1])\n zero_pose = torch.zeros((1, 72))\n if self.upright_start:\n zero_pose[0, :3] = torch.tensor([1.2091996, 1.2091996, 1.2091996])\n (\n verts,\n joints,\n skin_weights,\n joint_names,\n joint_offsets,\n joint_parents,\n joint_axes,\n joint_dofs,\n joint_range,\n contype,\n conaffinity,\n ) = (smpl_parser.get_mesh_offsets(\n zero_pose=zero_pose, betas=self.beta, flatfoot=self.flatfoot)\n if self.smpl_model != \"smplx\" else\n smpl_parser.get_mesh_offsets(v_template=v_template))\n\n if self.rel_joint_lm:\n if self.upright_start:\n joint_range = update_joint_limits_upright(joint_range)\n else:\n joint_range = update_joint_limits(joint_range)\n\n self.height = np.max(verts[:, 1]) - np.min(verts[:, 1])\n\n if (len(self.get_params(get_name=True)) > 1\n and not params is None): # ZL: dank code, very dank code\n self.set_params(params)\n size_dict = self.get_size()\n size_dict = self.enforce_length_size(size_dict)\n\n # Gear based size\n # gear_dict = self.get_gear()\n # for k, v in size_dict.items():\n # for idx, suffix in enumerate([\"_x\", \"_y\", \"_z\"]):\n # if k + suffix in gear_dict:\n # size_dict[k][idx] *= gear_dict[k + suffix]\n self.hull_dict = get_joint_geometries(\n verts,\n joints,\n skin_weights,\n joint_names,\n scale_dict=size_dict,\n geom_dir=f\"{self.model_dirs[-1]}/geom\",\n )\n self.skeleton.load_from_offsets(\n joint_offsets,\n joint_parents,\n joint_axes,\n joint_dofs,\n joint_range,\n hull_dict = self.hull_dict,\n sites={},\n scale=1,\n equalities={},\n exclude_contacts=[[\"Chest\", \"L_Shoulder\"],\n [\"Chest\", \"R_Shoulder\"],\n [\"Chest\", \"R_Thorax\"], [\"Chest\", \"L_Thorax\"],\n ['L_Hip', 'Pelvis'], ['R_Hip', 'Pelvis'],\n ['Torso', 'Pelvis'], ['L_Knee', 'L_Hip'],\n ['R_Knee', 'R_Hip'], ['Spine', 'Torso'],\n ['L_Ankle', 'L_Knee'], ['R_Ankle', 'R_Knee'],\n ['Chest', 'Spine'], ['L_Toe', 'L_Ankle'],\n ['R_Toe', 'R_Ankle'], ['Neck', 'Chest'],\n ['L_Thorax', 'Chest'], ['R_Thorax', 'Chest'],\n ['Head', 'Neck'], ['L_Shoulder', 'L_Thorax'],\n ['R_Shoulder', 'R_Thorax'],\n ['L_Elbow', 'L_Shoulder'],\n ['R_Elbow', 'R_Shoulder'],\n ['L_Wrist',\n 'L_Elbow'], ['R_Wrist', 'R_Elbow'],\n ['L_Hand', 'L_Wrist'], ['R_Hand',\n 'R_Wrist']],\n collision_groups=contype,\n conaffinity=conaffinity,\n simple_geom=False,\n real_weight = self.real_weight,\n replace_feet=self.replace_feet,\n )\n else:\n self.skeleton = Skeleton()\n if self.smpl_model == \"smpl\":\n zero_pose = torch.zeros((1, 72))\n else:\n zero_pose = torch.zeros((1, 156))\n if self.upright_start:\n zero_pose[0, :3] = torch.tensor(\n [1.2091996, 1.2091996, 1.2091996])\n\n verts, joints, skin_weights, joint_names, joint_offsets, parents_dict, channels, joint_range = smpl_parser.get_offsets(\n betas=self.beta, zero_pose=zero_pose)\n\n self.height = torch.max(verts[:, 1]) - torch.min(verts[:, 1])\n self.hull_dict = get_geom_dict(verts,\n joints,\n skin_weights,\n joint_names,\n scale_dict=size_dict)\n channels = [\"x\", \"y\", \"z\"] # ZL: need to fix\n if self.rel_joint_lm:\n if self.upright_start:\n joint_range = update_joint_limits_upright(joint_range)\n else:\n joint_range = update_joint_limits(joint_range)\n\n # print(\"enforcing symmetry\")\n # for k, v in joint_offsets.items():\n # if k.startswith(\"L_\"):\n # right_val = joint_offsets[k.replace(\"L_\", \"R_\")].copy()\n # right_val[1] = -right_val[1]\n # v[:] = right_val\n # elif k in [\"Torso\", \"Spine\", \"Chest\", \"Neck\", \"Head\"]:\n # v[1] = 0\n\n self.skeleton.load_from_offsets(joint_offsets,\n parents_dict,\n 1,\n joint_range,\n self.hull_dict, {},\n channels, {},\n upright_start=self.upright_start,\n remove_toe=self.remove_toe,\n freeze_hand = self.freeze_hand, \n box_body = self.box_body, \n big_ankle=self.big_ankle,\n real_weight_porpotion_capsules=self.real_weight_porpotion_capsules,\n real_weight_porpotion_boxes = self.real_weight_porpotion_boxes,\n real_weight = self.real_weight)\n self.bodies = [] ### Cleaning bodies list\n self.bone_length = np.array([np.linalg.norm(i) for i in joint_offsets.values()])\n parser = XMLParser(remove_blank_text=True)\n\n self.tree = parse(\n BytesIO(\n # self.skeleton.write_str(\n # bump_buffer=self.smpl_model == \"smplh\" or self.smpl_model == \"smplx\"\n # )\n self.skeleton.write_str(bump_buffer=True)),\n parser=parser,\n )\n\n self.local_coord = (self.tree.getroot().find(\n \".//compiler\").attrib[\"coordinate\"] == \"local\")\n root = self.tree.getroot().find(\"worldbody\").find(\"body\")\n\n self.add_body(root, None)\n self.init_bodies()\n self.param_names = self.get_params(get_name=True)\n self.init_params = self.get_params()\n self.init_tree = deepcopy(self.tree)\n if self.masterfoot:\n # self.add_masterfoot_capsule()\n self.add_masterfoot_box()\n\n # all_root = self.tree.getroot()\n # contact_node = Element(\"contact\", {})\n # SubElement(contact_node,\"exclude\",{\"name\": \"add01\", \"body1\": \"L_Shoulr\", \"body2\": \"Chest\"},)\n # SubElement(contact_node,\"exclude\",{\"name\": \"add02\", \"body1\": \"R_Shoulder\", \"body2\": \"Chest\"},)\n # all_root.append(contact_node)\n\n def in_body(self, body, point):\n return in_hull(self.hull_dict[body][\"norm_hull\"], point)\n\n def project_to_body(self, body, point):\n in_body = self.in_body(body, point)\n norm_points = self.hull_dict[body][\"norm_verts\"]\n if not in_body[0]:\n return norm_points[np.argmin(\n np.linalg.norm(norm_points - point, axis=1))]\n else:\n return point.squeeze()\n\n def get_gear(self):\n actuator_dict = {}\n for body in self.bodies:\n for joint in body.joints:\n if not joint.actuator is None:\n actuator_dict[joint.actuator.name] = joint.actuator.gear\n return actuator_dict\n\n def get_size(self):\n size_dict = {}\n for body in self.bodies:\n for geom in body.geoms:\n size_dict[body.name] = geom.size\n return size_dict\n\n def enforce_length_size(self, size_dict):\n distal_dir = {\n \"Pelvis\": 1,\n \"L_Hip\": 1,\n \"L_Knee\": 1,\n \"L_Ankle\": [1, 2],\n \"L_Toe\": [1, 2],\n \"R_Hip\": 1,\n \"R_Knee\": 1,\n \"R_Ankle\": [1, 2],\n \"R_Toe\": [1, 2],\n \"Torso\": 1,\n \"Spine\": 1,\n \"Chest\": 1,\n \"Neck\": 1,\n \"Head\": 1,\n \"L_Thorax\": 0,\n \"L_Shoulder\": 0,\n \"L_Elbow\": 0,\n \"L_Wrist\": 0,\n \"L_Hand\": 0,\n \"R_Thorax\": 0,\n \"R_Shoulder\": 0,\n \"R_Elbow\": 0,\n \"R_Wrist\": 0,\n \"R_Hand\": 0,\n }\n for k, v in size_dict.items():\n subset = np.array(v[distal_dir[k]])\n subset[subset <= 1] = 1\n v[distal_dir[k]] = subset\n\n return size_dict\n\n def add_body(self, body_node, parent_body):\n body = Body(body_node, parent_body, self, self.cfg, new_body=False)\n self.bodies.append(body)\n\n for body_node_c in body_node.findall(\"body\"):\n self.add_body(body_node_c, body)\n\n def init_bodies(self):\n for body in self.bodies:\n body.init()\n self.sync_node()\n\n def sync_node(self):\n for body in self.bodies:\n # body.reindex()\n body.sync_node()\n\n def add_masterfoot_box(self):\n self.joint_range_master = {\n \"L_Toe_x\": f\"-0.1 0.1\",\n \"L_Toe_y\": f\"-45.0 45\",\n \"L_Toe_z\": f\"-10 10\",\n \"R_Toe_x\": f\"-0.1 0.1\",\n \"R_Toe_y\": f\"-45 45\",\n \"R_Toe_z\": f\"-10 10\",\n \"L_Toe_1_joint_0\": f\"-0.1 0.1\",\n \"L_Toe_1_joint_1\": f\"-45 45\",\n \"L_Toe_1_joint_2\": f\"-10 10\",\n \"R_Toe_1_joint_0\": f\"-0.1 0.1\",\n \"R_Toe_1_joint_1\": f\"-45 45\",\n \"R_Toe_1_joint_2\": f\"-10 10\",\n \"L_Toe_1_1_joint_0\": f\"-0.1 0.1\",\n \"L_Toe_1_1_joint_1\": f\"-45 45\",\n \"L_Toe_1_1_joint_2\": f\"-10 10\",\n \"R_Toe_1_1_joint_0\": f\"-0.1 0.1\",\n \"R_Toe_1_1_joint_1\": f\"-45 45\",\n \"R_Toe_1_1_joint_2\": f\"-10 10\",\n \"L_Toe_2_joint_0\": f\"-0.1 0.1\",\n \"L_Toe_2_joint_1\": f\"-45 45\",\n \"L_Toe_2_joint_2\": f\"-10 10\",\n \"R_Toe_2_joint_0\": f\"-0.1 0.1\",\n \"R_Toe_2_joint_1\": f\"-45 45\",\n \"R_Toe_2_joint_2\": f\"-10 10\",\n }\n body_index = [3, 7]\n\n yellow_bone_length = 0.02\n yellow_toe_back = -0.02\n for idx in body_index:\n ankle2clone = body_ankle = self.bodies[idx]\n ankle_node = body_ankle.node\n flip_y = -1 if idx == 3 else 1\n\n for element in ankle_node.getiterator(): # remvoe the geom of the ankle\n if element.tag == \"geom\":\n ankle_node.remove(element)\n break\n\n child_pos = body_ankle.child[0].pos - body_ankle.pos\n body_ankle.geoms = [] # remove Ankel's original geom\n toe_x, toe_y, toe_z = child_pos\n ankles_zs, ankle_xs = self.hull_dict[body_ankle.name]['norm_verts'][:, 2], self.hull_dict[body_ankle.name]['norm_verts'][:, 0]\n ankle_y_max, ankle_y_min = self.hull_dict[body_ankle.name]['norm_verts'][:, 1].max(), self.hull_dict[body_ankle.name]['norm_verts'][:, 1].min()\n ankle_z_max, ankle_z_min = ankles_zs.max(), ankles_zs.min()\n toe_y_max, toe_y_min = self.hull_dict[body_ankle.name]['norm_verts'][:, 1].max(), self.hull_dict[body_ankle.name]['norm_verts'][:, 1].min()\n ankle_z_max_x = self.hull_dict[body_ankle.name]['norm_verts'][ankles_zs.argmax(), 0]\n if idx == 7:\n ankle_y_tgt, ankle_y_green = ankle_y_max, ankle_y_min\n else:\n ankle_y_tgt, ankle_y_green = ankle_y_min, ankle_y_max\n\n ankle_size = np.abs(toe_z - ankles_zs.min())\n\n ankle_z_min_neg = ankles_zs[ankle_xs < 0].min()\n ankle_z_span = ankle_z_max - ankle_z_min_neg\n ankle_y_span = ankle_y_max - ankle_y_min\n ankle_frac = 10\n green_y = (toe_y + ankle_y_tgt)/2 - ankle_y_span * 2/5 * flip_y\n\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"box\",\n \"pos\":\n f\"{(toe_x + yellow_toe_back)/2 - (toe_x - yellow_toe_back)/4} {(green_y + ankle_y_tgt)/2 } {ankle_z_min_neg + ankle_z_span * 9/ankle_frac /2}\",\n \"size\":\n f\"{(toe_x - yellow_toe_back)/4} {np.abs((ankle_y_tgt - green_y)/2)} {ankle_z_span * 9 / ankle_frac /2}\",\n \"quat\": f\"0 0 0 1\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n attributes = {\n \"type\": \"box\",\n \"pos\":\n f\"{(toe_x + yellow_toe_back)/2 + (toe_x - yellow_toe_back)/4} {(green_y + ankle_y_tgt)/2 } {ankle_z_min_neg + ankle_z_span * 6/ankle_frac /2}\",\n \"size\":\n f\"{(toe_x - yellow_toe_back)/4} {np.abs((ankle_y_tgt - green_y)/2)} {ankle_z_span * 6 / ankle_frac /2}\",\n \"quat\": f\"0 0 0 1\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n\n ############################################################ Nodes for red toes\n body_toe = body_ankle.child[0]\n body_toe_node = body_toe.node\n for element in body_toe_node.getiterator(): # remvoe the geom of the ankle\n if element.tag == \"geom\":\n body_toe_node.remove(element)\n elif element.tag == \"joint\":\n master_range = self.cfg.get(\"master_range\", 30)\n element.attrib[\"range\"] = self.joint_range_master.get(element.attrib[\"name\"], f\"-{master_range} {master_range}\")\n\n\n toe_x_max, toe_x_min = self.hull_dict[body_toe.name]['norm_verts'][:, 0].max(), self.hull_dict[body_toe.name]['norm_verts'][:, 0].min()\n # toe_y_max, toe_y_min = self.hull_dict[body_toe.name]['norm_verts'][:, 1].max(), self.hull_dict[body_toe.name]['norm_verts'][:, 1].min()\n # toe_z_max, toe_z_min = self.hull_dict[body_toe.name]['norm_verts'][:, 2].max(), self.hull_dict[body_toe.name]['norm_verts'][:, 2].min()\n\n attributes = {\n \"type\": \"box\",\n \"pos\":\n f\"{(toe_x_max)/4} {(green_y + ankle_y_tgt)/2 - toe_y} {ankle_z_min_neg + ankle_z_span * 4/ankle_frac /2- toe_z}\",\n \"size\":\n f\"{(toe_x_max)/4} {np.abs((ankle_y_tgt - green_y)/2)} {ankle_z_span * 4 / ankle_frac /2}\",\n \"quat\": f\"0 0 0 1\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(body_toe_node, \"geom\", attributes)\n body_toe.geoms.append(Geom(geom_node, body_toe))\n\n attributes = {\n \"type\": \"box\",\n \"pos\":\n f\"{(toe_x_max) * 3/4 } {(green_y + ankle_y_tgt)/2 - toe_y} {ankle_z_min_neg + ankle_z_span * 2/ankle_frac /2- toe_z}\",\n \"size\":\n f\"{(toe_x_max)/4} {np.abs((ankle_y_tgt - green_y)/2)} {ankle_z_span * 2 / ankle_frac /2}\",\n \"quat\": f\"0 0 0 1\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(body_toe_node, \"geom\", attributes)\n body_toe.geoms.append(Geom(geom_node, body_toe))\n\n # #################################### First additional toe (green one)\n green_z = ankle_z_max - ankle_size - ankle_z_span * 4 / ankle_frac\n toe_y_max, toe_y_min = self.hull_dict[body_toe.name]['norm_verts'][:, 1].max(), self.hull_dict[body_toe.name]['norm_verts'][:, 1].min()\n pos = np.array([yellow_bone_length, green_y, green_z])\n\n\n green_toe_body = self.add_body_joint_and_actuator(body_ankle, body_toe, pos, index_name = \"_1\")\n attributes = {\n \"type\": \"box\",\n \"pos\":\n f\"{(toe_x - yellow_bone_length)/2 } { (ankle_y_green - green_y)/2 } {ankle_z_min_neg + ankle_z_span * 5/ankle_frac /2 - green_z}\",\n \"size\":\n f\"{np.abs(toe_x - yellow_bone_length)/2} {np.abs(green_y - ankle_y_green)/2} {ankle_z_span * 5 / ankle_frac /2}\",\n \"quat\": f\"0 0 0 1\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(green_toe_body.node, \"geom\", attributes)\n green_toe_body.geoms.append(Geom(geom_node, green_toe_body))\n\n # #################################### Second additional toe (white one)\n pos = np.array([toe_x - yellow_bone_length, 0, toe_z - green_z])\n white_toe_body = self.add_body_joint_and_actuator(green_toe_body,\n green_toe_body,\n pos,\n index_name=\"_1\")\n\n attributes = {\n \"type\": \"box\",\n \"pos\":\n f\"{(toe_x_max ) * 2/5} { (ankle_y_green - green_y)/2 } {ankle_z_min_neg + ankle_z_span * 2 /ankle_frac /2- toe_z}\",\n \"size\":\n f\"{(toe_x_max ) * 2/5} {np.abs(green_y - ankle_y_green)/2} {ankle_z_span * 2 / ankle_frac /2}\",\n \"quat\": f\"0 0 0 1\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(white_toe_body.node, \"geom\", attributes)\n white_toe_body.geoms.append(Geom(geom_node, white_toe_body))\n\n\n #################################### Third additional toe (white one)\n ankle_x_min = self.hull_dict[body_ankle.name]['norm_verts'][:, 0].min()\n pos = np.array(\n [yellow_toe_back, (green_y + ankle_y_tgt) / 2 , toe_z])\n\n while_toe_body = self.add_body_joint_and_actuator(body_ankle, body_toe, pos, index_name = \"_2\")\n attributes = {\n \"type\": \"box\",\n \"pos\":\n f\"{(ankle_x_min - yellow_toe_back)/2} {0} {ankle_z_min_neg + ankle_z_span * 7 /ankle_frac /2- toe_z}\",\n \"size\":\n f\"{np.abs(ankle_x_min - yellow_toe_back)/2} {np.abs((ankle_y_tgt - green_y)/2)} {ankle_z_span * 7 / ankle_frac /2}\",\n \"quat\": f\"0 0 0 1\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(while_toe_body.node, \"geom\", attributes)\n while_toe_body.geoms.append(Geom(geom_node, while_toe_body))\n\n\n\n\n self.init_tree = deepcopy(self.tree)\n\n\n def add_masterfoot_capsule(self):\n masterfoot_v = self.cfg.get(\"masterfoot_v\", 0)\n body_index = [3, 7]\n self.joint_range_master = {\"L_Toe_x\": f\"-0.1 0.1\", \"L_Toe_y\": f\"-45 45\", \"L_Toe_z\": f\"-10 10\"}\n yellow_bone_length = 0.04\n yellow_toe_back = -0.02\n for idx in body_index:\n ankle2clone = body_ankle = self.bodies[idx]\n ankle_node = body_ankle.node\n flip_y = -1 if idx == 3 else 1\n\n for element in ankle_node.getiterator(): # remvoe the geom of the ankle\n if element.tag == \"geom\":\n ankle_node.remove(element)\n break\n child_pos = body_ankle.child[0].pos - body_ankle.pos\n body_ankle.geoms = [] # remove Ankel's original geom\n toe_x, toe_y, toe_z = child_pos\n\n ankle_y_max, ankle_y_min = self.hull_dict[body_ankle.name]['norm_verts'][:, 1].max(), self.hull_dict[body_ankle.name]['norm_verts'][:, 1].min()\n ankle_z_max, ankle_z_min = self.hull_dict[body_ankle.name]['norm_verts'][:, 2].max(), self.hull_dict[body_ankle.name]['norm_verts'][:, 2].min()\n toe_y_max, toe_y_min = self.hull_dict[body_ankle.name]['norm_verts'][:, 1].max(), self.hull_dict[body_ankle.name]['norm_verts'][:, 1].min()\n ankle_z_max_x = self.hull_dict[body_ankle.name]['norm_verts'][self.hull_dict[body_ankle.name]['norm_verts'][:, 2].argmax(), 0]\n if idx == 7:\n ankle_y_tgt = ankle_y_max\n else:\n ankle_y_tgt = ankle_y_min\n\n ankle_size = np.abs(toe_z - self.hull_dict[body_ankle.name]['norm_verts'][:, 2].min())\n ankle_z_span = ankle_z_max - ankle_z_min\n ankle_frac = 10\n\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{ankle_z_max_x} {toe_y } {ankle_z_max - ankle_size - ankle_z_span * 2/ankle_frac} {toe_x} {toe_y } {toe_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{ankle_z_max_x} {(toe_y + ankle_y_tgt)/2} {ankle_z_max - ankle_size- ankle_z_span * 1/ankle_frac} {toe_x} {(toe_y + ankle_y_tgt)/2} {toe_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{ankle_z_max_x} {ankle_y_tgt} {ankle_z_max - ankle_size- ankle_z_span * 0/ankle_frac} {toe_x} {ankle_y_tgt} {toe_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n ########################################################################\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{ankle_z_max_x} {toe_y} {ankle_z_max - ankle_size- ankle_z_span * 2/ankle_frac} {yellow_toe_back} {(toe_y + ankle_y_tgt)/2} {toe_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{ankle_z_max_x} {(toe_y + ankle_y_tgt)/2} {ankle_z_max - ankle_size- ankle_z_span * 1/ankle_frac} {yellow_toe_back} {(toe_y + ankle_y_tgt)/2} {toe_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{ankle_z_max_x} {ankle_y_tgt} {ankle_z_max - ankle_size- ankle_z_span * 0/ankle_frac} {yellow_toe_back} {(toe_y + ankle_y_tgt)/2} {toe_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n ############################################################\n green_z = ankle_z_max - ankle_size - ankle_z_span * 4/ankle_frac\n\n attributes = {\n \"size\": f\"{ankle_size}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{yellow_bone_length} {(toe_y + ankle_y_tgt)/2 - 0.05 * flip_y} {green_z} {yellow_toe_back} {(toe_y + ankle_y_tgt)/2} {toe_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(ankle_node, \"geom\", attributes)\n body_ankle.geoms.append(Geom(geom_node, body_ankle))\n\n\n ############################################################ Nodes for red toes\n body_toe = body_ankle.child[0]\n body_toe_node = body_toe.node\n for element in body_toe_node.getiterator(): # remvoe the geom of the toe\n if element.tag == \"geom\":\n body_toe_node.remove(element)\n elif element.tag == \"joint\":\n master_range = self.cfg.get(\"master_range\", 30)\n element.attrib[\"range\"] = self.joint_range_master.get(element.attrib[\"name\"], f\"-{master_range} {master_range}\")\n print(element.attrib[\"range\"])\n\n toe_x_max = self.hull_dict[body_toe.name]['norm_verts'][:, 0].max()\n toe_z_min_abs = np.abs(self.hull_dict[body_toe.name]['norm_verts'][:, 2].min())\n\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\": f\"{0.0} {0} {0} {toe_x_max} {0} {0}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(body_toe_node, \"geom\", attributes)\n body_toe.geoms.append(Geom(geom_node, body_toe))\n\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0.0} {(toe_y + ankle_y_tgt)/2 - toe_y} {0} {toe_x_max} {(toe_y + ankle_y_tgt)/2- toe_y} {0}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(body_toe_node, \"geom\", attributes)\n body_toe.geoms.append(Geom(geom_node, body_toe))\n\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0.0} {ankle_y_tgt- toe_y} {0} {toe_x_max} {ankle_y_tgt- toe_y} {0}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(body_toe_node, \"geom\", attributes)\n body_toe.geoms.append(Geom(geom_node, body_toe))\n\n\n #################################### First additional toe (green one)\n toe_y_max, toe_y_min = self.hull_dict[body_toe.name]['norm_verts'][:, 1].max(), self.hull_dict[body_toe.name]['norm_verts'][:, 1].min()\n if idx == 7:\n toe_y_tgt = toe_y_min + toe_z_min_abs\n else:\n toe_y_tgt = toe_y_max - toe_z_min_abs\n\n pos = np.array([yellow_bone_length, (toe_y + ankle_y_tgt)/2 - 0.05 * flip_y, green_z])\n green_toe_body = self.add_body_joint_and_actuator(body_ankle, body_toe, pos, index_name = \"_1\")\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0} {0} {0} {toe_x - yellow_bone_length} {0} {toe_z - green_z }\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(green_toe_body.node, \"geom\", attributes)\n green_toe_body.geoms.append(Geom(geom_node, green_toe_body))\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0} {toe_y_tgt + toe_z_min_abs * flip_y} {toe_z - green_z} {toe_x - yellow_bone_length} {toe_y_tgt + toe_z_min_abs* flip_y} {toe_z - green_z}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(green_toe_body.node, \"geom\", attributes)\n green_toe_body.geoms.append(Geom(geom_node, green_toe_body))\n\n #################################### Second additional toe (white one)\n pos = np.array([toe_x - yellow_bone_length, 0, toe_z - green_z])\n white_toe_body = self.add_body_joint_and_actuator(green_toe_body,\n green_toe_body,\n pos,\n index_name=\"_1\")\n\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0} {0} {0} {np.abs((toe_x_max - toe_x) * 3/4) } {0} {0}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(white_toe_body.node, \"geom\", attributes)\n white_toe_body.geoms.append(Geom(geom_node, white_toe_body))\n\n attributes = {\n \"size\": f\"{toe_z_min_abs }\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0} {toe_y_tgt + toe_z_min_abs * flip_y} {0} {np.abs((toe_x_max - toe_x) * 3/4) } {toe_y_tgt + toe_z_min_abs * flip_y} {0}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(white_toe_body.node, \"geom\", attributes)\n white_toe_body.geoms.append(Geom(geom_node, white_toe_body))\n\n #################################### Third additional toe (white one)\n ankle_x_min = self.hull_dict[body_ankle.name]['norm_verts'][:, 0].min()\n pos = np.array([yellow_toe_back, (toe_y + ankle_y_tgt)/2, toe_z])\n\n while_toe_body = self.add_body_joint_and_actuator(body_ankle, body_toe, pos, index_name = \"_2\")\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0} {toe_z_min_abs} {0} {ankle_x_min - yellow_toe_back + toe_z_min_abs} {toe_z_min_abs} {0}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(while_toe_body.node, \"geom\", attributes)\n while_toe_body.geoms.append(Geom(geom_node, while_toe_body))\n\n\n attributes = {\n \"size\": f\"{toe_z_min_abs}\",\n \"type\": \"capsule\",\n \"fromto\":\n f\"{0} {-toe_z_min_abs} {0} {ankle_x_min - yellow_toe_back + toe_z_min_abs} {-toe_z_min_abs} {0}\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n geom_node = SubElement(while_toe_body.node, \"geom\", attributes)\n while_toe_body.geoms.append(Geom(geom_node, while_toe_body))\n\n # attributes = {\n # \"size\": f\"{toe_z_min}\",\n # \"type\": \"capsule\",\n # \"fromto\":\n # f\"{0} {toe_y_tgt + toe_z_min * flip_y} {0} {toe_x - yellow_bone_length} {toe_y_tgt + toe_z_min* flip_y} {0}\",\n # \"contype\": \"0\",\n # \"conaffinity\": \"1\",\n # }\n # geom_node = SubElement(while_toe_body.node, \"geom\", attributes)\n # while_toe_body.geoms.append(Geom(geom_node, while_toe_body))\n\n\n self.init_tree = deepcopy(self.tree)\n\n def add_body_joint_and_actuator(self, parent_body, body, pos, index_name = \"_1\"):\n body_node =body.node\n new_node = deepcopy(body_node)\n new_node.attrib['pos'] = f\"{pos[0]} {pos[1]} {pos[2]}\"\n new_node.attrib['name'] = body.name + index_name\n\n actu_node = parent_body.tree.getroot().find(\"actuator\")\n if len(parent_body.child) > 0:\n # Recursively finding the last child to insert\n last_child = parent_body.child[-1]\n\n while len(last_child.child) > 0:\n last_child = last_child.child[-1]\n\n actu_insert_index = (actu_node.index(\n actu_node.find(f'motor[@joint=\"{last_child.joints[-1].name}\"]')) + 1)\n else:\n actu_insert_index = (actu_node.index(\n actu_node.find(\n f'motor[@joint=\"{parent_body.joints[-1].name}\"]')) + 1)\n\n for bnode in body_node.findall(\"body\"):\n body_node.remove(bnode)\n\n child_body = Body(\n new_node, parent_body, self, self.cfg, new_body = True\n ) # This needs to called after finding the actu_insert_index\n for element in new_node.getiterator():\n if element.tag == \"geom\":\n new_node.remove(element)\n if element.tag == \"joint\":\n master_range = self.cfg.get(\"master_range\", 30)\n element.attrib[\"range\"] = f\"-{master_range} {master_range}\"\n\n\n for joint in child_body.joints:\n new_actu_node = deepcopy(actu_node.find(f'motor[@joint=\"{joint.name}\"]'))\n joint.node.attrib[\"range\"] = self.joint_range_master.get(joint.node.attrib[\"name\"], f\"-{master_range} {master_range}\")\n new_actu_node.attrib['name'] += index_name\n\n actu_node.insert(actu_insert_index, new_actu_node)\n joint.actuator = Actuator(new_actu_node, joint)\n actu_insert_index += 1\n\n child_body.bone_offset = parent_body.bone_offset.copy()\n child_body.param_specs = deepcopy(parent_body.param_specs)\n child_body.param_inited = True\n child_body.rebuild()\n child_body.sync_node()\n parent_body.node.append(new_node)\n self.bodies.append(child_body)\n self.sync_node()\n return child_body\n\n def add_child_to_body(self, body):\n if body == self.bodies[0]:\n body2clone = body.child[0]\n else:\n body2clone = body\n child_node = deepcopy(body2clone.node)\n\n actu_node = body.tree.getroot().find(\"actuator\")\n\n if len(body.child) > 0:\n # Recursively finding the last child to insert\n last_child = body.child[-1]\n while len(last_child.child) > 0:\n last_child = last_child.child[-1]\n\n actu_insert_index = (actu_node.index(\n actu_node.find(\n f'motor[@joint=\"{last_child.joints[-1].name}\"]')) + 1)\n else:\n actu_insert_index = (actu_node.index(\n actu_node.find(f'motor[@joint=\"{body.joints[-1].name}\"]')) + 1)\n\n for bnode in child_node.findall(\"body\"):\n child_node.remove(bnode)\n\n ######## Special case for the the foot, template geom ##############\n child_body = Body(\n child_node, body, self, self.cfg, new_body=True\n ) # This needs to called after finding the actu_insert_index\n\n start = \" \".join([\n f\"{x:.6f}\".rstrip(\"0\").rstrip(\".\")\n for x in body.pos + np.array([0.0, -0.05, 0.05])\n ])\n\n attributes = {\n \"size\": \"0.020 0.1000 0.0100\",\n \"type\": \"box\",\n \"pos\": start,\n \"quat\": \"0.7071 -0.7071 0.0000 0.0000\",\n \"contype\": \"0\",\n \"conaffinity\": \"1\",\n }\n\n for element in child_node.getiterator():\n if element.tag == \"geom\":\n child_node.remove(element)\n\n geom_node = SubElement(child_node, \"geom\", attributes)\n child_body.geoms = [Geom(geom_node, child_body)]\n ######## Special case for the the foot, template geometry ##############\n\n for joint in child_body.joints:\n new_actu_node = deepcopy(\n actu_node.find(f'motor[@joint=\"{joint.name}\"]'))\n actu_node.insert(actu_insert_index, new_actu_node)\n joint.actuator = Actuator(new_actu_node, joint)\n actu_insert_index += 1\n child_body.bone_offset = body.bone_offset.copy()\n child_body.param_specs = deepcopy(body.param_specs)\n child_body.param_inited = True\n child_body.rebuild()\n child_body.sync_node()\n body.node.append(child_node)\n self.bodies.append(child_body)\n self.sync_node()\n\n def remove_body(self, body):\n body.node.getparent().remove(body.node)\n body.parent.child.remove(body)\n self.bodies.remove(body)\n actu_node = body.tree.getroot().find(\"actuator\")\n for joint in body.joints:\n actu_node.remove(joint.actuator.node)\n del body\n self.sync_node()\n\n def write_xml(self, fname):\n self.tree.write(fname, pretty_print=True)\n\n def export_xml_string(self):\n return etree.tostring(self.tree, pretty_print=True)\n\n def export_vis_string(self,\n num=2,\n smpl_robot=None,\n fname=None,\n num_cones=0):\n tree = deepcopy(self.tree)\n if smpl_robot is None:\n vis_tree = deepcopy(self.init_tree)\n else:\n vis_tree = deepcopy(smpl_robot.tree)\n\n # Removing actuators from the tree\n remove_elements = [\"actuator\", \"contact\", \"equality\"]\n for elem in remove_elements:\n node = tree.getroot().find(elem)\n if node is None:\n # print(f\"has no elem: {elem}\")\n pass\n else:\n node.getparent().remove(node)\n\n option = tree.getroot().find(\"option\")\n flag = SubElement(option, \"flag\", {\"contact\": \"disable\"})\n option.addnext(Element(\"size\", {\"njmax\": \"1000\"}))\n\n worldbody = tree.getroot().find(\"worldbody\")\n asset = tree.getroot().find(\"asset\")\n vis_worldbody = vis_tree.getroot().find(\"worldbody\")\n\n geom_body = vis_worldbody.find(\"geom\")\n\n vis_meshes = vis_tree.getroot().find(\"asset\").findall(\"mesh\")\n\n for i in range(1, num):\n vis_meshes = deepcopy(vis_meshes)\n for mesh in vis_meshes:\n old_file = mesh.attrib[\"file\"]\n mesh.attrib[\"file\"] = mesh.attrib[\"file\"].replace(\n \".stl\", f\"_{i}.stl\")\n shutil.copy(old_file, mesh.attrib[\"file\"])\n asset.append(mesh)\n\n body = vis_worldbody.find(\"body\")\n for i in range(1, num):\n new_body = deepcopy(body)\n new_body.attrib[\"name\"] = \"%d_%s\" % (i, new_body.attrib[\"name\"])\n new_body.find(\"geom\").attrib[\"rgba\"] = \"0.7 0 0 1\"\n\n for node in new_body.findall(\".//body\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n node.find(\"geom\").attrib[\"rgba\"] = \"0.7 0 0 1\"\n for node in new_body.findall(\".//joint\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//site\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//geom\"):\n node.attrib[\"mesh\"] = \"%s_%d\" % (node.attrib[\"mesh\"], i)\n worldbody.append(new_body)\n\n for i in range(num_cones):\n body_node = Element(\"body\", {\"pos\": \"0 0 0\"})\n geom_node = SubElement(\n body_node,\n \"geom\",\n {\n \"mesh\": \"cone\",\n \"type\": \"mesh\",\n \"rgba\": \"0.0 0.8 1.0 1.0\"\n },\n )\n worldbody.append(body_node)\n for i in range(num_cones):\n worldbody.append(\n Element(\n \"geom\",\n {\n \"fromto\": \"0.0 0.0 0.0 0.0 1.0 0.0\",\n \"rgba\": \"0.0 0.8 1.0 1.0\",\n \"type\": \"cylinder\",\n \"size\": \"0.0420\",\n },\n ))\n\n if fname is not None:\n print(\"Writing to file: %s\" % fname)\n tree.write(fname, pretty_print=True)\n vis_str = etree.tostring(tree, pretty_print=True)\n return vis_str\n\n def export_vis_string_self(self,\n num=3,\n smpl_robot=None,\n fname=None,\n num_cones=0):\n # colors = [\"0.8 0.6 .4 1\", \"0.7 0 0 1\", \"0.0 0.0 0.7 1\"] * num\n colors = [\n f\"{np.random.random():.3f} {np.random.random():.3f} {np.random.random():.3f} 1\"\n for _ in range(num)\n ]\n # Export multiple vis strings\n tree = deepcopy(self.tree)\n if smpl_robot is None:\n vis_tree = deepcopy(self.init_tree)\n else:\n vis_tree = deepcopy(smpl_robot.tree)\n\n # Removing actuators from the tree\n remove_elements = [\"actuator\", \"contact\", \"equality\"]\n for elem in remove_elements:\n node = tree.getroot().find(elem)\n if node is None:\n # print(f\"has no elem: {elem}\")\n pass\n else:\n node.getparent().remove(node)\n\n option = tree.getroot().find(\"option\")\n flag = SubElement(option, \"flag\", {\"contact\": \"disable\"})\n option.addnext(Element(\"size\", {\"njmax\": \"1000\"}))\n\n worldbody = tree.getroot().find(\"worldbody\")\n asset = tree.getroot().find(\"asset\")\n vis_worldbody = vis_tree.getroot().find(\"worldbody\")\n\n geom_body = vis_worldbody.find(\"geom\")\n\n vis_meshes = vis_tree.getroot().find(\"asset\").findall(\"mesh\")\n for i in range(1, num):\n cur_meshes = deepcopy(vis_meshes)\n for mesh in cur_meshes:\n old_file = mesh.attrib[\"file\"]\n mesh.attrib[\"file\"] = mesh.attrib[\"file\"].replace(\n \".stl\", f\"_{i}.stl\")\n shutil.copy(old_file, mesh.attrib[\"file\"])\n asset.append(mesh)\n\n body = vis_worldbody.find(\"body\")\n for i in range(1, num):\n new_body = deepcopy(body)\n new_body.attrib[\"name\"] = \"%d_%s\" % (i, new_body.attrib[\"name\"])\n new_body.find(\"geom\").attrib[\"rgba\"] = colors[i]\n\n for node in new_body.findall(\".//body\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n node.find(\"geom\").attrib[\"rgba\"] = colors[i]\n for node in new_body.findall(\".//joint\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//site\"):\n node.attrib[\"name\"] = \"%d_%s\" % (i, node.attrib[\"name\"])\n for node in new_body.findall(\".//geom\"):\n node.attrib[\"mesh\"] = \"%s_%d\" % (node.attrib[\"mesh\"], i)\n worldbody.append(new_body)\n\n if fname is not None:\n print(\"Writing to file: %s\" % fname)\n tree.write(fname, pretty_print=True)\n vis_str = etree.tostring(tree, pretty_print=True)\n return vis_str\n\n def demap_params(self, params):\n if not np.all((params <= 1.0) & (params >= -1.0)):\n print(f\"param out of bounds: {params}\")\n params = np.clip(params, -1.0, 1.0)\n if self.param_mapping == \"sin\":\n params = np.arcsin(params) / (0.5 * np.pi)\n return params\n\n def get_params(self, get_name=False):\n param_list = []\n if self.beta is not None and \"beta\" in self.param_specs:\n if get_name:\n param_list += [\"beta\"]\n else:\n beta = normalize_range(\n self.beta.numpy().squeeze(),\n self.param_specs[\"beta\"][\"lb\"],\n self.param_specs[\"beta\"][\"ub\"],\n )\n param_list.append(beta)\n\n for body in self.bodies:\n body.get_params(param_list, get_name)\n\n if not get_name and len(param_list) > 0:\n params = np.concatenate(param_list)\n params = self.demap_params(params)\n else:\n params = np.array(param_list)\n return params\n\n def map_params(self, params):\n if self.param_mapping == \"clip\":\n params = np.clip(params, -1.0, 1.0)\n elif self.param_mapping == \"sin\":\n params = np.sin(params * (0.5 * np.pi))\n return params\n\n def set_params(self, params):\n # clip params to range\n params = self.map_params(params)\n\n if \"beta\" in self.param_specs:\n self.beta = torch.from_numpy(\n denormalize_range(\n params[0:10],\n self.param_specs[\"beta\"][\"lb\"],\n self.param_specs[\"beta\"][\"ub\"],\n )[None, ])\n params = params[10:]\n\n for body in self.bodies:\n params = body.set_params(params)\n assert len(params) == 0 # all parameters need to be consumed!\n\n self.sync_node()\n\n def rebuild(self):\n for body in self.bodies:\n body.rebuild()\n body.sync_node()\n\n def get_gnn_edges(self):\n edges = []\n for i, body in enumerate(self.bodies):\n if body.parent is not None:\n j = self.bodies.index(body.parent)\n edges.append([i, j])\n edges.append([j, i])\n edges = np.stack(edges, axis=1)\n return edges" }, { "identifier": "SkeletonTree", "path": "poselib/poselib/skeleton/skeleton3d.py", "snippet": "class SkeletonTree(Serializable):\n \"\"\"\n A skeleton tree gives a complete description of a rigid skeleton. It describes a tree structure\n over a list of nodes with their names indicated by strings. Each edge in the tree has a local\n translation associated with it which describes the distance between the two nodes that it\n connects. \n\n Basic Usage:\n >>> t = SkeletonTree.from_mjcf(SkeletonTree.__example_mjcf_path__)\n >>> t\n SkeletonTree(\n node_names=['torso', 'front_left_leg', 'aux_1', 'front_left_foot', 'front_right_leg', 'aux_2', 'front_right_foot', 'left_back_leg', 'aux_3', 'left_back_foot', 'right_back_leg', 'aux_4', 'right_back_foot'],\n parent_indices=tensor([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11]),\n local_translation=tensor([[ 0.0000, 0.0000, 0.7500],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, -0.2000, 0.0000],\n [ 0.2000, -0.2000, 0.0000]])\n )\n >>> t.node_names\n ['torso', 'front_left_leg', 'aux_1', 'front_left_foot', 'front_right_leg', 'aux_2', 'front_right_foot', 'left_back_leg', 'aux_3', 'left_back_foot', 'right_back_leg', 'aux_4', 'right_back_foot']\n >>> t.parent_indices\n tensor([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11])\n >>> t.local_translation\n tensor([[ 0.0000, 0.0000, 0.7500],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [-0.2000, 0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [-0.2000, -0.2000, 0.0000],\n [ 0.0000, 0.0000, 0.0000],\n [ 0.2000, -0.2000, 0.0000],\n [ 0.2000, -0.2000, 0.0000]])\n >>> t.parent_of('front_left_leg')\n 'torso'\n >>> t.index('front_right_foot')\n 6\n >>> t[2]\n 'aux_1'\n \"\"\"\n\n __example_mjcf_path__ = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"tests/ant.xml\")\n\n def __init__(self, node_names, parent_indices, local_translation):\n \"\"\"\n :param node_names: a list of names for each tree node\n :type node_names: List[str]\n :param parent_indices: an int32-typed tensor that represents the edge to its parent.\\\n -1 represents the root node\n :type parent_indices: Tensor\n :param local_translation: a 3d vector that gives local translation information\n :type local_translation: Tensor\n \"\"\"\n ln, lp, ll = len(node_names), len(parent_indices), len(local_translation)\n assert len(set((ln, lp, ll))) == 1\n self._node_names = node_names\n self._parent_indices = parent_indices.long()\n self._local_translation = local_translation\n self._node_indices = {self.node_names[i]: i for i in range(len(self))}\n\n def __len__(self):\n \"\"\" number of nodes in the skeleton tree \"\"\"\n return len(self.node_names)\n\n def __iter__(self):\n \"\"\" iterator that iterate through the name of each node \"\"\"\n yield from self.node_names\n\n def __getitem__(self, item):\n \"\"\" get the name of the node given the index \"\"\"\n return self.node_names[item]\n\n def __repr__(self):\n return (\"SkeletonTree(\\n node_names={},\\n parent_indices={},\"\n \"\\n local_translation={}\\n)\".format(\n self._indent(repr(self.node_names)),\n self._indent(repr(self.parent_indices)),\n self._indent(repr(self.local_translation)),\n ))\n\n def _indent(self, s):\n return \"\\n \".join(s.split(\"\\n\"))\n\n @property\n def node_names(self):\n return self._node_names\n\n @property\n def parent_indices(self):\n return self._parent_indices\n\n @property\n def local_translation(self):\n return self._local_translation\n\n @property\n def num_joints(self):\n \"\"\" number of nodes in the skeleton tree \"\"\"\n return len(self)\n\n @classmethod\n def from_dict(cls, dict_repr, *args, **kwargs):\n return cls(\n list(map(str, dict_repr[\"node_names\"])),\n TensorUtils.from_dict(dict_repr[\"parent_indices\"], *args, **kwargs),\n TensorUtils.from_dict(dict_repr[\"local_translation\"], *args, **kwargs),\n )\n\n def to_dict(self):\n return OrderedDict([\n (\"node_names\", self.node_names),\n (\"parent_indices\", tensor_to_dict(self.parent_indices)),\n (\"local_translation\", tensor_to_dict(self.local_translation)),\n ])\n\n @classmethod\n def from_mjcf(cls, path: str) -> \"SkeletonTree\":\n \"\"\"\n Parses a mujoco xml scene description file and returns a Skeleton Tree.\n We use the model attribute at the root as the name of the tree.\n \n :param path:\n :type path: string\n :return: The skeleton tree constructed from the mjcf file\n :rtype: SkeletonTree\n \"\"\"\n tree = ET.parse(path)\n xml_doc_root = tree.getroot()\n xml_world_body = xml_doc_root.find(\"worldbody\")\n if xml_world_body is None:\n raise ValueError(\"MJCF parsed incorrectly please verify it.\")\n # assume this is the root\n xml_body_root = xml_world_body.find(\"body\")\n if xml_body_root is None:\n raise ValueError(\"MJCF parsed incorrectly please verify it.\")\n\n node_names = []\n parent_indices = []\n local_translation = []\n\n # recursively adding all nodes into the skel_tree\n def _add_xml_node(xml_node, parent_index, node_index):\n node_name = xml_node.attrib.get(\"name\")\n # parse the local translation into float list\n pos = np.fromstring(xml_node.attrib.get(\"pos\"), dtype=float, sep=\" \")\n node_names.append(node_name)\n parent_indices.append(parent_index)\n local_translation.append(pos)\n curr_index = node_index\n node_index += 1\n for next_node in xml_node.findall(\"body\"):\n node_index = _add_xml_node(next_node, curr_index, node_index)\n return node_index\n\n _add_xml_node(xml_body_root, -1, 0)\n\n return cls(\n node_names,\n torch.from_numpy(np.array(parent_indices, dtype=np.int32)),\n torch.from_numpy(np.array(local_translation, dtype=np.float32)),\n )\n\n def parent_of(self, node_name):\n \"\"\" get the name of the parent of the given node\n\n :param node_name: the name of the node\n :type node_name: string\n :rtype: string\n \"\"\"\n return self[int(self.parent_indices[self.index(node_name)].item())]\n\n def index(self, node_name):\n \"\"\" get the index of the node\n \n :param node_name: the name of the node\n :type node_name: string\n :rtype: int\n \"\"\"\n return self._node_indices[node_name]\n\n def drop_nodes_by_names(self, node_names: List[str], pairwise_translation=None) -> \"SkeletonTree\":\n new_length = len(self) - len(node_names)\n new_node_names = []\n new_local_translation = torch.zeros(new_length, 3, dtype=self.local_translation.dtype)\n new_parent_indices = torch.zeros(new_length, dtype=self.parent_indices.dtype)\n parent_indices = self.parent_indices.numpy()\n new_node_indices: dict = {}\n new_node_index = 0\n for node_index in range(len(self)):\n if self[node_index] in node_names:\n continue\n tb_node_index = parent_indices[node_index]\n if tb_node_index != -1:\n local_translation = self.local_translation[node_index, :]\n while tb_node_index != -1 and self[tb_node_index] in node_names:\n local_translation += self.local_translation[tb_node_index, :]\n tb_node_index = parent_indices[tb_node_index]\n assert tb_node_index != -1, \"the root node cannot be dropped\"\n\n if pairwise_translation is not None:\n local_translation = pairwise_translation[tb_node_index, node_index, :]\n else:\n local_translation = self.local_translation[node_index, :]\n\n new_node_names.append(self[node_index])\n new_local_translation[new_node_index, :] = local_translation\n if tb_node_index == -1:\n new_parent_indices[new_node_index] = -1\n else:\n new_parent_indices[new_node_index] = new_node_indices[self[tb_node_index]]\n new_node_indices[self[node_index]] = new_node_index\n new_node_index += 1\n\n return SkeletonTree(new_node_names, new_parent_indices, new_local_translation)\n\n def keep_nodes_by_names(self, node_names: List[str], pairwise_translation=None) -> \"SkeletonTree\":\n nodes_to_drop = list(filter(lambda x: x not in node_names, self))\n return self.drop_nodes_by_names(nodes_to_drop, pairwise_translation)" }, { "identifier": "flags", "path": "phc/utils/flags.py", "snippet": "class Flags(object):\n def __init__(self, items):" } ]
import glob import os import sys import pdb import os.path as osp import joblib import numpy as np import torch from isaacgym import gymapi, gymutil, gymtorch from phc.utils.motion_lib_smpl import MotionLibSMPL as MotionLibSMPL from uhc.smpllib.smpl_local_robot import SMPL_Robot from poselib.poselib.skeleton.skeleton3d import SkeletonTree from phc.utils.flags import flags
19,086
""" Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. Visualize motion library """ sys.path.append(os.getcwd())
""" Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. Visualize motion library """ sys.path.append(os.getcwd())
from phc.utils.motion_lib_smpl import MotionLibSMPL as MotionLibSMPL
0
2023-10-15 19:05:47+00:00
24k
e4s2023/E4S2023
run_UI.py
[ { "identifier": "UIOptions", "path": "options/ui_options.py", "snippet": "class UIOptions:\n\n\tdef __init__(self):\n\t\tself.parser = ArgumentParser()\n\t\tself.initialize()\n\n\tdef initialize(self):\n\t\tself.parser.add_argument('--exp_dir', type=str, default=\"/apdcephfs/share_1290939/zhianliu/running_results/our_editing/work_dirs/dummy\",help='Path to experiment output directory')\n\t\tself.parser.add_argument('--num_seg_cls', type=int, default=12,help='Segmentation mask class number')\n\t\tself.parser.add_argument('--remaining_layer_idx', type=int, default=13, help='剩余的几层不用mask')\n # ================= 模型设置 相关 =====================\n\t\tself.parser.add_argument('--out_size', type=int, default=1024,help='output image size') \n\t\tself.parser.add_argument('--n_styles', default=11, type=int, help='StyleGAN层数')\n\t\tself.parser.add_argument('--fsencoder_type', type=str, default=\"psp\", help='FS Encode网络类型')\n\t\tself.parser.add_argument('--extra_encoder_input', type=str, default=\"diff_map\", help='额外的style code补偿Encode网络输入类型') \n # ================= 数据集 相关 =====================\n\t\t\n\t\tself.parser.add_argument('--label_dir', default='./ui_run/testset/CelebA-HQ/test/labels', type=str, help='dataset label dir')\n\t\tself.parser.add_argument('--image_dir', default='./ui_run/testset/CelebA-HQ/test/images', type=str, help='dataset label dir')\n\t\tself.parser.add_argument('--ds_frac', default=1.0, type=float, help='dataset fraction')\n\t\tself.parser.add_argument('--test_batch_size', default=1, type=int, help='Batch size for testing and inference')\n\t\tself.parser.add_argument('--test_workers', default=4, type=int, help='Number of test/inference dataloader workers')\n\t\tself.parser.add_argument('--train_G', default=False, type=bool, help='Whether to train the styleGAN model')\n \n\t\tself.parser.add_argument('--output_size', default=1024, type=int, help='Output size of generator')\n\t\t# self.parser.add_argument('--checkpoint_path', default=\"/apdcephfs/share_1290939/zhianliu/py_projects/pytorch-DDP-demo/work_dirs/ablation_study/v_15_baseline_seg12_finetuneGD_8A100_remainLyrIdx13_flip_FFHQ_300KIters/checkpoints/iteration_300000.pt\", type=str, help='Path to model checkpoint')\n\t\t# self.parser.add_argument('--checkpoint_path', default=\"/our_editing-master/ckpts/iteration_120000.pt\", type=str, help='Path to model checkpoint')\n\t\tself.parser.add_argument('--checkpoint_path', default=\"pretrained/zhian/iteration_300000.pt\", type=str,\n\t\t\t\t\t\t\t\t help='Path to model checkpoint')\n\t\tself.parser.add_argument('--save_dir', default=\"./out_dir\", type=str, help='Path to save dir') \n\t\tself.parser.add_argument('--device', default='cuda:0', type=str, help='Which GPU(s) to use')\n\n\t\tself.parser.add_argument('--start_from_latent_avg', action='store_true',default=True, help='Whether to add average latent vector to generate codes from encoder.')\n\t\tself.parser.add_argument('--learn_in_w', action='store_true', help='Whether to learn in w space instead of w+')\n \n\tdef parse(self):\n\t\topts = self.parser.parse_args()\n\t\treturn opts" }, { "identifier": "Ui_Form", "path": "ui_run/ui.py", "snippet": "class Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n # Form.resize(1920, 1080)\n\n Form.resize(int(1920* SCALE), int(1080 * SCALE))\n\n # Form.resize(1980, 1100)\n\n\n # Label Buttons to change the semantic meanings of the Brush\n # First Row\n self.add_brush_widgets(Form)\n self.add_top_buttons(Form)\n self.add_label_buttons(Form)\n # self.add_label_buttons_seg19(Form)\n self.add_tool_buttons(Form)\n self.add_checkbox_widgets(Form)\n self.add_input_img_button(Form)\n self.add_ops_log_textBox(Form)\n self.add_ref_img_button(Form)\n\n self.graphicsView = QtWidgets.QGraphicsView(Form)\n self.graphicsView.setGeometry(QtCore.QRect(652* SCALE, 140* SCALE, 518* SCALE, 518* SCALE))\n self.graphicsView.setObjectName(\"graphicsView\")\n self.graphicsView_2 = QtWidgets.QGraphicsView(Form)\n self.graphicsView_2.setGeometry(QtCore.QRect(1204* SCALE, 140* SCALE, 518* SCALE, 518* SCALE))\n self.graphicsView_2.setObjectName(\"graphicsView_2\")\n\n self.graphicsView_GT = QtWidgets.QGraphicsView(Form)\n self.graphicsView_GT.setGeometry(QtCore.QRect(100* SCALE, 140* SCALE, 518* SCALE, 518* SCALE))\n self.graphicsView_GT.setObjectName(\"graphicsView_GT\")\n\n\n self.referDialog = ReferenceDialog(self)\n self.referDialog.setObjectName('Reference Dialog')\n # self.referDialog.setWindowTitle('Reference Image:')\n self.referDialog.setWindowTitle('Style Image')\n self.referDialogImage = QtWidgets.QLabel(self.referDialog)\n self.referDialogImage.setFixedSize(512, 512)\n # self.referDialog.show()\n\n self.snapshotDialog = SnapshotDialog(self)\n self.snapshotDialog.setObjectName('Snapshot Dialog')\n self.snapshotDialog.setWindowTitle('Reference Image:')\n self.snapshotDialogImage = QtWidgets.QLabel(self.snapshotDialog)\n self.snapshotDialogImage.setFixedSize(512, 512)\n\n self.add_intermediate_results_button(Form)\n self.add_alpha_bar(Form)\n\n QtCore.QMetaObject.connectSlotsByName(Form) # 绑定 信号和槽\n\n def retranslateUi(self, Form):\n # Form.setWindowTitle(_translate(\"Form\", \"Let's Party Face Manipulation v0.2\"))\n Form.setWindowTitle(_translate(\"Form\", \"Inteactive Editing\"))\n self.pushButton.setText(_translate(\"Form\", \"Open Image\"))\n self.pushButton_2.setText(_translate(\"Form\", \"Edit Style\"))\n self.pushButton_3.setText(_translate(\"Form\", \"Edit Shape\"))\n self.pushButton_4.setText(_translate(\"Form\", \"Recon\"))\n\n self.saveImg.setText(_translate(\"Form\", \"Save Img\"))\n\n def add_alpha_bar(self, Form): # alpha value,控制插值的程度应该是\n\n\n self.alphaLabel = QtWidgets.QLabel(Form)\n self.alphaLabel.setObjectName(\"alphaLabel\")\n self.alphaLabel.setGeometry(QtCore.QRect(Lb_x + 10*SCALE * Lb_row_shift + 10*SCALE * Lb_width + 40*SCALE, Lb_y, 150*SCALE, 20*SCALE))\n self.alphaLabel.setText('Alpha: 1.0')\n font = self.brushsizeLabel.font()\n font.setPointSize(10)\n font.setBold(True)\n self.alphaLabel.setFont(font)\n\n self.alphaSlider = QtWidgets.QSlider(Form)\n self.alphaSlider.setOrientation(QtCore.Qt.Horizontal)\n self.alphaSlider.setGeometry(QtCore.QRect(Lb_x + 10*SCALE * Lb_row_shift + 10 *SCALE* Lb_width + 150*SCALE, Lb_y, 225*SCALE, 10*SCALE))\n self.alphaSlider.setObjectName(\"alphaSlider\")\n self.alphaSlider.setMinimum(0)\n self.alphaSlider.setMaximum(20)\n self.alphaSlider.setValue(20)\n self.alphaSlider.valueChanged.connect(Form.change_alpha_value)\n\n def add_intermediate_results_button(self, Form): # 保存中间结果的 scroll Area\n\n self.snap_scrollArea = QtWidgets.QScrollArea(Form)\n self.snap_scrollArea.setGeometry(QtCore.QRect(100, Lb_y + Lb_height + Lb_col_shift + Lb_height, 1622* SCALE, 250* SCALE))\n self.snap_scrollArea.setWidgetResizable(True)\n self.snap_scrollArea.setObjectName(\"snap_scrollArea\")\n self.snap_scrollArea.setAlignment(Qt.AlignCenter)\n #self.snap_scrollArea.setStyleSheet(\"border-color: transparent\")\n self.snap_scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n\n\n self.snap_scrollAreaWidgetContents = QtWidgets.QWidget()\n self.snap_scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1622* SCALE, 250* SCALE))\n self.snap_scrollAreaWidgetContents.setObjectName(\"snap_scrollAreaWidgetContents\")\n\n self.snap_gridlLayout = QtWidgets.QGridLayout(self.snap_scrollAreaWidgetContents)\n # # snap_horizontalLayout.setContentsMargins(11, 11, 11, 11)\n self.snap_gridlLayout.setSpacing(20)\n self.snap_gridlLayout.setAlignment(Qt.AlignLeft)\n\n self.snap_style_button_list = []\n self.mask_snap_style_button_list = []\n\n for i in range(15):\n snap_style_button = QtWidgets.QPushButton()\n snap_style_button.setFixedSize(100, 100)\n snap_style_button.setStyleSheet(\"background-color: transparent\")\n snap_style_button.setIcon(QIcon())\n snap_style_button.setIconSize(QSize(100, 100))\n snap_style_button.clicked.connect(partial(self.open_snapshot_dialog, i))\n # snap_style_button.snap_shot_name = None\n self.snap_style_button_list.append(snap_style_button)\n # style_button.hide()\n self.snap_gridlLayout.addWidget(snap_style_button, 1, i)\n\n\n mask_snap_style_button = QtWidgets.QPushButton()\n mask_snap_style_button.setFixedSize(100, 100)\n mask_snap_style_button.setStyleSheet(\"background-color: transparent\")\n mask_snap_style_button.setIcon(QIcon())\n mask_snap_style_button.setIconSize(QSize(100, 100))\n self.mask_snap_style_button_list.append(mask_snap_style_button)\n # mask_snap_style_button.hide()\n self.snap_gridlLayout.addWidget(mask_snap_style_button, 0, i)\n\n\n self.snap_scrollArea.setWidget(self.snap_scrollAreaWidgetContents)\n\n def add_input_img_button(self, Form): # 右上角当前编辑的图片\n self.input_img_button = QtWidgets.QPushButton(Form)\n self.input_img_button.setGeometry(QtCore.QRect(1770*SCALE , 15*SCALE, 100*SCALE, 100*SCALE))\n self.input_img_button.setStyleSheet(\"background-color: transparent\")\n self.input_img_button.setFixedSize(100, 100)\n self.input_img_button.setIcon(QIcon(None))\n self.input_img_button.setIconSize(QSize(100, 100))\n self.input_img_button.clicked.connect(partial(Form.set_ref_img_path, 0))\n\n def add_checkbox_widgets(self, Form): # 右上角的复选框\n self.checkBoxGroupBox = QtWidgets.QGroupBox(\"Replace Style of Components\", Form)\n self.checkBoxGroupBox.setGeometry(QtCore.QRect(920* SCALE, 10* SCALE, 800, 100))\n\n layout = QtWidgets.QGridLayout()\n self.checkBoxGroup = QtWidgets.QButtonGroup(Form)\n self.checkBoxGroup.setExclusive(False)\n for i, j in enumerate(my_number_object):\n cb = QtWidgets.QCheckBox(my_number_object[j])\n self.checkBoxGroup.addButton(cb, i)\n layout.addWidget(cb, i//10, i%10)\n\n cb = QtWidgets.QCheckBox('ALL')\n self.checkBoxGroup.addButton(cb, )\n layout.addWidget(cb, (i+1)//10, (i+1)%10)\n\n self.checkBoxGroupBox.setLayout(layout)\n\n for i in range(len(my_number_object)):\n self.checkBoxGroup.button(i).setChecked(False)\n\n checkbox_status = [cb.isChecked() for cb in self.checkBoxGroup.buttons()]\n checkbox_status = checkbox_status[:len(my_number_object)]\n self.checkbox_status = checkbox_status\n self.checkBoxGroup.buttonToggled.connect(self.cb_event)\n\n def add_brush_widgets(self, Form):\n # KaustLogo = QtWidgets.QLabel(self)\n # # KaustLogo.setPixmap(QPixmap('icons/kaust_logo.svg').scaled(60, 60))\n # KaustLogo.setPixmap(QPixmap('ui_run/icons/1999780_200.png').scaled(60, 60))\n # KaustLogo.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 25, 80* SCALE, 80* SCALE))\n\n self.add_style_imgs_buttons(Form) # 加载右边的备选图片\n self.brushsizeLabel = QtWidgets.QLabel(Form)\n self.brushsizeLabel.setObjectName(\"brushsizeLabel\")\n self.brushsizeLabel.setGeometry(QtCore.QRect(int(Tb_x), 25, int(150 * SCALE), int(20 * SCALE)))\n self.brushsizeLabel.setText('Brush size: 6')\n font = self.brushsizeLabel.font()\n font.setPointSize(10)\n font.setBold(True)\n self.brushsizeLabel.setFont(font)\n\n self.brushSlider = QtWidgets.QSlider(Form)\n self.brushSlider.setOrientation(QtCore.Qt.Horizontal)\n self.brushSlider.setGeometry(QtCore.QRect(int(Tb_x + 150* SCALE), 25, int(600* SCALE), int(10* SCALE)))\n self.brushSlider.setObjectName(\"brushSlider\")\n self.brushSlider.setMinimum(1)\n self.brushSlider.setMaximum(100)\n self.brushSlider.setValue(8)\n self.brushSlider.valueChanged.connect(Form.change_brush_size) # 绑定slider bar的数值变化\n\n def add_top_buttons(self, Form): # 添加顶部的按钮\n self.pushButton = QtWidgets.QPushButton(Form)\n self.pushButton.setGeometry(QtCore.QRect(int(Tb_x), int(Tb_y), int(Tb_width), int(Tb_height)))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton.clicked.connect(Form.open)\n\n self.pushButton_2 = QtWidgets.QPushButton(Form)\n self.pushButton_2.setGeometry(QtCore.QRect(int(Tb_x + 1 * Tb_row_shift + 1 * Tb_width), int(Tb_y), int(Tb_width), int(Tb_height)))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.pushButton_2.clicked.connect(Form.mixing_ref_img_style)\n\n self.pushButton_3 = QtWidgets.QPushButton(Form)\n self.pushButton_3.setGeometry(QtCore.QRect(int(Tb_x + 2 * Tb_row_shift + 2 * Tb_width), int(Tb_y), int(Tb_width), int(Tb_height)))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.pushButton_3.clicked.connect(Form.editing)\n\n self.pushButton_4 = QtWidgets.QPushButton(Form)\n self.pushButton_4.setGeometry(QtCore.QRect(int(Tb_x + 3 * Tb_row_shift + 3 * Tb_width), int(Tb_y), int(Tb_width), int(Tb_height)))\n self.pushButton_4.setObjectName(\"pushButton_4\")\n self.pushButton_4.clicked.connect(Form.recon)\n\n self.saveImg = QtWidgets.QPushButton(Form)\n self.saveImg.setGeometry(QtCore.QRect(int(Tb_x + 4 * Tb_row_shift + 4 * Tb_width), int(Tb_y), int(Tb_width), int(Tb_height)))\n self.saveImg.setObjectName(\"saveImg\")\n self.saveImg.clicked.connect(Form.save_img)\n\n self.retranslateUi(Form)\n\n def add_tool_buttons(self, Form): # 左边的工具栏图片\n self.newButton = QtWidgets.QPushButton(Form)\n self.newButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60* SCALE), 140* SCALE + 60* SCALE*1 + 10* SCALE*1, 60* SCALE, 60* SCALE))\n self.newButton.setObjectName(\"openButton\")\n self.newButton.setIcon(QIcon('ui_run/icons/reset200.png'))\n self.newButton.setIconSize(QSize(60* SCALE, 60* SCALE))\n self.newButton.clicked.connect(Form.init_screen) # 重置\n\n # self.openButton = QtWidgets.QPushButton(Form)\n # self.openButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60* SCALE), 140* SCALE, 60* SCALE, 60* SCALE))\n # self.openButton.setObjectName(\"openButton\")\n # self.openButton.setIcon(QIcon('ui_run/icons/open.png'))\n # self.openButton.setIconSize(QSize(60* SCALE, 60* SCALE))\n # self.openButton.clicked.connect(Form.open) \n\n self.fillButton = QtWidgets.QPushButton(Form)\n self.fillButton.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60* SCALE), 140* SCALE + 60* SCALE*2 + 10* SCALE*2, 60* SCALE, 60* SCALE))\n self.fillButton.setObjectName(\"fillButton\")\n self.fillButton.setIcon(QIcon('ui_run/icons/paint_can.png'))\n self.fillButton.setIconSize(QSize(60* SCALE, 60* SCALE))\n self.fillButton.clicked.connect(partial(Form.mode_select, 2))\n\n self.brushButton = QtWidgets.QPushButton(Form)\n self.brushButton.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60* SCALE), 140* SCALE + 60* SCALE*3 + 10* SCALE*3, 60* SCALE, 60* SCALE))\n self.brushButton.setObjectName(\"brushButton\")\n self.brushButton.setIcon(QIcon('ui_run/icons/paint_brush.png'))\n self.brushButton.setIconSize(QSize(60* SCALE, 60* SCALE))\n self.brushButton.setStyleSheet(\"background-color: #85adad\")\n #self.brushButton.setStyleSheet(\"background-color:\")\n self.brushButton.clicked.connect(partial(Form.mode_select, 0))\n\n self.recButton = QtWidgets.QPushButton(Form)\n self.recButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60* SCALE), 140* SCALE + 60* SCALE * 4 + 10* SCALE * 4, 60* SCALE, 60* SCALE))\n self.recButton.setObjectName(\"undolButton\")\n self.recButton.setIcon(QIcon('ui_run/icons/brush_square.png'))\n self.recButton.setIconSize(QSize(60* SCALE, 60* SCALE))\n self.recButton.clicked.connect(partial(Form.mode_select, 1))\n\n self.undoButton = QtWidgets.QPushButton(Form)\n self.undoButton.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60* SCALE), 140* SCALE + 60* SCALE*5 + 10* SCALE*5, 60* SCALE, 60* SCALE))\n self.undoButton.setObjectName(\"undolButton\")\n self.undoButton.setIcon(QIcon('ui_run/icons/undo.png'))\n self.undoButton.setIconSize(QSize(60* SCALE, 60* SCALE))\n self.undoButton.clicked.connect(Form.undo)\n\n # self.saveButton = QtWidgets.QPushButton(Form)\n # self.saveButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60* SCALE), 140* SCALE + 60* SCALE * 6 + 10* SCALE * 6, 60* SCALE, 60* SCALE))\n # self.saveButton.setObjectName(\"saveButton\")\n # self.saveButton.setIcon(QIcon('ui_run/icons/save.png'))\n # self.saveButton.setIconSize(QSize(60* SCALE, 60* SCALE))\n # self.saveButton.clicked.connect(Form.save_img)\n\n def add_style_imgs_buttons(self, Form): # 添加一个style图片的部分(右边的滚动框)\n\n self.scrollArea = QtWidgets.QScrollArea(Form)\n self.scrollArea.setGeometry(QtCore.QRect(int(1756* SCALE), int(140* SCALE), 140, 512))\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n\n self.scrollArea.setAlignment(Qt.AlignCenter)\n # self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n\n self.scrollAreaWidgetContents = QtWidgets.QWidget() # 一个父widget,用来存放滚动区域的小图片\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, int(140 * SCALE), int(512 * SCALE)))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n\n\n verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)\n verticalLayout.setContentsMargins(11, 11, 11, 11)\n verticalLayout.setSpacing(6)\n\n\n # img_path_list = glob.glob('imgs/style_imgs_test/*.jpg')\n img_path_list = glob.glob('ui_run/testset/CelebA-HQ/test/images/*.jpg')\n img_path_list.sort()\n\n # style_button = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n # style_button.setFixedSize(100, 100)\n # style_button.setIcon(QIcon('ui_run/icons/random.png'))\n # style_button.setIconSize(QSize(100, 100))\n # # style_button.clicked.connect(Form.load_partial_average_feature) # 随机加载一个特征,还没实现这个功能\n # verticalLayout.addWidget(style_button)\n\n for img_path in img_path_list:\n style_button = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n style_button.setFixedSize(100, 100)\n style_button.setIcon(QIcon(img_path))\n style_button.setIconSize(QSize(100, 100))\n style_button.clicked.connect(partial(Form.set_ref_img_path, img_path))\n verticalLayout.addWidget(style_button)\n\n\n verticalLayout.addWidget(style_button)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n\n def add_label_buttons(self, Form): # 12个 mask的 颜色按钮\n\n self.color_Button = QtWidgets.QPushButton(Form) # 当前选定的颜色\n self.color_Button.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), int(Lb_y), 60, 60))\n self.color_Button.setObjectName(\"labelButton_0\")\n self.color_Button.setStyleSheet(\"background-color: %s;\" % number_color[1]) # 默认为 idx = 1\n\n\n self.labelButton_0 = QtWidgets.QPushButton(Form)\n self.labelButton_0.setGeometry(QtCore.QRect(int(Lb_x), int(Lb_y), int(Lb_width), int(Lb_height)))\n self.labelButton_0.setObjectName(\"labelButton_0\")\n self.labelButton_0.setText(_translate(\"Form\", \"background\"))\n self.labelButton_0.setStyleSheet(\"background-color: %s;\" % number_color[0]+ \" color: black\")\n self.labelButton_0.clicked.connect(partial(Form.switch_labels, 0))\n\n\n\n self.labelButton_1 = QtWidgets.QPushButton(Form)\n self.labelButton_1.setGeometry(QtCore.QRect(Lb_x + 1*Lb_row_shift + 1*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_1.setObjectName(\"labelButton_1\")\n self.labelButton_1.setText(_translate(\"Form\", \"lip\"))\n self.labelButton_1.setStyleSheet(\"background-color: %s;\" % number_color[1] + \" color: black\")\n self.labelButton_1.clicked.connect(partial(Form.switch_labels, 1))\n\n\n self.labelButton_2 = QtWidgets.QPushButton(Form)\n self.labelButton_2.setGeometry(QtCore.QRect(Lb_x + 2*Lb_row_shift + 2*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_2.setObjectName(\"labelButton_2\")\n self.labelButton_2.setText(_translate(\"Form\", \"eyebrows\"))\n self.labelButton_2.setStyleSheet(\"background-color: %s;\" % number_color[2] + \" color: black\")\n self.labelButton_2.clicked.connect(partial(Form.switch_labels, 2))\n \n\n self.labelButton_3 = QtWidgets.QPushButton(Form)\n self.labelButton_3.setGeometry(QtCore.QRect(Lb_x + 3*Lb_row_shift + 3*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_3.setObjectName(\"labelButton_3\")\n self.labelButton_3.setText(_translate(\"Form\", \"eyes\"))\n self.labelButton_3.setStyleSheet(\"background-color: %s;\" % number_color[3] + \" color: black\")\n self.labelButton_3.clicked.connect(partial(Form.switch_labels, 3))\n\n\n self.labelButton_4 = QtWidgets.QPushButton(Form)\n self.labelButton_4.setGeometry(QtCore.QRect(Lb_x + 4*Lb_row_shift + 4*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_4.setObjectName(\"labelButton_4\")\n self.labelButton_4.setText(_translate(\"Form\", \"hair\"))\n self.labelButton_4.setStyleSheet(\"background-color: %s;\" % number_color[4] + \" color: black\")\n self.labelButton_4.clicked.connect(partial(Form.switch_labels, 4))\n\n\n self.labelButton_5 = QtWidgets.QPushButton(Form)\n self.labelButton_5.setGeometry(QtCore.QRect(Lb_x + 5*Lb_row_shift + 5*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_5.setObjectName(\"labelButton_5\")\n self.labelButton_5.setText(_translate(\"Form\", \"nose\"))\n self.labelButton_5.setStyleSheet(\"background-color: %s;\" % number_color[5] + \" color: black\")\n self.labelButton_5.clicked.connect(partial(Form.switch_labels, 5))\n\n\n self.labelButton_6 = QtWidgets.QPushButton(Form)\n self.labelButton_6.setGeometry(QtCore.QRect(Lb_x + 6*Lb_row_shift + 6*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_6.setObjectName(\"labelButton_6\")\n self.labelButton_6.setText(_translate(\"Form\", \"skin\"))\n self.labelButton_6.setStyleSheet(\"background-color: %s;\" % number_color[6] + \" color: black\")\n self.labelButton_6.clicked.connect(partial(Form.switch_labels, 6))\n\n\n self.labelButton_7 = QtWidgets.QPushButton(Form)\n self.labelButton_7.setGeometry(QtCore.QRect(Lb_x + 7*Lb_row_shift + 7*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_7.setObjectName(\"labelButton_7\")\n self.labelButton_7.setText(_translate(\"Form\", \"ears\"))\n self.labelButton_7.setStyleSheet(\"background-color: %s;\" % number_color[7] + \" color: black\")\n self.labelButton_7.clicked.connect(partial(Form.switch_labels, 7))\n\n\n self.labelButton_8 = QtWidgets.QPushButton(Form)\n self.labelButton_8.setGeometry(QtCore.QRect(Lb_x + 8*Lb_row_shift + 8*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_8.setObjectName(\"labelButton_8\")\n self.labelButton_8.setText(_translate(\"Form\", \"belowface\"))\n self.labelButton_8.setStyleSheet(\"background-color: %s;\" % number_color[8] + \" color: black\")\n self.labelButton_8.clicked.connect(partial(Form.switch_labels, 8))\n\n self.labelButton_9 = QtWidgets.QPushButton(Form)\n self.labelButton_9.setGeometry(QtCore.QRect(Lb_x + 9 * Lb_row_shift + 9 * Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_9.setObjectName(\"labelButton_9\")\n self.labelButton_9.setText(_translate(\"Form\", \"mouth\"))\n self.labelButton_9.setStyleSheet(\"background-color: %s;\" % number_color[9] + \" color: black\")\n self.labelButton_9.clicked.connect(partial(Form.switch_labels, 9))\n\n\n # Second Row\n self.labelButton_10 = QtWidgets.QPushButton(Form)\n self.labelButton_10.setGeometry(QtCore.QRect(Lb_x,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_10.setObjectName(\"labelButton_10\")\n self.labelButton_10.setText(_translate(\"Form\", \"eye_glass\"))\n self.labelButton_10.setStyleSheet(\"background-color: %s;\" % number_color[10] + \" color: black\")\n self.labelButton_10.clicked.connect(partial(Form.switch_labels, 10))\n\n\n self.labelButton_11 = QtWidgets.QPushButton(Form)\n self.labelButton_11.setGeometry(QtCore.QRect(Lb_x + 1*Lb_row_shift + 1*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_11.setObjectName(\"labelButton_11\")\n self.labelButton_11.setText(_translate(\"Form\", \"ear_rings\"))\n self.labelButton_11.setStyleSheet(\"background-color: %s;\" % number_color[11] + \" color: black\")\n self.labelButton_11.clicked.connect(partial(Form.switch_labels, 11))\n\n def add_label_buttons_seg19(self,Form): # 19个 mask的 颜色按钮\n self.color_Button = QtWidgets.QPushButton(Form) # 当前选定的颜色\n self.color_Button.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), Lb_y, 60, 60))\n self.color_Button.setObjectName(\"labelButton_0\")\n self.color_Button.setStyleSheet(\"background-color: %s;\" % number_color[1]) # 默认为 idx = 1\n\n\n self.labelButton_0 = QtWidgets.QPushButton(Form)\n self.labelButton_0.setGeometry(QtCore.QRect(Lb_x, Lb_y, Lb_width, Lb_height))\n self.labelButton_0.setObjectName(\"labelButton_0\")\n self.labelButton_0.setText(_translate(\"Form\", \"background\"))\n self.labelButton_0.setStyleSheet(\"background-color: %s;\" % number_color[0]+ \" color: black\")\n self.labelButton_0.clicked.connect(partial(Form.switch_labels, 0))\n\n\n self.labelButton_1 = QtWidgets.QPushButton(Form)\n self.labelButton_1.setGeometry(QtCore.QRect(Lb_x + 1*Lb_row_shift + 1*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_1.setObjectName(\"labelButton_1\")\n self.labelButton_1.setText(_translate(\"Form\", \"skin\"))\n self.labelButton_1.setStyleSheet(\"background-color: %s;\" % number_color[1] + \" color: black\")\n self.labelButton_1.clicked.connect(partial(Form.switch_labels, 1))\n\n\n self.labelButton_2 = QtWidgets.QPushButton(Form)\n self.labelButton_2.setGeometry(QtCore.QRect(Lb_x + 2*Lb_row_shift + 2*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_2.setObjectName(\"labelButton_2\")\n self.labelButton_2.setText(_translate(\"Form\", \"nose\"))\n self.labelButton_2.setStyleSheet(\"background-color: %s;\" % number_color[2] + \" color: black\")\n self.labelButton_2.clicked.connect(partial(Form.switch_labels, 2))\n \n\n self.labelButton_3 = QtWidgets.QPushButton(Form)\n self.labelButton_3.setGeometry(QtCore.QRect(Lb_x + 3*Lb_row_shift + 3*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_3.setObjectName(\"labelButton_3\")\n self.labelButton_3.setText(_translate(\"Form\", \"eye_g\"))\n self.labelButton_3.setStyleSheet(\"background-color: %s;\" % number_color[3] + \" color: black\")\n self.labelButton_3.clicked.connect(partial(Form.switch_labels, 3))\n\n\n self.labelButton_4 = QtWidgets.QPushButton(Form)\n self.labelButton_4.setGeometry(QtCore.QRect(Lb_x + 4*Lb_row_shift + 4*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_4.setObjectName(\"labelButton_4\")\n self.labelButton_4.setText(_translate(\"Form\", \"l_eye\"))\n self.labelButton_4.setStyleSheet(\"background-color: %s;\" % number_color[4] + \" color: black\")\n self.labelButton_4.clicked.connect(partial(Form.switch_labels, 4))\n\n\n self.labelButton_5 = QtWidgets.QPushButton(Form)\n self.labelButton_5.setGeometry(QtCore.QRect(Lb_x + 5*Lb_row_shift + 5*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_5.setObjectName(\"labelButton_5\")\n self.labelButton_5.setText(_translate(\"Form\", \"r_eye\"))\n self.labelButton_5.setStyleSheet(\"background-color: %s;\" % number_color[5] + \" color: black\")\n self.labelButton_5.clicked.connect(partial(Form.switch_labels, 5))\n\n\n self.labelButton_6 = QtWidgets.QPushButton(Form)\n self.labelButton_6.setGeometry(QtCore.QRect(Lb_x + 6*Lb_row_shift + 6*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_6.setObjectName(\"labelButton_6\")\n self.labelButton_6.setText(_translate(\"Form\", \"l_brow\"))\n self.labelButton_6.setStyleSheet(\"background-color: %s;\" % number_color[6] + \" color: black\")\n self.labelButton_6.clicked.connect(partial(Form.switch_labels, 6))\n\n\n self.labelButton_7 = QtWidgets.QPushButton(Form)\n self.labelButton_7.setGeometry(QtCore.QRect(Lb_x + 7*Lb_row_shift + 7*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_7.setObjectName(\"labelButton_7\")\n self.labelButton_7.setText(_translate(\"Form\", \"r_brow\"))\n self.labelButton_7.setStyleSheet(\"background-color: %s;\" % number_color[7] + \" color: black\")\n self.labelButton_7.clicked.connect(partial(Form.switch_labels, 7))\n\n\n self.labelButton_8 = QtWidgets.QPushButton(Form)\n self.labelButton_8.setGeometry(QtCore.QRect(Lb_x + 8*Lb_row_shift + 8*Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_8.setObjectName(\"labelButton_8\")\n self.labelButton_8.setText(_translate(\"Form\", \"l_ear\"))\n self.labelButton_8.setStyleSheet(\"background-color: %s;\" % number_color[8] + \" color: black\")\n self.labelButton_8.clicked.connect(partial(Form.switch_labels, 8))\n\n self.labelButton_9 = QtWidgets.QPushButton(Form)\n self.labelButton_9.setGeometry(QtCore.QRect(Lb_x + 9 * Lb_row_shift + 9 * Lb_width, Lb_y, Lb_width, Lb_height))\n self.labelButton_9.setObjectName(\"labelButton_9\")\n self.labelButton_9.setText(_translate(\"Form\", \"r_ear\"))\n self.labelButton_9.setStyleSheet(\"background-color: %s;\" % number_color[9] + \" color: black\")\n self.labelButton_9.clicked.connect(partial(Form.switch_labels, 9))\n\n\n # Second Row\n self.labelButton_10 = QtWidgets.QPushButton(Form)\n self.labelButton_10.setGeometry(QtCore.QRect(Lb_x,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_10.setObjectName(\"labelButton_10\")\n self.labelButton_10.setText(_translate(\"Form\", \"mouth\"))\n self.labelButton_10.setStyleSheet(\"background-color: %s;\" % number_color[10] + \" color: black\")\n self.labelButton_10.clicked.connect(partial(Form.switch_labels, 10))\n\n\n self.labelButton_11 = QtWidgets.QPushButton(Form)\n self.labelButton_11.setGeometry(QtCore.QRect(Lb_x + 1*Lb_row_shift + 1*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_11.setObjectName(\"labelButton_11\")\n self.labelButton_11.setText(_translate(\"Form\", \"u_lip\"))\n self.labelButton_11.setStyleSheet(\"background-color: %s;\" % number_color[11] + \" color: black\")\n self.labelButton_11.clicked.connect(partial(Form.switch_labels, 11))\n\n self.labelButton_12 = QtWidgets.QPushButton(Form)\n self.labelButton_12.setGeometry(QtCore.QRect(Lb_x + 2*Lb_row_shift + 2*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_12.setObjectName(\"labelButton_12\")\n self.labelButton_12.setText(_translate(\"Form\", \"l_lip\"))\n self.labelButton_12.setStyleSheet(\"background-color: %s;\" % number_color[12] + \" color: black\")\n self.labelButton_12.clicked.connect(partial(Form.switch_labels, 12))\n \n self.labelButton_13 = QtWidgets.QPushButton(Form)\n self.labelButton_13.setGeometry(QtCore.QRect(Lb_x + 3*Lb_row_shift + 3*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_13.setObjectName(\"labelButton_13\")\n self.labelButton_13.setText(_translate(\"Form\", \"hair\"))\n self.labelButton_13.setStyleSheet(\"background-color: %s;\" % number_color[13] + \" color: black\")\n self.labelButton_13.clicked.connect(partial(Form.switch_labels, 13))\n \n self.labelButton_14 = QtWidgets.QPushButton(Form)\n self.labelButton_14.setGeometry(QtCore.QRect(Lb_x + 4*Lb_row_shift + 4*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_14.setObjectName(\"labelButton_14\")\n self.labelButton_14.setText(_translate(\"Form\", \"hat\"))\n self.labelButton_14.setStyleSheet(\"background-color: %s;\" % number_color[14] + \" color: black\")\n self.labelButton_14.clicked.connect(partial(Form.switch_labels, 14))\n \n self.labelButton_15 = QtWidgets.QPushButton(Form)\n self.labelButton_15.setGeometry(QtCore.QRect(Lb_x + 5*Lb_row_shift + 5*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n \n self.labelButton_15.setObjectName(\"labelButton_15\")\n self.labelButton_15.setText(_translate(\"Form\", \"ear_r\"))\n self.labelButton_15.setStyleSheet(\"background-color: %s;\" % number_color[15] + \" color: black\")\n self.labelButton_15.clicked.connect(partial(Form.switch_labels, 15))\n\n\n self.labelButton_16 = QtWidgets.QPushButton(Form)\n self.labelButton_16.setGeometry(QtCore.QRect(Lb_x + 6*Lb_row_shift + 6*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_16.setObjectName(\"labelButton_16\")\n self.labelButton_16.setText(_translate(\"Form\", \"neck_l\"))\n self.labelButton_16.setStyleSheet(\"background-color: %s;\" % number_color[16] + \" color: black\")\n self.labelButton_16.clicked.connect(partial(Form.switch_labels, 16))\n\n self.labelButton_17 = QtWidgets.QPushButton(Form)\n self.labelButton_17.setGeometry(QtCore.QRect(Lb_x + 7*Lb_row_shift + 7*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_17.setObjectName(\"labelButton_17\")\n self.labelButton_17.setText(_translate(\"Form\", \"neck\"))\n self.labelButton_17.setStyleSheet(\"background-color: %s;\" % number_color[17] + \" color: black\")\n self.labelButton_17.clicked.connect(partial(Form.switch_labels, 17))\n\n self.labelButton_18 = QtWidgets.QPushButton(Form)\n self.labelButton_18.setGeometry(QtCore.QRect(Lb_x + 8*Lb_row_shift + 8*Lb_width,\n Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))\n self.labelButton_18.setObjectName(\"labelButton_18\")\n self.labelButton_18.setText(_translate(\"Form\", \"cloth\"))\n self.labelButton_18.setStyleSheet(\"background-color: %s;\" % number_color[18] + \" color: black\")\n self.labelButton_18.clicked.connect(partial(Form.switch_labels, 18))\n\n\n def add_ops_log_textBox(self,Form): # 操作日志框\n\n self.opsLogLabel = QtWidgets.QLabel(Form)\n self.opsLogLabel.setObjectName(\"opsLogLabel\")\n self.opsLogLabel.setGeometry(QtCore.QRect(Lb_x + 10*SCALE * Lb_row_shift + 10*SCALE * Lb_width + 40*SCALE, Lb_y + 50, 150*SCALE, 20*SCALE))\n self.opsLogLabel.setText('Logging ')\n font = self.brushsizeLabel.font()\n font.setPointSize(10)\n font.setBold(True)\n self.opsLogLabel.setFont(font)\n\n self.opsLogTextBox = QtWidgets.QPlainTextEdit(Form)\n self.opsLogTextBox.setReadOnly(True)\n self.opsLogTextBox.setObjectName(\"opsLogTextBox\")\n self.opsLogTextBox.setGeometry(QtCore.QRect(Lb_x + 10*SCALE * Lb_row_shift + 10 *SCALE* Lb_width + 150*SCALE, Lb_y+35, 225*SCALE, 40*SCALE))\n \n def add_ref_img_button(self, Form): # 右下角当前reference 的图片\n self.ref_img_button = QtWidgets.QPushButton(Form)\n self.ref_img_button.setGeometry(QtCore.QRect(1770*SCALE , 800*SCALE, 100*SCALE, 100*SCALE))\n self.ref_img_button.setStyleSheet(\"background-color: transparent\")\n self.ref_img_button.setFixedSize(100, 100)\n self.ref_img_button.setIcon(QIcon(None))\n self.ref_img_button.setIconSize(QSize(100, 100))\n \n\n def cb_event(self, id, ifchecked):\n\n if id.text() == 'ALL':\n if ifchecked:\n for cb in self.checkBoxGroup.buttons():\n cb.setChecked(True)\n else:\n for cb in self.checkBoxGroup.buttons():\n cb.setChecked(False)\n self.change_cb_state()\n\n def change_cb_state(self):\n checkbox_status = [cb.isChecked() for cb in self.checkBoxGroup.buttons()]\n checkbox_status = checkbox_status[:len(my_number_object)]\n #self.obj_dic_back = copy.deepcopy(self.obj_dic)\n self.checkbox_status = checkbox_status" }, { "identifier": "GraphicsScene", "path": "ui_run/mouse_event.py", "snippet": "class GraphicsScene(QGraphicsScene):\n def __init__(self, modes, Form):\n QGraphicsScene.__init__(self)\n self.modes = modes\n self.mouse_clicked = False\n self.prev_pt = None\n self.history_list = []\n\n # brush color\n self.color = '#cc0000'\n self.label = 1\n self.brush_size = 6\n self.Form = Form\n\n\n def reset(self):\n self.prev_pt = None\n\n self.history_list = []\n\n\n def reset_items(self):\n for i in range(len(self.items())):\n item = self.items()[0]\n self.removeItem(item)\n\n\n\n def mousePressEvent(self, event):\n self.mouse_clicked = True\n\n if self.modes == 1:\n self.rec_top_left = event.scenePos()\n self.old_recItem = None\n\n elif self.modes == 2:\n\n img_current_point = (int(event.scenePos().y()), int(event.scenePos().x())) # label map的当前位置 (y,x)格式,即(行,列)\n scene_current_point= (int(event.scenePos().x()), int(event.scenePos().y())) # scene 的当前位置(x,y)格式\n\n current_color_label = self.Form.mat_img[img_current_point][0]\n thresh = np.uint8(self.Form.mat_img[:, :, 0] == current_color_label) * 255\n cnts = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n Contours_num = None\n\n for i in range(len(cnts[0])):\n whether_in_shape = cv2.pointPolygonTest(cnts[0][i], scene_current_point, False) # 判断一个点是否在多边形内,返回-1表示在外部,1表示在内部,0表示在多边形上\n if whether_in_shape == 1:\n Contours_num = i\n break\n\n if Contours_num != None:\n qpoints = [QPointF(pt[0][0], pt[0,1]) for pt in cnts[0][Contours_num]]\n PolygonItem = QGraphicsPolygonItem(QPolygonF(qpoints)) # 画多边形\n PolygonItem.setBrush(QBrush(QColor(self.color)))\n PolygonItem.setPen(QPen(QColor(self.color), 2, Qt.SolidLine))\n\n self.addItem(PolygonItem)\n\n\n fill = {}\n fill['contours'] = cnts[0]\n fill['contours_num'] = Contours_num\n fill['label'] = self.label\n fill['shape'] = 'Fill'\n\n\n self.history_list.append(fill)\n self.convert_fill(fill)\n # self.Form.run_deep_model()\n\n\n\n\n def mouseReleaseEvent(self, event):\n self.prev_pt = None\n self.mouse_clicked = False\n\n if self.modes == 1:\n self.old_recItem = None\n\n\n\n def mouseMoveEvent(self, event):\n if self.mouse_clicked:\n # print(event.scenePos())\n if self.modes == 0:\n if self.prev_pt:\n self.drawStroke(self.prev_pt, event.scenePos())\n self.prev_pt = event.scenePos()\n\n else:\n self.prev_pt = event.scenePos()\n\n if self.modes == 1:\n self.drawRec(self.rec_top_left, event.scenePos())\n\n\n elif self.modes == 2:\n print('do nothing')\n\n\n\n\n def drawStroke(self, prev_pt, curr_pt):\n lineItem = QGraphicsLineItem(QLineF(prev_pt, curr_pt))\n lineItem.setPen(QPen(QColor(self.color), self.brush_size, Qt.SolidLine, cap=Qt.RoundCap, join=Qt.RoundJoin)) # rect\n self.addItem(lineItem)\n\n stroke = {}\n stroke['prev'] = (int(prev_pt.x()), int(prev_pt.y()))\n stroke['curr'] = (int(curr_pt.x()), int(curr_pt.y()))\n stroke['label'] = self.label\n stroke['brush_size'] = self.brush_size\n stroke['shape'] = 'Stroke'\n self.history_list.append(stroke)\n self.convert_stroke(stroke)\n # self.Form.run_deep_model()\n\n def drawRec(self, prev_pt, curr_pt):\n\n top_left = (int(min(prev_pt.x(), curr_pt.x())), int(min(prev_pt.y(), curr_pt.y())))\n bottom_right = (int(max(prev_pt.x(), curr_pt.x())), int(max(prev_pt.y(), curr_pt.y())))\n\n recItem = QGraphicsRectItem(QRectF(QPointF(top_left[0], top_left[1]), QPointF(bottom_right[0], bottom_right[1])))\n recItem.setBrush(QBrush(QColor(self.color)))\n recItem.setPen(QPen(Qt.NoPen))\n\n self.addItem(recItem)\n\n if self.old_recItem == None:\n self.old_recItem = recItem\n self.old_rec_mat_img = self.Form.mat_img.copy()\n else:\n self.removeItem(self.old_recItem)\n self.old_recItem = recItem\n self.history_list.pop()\n\n rec = {}\n\n\n rec['prev'] = top_left\n rec['curr'] = bottom_right\n\n rec['label'] = self.label\n rec['brush_size'] = None\n rec['shape'] = 'Rec'\n\n self.history_list.append(rec)\n\n self.Form.mat_img = self.old_rec_mat_img.copy()\n self.convert_rec(rec)\n # self.Form.run_deep_model()\n\n\n\n\n def convert_stroke(self, stroke_point):\n if len(stroke_point) == 5:\n color = stroke_point['label']\n cv2.line(self.Form.mat_img, stroke_point['prev'], stroke_point['curr'], (color, color, color), stroke_point['brush_size'])\n else:\n print(\"wrong stroke\")\n\n\n def convert_rec(self, rectangle):\n if len(rectangle) == 5:\n color = rectangle['label']\n cv2.rectangle(self.Form.mat_img, rectangle['prev'], rectangle['curr'], (color, color, color), -1)\n else:\n print(\"wrong rectangle\")\n\n def convert_fill(self, fill):\n if len(fill) == 4:\n color = fill['label']\n cv2.drawContours(self.Form.mat_img, fill['contours'], fill['contours_num'],(color, color, color), -1) # 填充轮廓多边形\n else:\n print(\"wrong fill\")\n\n\n\n\n def undo(self):\n if len(self.items())>1:\n\n if self.history_list[-1]['shape'] == 'Rec':\n item = self.items()[0]\n self.removeItem(item)\n self.history_list.pop()\n\n elif self.history_list[-1]['shape'] == 'Stroke':\n if len(self.items())>=6:\n for i in range(6):\n item = self.items()[0]\n self.removeItem(item)\n self.history_list.pop()\n else:\n for i in range(len(self.items())-1):\n item = self.items()[0]\n self.removeItem(item)\n self.history_list.pop()\n elif self.history_list[-1]['shape'] == 'Fill':\n item = self.items()[0]\n self.removeItem(item)\n self.history_list.pop()\n\n self.Form.mat_img = self.Form.mat_img_org.copy()\n for pts in self.history_list:\n if pts['shape'] == 'Stroke':\n self.convert_stroke(pts)\n elif pts['shape'] == 'Rec':\n self.convert_rec(pts)\n elif pts['shape'] == 'Fill':\n self.convert_fill(pts)\n # self.Form.run_deep_model()" }, { "identifier": "number_color", "path": "ui_run/util.py", "snippet": "def color_pred(pred):\ndef celebAHQ_masks_to_faceParser_mask_detailed(celebA_mask):\nCOMPS = ['background', 'lip', 'eyebrows', 'eyes', 'hair', 'nose', 'skin', 'ears', 'belowface','mouth','eye_glass','ear_rings']" }, { "identifier": "Net3", "path": "models/networks.py", "snippet": "class Net3(nn.Module):\n \"\"\" FSEncoder + styleGAN2 \"\"\"\n\n def __init__(self,opts,):\n super(Net3, self).__init__()\n self.opts=opts\n assert self.opts.fsencoder_type in [\"psp\",\"sean\"]\n if self.opts.fsencoder_type==\"psp\":\n self.encoder = FSEncoder_PSP(mode='ir_se', opts=self.opts)\n dim_s_code = 256 + 512 + 512\n else:\n self.encoder = FSEncoder_SEAN(input_nc=3, output_nc=512,in_size = 256)\n dim_s_code = 512\n \n self.split_layer_idx = 5\n self.remaining_layer_idx = self.opts.remaining_layer_idx\n \n # 区分component 的 W+ space 的 MLPs\n self.MLPs = nn.ModuleList()\n for i in range(self.opts.num_seg_cls):\n self.MLPs.append(\n LocalMLP(\n dim_component=dim_s_code,\n dim_style=512,\n num_w_layers= self.remaining_layer_idx if self.remaining_layer_idx != 17 else 18\n )\n )\n \n self.G = Generator(size=self.opts.out_size, style_dim=512, n_mlp=8, split_layer_idx = self.split_layer_idx, remaining_layer_idx = self.remaining_layer_idx)\n\n # styleGAN的参数是否更新\n if not self.opts.train_G:\n for param in self.G.parameters():\n param.requires_grad = False\n # 注意,styleGAN的8层FC是永远不更新的\n else:\n for param in self.G.style.parameters():\n param.requires_grad = False\n \n # styleGAN的倒数几层不更新 (包括convs 和 ToRGBs)\n if self.remaining_layer_idx != 17:\n for param in self.G.convs[-(17-self.remaining_layer_idx):].parameters():\n param.requires_grad = False\n for param in self.G.to_rgbs[-(17-self.remaining_layer_idx)//2 - 1:].parameters():\n param.requires_grad = False\n \n \n def forward(self, img,mask, resize=False, randomize_noise=True,return_latents=False):\n \"\"\"输入一张RGB图和对应的mask,\n (1) encoder 得到对应的F/S空间的特征,\n (2) 再送到styleGAN得到一张输出的图片\n\n Args:\n img (Tensor): 一对RGB图, each with shape [bs,3,1024,1024]\n mask ([type]): 一对RGB图对应的mask图, each with shape [bs,#seg_cls,1024,1024]\n resize (bool, optional): G生成的图片是否 resize. Defaults to True.\n randomize_noise (bool, optional): 是否加入随机噪声. Defaults to True.\n return_latents (bool, optional): 是否返回style codes. Defaults to False.\n\n Returns:\n [type]: [description]\n \"\"\"\n if self.opts.fsencoder_type==\"psp\":\n codes_vector, structure_feats = self.encoder(F.interpolate(img,(256,256),mode='bilinear'), mask) # [bs,#seg_cls, D], [bs,C,32,32]\n else:\n codes_vector, structure_feats = self.encoder(F.interpolate(img,(256,256),mode='bilinear'), mask) # [bs,#seg_cls, D], [bs,C,32,32]\n codes=[]\n bs, num_comp = codes_vector.size(0), codes_vector.size(1)\n for i in range(num_comp):\n codes.append(self.MLPs[i](codes_vector[:,i,:])) \n codes=torch.stack(codes,dim=1) # [bs, #seg_cls, 13, 512]\n \n \n # # 剩下的几层不用分component\n # remaining_codes=[]\n # for i in range(len(self.remain_MLPs)):\n # remaining_codes.append(self.remain_MLPs[i](codes_vector.view(bs, -1)))\n # remaining_codes = torch.stack(remaining_codes,dim=1) # [bs,5,512]\n\n # normalize with respect to the center of an average face\n if self.opts.start_from_latent_avg:\n if self.opts.learn_in_w:\n # 为了保持接口统一,将后3层的 style code 也扩展出一个 #seg_cls 维度\n codes = codes + self.latent_avg[:self.remaining_layer_idx, :].repeat(codes.shape[0],codes.shape[1],1)\n remaining_codes = self.latent_avg[self.remaining_layer_idx:, :].repeat(bs, num_comp, 1) \n codes = torch.cat([codes, remaining_codes],dim=2)\n else:\n if self.remaining_layer_idx != 17:\n codes = codes + self.latent_avg[:self.remaining_layer_idx, :].repeat(codes.shape[0],codes.shape[1],1, 1)\n remaining_codes = self.latent_avg[self.remaining_layer_idx:, :].repeat(bs, num_comp, 1, 1) \n codes = torch.cat([codes, remaining_codes],dim=2)\n else:\n codes = codes + self.latent_avg.repeat(codes.shape[0],codes.shape[1],1, 1)\n \n # 1. 完全使用 style code i.e., G(w)\n images1, result_latent, structure_feats_GT = self.G([codes], structure_feats, mask, input_is_latent=True,\n randomize_noise=randomize_noise,return_latents=return_latents,\n use_structure_code=False)\n \n \n # # 2. 使用 style code 和 strcture code i.e., G(w,F)\n # images2, _ , _ = self.G([codes], structure_feats, mask, input_is_latent=True,\n # randomize_noise=randomize_noise,return_latents=return_latents,\n # use_structure_code=True)\n \n if return_latents:\n return images1, structure_feats_GT, result_latent\n else:\n return images1, structure_feats_GT\n\n def get_style(self, img, mask):\n \"\"\"输入一张RGB图和对应的mask, 得到各个component 对应的style codes\n \n Args:\n img (Tensor): RGB图, each with shape [bs,3,1024,1024]\n mask (Tensor): RGB图对应的mask图, each with shape [bs,#seg_cls,1024,1024]\n \n Returns:\n structure_feats(Tensor): 图片的structure code, with shape [bs,512,32,32], 注意,这里其实是相对于StyleGAN第层输出的残差\n all_codes(Tensor): 各个component 对应的style codes, with shape [bs,#comp,18,512]。\n !!! 注意,前7层的各个compnent其实没有意义,只是为了统一接口让shape保持一致,用的时候只用第1个即可 !!!\n \"\"\"\n if self.opts.fsencoder_type==\"psp\":\n codes_vector, structure_feats = self.encoder(F.interpolate(img,(256,256),mode='bilinear'), mask) # [bs,#seg_cls, D], [bs,C,32,32]\n else:\n codes_vector, structure_feats = self.encoder(F.interpolate(img,(256,256),mode='bilinear'), mask) # [bs,#seg_cls, D], [bs,C,32,32]\n codes=[]\n bs, num_comp = codes_vector.size(0), codes_vector.size(1)\n for i in range(num_comp):\n codes.append(self.MLPs[i](codes_vector[:,i,:])) \n codes=torch.stack(codes,dim=1) # [bs, #seg_cls, 11,512]\n\n # # 剩下的几层不用分component\n # remaining_codes=[]\n # for i in range(len(self.remain_MLPs)):\n # remaining_codes.append(self.remain_MLPs[i](codes_vector.view(bs, -1)))\n # remaining_codes = torch.stack(remaining_codes,dim=1) # [bs,5,512]\n\n # normalize with respect to the center of an average face\n if self.opts.start_from_latent_avg:\n if self.opts.learn_in_w:\n # 为了保持接口统一,将后3层的 style code 也扩展出一个 #seg_cls 维度\n codes = codes + self.latent_avg[:self.remaining_layer_idx, :].repeat(codes.shape[0],codes.shape[1],1)\n remaining_codes = self.latent_avg[self.remaining_layer_idx:, :].repeat(bs, num_comp, 1) \n style_codes = torch.cat([codes, remaining_codes],dim=2)\n else:\n if self.remaining_layer_idx != 17:\n codes = codes + self.latent_avg[:self.remaining_layer_idx, :].repeat(codes.shape[0],codes.shape[1],1, 1)\n remaining_codes = self.latent_avg[self.remaining_layer_idx:, :].repeat(bs, num_comp, 1, 1) \n style_codes = torch.cat([codes, remaining_codes],dim=2)\n else:\n style_codes = codes + self.latent_avg.repeat(codes.shape[0],codes.shape[1],1, 1)\n \n return structure_feats, style_codes\n\n def get_style_vectors(self, img, mask):\n \"\"\"输入一张RGB图和对应的mask, 得到各个component 对应的style vectors\n \n Args:\n img (Tensor): RGB图, each with shape [bs,3,1024,1024]\n mask (Tensor): RGB图对应的mask图, each with shape [bs,#seg_cls,1024,1024]\n \n Returns:\n style_vectors(Tensor): with shape [bs,#seg_cls,512]\n \"\"\"\n if self.opts.fsencoder_type==\"psp\":\n style_vectors, structure_feats = self.encoder(F.interpolate(img,(256,256),mode='bilinear'), mask) # [bs,#seg_cls, D], [bs,C,32,32]\n else:\n style_vectors, structure_feats = self.encoder(F.interpolate(img,(256,256),mode='bilinear'), mask) # [bs,#seg_cls, D], [bs,C,32,32]\n \n return style_vectors, structure_feats\n \n def cal_style_codes(self,style_vectors):\n \"\"\"根据每个compnent的 style vector转到styleGAN的style code\"\"\"\n \n codes=[]\n bs, num_comp = style_vectors.size(0), style_vectors.size(1)\n for i in range(num_comp):\n codes.append(self.MLPs[i](style_vectors[:,i,:])) \n codes=torch.stack(codes,dim=1) # [bs, #seg_cls, 11,512]\n\n # # 剩下的几层不用分component\n # remaining_codes=[]\n # for i in range(len(self.remain_MLPs)):\n # remaining_codes.append(self.remain_MLPs[i](style_vectors.view(bs, -1)))\n # remaining_codes = torch.stack(remaining_codes,dim=1) # [bs,5,512]\n\n # normalize with respect to the center of an average face\n if self.opts.start_from_latent_avg:\n if self.opts.learn_in_w:\n # 为了保持接口统一,将后3层的 style code 也扩展出一个 #seg_cls 维度\n codes = codes + self.latent_avg[:self.remaining_layer_idx, :].repeat(codes.shape[0],codes.shape[1],1)\n remaining_codes = self.latent_avg[self.remaining_layer_idx:, :].repeat(bs, num_comp, 1) \n style_codes = torch.cat([codes, remaining_codes],dim=2)\n else:\n if self.remaining_layer_idx != 17:\n codes = codes + self.latent_avg[:self.remaining_layer_idx, :].repeat(codes.shape[0],codes.shape[1],1, 1)\n remaining_codes = self.latent_avg[self.remaining_layer_idx:, :].repeat(bs, num_comp, 1, 1) \n style_codes = torch.cat([codes, remaining_codes],dim=2)\n else:\n style_codes = codes + self.latent_avg.repeat(codes.shape[0],codes.shape[1],1, 1)\n \n return style_codes\n\n def gen_img(self, struc_codes, style_codes, mask, randomize_noise=True, noise=None, return_latents=False):\n \"\"\"输入一张mask 和 对应各components的style codes,以及这张图片的structure code, 生成一张图片\n \n Args:\n style_codes (Tensor): 各个component 对应的style codes, with shape [bs,#comp,18,512]\n struc_codes (Tensor)\n mask (Tensor): mask图, with shape [bs,#seg_cls,1024,1024]\n \n randomize_noise (bool, optional): 是否加入随机噪声. Defaults to True.\n return_latents (bool, optional): 是否返回style codes. Defaults to False.\n\n Returns:\n [type]: [description]\n \"\"\"\n \n images, result_latent, structure_feats = self.G([style_codes], struc_codes, mask, input_is_latent=True,\n randomize_noise=randomize_noise,noise=noise,return_latents=return_latents,\n use_structure_code=False)\n\n if return_latents:\n return images, result_latent, structure_feats\n else:\n return images,-1, structure_feats" }, { "identifier": "torch_utils", "path": "utils/torch_utils.py", "snippet": "def saveTensorToFile(tensor, save_path):\ndef interpolate(img, size):\ndef readImgAsTensor(img_path, gray=False, to_tensor=True, size=1024):\ndef featMap2im(var):\ndef tensor2im(var, is_zero_center: bool = True, ):\ndef im2tensor(var, add_c_dim: bool = False, norm: bool = True, std: bool = False):\ndef tensor2map(var,shown_mask_indices=None):\ndef vis_mask_in_color(mask):\ndef get_colors():\ndef vis_faces(log_hooks1):\ndef vis_faces_no_id(hooks_dict1, fig, gs, i):\ndef aggregate_loss_dict(agg_loss_dict):\ndef labelMap2OneHot(label, num_cls):\ndef remove_module_prefix(state_dict,prefix):\ndef requires_grad(model, flag=True):\ndef accumulate(model1, model2, decay=0.999):\n C, H, W = tensor.size()" }, { "identifier": "CelebAHQDataset", "path": "datasets/dataset.py", "snippet": "class CelebAHQDataset(Dataset):\n \"\"\"\n CelebA-HQ数据集,具体数据来自于 https://github.com/ZPdesu/SEAN\n \"\"\"\n def __init__(self, dataset_root, mode=\"test\",\n img_transform=TO_TENSOR, label_transform=TO_TENSOR,\n load_vis_img=False, fraction=1.0,\n flip_p=-1, # negative means not flipping\n specific_ids: Union[list, tuple] = None,\n paired: bool = False,\n shuffle: bool = False,\n ):\n assert mode in (\"train\", \"test\", \"all\"), \"CelebAHQDataset mode type unsupported!\"\n self.mode = mode\n if mode in (\"all\",):\n self.roots = [osp.join(dataset_root, \"train\"), osp.join(dataset_root, \"test\")]\n else:\n self.roots = [osp.join(dataset_root, self.mode)]\n self.img_transform = img_transform\n self.label_transform = label_transform\n self.load_vis_img = load_vis_img\n self.fraction = fraction\n self.flip_p = flip_p\n self.paired = paired\n\n self.imgs = []\n self.labels = []\n self.labels_vis = []\n for root in self.roots:\n imgs = sorted(make_dataset(osp.join(root, \"images\")))\n imgs = imgs[:int(len(imgs)*self.fraction)]\n\n labels = sorted(make_dataset(osp.join(root, \"labels\")))\n labels = labels[:int(len(labels)*self.fraction)]\n\n labels_vis = sorted(make_dataset(osp.join(root, \"vis\"))) if self.load_vis_img else None\n labels_vis = labels_vis[:int(len(labels_vis)*self.fraction)] if self.load_vis_img else []\n\n self.imgs.extend(imgs)\n self.labels.extend(labels)\n self.labels_vis.extend(labels_vis)\n\n self.imgs, self.labels, self.labels_vis = self._filter_specific_ids(specific_ids)\n\n if self.load_vis_img:\n assert len(self.imgs) == len(self.labels) == len(self.labels_vis)\n else:\n assert len(self.imgs) == len(self.labels)\n\n print(f\"[CelebAHQDataset] files loaded. mode={self.mode}, #imgs={len(self.imgs)}, \"\n f\"#labels={len(self.labels)}, #vis={len(self.labels_vis)}\")\n\n # # 优化 600 个iteration 的style code保存路径\n # self.optim_codes_dir = \"/apdcephfs/share_1290939/zhianliu/py_projects/pytorch-DDP-demo/work_dirs/v0_8_stage2_entypeSEAN/optim_Results\"\n \n # image pairs indices\n self.indices = np.arange(len(self.imgs))\n\n # TODO: shuffle the indices\n if shuffle:\n np.random.shuffle(self.indices)\n\n self.pair_indices = self.indices.reshape(-1, 2)\n\n def __len__(self):\n if not self.paired:\n return len(self.indices)\n else:\n return len(self.pair_indices)\n\n def _filter_specific_ids(self, specific_ids: tuple):\n \"\"\" filter the images according to the specific_ids\n \"\"\"\n if specific_ids is None:\n return self.imgs, self.labels, self.labels_vis\n elif self.fraction < 1.0:\n raise ValueError(\"[CelebAHQDataset] specific_ids and fraction cannot be set simultaneously!\")\n\n # parse the tuple into two lists, e.g. ((\"train\",\"12\"), (\"test\",\"45\")) -> (\"train\",\"train\") and (\"12\",\"45\")\n spec_modes, spec_ids = [], []\n id_order_dict = {}\n for idx, spec_id in enumerate(specific_ids):\n one_mode, one_id = spec_id[0], spec_id[1]\n spec_modes.append(one_mode)\n spec_ids.append(one_id)\n id_order_dict[one_id] = {\n \"mode\": one_mode, \"order\": idx,\n }\n\n # filter and re-order\n ret_imgs = [\"\"] * len(specific_ids)\n ret_labels = [\"\"] * len(specific_ids)\n ret_labels_vis = [\"\"] * len(specific_ids)\n found_cnt = 0\n for k in range(len(spec_ids)): # target specific ids\n one_spec_mode = spec_modes[k]\n one_spec_id = spec_ids[k]\n for idx in range(len(self.imgs)): # full dataset\n one_img = self.imgs[idx]\n one_label = self.labels[idx]\n one_label_vis = self.labels_vis[idx] if self.load_vis_img else None\n if one_spec_mode in one_img and one_spec_id == osp.basename(one_img): # found one\n found_cnt += 1\n one_spec_order = id_order_dict[one_spec_id][\"order\"]\n ret_imgs[one_spec_order] = one_img\n ret_labels[one_spec_order] = one_label\n ret_labels_vis[one_spec_order] = one_label_vis\n break\n\n if found_cnt < len(specific_ids):\n print(f\"[[Warning]][CelebAHQDataset] not enough images found (={found_cnt}) for \"\n f\"specific ids (={len(specific_ids)})!\")\n\n ret_imgs = list(filter(None, ret_imgs))\n ret_labels = list(filter(None, ret_labels))\n ret_labels_vis = list(filter(None, ret_labels_vis))\n return ret_imgs, ret_labels, ret_labels_vis\n\n def load_single_image(self, index):\n \"\"\"把一张图片的 原图, seg mask, 以及mask对应可视化的图都加载进来\n Args:\n index (int): 图片的索引\n Return:\n img: RGB图\n label: seg mask\n label_vis: seg mask的可视化图\n \"\"\"\n img_path = self.imgs[index]\n img = Image.open(img_path).convert('RGB')\n if self.img_transform is not None:\n img = self.img_transform(img)\n\n label = self.labels[index]\n # label = osp.join(\"/apdcephfs/share_1290939/zhianliu/py_projects/our_editing/ui_results\",\"%s_mask.png\"%osp.basename(label)[:-4])\n label = Image.open(label).convert('L')\n if self.label_transform is not None:\n label = self.label_transform(label)\n\n if self.load_vis_img:\n label_vis = self.labels_vis[index]\n label_vis = Image.open(label_vis).convert('RGB')\n label_vis = TO_TENSOR(label_vis)\n else:\n label_vis = -1 # unified interface\n return img, label, label_vis, img_path\n\n def _output_item(self, idx):\n if not self.paired:\n index = self.indices[idx]\n img, label, label_vis, img_path = self.load_single_image(index)\n if self.flip_p > 0:\n if random.random() < self.flip_p:\n img = TF.hflip(img)\n label = TF.hflip(label)\n return img, label, label_vis, img_path\n else:\n index1 = self.indices[idx * 2]\n index2 = self.indices[idx * 2 + 1]\n img1, label1, label_vis1, img_path1 = self.load_single_image(index1)\n img2, label2, label_vis2, img_path2 = self.load_single_image(index2)\n if self.flip_p > 0:\n if random.random() < self.flip_p:\n img1 = TF.hflip(img1)\n label1 = TF.hflip(label1)\n if random.random() < self.flip_p:\n img2 = TF.hflip(img2)\n label2 = TF.hflip(label2)\n return {\n \"bag1\": (img1, label1, label_vis1, img_path1),\n \"bag2\": (img2, label2, label_vis2, img_path2)\n }\n\n def __getitem__(self, idx):\n return self._output_item(idx)\n \n # # 1阶段重建的图片\n # img_name = osp.basename(self.imgs[index])[:-4]\n # recon_img = Image.open(osp.join(self.optim_codes_dir,img_name,\"%s_recon.png\"%img_name)).convert('RGB')\n # if self.img_transform is not None:\n # recon_img = self.img_transform(recon_img)\n \n # # 优化后的code\n # optim_code_path = osp.join(self.optim_codes_dir,img_name,\"%s_0600.npy\"%img_name)\n # assert osp.exists(optim_code_path), \"%s 文件不存在!\"%optim_code_path\n # optimed_style_code = np.load(optim_code_path)[0]\n \n # return img, recon_img, optimed_style_code, label, label_vis\n \n # pair_indices = self.pair_indices[idx, :]\n\n # img1, label1, label_vis1 = self.load_single_image(pair_indices[0])\n # img2, label2, label_vis2 = self.load_single_image(pair_indices[1])\n\n # return (img1, img2), (label1, label2), (label_vis1, label_vis2)" }, { "identifier": "get_transforms", "path": "datasets/dataset.py", "snippet": "def get_transforms(normalize=True, toTensor=True):\n transform_list = []\n if toTensor:\n transform_list += [transforms.ToTensor()]\n\n if normalize:\n transform_list += [transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))]\n return transforms.Compose(transform_list)" }, { "identifier": "TO_TENSOR", "path": "datasets/dataset.py", "snippet": "TO_TENSOR = transforms.ToTensor()" }, { "identifier": "NORMALIZE", "path": "datasets/dataset.py", "snippet": "NORMALIZE = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))" } ]
from options.ui_options import UIOptions from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtPrintSupport import QPrintDialog, QPrinter from ui_run.ui import Ui_Form from ui_run.mouse_event import GraphicsScene from ui_run.util import number_color, color_pred,celebAHQ_masks_to_faceParser_mask_detailed, my_number_object, COMPS from PIL import Image from PyQt5 import QtGui from models.networks import Net3 from glob import glob from utils import torch_utils from datasets.dataset import CelebAHQDataset, get_transforms, TO_TENSOR, NORMALIZE import sys import cv2 import skimage.io import qdarkstyle import qdarkgraystyle import os import numpy as np import skimage.io import os import torch import copy import torchvision.transforms as transforms
18,155
class ExWindow(QMainWindow): def __init__(self, opt): super().__init__() self.EX = Ex(opt) self.setWindowIcon(QtGui.QIcon('ui_run/icons/edit_icon.svg')) class Ex(QWidget, Ui_Form): @pyqtSlot() def change_brush_size(self): # 改变画刷的 粗细 self.scene.brush_size = self.brushSlider.value() self.brushsizeLabel.setText('Brush size: %d' % self.scene.brush_size) @pyqtSlot() def change_alpha_value(self): self.alpha = self.alphaSlider.value() / 20 self.alphaLabel.setText('Alpha: %.2f' % self.alpha) @pyqtSlot() def switch_labels(self, label): # 换了一种label颜色按钮 self.scene.label = label self.scene.color = number_color[label] self.color_Button.setStyleSheet("background-color: %s;" % self.scene.color) @pyqtSlot() def undo(self): self.scene.undo() def __init__(self, opt): super().__init__() self.init_deep_model(opt) self.setupUi(self) self.show() # 下面都是一些默认值 self.modes = 0 self.alpha = 1 # 插值的alpha self.ref_style_img_path = None self.mouse_clicked = False
class ExWindow(QMainWindow): def __init__(self, opt): super().__init__() self.EX = Ex(opt) self.setWindowIcon(QtGui.QIcon('ui_run/icons/edit_icon.svg')) class Ex(QWidget, Ui_Form): @pyqtSlot() def change_brush_size(self): # 改变画刷的 粗细 self.scene.brush_size = self.brushSlider.value() self.brushsizeLabel.setText('Brush size: %d' % self.scene.brush_size) @pyqtSlot() def change_alpha_value(self): self.alpha = self.alphaSlider.value() / 20 self.alphaLabel.setText('Alpha: %.2f' % self.alpha) @pyqtSlot() def switch_labels(self, label): # 换了一种label颜色按钮 self.scene.label = label self.scene.color = number_color[label] self.color_Button.setStyleSheet("background-color: %s;" % self.scene.color) @pyqtSlot() def undo(self): self.scene.undo() def __init__(self, opt): super().__init__() self.init_deep_model(opt) self.setupUi(self) self.show() # 下面都是一些默认值 self.modes = 0 self.alpha = 1 # 插值的alpha self.ref_style_img_path = None self.mouse_clicked = False
self.scene = GraphicsScene(self.modes, self) # 用来编辑的 scene
2
2023-10-15 12:15:01+00:00
24k
sotopia-lab/sotopia
sotopia/server.py
[ { "identifier": "Agents", "path": "sotopia/agents/llm_agent.py", "snippet": "class Agents(dict[str, BaseAgent[Observation, AgentAction]]):\n def reset(self) -> None:\n for agent in self.values():\n agent.reset()\n\n def act(self, obs: dict[str, Observation]) -> dict[str, AgentAction]:\n return {\n agent_name: agent.act(obs[agent_name])\n for agent_name, agent in self.items()\n }" }, { "identifier": "HumanAgent", "path": "sotopia/agents/llm_agent.py", "snippet": "class HumanAgent(BaseAgent[Observation, AgentAction]):\n \"\"\"\n A human agent that takes input from the command line.\n \"\"\"\n\n def __init__(\n self,\n agent_name: str | None = None,\n uuid_str: str | None = None,\n agent_profile: AgentProfile | None = None,\n ) -> None:\n super().__init__(\n agent_name=agent_name,\n uuid_str=uuid_str,\n agent_profile=agent_profile,\n )\n\n @property\n def goal(self) -> str:\n if self._goal is not None:\n return self._goal\n goal = input(\"Goal: \")\n return goal\n\n @goal.setter\n def goal(self, goal: str) -> None:\n self._goal = goal\n\n def act(self, obs: Observation) -> AgentAction:\n self.recv_message(\"Environment\", obs)\n\n print(\"Available actions:\")\n for i, action in enumerate(obs.available_actions):\n print(f\"{i}: {action}\")\n\n action_type = obs.available_actions[int(input(\"Action type: \"))]\n argument = input(\"Argument: \")\n\n return AgentAction(action_type=action_type, argument=argument)\n\n async def aact(self, obs: Observation) -> AgentAction:\n self.recv_message(\"Environment\", obs)\n\n print(\"Available actions:\")\n for i, action in enumerate(obs.available_actions):\n print(f\"{i}: {action}\")\n\n if obs.available_actions != [\"none\"]:\n action_type_number = await ainput(\n \"Action type (Please only input the number): \"\n )\n try:\n action_type_number = int(action_type_number) # type: ignore\n except:\n print(\"Please input a number.\")\n action_type_number = await ainput(\n \"Action type (Please only input the number): \"\n )\n action_type_number = int(action_type_number) # type: ignore\n assert isinstance(\n action_type_number, int\n ), \"Please input a number.\"\n action_type = obs.available_actions[action_type_number]\n else:\n action_type = \"none\"\n if action_type in [\"speak\", \"non-verbal communication\"]:\n argument = await ainput(\"Argument: \")\n else:\n argument = \"\"\n\n return AgentAction(action_type=action_type, argument=argument)" }, { "identifier": "LLMAgent", "path": "sotopia/agents/llm_agent.py", "snippet": "class LLMAgent(BaseAgent[Observation, AgentAction]):\n def __init__(\n self,\n agent_name: str | None = None,\n uuid_str: str | None = None,\n agent_profile: AgentProfile | None = None,\n model_name: LLM_Name = \"gpt-3.5-turbo\",\n script_like: bool = False,\n ) -> None:\n super().__init__(\n agent_name=agent_name,\n uuid_str=uuid_str,\n agent_profile=agent_profile,\n )\n self.model_name = model_name\n self.script_like = script_like\n\n @property\n def goal(self) -> str:\n if self._goal is not None:\n return self._goal\n assert (\n len(self.inbox) > 0\n ), \"attribute goal has to be called after at least one step\"\n goal = generate_goal(\n self.model_name,\n background=self.inbox[0][\n 1\n ].to_natural_language(), # Only consider the first message for now\n )\n return goal\n\n @goal.setter\n def goal(self, goal: str) -> None:\n self._goal = goal\n\n def act(\n self,\n obs: Observation,\n gen_func: Callable[..., AgentAction] = generate_action,\n ) -> AgentAction:\n self.recv_message(\"Environment\", obs)\n\n if len(obs.available_actions) == 1 and \"none\" in obs.available_actions:\n return AgentAction(action_type=\"none\", argument=\"\")\n else:\n action = gen_func(\n self.model_name,\n history=\"\\n\".join(\n f\"{y.to_natural_language()}\" for x, y in self.inbox\n ),\n turn_number=obs.turn_number,\n action_types=obs.available_actions,\n agent=self.agent_name,\n goal=self.goal,\n )\n return action\n\n async def aact(self, obs: Observation) -> AgentAction:\n self.recv_message(\"Environment\", obs)\n\n if len(obs.available_actions) == 1 and \"none\" in obs.available_actions:\n return AgentAction(action_type=\"none\", argument=\"\")\n else:\n action, prompt = await agenerate_action(\n self.model_name,\n history=\"\\n\".join(\n f\"{y.to_natural_language()}\" for x, y in self.inbox\n ),\n turn_number=obs.turn_number,\n action_types=obs.available_actions,\n agent=self.agent_name,\n goal=self.goal,\n script_like=self.script_like,\n )\n return action" }, { "identifier": "ScriptWritingAgent", "path": "sotopia/agents/llm_agent.py", "snippet": "class ScriptWritingAgent(LLMAgent):\n def __init__(\n self,\n agent_name: str | None = None,\n uuid_str: str | None = None,\n agent_profile: AgentProfile | None = None,\n model_name: LLM_Name = \"gpt-3.5-turbo\",\n agent_names: list[str] = [],\n background: ScriptBackground | None = None,\n ) -> None:\n super().__init__(\n agent_name=agent_name,\n uuid_str=uuid_str,\n agent_profile=agent_profile,\n )\n self.model_name = model_name\n self.agent_names = agent_names\n assert background is not None, \"background cannot be None\"\n self.background = background\n\n async def aact(self, obs: Observation) -> AgentAction:\n self.recv_message(\"Environment\", obs)\n message_to_compose = [\n y for idx, (x, y) in enumerate(self.inbox) if idx != 0\n ]\n\n history = \"\\n\".join(\n f\"{y.to_natural_language()}\" for y in message_to_compose\n )\n print(\"Current agent: \", self.agent_name)\n print(\"Composed history: \", history)\n\n action, prompt = await agenerate_script(\n model_name=self.model_name,\n background=self.background,\n agent_names=self.agent_names,\n history=history,\n agent_name=self.agent_name,\n single_step=True,\n )\n # action: tuple[\n # list[list[tuple[str, str, Message]]], list[tuple[str, Message]]\n # ]\n returned_action = cast(AgentAction, action[1][0][1])\n print(\"Action: \", returned_action, type(returned_action))\n # print(\"Action: \", action)\n # exit(0)\n\n return returned_action" }, { "identifier": "SpeakAgent", "path": "sotopia/agents/llm_agent.py", "snippet": "class SpeakAgent(LLMAgent):\n def act(\n self,\n obs: Observation,\n gen_func: Callable[..., AgentAction] = generate_action_speak,\n ) -> AgentAction:\n return super().act(obs, gen_func=gen_func)" }, { "identifier": "RedisAgent", "path": "sotopia/agents/redis_agent.py", "snippet": "class RedisAgent(BaseAgent[Observation, AgentAction]):\n \"\"\"An agent use redis as a message broker.\"\"\"\n\n def __init__(\n self,\n agent_name: str | None = None,\n uuid_str: str | None = None,\n session_id: str | None = None,\n agent_profile: AgentProfile | None = None,\n ) -> None:\n super().__init__(\n agent_name=agent_name,\n uuid_str=uuid_str,\n agent_profile=agent_profile,\n )\n # super().__init__(agent_name=agent_name, uuid_str=uuid_str)\n self.session_id = session_id or str(uuid4())\n self.sender_id = str(uuid4())\n print(f\"session id: {self.session_id}\")\n print(\"step 1: connect to the server\")\n assert (\n \"FASTAPI_URL\" in os.environ\n ), \"To use redis agent, you have to launch a FastAPI server and set FASTAPI_URL\"\n self._URL = os.environ[\"FASTAPI_URL\"]\n response = requests.request(\n \"POST\",\n f\"{self._URL}/connect/{self.session_id}/server/{self.sender_id}\",\n )\n assert (\n response.status_code == 200 and response.text == \"[]\"\n ), \"Failed to connect to the server\"\n logging.info(f\"Session ID: {self.session_id}\")\n # logging.info(f\"Sender ID: {self.sender_id}\")\n\n def act(\n self,\n obs: Observation,\n ) -> AgentAction:\n raise NotImplementedError\n\n async def aact(\n self,\n obs: Observation,\n ) -> AgentAction:\n self.recv_message(\"Environment\", obs)\n\n if len(obs.available_actions) == 1 and \"none\" in obs.available_actions:\n if obs.turn_number == 0:\n async with aiohttp.ClientSession() as session:\n print(\"step 2: post observation to the message list\")\n response = await session.request(\n \"POST\",\n f\"{self._URL}/send/{self.session_id}/{self.sender_id}\",\n data=obs.to_natural_language(),\n )\n assert response.status == 200, response\n sorted_message_list: list[tuple[float, str, str]] = list(\n map(\n lambda x: MessageTransaction.parse_obj(\n x\n ).to_tuple(),\n await response.json(),\n )\n )\n last_timestamp = sorted_message_list[-1][0]\n return AgentAction(action_type=\"none\", argument=\"\")\n else:\n async with aiohttp.ClientSession() as session:\n # 1. post observation to the message list\n response = await session.request(\n \"POST\",\n f\"{self._URL}/send/{self.session_id}/{self.sender_id}\",\n data=obs.to_natural_language(),\n )\n assert response.status == 200, response\n sorted_message_list = list(\n map(\n lambda x: MessageTransaction.parse_obj(x).to_tuple(),\n await response.json(),\n )\n )\n last_timestamp = sorted_message_list[-1][0]\n\n print(\"step 2: unlock the server for the client\")\n # 2. unlock the server for the client\n response = await session.request(\n \"PUT\",\n f\"{self._URL}/lock/{self.session_id}/{self.sender_id}/action\",\n )\n assert response.status == 200, response\n\n print(\"step 3: wait for the client to post their message\")\n # 3. wait for the client to post their message\n for _ in range(300):\n response = await session.request(\n \"GET\",\n f\"{self._URL}/get/{self.session_id}\",\n )\n # print(f\"get response: {response}\")\n assert response.status == 200, response\n sorted_message_list = list(\n map(\n lambda x: MessageTransaction.parse_obj(\n x\n ).to_tuple(),\n await response.json(),\n )\n )\n if (\n sorted_message_list[-1][0] > last_timestamp\n and sorted_message_list[-1][1] == \"client\"\n ):\n # 3.a if the client has posted their message, lock the server for the client\n response = await session.request(\n \"PUT\",\n f\"{self._URL}/lock/{self.session_id}/{self.sender_id}/no%20action\",\n )\n assert response.status == 200, response\n break\n else:\n # 3.b if the client has not posted their message, wait for 0.1 second and retry\n await asyncio.sleep(1)\n else:\n response = await session.request(\n \"PUT\",\n f\"{self._URL}/lock/{self.session_id}/{self.sender_id}/no%20action\",\n )\n self.reset(\n \"Someone has left or the conversation is too long.\"\n )\n return AgentAction(action_type=\"leave\", argument=\"\")\n action_string = sorted_message_list[-1][2]\n try:\n action = AgentAction.parse_raw(action_string)\n return action\n except pydantic.error_wrappers.ValidationError:\n logging.warn(\n \"Failed to parse action string {}. Fall back to speak\".format(\n action_string\n )\n )\n return AgentAction(\n action_type=\"speak\", argument=sorted_message_list[-1][2]\n )\n\n def reset(\n self,\n reset_reason: str = \"\",\n ) -> None:\n super().reset()\n try:\n if reset_reason != \"\":\n response = requests.request(\n \"POST\",\n f\"{self._URL}/send/{self.session_id}/{self.sender_id}\",\n json=reset_reason,\n )\n assert response.status_code == 200\n\n except Exception as e:\n logging.error(f\"Failed to reset RedisAgent {self.sender_id}: {e}\")" }, { "identifier": "BaseAgent", "path": "sotopia/agents/base_agent.py", "snippet": "class BaseAgent(Generic[ObsType, ActType], MessengerMixin):\n def __init__(\n self,\n agent_name: str | None = None,\n uuid_str: str | None = None,\n agent_profile: AgentProfile | None = None,\n ) -> None:\n MessengerMixin.__init__(self)\n if agent_profile is not None:\n self.profile = agent_profile\n self.agent_name = (\n self.profile.first_name + \" \" + self.profile.last_name\n )\n elif uuid_str is not None:\n # try retrieving profile from database\n try:\n self.profile = AgentProfile.get(pk=uuid_str)\n except NotFoundError:\n raise ValueError(\n f\"Agent with uuid {uuid_str} not found in database\"\n )\n self.agent_name = (\n self.profile.first_name + \" \" + self.profile.last_name\n )\n else:\n assert (\n agent_name is not None\n ), \"Either agent_name or uuid_str must be provided\"\n self.agent_name = agent_name\n\n self._goal: str | None = None\n\n @property\n def goal(self) -> str:\n assert (\n self._goal is not None\n ), \"attribute goal has to be set before use\"\n return self._goal\n\n @goal.setter\n def goal(self, goal: str) -> None:\n self._goal = goal\n\n def act(self, obs: ObsType) -> ActType:\n raise NotImplementedError\n\n async def aact(self, obs: ObsType) -> ActType:\n raise NotImplementedError\n\n def reset(self) -> None:\n self.reset_inbox()" }, { "identifier": "EpisodeLog", "path": "sotopia/database/logs.py", "snippet": "class EpisodeLog(JsonModel):\n # Note that we did not validate the following constraints:\n # 1. The number of turns in messages and rewards should be the same or off by 1\n # 2. The agents in the messages are the same as the agetns\n\n environment: str = Field(index=True)\n agents: list[str] = Field(index=True)\n tag: str | None = Field(index=True)\n models: list[str] | None = Field(index=True)\n messages: list[list[tuple[str, str, str]]] # Messages arranged by turn\n reasoning: str\n rewards: list[\n tuple[float, dict[str, float]] | float\n ] # Rewards arranged by turn\n rewards_prompt: str\n\n @root_validator\n def agent_number_message_number_reward_number_turn_number_match(\n cls, values: Any\n ) -> Any:\n agents, _, reasoning, rewards = (\n values.get(\"agents\"),\n values.get(\"messages\"),\n values.get(\"reasoning\"),\n values.get(\"rewards\"),\n )\n agent_number = len(agents)\n\n assert (\n len(rewards) == agent_number\n ), f\"Number of agents in rewards {len(rewards)} and agents {agent_number} do not match\"\n return values\n\n def render_for_humans(self) -> tuple[list[AgentProfile], list[str]]:\n \"\"\"Generate a human readable version of the episode log.\n\n Returns:\n A tuple of (a list of agent_profiles, a list of str): The agent profiles, and the messages and rewards in each turn.\n \"\"\"\n\n agent_profiles = [\n AgentProfile.get(pk=uuid_str) for uuid_str in self.agents\n ]\n messages_and_rewards = []\n for idx, turn in enumerate(self.messages):\n messages_in_this_turn = []\n if idx == 0:\n assert (\n len(turn) >= 2\n ), \"The first turn should have at least environemnt messages\"\n messages_in_this_turn.append(turn[0][2])\n messages_in_this_turn.append(turn[1][2])\n for sender, receiver, message in turn:\n if receiver == \"Environment\":\n if sender != \"Environment\":\n if \"did nothing\" in message:\n continue\n else:\n if \"said:\" in message:\n messages_in_this_turn.append(\n f\"{sender} {message}\"\n )\n else:\n messages_in_this_turn.append(\n f\"{sender}: {message}\"\n )\n else:\n messages_in_this_turn.append(message)\n messages_and_rewards.append(\"\\n\".join(messages_in_this_turn))\n messages_and_rewards.append(f\"The reasoning is:\\n{self.reasoning}\")\n messages_and_rewards.append(\n f\"The rewards are:\\nAgent 1: {self.rewards[0]}\\nAgent 2: {self.rewards[1]}\"\n )\n return agent_profiles, messages_and_rewards" }, { "identifier": "AgentProfile", "path": "sotopia/database/persistent_profile.py", "snippet": "class AgentProfile(JsonModel):\n first_name: str = Field(index=True)\n last_name: str = Field(index=True)\n age: int = Field(index=True, default_factory=lambda: 0)\n occupation: str = Field(index=True, default_factory=lambda: \"\")\n gender: str = Field(index=True, default_factory=lambda: \"\")\n gender_pronoun: str = Field(index=True, default_factory=lambda: \"\")\n public_info: str = Field(index=True, default_factory=lambda: \"\")\n big_five: str = Field(index=True, default_factory=lambda: \"\")\n moral_values: list[str] = Field(index=False, default_factory=lambda: [])\n schwartz_personal_values: list[str] = Field(\n index=False, default_factory=lambda: []\n )\n personality_and_values: str = Field(index=True, default_factory=lambda: \"\")\n decision_making_style: str = Field(index=True, default_factory=lambda: \"\")\n secret: str = Field(default_factory=lambda: \"\")\n model_id: str = Field(default_factory=lambda: \"\")" }, { "identifier": "EnvironmentProfile", "path": "sotopia/database/persistent_profile.py", "snippet": "class EnvironmentProfile(JsonModel):\n codename: str = Field(\n index=True,\n default_factory=lambda: \"\",\n description=\"The codename of the environment\",\n )\n source: str = Field(\n index=True,\n default_factory=lambda: \"\",\n description=\"The source of the environment\",\n )\n scenario: str = Field(\n index=True,\n default_factory=lambda: \"\",\n description=\"A concrete scenario of where the social interaction takes place, the scenario should have two agents (agent1 and agent2), and you should illustrate the relationship between the two agents, and for what purpose agent1 is interacting with agent2. Please avoid mentioning specific names and occupations in the scenario and keep all the mentions gender-neutral. Also avoid generating scenarios that requires childrend (below 18) or elderly (above 70) to be involved.\",\n )\n agent_goals: list[str] = Field(\n default_factory=lambda: [],\n description=\"The social goals of each agent, which could include <extra_info>...</extra_info>, <clarification_hint>...</clarification_hint>, and <strategy_hint>...</strategy_hint> to help the agent achieve the goal. Avoid providing too specific strategy hint, try to be as abstract as possible. For example, use 'you can provide financial benefits to achieve your goal' instead of 'you can buy him a boba tea to achieve your goal.'\",\n )\n relationship: RelationshipType = Field(\n index=True,\n default_factory=lambda: RelationshipType.stranger,\n description=\"The relationship between the two agents, choose from: stranger, know_by_name, acquaintance, friend, romantic_relationship, family_member. Do not make up a relationship, but choose from the list, 0 means stranger, 1 means know_by_name, 2 means acquaintance, 3 means friend, 4 means romantic_relationship, 5 means family_member\",\n )\n age_constraint: str | None = Field(\n default_factory=lambda: None,\n description=\"The age constraint of the environment, a list of tuples, each tuple is a range of age, e.g., '[(18, 25), (30, 40)]' means the environment is only available to agent one between 18 and 25, and agent two between 30 and 40\",\n )\n occupation_constraint: str | None = Field(\n default_factory=lambda: None,\n description=\"The occupation constraint of the environment, a list of lists, each list is a list of occupations, e.g., '[['student', 'teacher'], ['doctor', 'nurse']]' means the environment is only available to agent one if agent one is a student or a teacher, and agent two is a doctor or a nurse\",\n )\n agent_constraint: list[list[str]] | None = Field(\n default_factory=lambda: None,\n )" }, { "identifier": "ParallelSotopiaEnv", "path": "sotopia/envs/parallel.py", "snippet": "class ParallelSotopiaEnv(\n ParallelEnv[str, Observation, AgentAction], MessengerMixin\n):\n def __init__(\n self,\n available_action_types: set[ActionType] = set(\n [\"none\", \"speak\", \"non-verbal communication\", \"action\", \"leave\"]\n ),\n action_order: Literal[\n \"simutaneous\", \"round-robin\", \"random\"\n ] = \"simutaneous\",\n model_name: LLM_Name = \"gpt-3.5-turbo\",\n evaluators: list[Evaluator] = [],\n terminal_evaluators: list[Evaluator] = [],\n uuid_str: str | None = None,\n env_profile: EnvironmentProfile | None = None,\n ) -> None:\n \"\"\"A sotopia environment for parallel agents.\n\n Args:\n available_action_types (set[ActionType], optional): The action types that are available to the agents. Defaults to set([\"none\", \"speak\", \"non-verbal communication\", \"action\"]).\n action_order (Literal[\"simutaneous\", \"round-robin\", \"random\"], optional): The order in which the agents take actions. Defaults to \"simutaneous\".\n model_name (LLM_Name, optional): The name of the language model to use. Defaults to \"gpt-3.5-turbo\".\n \"\"\"\n super().__init__()\n self.model_name = model_name\n self.background = ScriptBackground(\n scenario=\"\",\n p1_background=\"\",\n p2_background=\"\",\n p1_goal=\"\",\n p2_goal=\"\",\n p1_name=\"\",\n p2_name=\"\",\n )\n\n self.agents = []\n self.action_spaces = {}\n self.available_action_types = list(available_action_types)\n self.action_order = action_order\n self.action_mask: list[bool] = []\n self.evaluators = evaluators\n self.terminal_evaluators = terminal_evaluators\n\n # if an environment profile is provided, use it\n assert (\n env_profile or uuid_str\n ), \"Either env_profile or uuid_str must be provided\"\n if env_profile is not None:\n self.profile = env_profile\n # if a uuid is provided, try to load the environment profile from the database\n elif uuid_str is not None:\n # try retrieving profile from database\n try:\n self.profile = EnvironmentProfile.get(pk=uuid_str)\n except NotFoundError:\n raise ValueError(\n f\"Agent with uuid {uuid_str} not found in database\"\n )\n\n @configurable\n def reset(\n self,\n seed: int | None = None,\n options: dict[str, str] | None = None,\n agents: Agents | None = None,\n omniscient: bool = False,\n lite: bool = False,\n ) -> dict[str, Observation]:\n \"\"\"Starting a new episode. Must be called before step().\n\n Args:\n seed (int, optional): Seed for the environment. Defaults to None. Not used right now.\n options (dict, optional): Options for the environment. Defaults to None.\n \"partial_background_file\" (str): Path to a json file which need to contain a ScriptBackground object. The backgound can be incompleted (\"unknown\" for missing parts), and the missing parts will be filled in by the environment.\n \"full_background_file\" (str): Path to a json file which need to contain a ScriptBackground object. The backgound must be completed (no \"unknown\" for missing parts).\n omniscient (bool, optional): Whether the agents know the other agent's goal. Defaults to False.\n \"\"\"\n super().__init__()\n MessengerMixin.reset_inbox(self)\n assert (\n not options\n or not (\"partial_background_file\" in options)\n and not (\"full_background_file\" in options)\n ), \"partial_background_file and full_background_file are not supported anymore\"\n if agents is not None:\n assert agents, \"agents must be provided\"\n assert len(agents) == 2, \"Only supporting two agents right now\"\n agent_names = list(agents.keys())\n agent_goals = self.profile.agent_goals\n assert (\n len(agent_goals) == 2\n ), \"Only supporting two agents right now\"\n\n raw_background = ScriptBackground(\n scenario=self.profile.scenario,\n p1_background=get_bio(\n self.profile.relationship,\n agents[agent_names[0]].profile,\n agent_id=0,\n ),\n p2_background=get_bio(\n self.profile.relationship,\n agents[agent_names[1]].profile,\n agent_id=1,\n ),\n p1_goal=f\"<root viewer='agent_0'>{agent_goals[0]}</root>\",\n p2_goal=f\"<root viewer='agent_1'>{agent_goals[1]}</root>\",\n p1_name=agent_names[0],\n p2_name=agent_names[1],\n )\n\n if lite:\n raw_background.p1_background = \"\"\n raw_background.p2_background = \"\"\n\n self.background = ScriptBackground(\n scenario=render_text_for_environment(raw_background.scenario),\n p1_background=render_text_for_environment(\n raw_background.p1_background\n ),\n p2_background=render_text_for_environment(\n raw_background.p2_background\n ),\n p1_goal=render_text_for_environment(raw_background.p1_goal),\n p2_goal=render_text_for_environment(raw_background.p2_goal),\n p1_name=raw_background.p1_name,\n p2_name=raw_background.p2_name,\n )\n else:\n raise ValueError(\"agents must be provided\")\n\n self.agents = [self.background.p1_name, self.background.p2_name]\n agent_backgrounds: list[ScriptBackground] = []\n if omniscient:\n for i in range(self.num_agents):\n agent_backgrounds.append(copy.deepcopy(self.background))\n else:\n for i in range(self.num_agents):\n agent_backgrounds.append(\n ScriptBackground(\n scenario=render_text_for_agent(\n raw_background.scenario, i\n ),\n p1_background=render_text_for_agent(\n raw_background.p1_background, i\n ),\n p2_background=render_text_for_agent(\n raw_background.p2_background, i\n ),\n p1_goal=render_text_for_agent(\n raw_background.p1_goal, i\n ),\n p2_goal=render_text_for_agent(\n raw_background.p2_goal, i\n ),\n p1_name=raw_background.p1_name,\n p2_name=raw_background.p2_name,\n )\n )\n background_for_a = agent_backgrounds[0]\n background_for_b = agent_backgrounds[1]\n\n print(\"Is the agent omniscient?\", omniscient)\n if not omniscient:\n background_for_a.p2_goal = \"Unknown\"\n background_for_b.p1_goal = \"Unknown\"\n\n self.action_spaces = {\n agent: Dict(\n dict(\n action_type=Discrete(len(self.available_action_types)),\n argument=Text(256),\n )\n )\n for agent in self.agents\n }\n self.turn_number = 0\n self.action_mask = [False for _ in self.agents]\n if self.action_order == \"round-robin\":\n self.action_mask[0] = True\n elif self.action_order == \"random\":\n self.action_mask[\n random.randint(0, len(self.action_mask) - 1)\n ] = True\n else:\n self.action_mask = [True for _ in self.agents]\n\n self.recv_message(\"Environment\", self.background)\n\n return {\n self.background.p1_name: Observation(\n last_turn=background_for_a.to_natural_language(),\n turn_number=0,\n available_actions=list(self.available_action_types)\n if self.action_mask[0]\n else [\"none\"],\n ),\n self.background.p2_name: Observation(\n last_turn=background_for_b.to_natural_language(),\n turn_number=0,\n available_actions=list(self.available_action_types)\n if self.action_mask[1]\n else [\"none\"],\n ),\n }\n\n @beartype\n def step(\n self, actions: dict[str, AgentAction] | dict[str, dict[str, int | str]]\n ) -> tuple[\n dict[str, Observation],\n dict[str, float],\n dict[str, bool],\n dict[str, bool],\n dict[str, dict[Any, Any]],\n ]:\n # Time step ++\n self.turn_number += 1\n\n # For action sampled from action space, it needs to be converted into AgentAction\n complied_actions: dict[str, AgentAction] = {}\n for key in actions.keys():\n action = actions[key]\n if isinstance(action, AgentAction):\n complied_actions[key] = action\n else:\n action[\"action_type\"] = self.available_action_types[\n int(action[\"action_type\"])\n ]\n complied_actions[key] = AgentAction.parse_obj(action)\n\n # Masking actions from agent that are in turn\n for idx, agent in enumerate(self.agents):\n if not self.action_mask[idx]:\n complied_actions[agent] = AgentAction(\n action_type=\"none\", argument=\"\"\n )\n\n self.recv_message(\n \"Environment\", SimpleMessage(message=f\"Turn #{self.turn_number}\")\n )\n for agent, action in complied_actions.items():\n self.recv_message(agent, action)\n\n response = unweighted_aggregate_evaluate(\n list(\n itertools.chain(\n *(\n evaluator(\n turn_number=self.turn_number, messages=self.inbox\n )\n for evaluator in self.evaluators\n )\n )\n )\n )\n\n self.action_mask = [False for _ in self.agents]\n if self.action_order == \"round-robin\":\n self.action_mask[self.turn_number % len(self.action_mask)] = True\n elif self.action_order == \"random\":\n self.action_mask[\n random.randint(0, len(self.action_mask) - 1)\n ] = True\n else:\n self.action_mask = [True for _ in self.agents]\n obs = _actions_to_natural_language(complied_actions)\n return (\n {\n self.background.p1_name: Observation(\n last_turn=render_text_for_agent(obs, agent_id=0),\n turn_number=self.turn_number,\n available_actions=list(self.available_action_types)\n if self.action_mask[0]\n else [\"none\"],\n ),\n self.background.p2_name: Observation(\n last_turn=render_text_for_agent(obs, agent_id=1),\n turn_number=self.turn_number,\n available_actions=list(self.available_action_types)\n if self.action_mask[1]\n else [\"none\"],\n ),\n },\n {\n self.background.p1_name: (\n response.p1_rate\n if isinstance(response.p1_rate, float)\n else response.p1_rate[0]\n )\n if response.p1_rate\n else 0,\n self.background.p2_name: (\n response.p2_rate\n if isinstance(response.p2_rate, float)\n else response.p2_rate[0]\n )\n if response.p2_rate\n else 0,\n },\n {\n self.background.p1_name: response.terminated,\n self.background.p2_name: response.terminated,\n },\n {\n self.background.p1_name: False,\n self.background.p2_name: False,\n },\n {\n self.background.p1_name: {\n \"comments\": response.comments or \"\",\n \"complete_rating\": response.p1_rate or 0,\n },\n self.background.p2_name: {\n \"comments\": response.comments or \"\",\n \"complete_rating\": response.p2_rate or 0,\n },\n },\n )\n\n @beartype\n async def astep(\n self, actions: dict[str, AgentAction] | dict[str, dict[str, int | str]]\n ) -> tuple[\n dict[str, Observation],\n dict[str, float],\n dict[str, bool],\n dict[str, bool],\n dict[str, dict[Any, Any]],\n ]:\n # Time step ++\n self.turn_number += 1\n\n # For action sampled from action space, it needs to be converted into AgentAction\n complied_actions: dict[str, AgentAction] = {}\n for key in actions.keys():\n action = actions[key]\n if isinstance(action, AgentAction):\n complied_actions[key] = action\n else:\n action[\"action_type\"] = self.available_action_types[\n int(action[\"action_type\"])\n ]\n complied_actions[key] = AgentAction.parse_obj(action)\n\n # Masking actions from agent that are in turn\n for idx, agent in enumerate(self.agents):\n if not self.action_mask[idx]:\n complied_actions[agent] = AgentAction(\n action_type=\"none\", argument=\"\"\n )\n\n self.recv_message(\n \"Environment\", SimpleMessage(message=f\"Turn #{self.turn_number}\")\n )\n for agent, action in complied_actions.items():\n self.recv_message(agent, action)\n\n response = unweighted_aggregate_evaluate(\n list(\n itertools.chain(\n *await asyncio.gather(\n *[\n evaluator.__acall__(\n turn_number=self.turn_number,\n messages=self.inbox,\n )\n for evaluator in self.evaluators\n ]\n )\n )\n )\n )\n\n if response.terminated:\n terminal_response = unweighted_aggregate_evaluate(\n list(\n itertools.chain(\n *await asyncio.gather(\n *[\n evaluator.__acall__(\n turn_number=self.turn_number,\n messages=self.inbox,\n )\n for evaluator in self.terminal_evaluators\n ]\n )\n )\n )\n )\n # incorporate terminal response into response\n response.p1_rate = response.p1_rate or terminal_response.p1_rate\n response.p2_rate = response.p2_rate or terminal_response.p2_rate\n if response.comments and terminal_response.comments:\n response.comments += terminal_response.comments\n elif terminal_response.comments:\n response.comments = terminal_response.comments\n\n self.action_mask = [False for _ in self.agents]\n if self.action_order == \"round-robin\":\n self.action_mask[self.turn_number % len(self.action_mask)] = True\n elif self.action_order == \"random\":\n self.action_mask[\n random.randint(0, len(self.action_mask) - 1)\n ] = True\n else:\n self.action_mask = [True for _ in self.agents]\n obs = _actions_to_natural_language(complied_actions)\n info = {\n self.background.p1_name: {\n \"comments\": response.comments or \"\",\n \"complete_rating\": response.p1_rate or 0,\n },\n self.background.p2_name: {\n \"comments\": response.comments or \"\",\n \"complete_rating\": response.p2_rate or 0,\n },\n }\n if response.terminated:\n info[\"rewards_prompt\"] = {\"overall_prompt\": self.terminal_evaluators[0].prompt} # type: ignore\n\n return (\n {\n self.background.p1_name: Observation(\n last_turn=render_text_for_agent(obs, agent_id=0),\n turn_number=self.turn_number,\n available_actions=list(self.available_action_types)\n if self.action_mask[0]\n else [\"none\"],\n ),\n self.background.p2_name: Observation(\n last_turn=render_text_for_agent(obs, agent_id=1),\n turn_number=self.turn_number,\n available_actions=list(self.available_action_types)\n if self.action_mask[1]\n else [\"none\"],\n ),\n },\n {\n self.background.p1_name: (\n response.p1_rate\n if isinstance(response.p1_rate, float)\n else response.p1_rate[0]\n )\n if response.p1_rate\n else 0,\n self.background.p2_name: (\n response.p2_rate\n if isinstance(response.p2_rate, float)\n else response.p2_rate[0]\n )\n if response.p2_rate\n else 0,\n },\n {\n self.background.p1_name: response.terminated,\n self.background.p2_name: response.terminated,\n },\n {\n self.background.p1_name: False,\n self.background.p2_name: False,\n },\n info,\n )\n\n def render(self, mode: str = \"human\") -> None:\n pass\n\n def close(self) -> None:\n pass" }, { "identifier": "ReachGoalLLMEvaluator", "path": "sotopia/envs/evaluators.py", "snippet": "class ReachGoalLLMEvaluator(Evaluator):\n @beartype\n def __init__(\n self, model_name: LLM_Name, response_format: str = \"basic\"\n ) -> None:\n self.model_name = model_name\n self.prompt = \"\"\n self.response_format = response_format\n\n def __call__(\n self, turn_number: int, messages: list[tuple[str, Message]]\n ) -> list[tuple[str, tuple[tuple[str, int | float | bool], str]]]:\n raise NotImplementedError(\n \"ReachGoalLLMEvaluator is not implemented for synchronous evaluation\"\n )\n\n @gin.configurable\n @beartype\n async def __acall__(\n self,\n turn_number: int,\n messages: list[tuple[str, Message]] | None,\n history: str = \"\",\n temperature: float = 0.7,\n ) -> list[tuple[str, tuple[tuple[str, int | float | bool], str]]]:\n # filter did nothing\n if not history and messages:\n messages_filtered = [\n (x, y)\n for x, y in messages\n if \"did nothing\" not in y.to_natural_language()\n ]\n history = \"\\n\".join(\n [\n f\"{x} {y.to_natural_language()}\"\n if x != \"Environment\"\n else y.to_natural_language()\n for x, y in messages_filtered\n ]\n )\n response_format_class = (\n EnvResponsePlus if self.response_format == \"plus\" else EnvResponse\n )\n\n try:\n response: EnvResponsePlus | EnvResponse # fix type error from langchain 0.0.264. we don't need this line for langchain 0.0.263\n response, prompt = await agenerate(\n model_name=self.model_name,\n template=\"\"\"{history},\n Based on previous interactions, evaluate how well participants achieve their goals.\n Please following the format:\n {format_instructions}\n \"\"\",\n input_values=dict(history=history),\n output_parser=PydanticOutputParser[\n EnvResponsePlus | EnvResponse\n ](pydantic_object=response_format_class),\n temperature=temperature,\n )\n self.prompt = prompt\n response_list = []\n # TODO: multiple agents\n for dimension in response.agent_1_evaluation.dict().keys():\n response_list.append(\n (\n \"agent_1\",\n (\n (\n dimension,\n response.agent_1_evaluation.dict()[dimension][\n 1\n ],\n ),\n response.agent_1_evaluation.dict()[dimension][0],\n ),\n )\n )\n response_list.append(\n (\n \"agent_2\",\n (\n (\n dimension,\n response.agent_2_evaluation.dict()[dimension][\n 1\n ],\n ),\n response.agent_2_evaluation.dict()[dimension][0],\n ),\n )\n )\n return response_list\n except Exception as e:\n log.debug(f\"[red] Failed to generate environment response. {e}\")\n return []" }, { "identifier": "RuleBasedTerminatedEvaluator", "path": "sotopia/envs/evaluators.py", "snippet": "class RuleBasedTerminatedEvaluator(Evaluator):\n def __init__(\n self, max_turn_number: int = 20, max_stale_turn: int = 2\n ) -> None:\n self.max_turn_number = max_turn_number\n self.max_stale_turn = max_stale_turn\n\n def __call__(\n self, turn_number: int, messages: list[tuple[str, Message]]\n ) -> list[tuple[str, tuple[tuple[str, int | float | bool], str]]]:\n # Rule 1: If the conversation is too long, terminate the conversation\n conversation_too_long = turn_number > self.max_turn_number\n # Rule 2: If one of the players leaves, terminate the conversation\n p1_leaving = (\n len(messages) > 1\n and isinstance(messages[-2][1], AgentAction)\n and messages[-2][1].action_type == \"leave\"\n )\n p2_leaving = (\n bool(len(messages))\n and isinstance(messages[-1][1], AgentAction)\n and messages[-1][1].action_type == \"leave\"\n )\n # Rule 3: If the conversation is stale for too long, terminate the conversation\n stale_count = 0\n for message in messages[::-1]:\n if message[0] == \"Environment\":\n continue\n assert isinstance(message[1], AgentAction)\n if message[1].action_type == \"none\":\n stale_count += 1\n else:\n break\n if stale_count > self.max_stale_turn:\n break\n stale_too_long = stale_count > self.max_stale_turn\n terminated = (\n conversation_too_long or p1_leaving or p2_leaving or stale_too_long\n )\n reasons_for_termination = (\n f\"{'The conversation is too long; ' if conversation_too_long else ''}\"\n f\"{'Agent 1 is leaving; ' if p1_leaving else ''}\"\n f\"{'Agent 2 is leaving; ' if p2_leaving else ''}\"\n f\"{'The conversation stales for too long; ' if stale_too_long else ''}\"\n )\n return [\n (\n \"environment\",\n ((\"terminated\", terminated), reasons_for_termination),\n )\n ]\n\n async def __acall__(\n self, turn_number: int, messages: list[tuple[str, Message]]\n ) -> list[tuple[str, tuple[tuple[str, int | float | bool], str]]]:\n return self(turn_number, messages)" }, { "identifier": "unweighted_aggregate_evaluate", "path": "sotopia/envs/evaluators.py", "snippet": "@beartype\ndef unweighted_aggregate_evaluate(\n responses: list[tuple[str, tuple[tuple[str, int | float | bool], str]]],\n) -> ScriptEnvironmentResponse:\n \"\"\"\n Aggregate the responses from the environment\n\n Args:\n responses (list[tuple[str, tuple[tuple[str, int | bool], str]]]): list of responses from the environment\n Each response is a tuple of (agent_name/environment, (response, reasoning))\n \"\"\"\n responses_dict: dict[\n str, list[tuple[tuple[str, int | float | bool], str]]\n ] = defaultdict(list)\n for response in responses:\n assert response[0] == \"environment\" or response[0].startswith(\"agent\")\n responses_dict[response[0]].append(response[1])\n\n environment_responses: tuple[dict[str, float | int | bool], str] = ({}, \"\")\n agent_1_responses: tuple[dict[str, float | int | bool], str] = ({}, \"\")\n agent_2_responses: tuple[dict[str, float | int | bool], str] = ({}, \"\")\n for k, v in responses_dict.items():\n if k == \"environment\":\n environment_responses = _reduce(v)\n else:\n if k == \"agent_1\":\n agent_1_responses = _reduce(v)\n elif k == \"agent_2\":\n agent_2_responses = _reduce(v)\n else:\n # TODO: supports more than two agents\n raise ValueError(f\"Only supports agent_1 and agent_2, got {k}\")\n\n comments = (\n (\n f\"Environment comments: {environment_responses[1]}\\n\"\n if environment_responses[1]\n else \"\"\n )\n + (\n f\"Agent 1 comments:\\n{agent_1_responses[1]}\\n\"\n if agent_1_responses[1]\n else \"\"\n )\n + (\n f\"Agent 2 comments:\\n{agent_2_responses[1]}\\n\"\n if agent_2_responses[1]\n else \"\"\n )\n )\n if (\n \"terminated\" in environment_responses[0]\n and environment_responses[0][\"terminated\"]\n ):\n log.debug(f\"[green] The conversation is terminated. {response}\")\n return ScriptEnvironmentResponse(\n terminated=environment_responses[0][\"terminated\"]\n if \"terminated\" in environment_responses[0]\n else False,\n p1_rate=(\n agent_1_responses[0][\"overall_score\"]\n if \"overall_score\" in agent_1_responses[0]\n else 0,\n agent_1_responses[0],\n )\n if agent_1_responses != ({}, \"\")\n else None,\n p2_rate=(\n agent_2_responses[0][\"overall_score\"]\n if \"overall_score\" in agent_2_responses[0]\n else 0,\n agent_2_responses[0],\n )\n if agent_2_responses != ({}, \"\")\n else None,\n comments=comments,\n )" }, { "identifier": "LLM_Name", "path": "sotopia/generation_utils/generate.py", "snippet": "class EnvResponse(BaseModel):\nclass EnvResponsePydanticOutputParser(PydanticOutputParser[EnvResponse]):\nclass ListOfIntOutputParser(BaseOutputParser[list[int]]):\nclass ListOfStrOutputParser(BaseOutputParser[list[str]]):\nclass StrOutputParser(BaseOutputParser[str]):\nclass ScriptOutputParser(BaseOutputParser[ScriptInteractionReturnType]):\n def __init__(self, pydantic_object: Type[BaseModel] = EnvResponse) -> None:\n def parse(self, text: str) -> EnvResponse:\n def get_format_instructions(self) -> str:\n def __init__(\n self,\n number_of_int: int | None = None,\n range_of_int: tuple[int, int] | None = None,\n ):\n def _get_description_text(self) -> str:\n def get_format_instructions(self) -> str:\n def parse(self, output: str) -> list[int]:\n def _type(self) -> str:\n def __init__(\n self,\n number_of_str: int | None = None,\n ):\n def _get_description_text(self) -> str:\n def get_format_instructions(self) -> str:\n def parse(self, output: str) -> list[str]:\n def _type(self) -> str:\n def __init__(self) -> None:\n def get_format_instructions(self) -> str:\n def parse(self, output: str) -> str:\n def _type(self) -> str:\n def get_format_instructions(self) -> str:\n def parse(self, output: str) -> ScriptInteractionReturnType:\n def _type(self) -> str:\ndef _return_fixed_model_version(\n model_name: Literal[\"gpt-3.5-turbo\", \"gpt-4\", \"gpt-4-turbo\"]\n) -> str:\ndef obtain_chain(\n model_name: LLM_Name,\n template: str,\n input_variables: list[str],\n temperature: float = 0.7,\n max_retries: int = 6,\n) -> LLMChain:\ndef format_bad_output_for_script(\n ill_formed_output: str,\n format_instructions: str,\n agents: list[str],\n model_name: LLM_Name = \"gpt-3.5-turbo\",\n) -> str:\ndef format_bad_output(\n ill_formed_output: str,\n format_instructions: str,\n model_name: LLM_Name = \"gpt-3.5-turbo\",\n) -> str:\ndef generate(\n model_name: LLM_Name,\n template: str,\n input_values: dict[str, str],\n output_parser: BaseOutputParser[OutputType],\n temperature: float = 0.7,\n) -> OutputType:\nasync def agenerate(\n model_name: LLM_Name,\n template: str,\n input_values: dict[str, str],\n output_parser: BaseOutputParser[OutputType],\n temperature: float = 0.7,\n) -> tuple[OutputType, str]:\ndef generate_episode(\n model_name: LLM_Name,\n participants: str = \"Jack (a greedy person), Rose\",\n topic: str = \"lawsuit\",\n extra_info: str = \"\",\n) -> EnvResponse:\nasync def agenerate_env_profile(\n model_name: LLM_Name,\n inspiration_prompt: str = \"asking my boyfriend to stop being friends with his ex\",\n examples: str = \"\",\n temperature: float = 0.7,\n) -> tuple[EnvironmentProfile, str]:\nasync def agenerate_relationship_profile(\n model_name: LLM_Name,\n agents_profiles: list[str],\n) -> tuple[RelationshipProfile, str]:\nasync def agenerate_enviroment_profile(\n model_name: LLM_Name,\n inspiration_prompt: str = \"asking my boyfriend to stop being friends with his ex\",\n examples: str = \"\",\n) -> tuple[EnvironmentProfile, str]:\ndef fill_in_background(\n model_name: LLM_Name,\n partial_background: ScriptBackground,\n) -> ScriptBackground:\ndef generate_action(\n model_name: LLM_Name,\n history: str,\n turn_number: int,\n action_types: list[ActionType],\n agent: str,\n goal: str,\n) -> AgentAction:\ndef generate_action_speak(\n model_name: LLM_Name,\n history: str,\n turn_number: int,\n action_types: list[ActionType],\n agent: str,\n goal: str,\n) -> AgentAction:\nasync def agenerate_action(\n model_name: LLM_Name,\n history: str,\n turn_number: int,\n action_types: list[ActionType],\n agent: str,\n goal: str,\n temperature: float = 0.7,\n script_like: bool = False,\n) -> tuple[AgentAction, str]:\nasync def agenerate_script(\n model_name: LLM_Name,\n background: ScriptBackground,\n temperature: float = 0.7,\n agent_names: list[str] = [],\n agent_name: str = \"\",\n history: str = \"\",\n single_step: bool = False,\n) -> tuple[ScriptInteractionReturnType, str]:\ndef process_history(\n script: ScriptBackground | EnvResponse | dict[str, AgentAction]\n) -> str:\ndef generate_init_profile(\n model_name: LLM_Name, basic_info: dict[str, str]\n) -> str:\ndef convert_narratives(model_name: LLM_Name, narrative: str, text: str) -> str:\ndef generate_goal(model_name: LLM_Name, background: str) -> str:" }, { "identifier": "AgentAction", "path": "sotopia/messages/message_classes.py", "snippet": "class AgentAction(Message):\n action_type: ActionType = Field(\n description=\"whether to speak at this turn or choose to not do anything\"\n )\n argument: str = Field(\n description=\"the utterance if choose to speak, the expression or gesture if choose non-verbal communication, or the physical action if choose action\"\n )\n\n def to_natural_language(self) -> str:\n match self.action_type:\n case \"none\":\n return \"did nothing\"\n case \"speak\":\n return f'said: \"{self.argument}\"'\n case \"non-verbal communication\":\n return f\"[{self.action_type}] {self.argument}\"\n case \"action\":\n return f\"[{self.action_type}] {self.argument}\"\n case \"leave\":\n return \"left the conversation\"" }, { "identifier": "Message", "path": "sotopia/messages/message_classes.py", "snippet": "class Message(BaseModel):\n \"\"\"\n An interface for messages.\n There is only one required method: to_natural_language\n \"\"\"\n\n def to_natural_language(self) -> str:\n raise NotImplementedError" }, { "identifier": "Observation", "path": "sotopia/messages/message_classes.py", "snippet": "class Observation(Message):\n last_turn: str = Field(description=\"the last turn of the conversation\")\n turn_number: int = Field(description=\"the turn number of the conversation\")\n available_actions: list[ActionType] = Field(\n description=\"the available actions\"\n )\n\n def to_natural_language(self) -> str:\n if self.turn_number == 0:\n return f\"\\n{self.last_turn}\\nConversation Starts:\\n\"\n else:\n return f\"Turn #{self.turn_number-1}: {self.last_turn}\\n\"" }, { "identifier": "ScriptBackground", "path": "sotopia/messages/message_classes.py", "snippet": "class ScriptBackground(Message):\n scenario: str = Field(description=\"scenario of the episode\")\n p1_name: str = Field(description=\"name of participant 1\")\n p2_name: str = Field(description=\"name of participant 2\")\n p1_background: str = Field(description=\"background of participant 1\")\n p2_background: str = Field(description=\"background of participant 2\")\n p1_goal: str = Field(description=\"goal of participant 1\")\n p2_goal: str = Field(description=\"goal of participant 2\")\n\n def to_natural_language(self) -> str:\n if self.p1_background and self.p2_background:\n return format_docstring(\n f\"\"\"Here is the context of this interaction:\n Scenario: {self.scenario}\n Participants: {self.p1_name} and {self.p2_name}\n {self.p1_name}'s background: {self.p1_background}\n {self.p2_name}'s background: {self.p2_background}\n {self.p1_name}'s goal: {self.p1_goal}\n {self.p2_name}'s goal: {self.p2_goal}\n \"\"\"\n )\n else:\n return format_docstring(\n f\"\"\"Here is the context of this interaction:\n Scenario: {self.scenario}\n Participants: {self.p1_name} and {self.p2_name}\n {self.p1_name}'s goal: {self.p1_goal}\n {self.p2_name}'s goal: {self.p2_goal}\n \"\"\"\n )" }, { "identifier": "ScriptEnvironmentResponse", "path": "sotopia/messages/message_classes.py", "snippet": "class ScriptEnvironmentResponse(Message):\n terminated: bool = Field(\n description=\"whether the conversation is terminated\",\n default_factory=lambda: False,\n )\n p1_rate: float | tuple[float, dict[str, float]] | None = Field(\n description=\"rating of participant 1, on the scale of 1 to 10\"\n )\n p2_rate: float | tuple[float, dict[str, float]] | None = Field(\n description=\"rating of participant 2, on the scale of 1 to 10\"\n )\n comments: str | None = Field(\n description=\"All of the comments supporting the termination and rating\"\n )\n\n def to_natural_language(self) -> str:\n reason_to_stop = format_docstring(\n f\"\"\"Environment response:\n {\"The conversation is terminated.\" if self.terminated else \"\"}\n {\"Rating of participant 1\" + str(self.p1_rate) if self.p1_rate is not None else \"\"}\n {\"Rating of participant 2\" + str(self.p2_rate) if self.p2_rate is not None else \"\"}\n {self.comments if self.comments is not None else \"\"}\n \"\"\"\n )\n clean_text = \"\"\n for line in reason_to_stop.split(\"\\n\"):\n if line.strip():\n clean_text += line + \"\\n\"\n return clean_text" }, { "identifier": "ScriptInteraction", "path": "sotopia/messages/message_classes.py", "snippet": "class ScriptInteraction(Message):\n interactions: str = Field(\n description=\"\"\"The interaction between the two participants in maximum 20 turns. Each turn is separated by a newline, and should only describe one agent. Following the structure:\n Turn #x\n [participant's name] [action] {argument for some actions}\n\n You can use different types of actions, but only use one in each turn. You should move other information into argument part. Below shows a python code snippet of the format for each action type:\n match self.action_type:\n case \"none\":\n return \"did nothing\"\n case \"speak\":\n return f'said: \"{self.argument}\"'\n case \"non-verbal communication\":\n return f\"[{self.action_type}] {self.argument}\"\n case \"action\":\n return f\"[{self.action_type}] {self.argument}\"\n case \"leave\":\n return \"left the conversation\"\n\n For example, the following is acceptable:\n Turn #x\n Oliver Thompson said: \"Hey Esmeralda, what's wrong? You seem upset.\"\n Turn #x\n Esmeralda Solis [action] moved closer\n Turn #x\n Oliver Thompson [non-verbal communication] smiled\n Turn #x\n Esmeralda Solis did nothing\n Turn #x\n Oliver Thompson left the conversation\n Turn #x\n Esmeralda Solis [action] leaned in and lowered her voice: \"Sorry\"\n\n And the following is not acceptable:\n Turn #1\n Oliver Thompson [speak] said: \"Hey Esmeralda, what's wrong? You seem upset.\"\n Turn #1\n Esmeralda Solis non-verbal communication moved closer\n \"\"\"\n )\n\n def to_natural_language(self) -> str:\n return self.interactions\n\n def parse(\n self, agent_names: list[str], background: str\n ) -> tuple[\n list[list[tuple[str, str, Message]]], list[tuple[str, Message]]\n ]:\n interaction = self.interactions\n # print(\"Interaction: \", interaction)\n lines = self.split_by_turn(interaction)\n\n agent_results = []\n results: list[list[tuple[str, str, Message]]] = [\n [\n (\n \"Environment\",\n name,\n Observation(\n last_turn=background,\n turn_number=0,\n available_actions=[\"none\"],\n ),\n )\n for name in agent_names\n ]\n ]\n\n for line_idx, line in enumerate(lines):\n try:\n res = self.parse_single_dialogue(line)\n action: AgentAction = cast(AgentAction, res[\"action\"])\n argument: str = cast(str, res[\"argument\"])\n turn: int = cast(int, res[\"turn\"])\n name: str = cast(str, res[\"name\"])\n\n parsed_action = AgentAction(\n action_type=action, argument=argument\n )\n if name not in agent_names:\n print(\n f\"The name of the agent, {name}, is not in the list of agent names, {agent_names}\"\n )\n name = agent_names[\n line_idx % 2\n ] # TODO Not sure what name to be set here\n except Exception as e:\n print(\n f\"Error when parsing the dialogue: {line}\",\n f\"The error is: {e}\",\n )\n raise e\n parsed_action = AgentAction(action_type=\"none\", argument=\"\")\n name = agent_names[line_idx % 2] # TODO same question as above\n inactive_agent_name = (\n agent_names[0] if name == agent_names[1] else agent_names[1]\n )\n results.append(\n [\n (\n \"Environment\",\n name,\n Observation(\n last_turn=\"environment is the agent\",\n turn_number=line_idx + 1,\n available_actions=[\"none\"],\n ),\n )\n for name in agent_names\n ]\n + [\n (name, \"Environment\", parsed_action),\n (\n inactive_agent_name,\n \"Environment\",\n AgentAction(\n action_type=\"none\", argument=\"did nothing\"\n ),\n ),\n ]\n )\n\n agent_results.append((name, parsed_action))\n # print(\"Parsed agent results: \", agent_results)\n return (results, agent_results) # type: ignore\n\n def parse_single_dialogue(\n self, dialogue: str\n ) -> dict[str, str | int | AgentAction | None]:\n \"\"\"Parse a single dialogue string and return a dictionary with turn, name, action, and argument.\"\"\"\n\n # Match the turn number and name. Assume all agent name starts with a capital letter and is followed by lowercase letters\n match_turn_name = re.match(\n r\"Turn #?(\\d+):?\\s*\\n((?:[A-Z]['a-z]* ?)+)\", dialogue\n )\n\n if not match_turn_name:\n raise ValueError(\n f\"The dialogue does not match the expected format: {dialogue}\"\n )\n return (\n None # TODO Which should we use, return None or raise error?\n )\n\n turn, name = match_turn_name.groups()\n action_content = dialogue[\n len(match_turn_name.group(0)) :\n ].strip() # Extract the action content\n\n # Check for different action types\n if \"did nothing\" in action_content:\n action, argument = \"none\", \"\"\n elif match := re.match(r'said: \"(.*?)\"', action_content):\n action, argument = \"speak\", match.group(1)\n action, argument = action.strip(), argument.strip()\n elif match := re.match(r'\\[speak\\] said: \"(.*?)\"', action_content):\n action, argument = \"speak\", match.group(1)\n action, argument = action.strip(), argument.strip()\n elif match := re.match(\n r\"\\[(non-verbal communication|action)\\] (.*)\", action_content\n ):\n action, argument = match.groups()\n elif \"left the conversation\" in action_content:\n # TODO Make it more elegant to handle the situation of `left the conversation.`\n action, argument = \"leave\", \"\"\n else:\n action, argument = None, None\n\n parsed_item = {\n \"turn\": int(turn),\n \"name\": name.strip(),\n \"action\": action,\n \"argument\": argument,\n }\n return parsed_item\n\n def split_by_turn(self, input_string: str) -> list[str]:\n \"\"\"Split the input dialogue string by turn and return a list of dialogues.\"\"\"\n # Split using 'Turn #' as delimiter, but keep the delimiter in the results\n dialogues = re.split(r\"(?=Turn #?\\d+)\", input_string)\n # Remove any empty strings and strip whitespace\n dialogues = [\n dialogue.strip() for dialogue in dialogues if dialogue.strip()\n ]\n dialogues = [\n dialogue for dialogue in dialogues if dialogue.startswith(\"Turn\")\n ]\n # Change from Turn #x to Turn (#)x (# is optional)\n dialogues[-1] = \"\\n\".join(\n dialogues[-1].split(\"\\n\")[:2]\n ) # Discard further input in the last turn\n # print(\"Dialogues: \", dialogues)\n return dialogues\n\n @staticmethod\n def default_value_for_return_type() -> ScriptInteractionReturnType:\n results_1: list[list[tuple[str, str, Message]]] = [\n [\n (\n \"Environment\",\n name,\n Observation(\n last_turn=\"Environment is the agent\",\n turn_number=0,\n available_actions=[\"none\"],\n ),\n )\n for name in [\"none\", \"none\"]\n ]\n ]\n results_2: list[tuple[str, Message]] = [\n (\"\", AgentAction(action_type=\"none\", argument=\"\"))\n ]\n return (results_1, results_2)" }, { "identifier": "BaseSampler", "path": "sotopia/samplers/base_sampler.py", "snippet": "class BaseSampler(Generic[ObsType, ActType]):\n def __init__(\n self,\n env_candidates: Sequence[EnvironmentProfile | str] | None = None,\n agent_candidates: Sequence[AgentProfile | str] | None = None,\n ) -> None:\n def sample(\n self,\n agent_classes: Type[BaseAgent[ObsType, ActType]]\n | list[Type[BaseAgent[ObsType, ActType]]],\n n_agent: int = 2,\n replacement: bool = True,\n size: int = 1,\n env_params: dict[str, Any] = {},\n agents_params: list[dict[str, Any]] = [{}, {}],\n ) -> Generator[EnvAgentCombo[ObsType, ActType], None, None]:" }, { "identifier": "ConstraintBasedSampler", "path": "sotopia/samplers/constraint_based_sampler.py", "snippet": "class ConstraintBasedSampler(BaseSampler[ObsType, ActType]):\n def sample(\n self,\n agent_classes: Type[BaseAgent[ObsType, ActType]]\n | list[Type[BaseAgent[ObsType, ActType]]],\n n_agent: int = 2,\n replacement: bool = True,\n size: int = 10,\n env_params: dict[str, Any] = {},\n agents_params: list[dict[str, Any]] = [{}, {}],\n ) -> Generator[EnvAgentCombo[ObsType, ActType], None, None]:\n \"\"\"\n Sample an environment and a list of agents based on the constraints of the environment.\n\n Note: Sampling without replacement is only restricted to single env candidate.\n This is due to the fact that the number of possible combinations of env and agents is huge.\n Please sample for each env separately if you want to sample without replacement.\n \"\"\"\n assert (\n not isinstance(agent_classes, list)\n or len(agent_classes) == n_agent\n ), f\"agent_classes should be a list of length {n_agent} or a single agent class\"\n\n if not isinstance(agent_classes, list):\n agent_classes = [agent_classes] * n_agent\n assert (\n len(agents_params) == n_agent\n ), f\"agents_params should be a list of length {n_agent}\"\n\n env_profiles: list[EnvironmentProfile] = []\n agents_which_fit_scenario: list[list[str]] = []\n\n agent_candidate_ids: set[str] | None = None\n if self.agent_candidates:\n agent_candidate_ids = set(\n str(agent.pk) if not isinstance(agent, str) else agent\n for agent in self.agent_candidates\n )\n else:\n agent_candidate_ids = None\n\n if not replacement:\n assert self.env_candidates and len(self.env_candidates) == 1, (\n \"Sampling without replacement is only restricted to single env candidate (must be provided in the constructor). \"\n \"This is due to the fact that the number of possible combinations of env and agents is huge. \"\n \"Please sample for each env separately if you want to sample without replacement.\"\n )\n\n env_profile_id = (\n self.env_candidates[0].pk\n if not isinstance(self.env_candidates[0], str)\n else self.env_candidates[0]\n )\n\n assert env_profile_id, \"Env candidate must have an id\"\n\n agents_which_fit_scenario = _get_fit_agents_for_one_env(\n env_profile_id, agent_candidate_ids, size\n )\n env_profiles = (\n [EnvironmentProfile.get(env_profile_id)] * size\n if isinstance(self.env_candidates[0], str)\n else [self.env_candidates[0]] * size\n )\n else:\n for _ in range(size):\n if self.env_candidates:\n env_profile = random.choice(self.env_candidates)\n if isinstance(env_profile, str):\n env_profile = EnvironmentProfile.get(env_profile)\n else:\n env_profile_id = random.choice(\n list(EnvironmentProfile.all_pks())\n )\n env_profile = EnvironmentProfile.get(env_profile_id)\n env_profiles.append(env_profile)\n env_profile_id = env_profile.pk\n assert env_profile_id, \"Env candidate must have an id\"\n agents_which_fit_scenario.append(\n _get_fit_agents_for_one_env(\n env_profile_id, agent_candidate_ids, 1\n )[0]\n )\n\n assert (\n len(env_profiles) == size\n ), \"Number of env_profiles is not equal to size\"\n assert (\n len(agents_which_fit_scenario) == size\n ), \"Number of agents_which_fit_scenario is not equal to size\"\n\n for env_profile, agent_profile_id_list in zip(\n env_profiles, agents_which_fit_scenario\n ):\n env = ParallelSotopiaEnv(env_profile=env_profile, **env_params)\n agent_profiles = [\n AgentProfile.get(id) for id in agent_profile_id_list\n ]\n\n agents = [\n agent_class(agent_profile=agent_profile, **agent_params)\n for agent_class, agent_profile, agent_params in zip(\n agent_classes, agent_profiles, agents_params\n )\n ]\n # set goal for each agent\n for agent, goal in zip(agents, env.profile.agent_goals):\n agent.goal = goal\n\n yield env, agents" }, { "identifier": "UniformSampler", "path": "sotopia/samplers/uniform_sampler.py", "snippet": "class UniformSampler(BaseSampler[ObsType, ActType]):\n def sample(\n self,\n agent_classes: Type[BaseAgent[ObsType, ActType]]\n | list[Type[BaseAgent[ObsType, ActType]]],\n n_agent: int = 2,\n replacement: bool = True,\n size: int = 1,\n env_params: dict[str, Any] = {},\n agents_params: list[dict[str, Any]] = [{}, {}],\n ) -> Generator[EnvAgentCombo[ObsType, ActType], None, None]:\n \"\"\"\n Sample an environment and `n_agent` agents.\n\n Runtime checks:\n 1. If `agent_classes` is a list, it should have length `n_agent`.\n 2. `agents_params` should also be a list of length `n_agent`.\n\n Note: Currently, uniform sampling without replacement is not supported.\n This is due to the difficulty of sequentially sampling environment and agents.\n In theory, we can reject samples that have been sampled before, but this is not efficient.\n Please open an issue if you need this feature.\n \"\"\"\n assert (\n not isinstance(agent_classes, list)\n or len(agent_classes) == n_agent\n ), f\"agent_classes should be a list of length {n_agent} or a single agent class\"\n\n if not isinstance(agent_classes, list):\n agent_classes = [agent_classes] * n_agent\n assert (\n len(agents_params) == n_agent\n ), f\"agents_params should be a list of length {n_agent}\"\n\n assert (\n replacement\n ), \"Uniform sampling without replacement is not supported yet\"\n\n for _ in range(size):\n if self.env_candidates:\n env_profile = random.choice(self.env_candidates)\n if isinstance(env_profile, str):\n env_profile = EnvironmentProfile.get(env_profile)\n else:\n env_profile_id = random.choice(\n list(EnvironmentProfile.all_pks())\n )\n env_profile = EnvironmentProfile.get(env_profile_id)\n env = ParallelSotopiaEnv(env_profile=env_profile, **env_params)\n\n if self.agent_candidates:\n agent_profile_candidates = self.agent_candidates\n if len(agent_profile_candidates) < n_agent:\n raise ValueError(\n f\"Number of agent candidates ({len(agent_profile_candidates)}) is less than number of agents ({n_agent})\"\n )\n else:\n agent_profile_candidates_keys = list(AgentProfile.all_pks())\n if len(agent_profile_candidates_keys) < n_agent:\n raise ValueError(\n f\"Number of agent profile candidates ({len(agent_profile_candidates_keys)}) in database is less than number of agents ({n_agent})\"\n )\n agent_profile_candidates = [\n AgentProfile.get(pk=pk)\n for pk in agent_profile_candidates_keys\n ]\n\n if len(agent_profile_candidates) == n_agent:\n agent_profiles_maybe_id = agent_profile_candidates\n else:\n agent_profiles_maybe_id = random.sample(\n agent_profile_candidates, n_agent\n )\n agent_profiles = [\n i if isinstance(i, AgentProfile) else AgentProfile.get(i)\n for i in agent_profiles_maybe_id\n ]\n agents = [\n agent_class(agent_profile=agent_profile, **agent_params)\n for agent_class, agent_profile, agent_params in zip(\n agent_classes, agent_profiles, agents_params\n )\n ]\n # set goal for each agent\n for agent, goal in zip(agents, env.profile.agent_goals):\n agent.goal = goal\n\n yield env, agents" } ]
import asyncio import functools import itertools import logging import gin import rich from typing import Callable, Literal, Sequence, Type, cast from beartype import beartype from tqdm.asyncio import tqdm_asyncio from sotopia.agents import ( Agents, HumanAgent, LLMAgent, RedisAgent, ScriptWritingAgent, SpeakAgent, ) from sotopia.agents.base_agent import BaseAgent from sotopia.database import EpisodeLog from sotopia.database.persistent_profile import ( AgentProfile, EnvironmentProfile, ) from sotopia.envs import ParallelSotopiaEnv from sotopia.envs.evaluators import ( ReachGoalLLMEvaluator, RuleBasedTerminatedEvaluator, unweighted_aggregate_evaluate, ) from sotopia.generation_utils.generate import LLM_Name, agenerate_script from sotopia.messages import AgentAction, Message, Observation from sotopia.messages.message_classes import ( ScriptBackground, ScriptEnvironmentResponse, ScriptInteraction, ) from sotopia.samplers import ( BaseSampler, ConstraintBasedSampler, EnvAgentCombo, UniformSampler, )
20,199
# Create Environment and agents # This step will be moved to outside this function env_params = { "model_name": model_dict["env"], "action_order": action_order, "evaluators": [ RuleBasedTerminatedEvaluator(max_turn_number=20, max_stale_turn=2), ], "terminal_evaluators": [ ReachGoalLLMEvaluator(model_dict["env"]), ], } agents_model_dict = { "agent1": model_dict["agent1"], "agent2": model_dict["agent2"], } def get_agent_class( model_name: str, ) -> Type[BaseAgent[Observation, AgentAction]]: if model_name == "human": return HumanAgent elif script_like and not json_in_script: return ScriptWritingAgent else: return LLMAgent if env_agent_combo_list: assert ( type(sampler) is BaseSampler ), "No sampler should be used when `env_agent_combo_list` is empty" env_agent_combo_iter = iter(env_agent_combo_list) else: env_agent_combo_iter = sampler.sample( agent_classes=[ get_agent_class(model_name) for model_name in agents_model_dict.values() ], n_agent=len(agents_model_dict), env_params=env_params, agents_params=[ {"model_name": model_name} if model_name != "human" else {} for model_name in agents_model_dict.values() ], ) episode_futures = [ arun_one_episode( env=env_agent_combo[0], agent_list=env_agent_combo[1], model_dict=model_dict, omniscient=omniscient, script_like=script_like, json_in_script=json_in_script, tag=tag, push_to_db=push_to_db, ) for env_agent_combo in env_agent_combo_iter ] batch_results = ( await tqdm_asyncio.gather(*episode_futures, desc="Running one batch") if using_async else [await i for i in episode_futures] ) return cast(list[list[tuple[str, str, Message]]], batch_results) async def arun_one_script( env: ParallelSotopiaEnv, agent_list: Sequence[BaseAgent[Observation, AgentAction]], model_dict: dict[str, LLM_Name], omniscient: bool = False, tag: str | None = None, push_to_db: bool = False, ) -> list[tuple[str, str, Message]]: """ Generate script for one episode Args: omniscient (bool): Whether the agent knows the goal of the other """ agents = Agents({agent.agent_name: agent for agent in agent_list}) env.reset(agents=agents, omniscient=omniscient) agent_names = [agent.agent_name for agent in agent_list] assert ( len(agent_names) == 2 ), f"only support 2 agents, current: {agent_names}" script_background = env.inbox[0][1] assert isinstance(script_background, ScriptBackground) story, prompt = await agenerate_script( model_name=model_dict["env"], background=script_background, agent_names=agent_names, ) messages, agent_messages = story env_message = [("Environment", script_background)] agent_messages = env_message + agent_messages evaluator = ReachGoalLLMEvaluator(model_name="gpt-4") response = unweighted_aggregate_evaluate( list( itertools.chain( *await asyncio.gather( *[ sing_evaluator.__acall__( turn_number=-1, messages=agent_messages, ) for sing_evaluator in [evaluator] ] ) ) ) ) info: dict[
@beartype def run_sync_server( model_name_dict: dict[str, LLM_Name], action_order: Literal["simutaneous", "round-robin", "random"], agents_info: dict[str, dict[str, str]] | None = None, partial_background_file: str | None = None, full_background_file: str | None = None, mode: str | None = None, ) -> list[tuple[str, str, Message]]: # Create Environment and agents # This step will be moved to outside this function env = ParallelSotopiaEnv( model_name=model_name_dict["env"], action_order=action_order, evaluators=[ RuleBasedTerminatedEvaluator(), ], ) if partial_background_file: environment_messages = env.reset( options={"partial_background_file": partial_background_file} ) elif full_background_file: environment_messages = env.reset( options={"full_background_file": full_background_file} ) else: environment_messages = env.reset() agents = Agents() agents_model_names = [model_name_dict["agent1"], model_name_dict["agent2"]] for agent_name, agent_model in zip(env.agents, agents_model_names): if agent_model == "human": agents[agent_name] = HumanAgent(agent_name) elif mode == "speak": agents[agent_name] = SpeakAgent(agent_name, model_name=agent_model) else: agents[agent_name] = LLMAgent(agent_name, model_name=agent_model) agents.reset() messages: list[tuple[str, str, Message]] = [] # Main Event Loop done = False for agent_name in env.agents: messages.append( ("Environment", agent_name, environment_messages[agent_name]) ) while not done: # gather agent messages agent_messages: dict[str, AgentAction] = dict() for agent_name in env.agents: if agents_info is not None: agents[agent_name].goal = agents_info[agent_name]["goal"] agent_messages[agent_name] = agents[agent_name].act( environment_messages[agent_name] ) messages.append( (agent_name, "Environment", agent_messages[agent_name]) ) # send agent messages to environment environment_messages, _, terminated, ___, ____ = env.step( agent_messages ) for agent_name in env.agents: messages.append( ("Environment", agent_name, environment_messages[agent_name]) ) done = all(terminated.values()) return messages @gin.configurable async def arun_one_episode( env: ParallelSotopiaEnv, agent_list: Sequence[BaseAgent[Observation, AgentAction]], model_dict: dict[str, LLM_Name], omniscient: bool = False, script_like: bool = False, json_in_script: bool = False, tag: str | None = None, push_to_db: bool = False, ) -> list[tuple[str, str, Message]]: agents = Agents({agent.agent_name: agent for agent in agent_list}) environment_messages = env.reset(agents=agents, omniscient=omniscient) agents_model_names = [model_dict["agent1"], model_dict["agent2"]] for agent_name, agent_model in zip(env.agents, agents_model_names): if agent_model == "human": agents[agent_name] = HumanAgent(agent_name) elif agent_model == "redis": agents[agent_name] = RedisAgent(agent_name) elif script_like and not json_in_script: agents[agent_name] = ScriptWritingAgent( agent_name, model_name=agent_model, background=env.background, agent_names=env.agents, ) else: agents[agent_name] = LLMAgent( agent_name, model_name=agent_model, script_like=script_like ) agents.reset() messages: list[list[tuple[str, str, Message]]] = [] # Main Event Loop done = False messages.append( [ ("Environment", agent_name, environment_messages[agent_name]) for agent_name in env.agents ] ) # set goal for agents for index, agent_name in enumerate(env.agents): agents[agent_name].goal = env.profile.agent_goals[index] rewards: list[list[float]] = [] reasons: list[str] = [] while not done: # gather agent messages agent_messages: dict[str, AgentAction] = dict() actions = await asyncio.gather( *[ agents[agent_name].aact(environment_messages[agent_name]) for agent_name in env.agents ] ) if script_like: # manually mask one message agent_mask = env.action_mask for idx in range(len(agent_mask)): print("Current mask: ", agent_mask) if agent_mask[idx] == 0: print("Action not taken: ", actions[idx]) actions[idx] = AgentAction(action_type="none", argument="") else: print("Current action taken: ", actions[idx]) # actions = cast(list[AgentAction], actions) for idx, agent_name in enumerate(env.agents): agent_messages[agent_name] = actions[idx] messages[-1].append( (agent_name, "Environment", agent_messages[agent_name]) ) # send agent messages to environment ( environment_messages, rewards_in_turn, terminated, ___, info, ) = await env.astep(agent_messages) messages.append( [ ("Environment", agent_name, environment_messages[agent_name]) for agent_name in env.agents ] ) # print("Environment message: ", environment_messages) # exit(0) rewards.append( [rewards_in_turn[agent_name] for agent_name in env.agents] ) reasons.append( " ".join(info[agent_name]["comments"] for agent_name in env.agents) ) done = all(terminated.values()) # TODO: clean up this part epilog = EpisodeLog( environment=env.profile.pk, agents=[agent.profile.pk for agent in agent_list], tag=tag, models=[model_dict["env"], model_dict["agent1"], model_dict["agent2"]], messages=[ [ (m[0], m[1], m[2].to_natural_language()) for m in messages_in_turn ] for messages_in_turn in messages ], reasoning=info[env.agents[0]]["comments"], rewards=[ info[agent_name]["complete_rating"] for agent_name in env.agents ], rewards_prompt=info["rewards_prompt"]["overall_prompt"], ) rich.print(epilog.rewards_prompt) agent_profiles, conversation = epilog.render_for_humans() for agent_profile in agent_profiles: rich.print(agent_profile) for message in conversation: rich.print(message) if push_to_db: try: epilog.save() except Exception as e: logging.error(f"Failed to save episode log: {e}") # flatten nested list messages return list(itertools.chain(*messages)) @gin.configurable @beartype async def run_async_server( model_dict: dict[str, LLM_Name], sampler: BaseSampler[Observation, AgentAction] = BaseSampler(), action_order: Literal[ "simutaneous", "round-robin", "random" ] = "round-robin", env_agent_combo_list: list[EnvAgentCombo[Observation, AgentAction]] = [], omniscient: bool = False, script_like: bool = False, json_in_script: bool = False, tag: str | None = None, push_to_db: bool = False, using_async: bool = True, ) -> list[list[tuple[str, str, Message]]]: """ Doc incomplete Args: omniscient (bool): Whether the agent knows the goal of the other, default to False script_like (bool): Whether we generate the turn in script like manner, default to False json_in_script (bool): Whether we requires the script generator to return json (Only valid when script_like is True), default to False Note: env_agent_combo_list is optional. When it defaults to [], sampler is used else the sampler is not used. Please pass in BaseSampler or simply not specify it when using this option. """ assert not ( push_to_db and tag is None ), "please provide a tag when push to db" # Create Environment and agents # This step will be moved to outside this function env_params = { "model_name": model_dict["env"], "action_order": action_order, "evaluators": [ RuleBasedTerminatedEvaluator(max_turn_number=20, max_stale_turn=2), ], "terminal_evaluators": [ ReachGoalLLMEvaluator(model_dict["env"]), ], } agents_model_dict = { "agent1": model_dict["agent1"], "agent2": model_dict["agent2"], } def get_agent_class( model_name: str, ) -> Type[BaseAgent[Observation, AgentAction]]: if model_name == "human": return HumanAgent elif script_like and not json_in_script: return ScriptWritingAgent else: return LLMAgent if env_agent_combo_list: assert ( type(sampler) is BaseSampler ), "No sampler should be used when `env_agent_combo_list` is empty" env_agent_combo_iter = iter(env_agent_combo_list) else: env_agent_combo_iter = sampler.sample( agent_classes=[ get_agent_class(model_name) for model_name in agents_model_dict.values() ], n_agent=len(agents_model_dict), env_params=env_params, agents_params=[ {"model_name": model_name} if model_name != "human" else {} for model_name in agents_model_dict.values() ], ) episode_futures = [ arun_one_episode( env=env_agent_combo[0], agent_list=env_agent_combo[1], model_dict=model_dict, omniscient=omniscient, script_like=script_like, json_in_script=json_in_script, tag=tag, push_to_db=push_to_db, ) for env_agent_combo in env_agent_combo_iter ] batch_results = ( await tqdm_asyncio.gather(*episode_futures, desc="Running one batch") if using_async else [await i for i in episode_futures] ) return cast(list[list[tuple[str, str, Message]]], batch_results) async def arun_one_script( env: ParallelSotopiaEnv, agent_list: Sequence[BaseAgent[Observation, AgentAction]], model_dict: dict[str, LLM_Name], omniscient: bool = False, tag: str | None = None, push_to_db: bool = False, ) -> list[tuple[str, str, Message]]: """ Generate script for one episode Args: omniscient (bool): Whether the agent knows the goal of the other """ agents = Agents({agent.agent_name: agent for agent in agent_list}) env.reset(agents=agents, omniscient=omniscient) agent_names = [agent.agent_name for agent in agent_list] assert ( len(agent_names) == 2 ), f"only support 2 agents, current: {agent_names}" script_background = env.inbox[0][1] assert isinstance(script_background, ScriptBackground) story, prompt = await agenerate_script( model_name=model_dict["env"], background=script_background, agent_names=agent_names, ) messages, agent_messages = story env_message = [("Environment", script_background)] agent_messages = env_message + agent_messages evaluator = ReachGoalLLMEvaluator(model_name="gpt-4") response = unweighted_aggregate_evaluate( list( itertools.chain( *await asyncio.gather( *[ sing_evaluator.__acall__( turn_number=-1, messages=agent_messages, ) for sing_evaluator in [evaluator] ] ) ) ) ) info: dict[
str, dict[str, str | ScriptEnvironmentResponse | float | None]
19
2023-10-23 19:47:26+00:00
24k
f0uriest/interpax
tests/test_interpolate.py
[ { "identifier": "fft_interp1d", "path": "interpax/_fourier.py", "snippet": "@partial(jit, static_argnames=\"n\")\ndef fft_interp1d(f: jax.Array, n: int, sx: jax.Array = None, dx: float = 1.0):\n \"\"\"Interpolation of a 1d periodic function via FFT.\n\n Parameters\n ----------\n f : ndarray, shape(nx, ...)\n Source data. Assumed to cover 1 full period, excluding the endpoint.\n n : int\n Number of desired interpolation points.\n sx : ndarray or None\n Shift in x to evaluate at. If original data is f(x), interpolates to f(x + sx)\n dx : float\n Spacing of source points\n\n Returns\n -------\n fi : ndarray, shape(n, ..., len(sx))\n Interpolated (and possibly shifted) data points\n \"\"\"\n c = jnp.fft.ifft(f, axis=0)\n nx = c.shape[0]\n if sx is not None:\n sx = jnp.exp(-1j * 2 * jnp.pi * jnp.fft.fftfreq(nx)[:, None] * sx / dx)\n c = (c[None].T * sx).T\n c = jnp.moveaxis(c, 0, -1)\n pad = ((n - nx) // 2, n - nx - (n - nx) // 2)\n if nx % 2 != 0:\n pad = pad[::-1]\n c = jnp.fft.ifftshift(_pad_along_axis(jnp.fft.fftshift(c, axes=0), pad, axis=0))\n return jnp.fft.fft(c, axis=0).real" }, { "identifier": "fft_interp2d", "path": "interpax/_fourier.py", "snippet": "@partial(jit, static_argnames=(\"n1\", \"n2\"))\ndef fft_interp2d(\n f: jax.Array,\n n1: int,\n n2: int,\n sx: jax.Array = None,\n sy: jax.Array = None,\n dx: float = 1.0,\n dy: float = 1.0,\n):\n \"\"\"Interpolation of a 2d periodic function via FFT.\n\n Parameters\n ----------\n f : ndarray, shape(nx, ny, ...)\n Source data. Assumed to cover 1 full period, excluding the endpoint.\n n1, n2 : int\n Number of desired interpolation points in x and y directions\n sx, sy : ndarray or None\n Shift in x and y to evaluate at. If original data is f(x,y), interpolates to\n f(x + sx, y + sy). Both must be provided or None\n dx, dy : float\n Spacing of source points in x and y\n\n Returns\n -------\n fi : ndarray, shape(n1, n2, ..., len(sx))\n Interpolated (and possibly shifted) data points\n \"\"\"\n c = jnp.fft.ifft2(f, axes=(0, 1))\n nx, ny = c.shape[:2]\n if (sx is not None) and (sy is not None):\n sx = jnp.exp(-1j * 2 * jnp.pi * jnp.fft.fftfreq(nx)[:, None] * sx / dx)\n sy = jnp.exp(-1j * 2 * jnp.pi * jnp.fft.fftfreq(ny)[:, None] * sy / dy)\n c = (c[None].T * sx[None, :, :] * sy[:, None, :]).T\n c = jnp.moveaxis(c, 0, -1)\n padx = ((n1 - nx) // 2, n1 - nx - (n1 - nx) // 2)\n pady = ((n2 - ny) // 2, n2 - ny - (n2 - ny) // 2)\n if nx % 2 != 0:\n padx = padx[::-1]\n if ny % 2 != 0:\n pady = pady[::-1]\n\n c = jnp.fft.ifftshift(\n _pad_along_axis(jnp.fft.fftshift(c, axes=0), padx, axis=0), axes=0\n )\n c = jnp.fft.ifftshift(\n _pad_along_axis(jnp.fft.fftshift(c, axes=1), pady, axis=1), axes=1\n )\n\n return jnp.fft.fft2(c, axes=(0, 1)).real" }, { "identifier": "Interpolator1D", "path": "interpax/_spline.py", "snippet": "class Interpolator1D(eqx.Module):\n \"\"\"Convenience class for representing a 1D interpolated function.\n\n Parameters\n ----------\n x : ndarray, shape(Nx,)\n coordinates of known function values (\"knots\")\n f : ndarray, shape(Nx,...)\n function values to interpolate\n method : str\n method of interpolation\n\n - ``'nearest'``: nearest neighbor interpolation\n - ``'linear'``: linear interpolation\n - ``'cubic'``: C1 cubic splines (aka local splines)\n - ``'cubic2'``: C2 cubic splines (aka natural splines)\n - ``'catmull-rom'``: C1 cubic centripetal \"tension\" splines\n - ``'cardinal'``: C1 cubic general tension splines. If used, can also pass\n keyword parameter ``c`` in float[0,1] to specify tension\n - ``'monotonic'``: C1 cubic splines that attempt to preserve monotonicity in the\n data, and will not introduce new extrema in the interpolated points\n - ``'monotonic-0'``: same as ``'monotonic'`` but with 0 first derivatives at\n both endpoints\n\n extrap : bool, float, array-like\n whether to extrapolate values beyond knots (True) or return nan (False),\n or a specified value to return for query points outside the bounds. Can\n also be passed as a 2 element array or tuple to specify different conditions\n for xq<x[0] and x[-1]<xq\n period : float > 0, None\n periodicity of the function. If given, function is assumed to be periodic\n on the interval [0,period]. None denotes no periodicity\n\n Notes\n -----\n This class is registered as a PyTree in JAX (it is actually an equinox.Module)\n so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)\n\n \"\"\"\n\n x: jax.Array\n f: jax.Array\n derivs: dict\n method: str\n extrap: Union[bool, float, tuple]\n period: Union[None, float]\n axis: int\n\n def __init__(\n self,\n x: jax.Array,\n f: jax.Array,\n method: str = \"cubic\",\n extrap: Union[bool, float, tuple] = False,\n period: Union[None, float] = None,\n **kwargs,\n ):\n x, f = map(jnp.asarray, (x, f))\n axis = kwargs.get(\"axis\", 0)\n fx = kwargs.pop(\"fx\", None)\n\n errorif(\n (len(x) != f.shape[axis]) or (jnp.ndim(x) != 1),\n ValueError,\n \"x and f must be arrays of equal length\",\n )\n errorif(method not in METHODS_1D, ValueError, f\"unknown method {method}\")\n\n self.x = x\n self.f = f\n self.axis = axis\n self.method = method\n self.extrap = extrap\n self.period = period\n\n if fx is None:\n fx = approx_df(x, f, method, axis, **kwargs)\n\n self.derivs = {\"fx\": fx}\n\n def __call__(self, xq: jax.Array, dx: int = 0):\n \"\"\"Evaluate the interpolated function or its derivatives.\n\n Parameters\n ----------\n xq : ndarray, shape(Nq,)\n Query points where interpolation is desired\n dx : int >= 0\n Derivative to take.\n\n Returns\n -------\n fq : ndarray, shape(Nq, ...)\n Interpolated values.\n \"\"\"\n return interp1d(\n xq,\n self.x,\n self.f,\n self.method,\n dx,\n self.extrap,\n self.period,\n **self.derivs,\n )" }, { "identifier": "Interpolator2D", "path": "interpax/_spline.py", "snippet": "class Interpolator2D(eqx.Module):\n \"\"\"Convenience class for representing a 2D interpolated function.\n\n Parameters\n ----------\n x : ndarray, shape(Nx,)\n x coordinates of known function values (\"knots\")\n y : ndarray, shape(Ny,)\n y coordinates of known function values (\"knots\")\n f : ndarray, shape(Nx,Ny,...)\n function values to interpolate\n method : str\n method of interpolation\n\n - ``'nearest'``: nearest neighbor interpolation\n - ``'linear'``: linear interpolation\n - ``'cubic'``: C1 cubic splines (aka local splines)\n - ``'cubic2'``: C2 cubic splines (aka natural splines)\n - ``'catmull-rom'``: C1 cubic centripetal \"tension\" splines\n - ``'cardinal'``: C1 cubic general tension splines. If used, can also pass\n keyword parameter ``c`` in float[0,1] to specify tension\n\n extrap : bool, float, array-like\n whether to extrapolate values beyond knots (True) or return nan (False),\n or a specified value to return for query points outside the bounds. Can\n also be passed as an array or tuple to specify different conditions\n [[xlow, xhigh],[ylow,yhigh]]\n period : float > 0, None, array-like, shape(2,)\n periodicity of the function in x, y directions. None denotes no periodicity,\n otherwise function is assumed to be periodic on the interval [0,period]. Use a\n single value for the same in both directions.\n\n Notes\n -----\n This class is registered as a PyTree in JAX (it is actually an equinox.Module)\n so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)\n\n \"\"\"\n\n x: jax.Array\n y: jax.Array\n f: jax.Array\n derivs: dict\n method: str\n extrap: Union[bool, float, tuple]\n period: Union[None, float, tuple]\n axis: int\n\n def __init__(\n self,\n x: jax.Array,\n y: jax.Array,\n f: jax.Array,\n method: str = \"cubic\",\n extrap: Union[bool, float, tuple] = False,\n period: Union[None, float, tuple] = None,\n **kwargs,\n ):\n x, y, f = map(jnp.asarray, (x, y, f))\n axis = kwargs.get(\"axis\", 0)\n fx = kwargs.pop(\"fx\", None)\n fy = kwargs.pop(\"fy\", None)\n fxy = kwargs.pop(\"fxy\", None)\n\n errorif(\n (len(x) != f.shape[0]) or (x.ndim != 1),\n ValueError,\n \"x and f must be arrays of equal length\",\n )\n errorif(\n (len(y) != f.shape[1]) or (y.ndim != 1),\n ValueError,\n \"y and f must be arrays of equal length\",\n )\n errorif(method not in METHODS_2D, ValueError, f\"unknown method {method}\")\n\n self.x = x\n self.y = y\n self.f = f\n self.axis = axis\n self.method = method\n self.extrap = extrap\n self.period = period\n\n if fx is None:\n fx = approx_df(x, f, method, 0, **kwargs)\n if fy is None:\n fy = approx_df(y, f, method, 1, **kwargs)\n if fxy is None:\n fxy = approx_df(y, fx, method, 1, **kwargs)\n\n self.derivs = {\"fx\": fx, \"fy\": fy, \"fxy\": fxy}\n\n def __call__(self, xq: jax.Array, yq: jax.Array, dx: int = 0, dy: int = 0):\n \"\"\"Evaluate the interpolated function or its derivatives.\n\n Parameters\n ----------\n xq, yq : ndarray, shape(Nq,)\n x, y query points where interpolation is desired\n dx, dy : int >= 0\n Derivative to take in x, y directions.\n\n Returns\n -------\n fq : ndarray, shape(Nq, ...)\n Interpolated values.\n \"\"\"\n return interp2d(\n xq,\n yq,\n self.x,\n self.y,\n self.f,\n self.method,\n (dx, dy),\n self.extrap,\n self.period,\n **self.derivs,\n )" }, { "identifier": "Interpolator3D", "path": "interpax/_spline.py", "snippet": "class Interpolator3D(eqx.Module):\n \"\"\"Convenience class for representing a 3D interpolated function.\n\n Parameters\n ----------\n x : ndarray, shape(Nx,)\n x coordinates of known function values (\"knots\")\n y : ndarray, shape(Ny,)\n y coordinates of known function values (\"knots\")\n z : ndarray, shape(Nz,)\n z coordinates of known function values (\"knots\")\n f : ndarray, shape(Nx,Ny,Nz,...)\n function values to interpolate\n method : str\n method of interpolation\n\n - ``'nearest'``: nearest neighbor interpolation\n - ``'linear'``: linear interpolation\n - ``'cubic'``: C1 cubic splines (aka local splines)\n - ``'cubic2'``: C2 cubic splines (aka natural splines)\n - ``'catmull-rom'``: C1 cubic centripetal \"tension\" splines\n - ``'cardinal'``: C1 cubic general tension splines. If used, can also pass\n keyword parameter ``c`` in float[0,1] to specify tension\n\n extrap : bool, float, array-like\n whether to extrapolate values beyond knots (True) or return nan (False),\n or a specified value to return for query points outside the bounds. Can\n also be passed as an array or tuple to specify different conditions\n [[xlow, xhigh],[ylow,yhigh]]\n period : float > 0, None, array-like, shape(2,)\n periodicity of the function in x, y, z directions. None denotes no periodicity,\n otherwise function is assumed to be periodic on the interval [0,period]. Use a\n single value for the same in both directions.\n\n Notes\n -----\n This class is registered as a PyTree in JAX (it is actually an equinox.Module)\n so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)\n\n \"\"\"\n\n x: jax.Array\n y: jax.Array\n z: jax.Array\n f: jax.Array\n derivs: dict\n method: str\n extrap: Union[bool, float, tuple]\n period: Union[None, float, tuple]\n axis: int\n\n def __init__(\n self,\n x: jax.Array,\n y: jax.Array,\n z: jax.Array,\n f: jax.Array,\n method: str = \"cubic\",\n extrap: Union[bool, float, tuple] = False,\n period: Union[None, float, tuple] = None,\n **kwargs,\n ):\n x, y, z, f = map(jnp.asarray, (x, y, z, f))\n axis = kwargs.get(\"axis\", 0)\n\n errorif(\n (len(x) != f.shape[0]) or (x.ndim != 1),\n ValueError,\n \"x and f must be arrays of equal length\",\n )\n errorif(\n (len(y) != f.shape[1]) or (y.ndim != 1),\n ValueError,\n \"y and f must be arrays of equal length\",\n )\n errorif(\n (len(z) != f.shape[2]) or (z.ndim != 1),\n ValueError,\n \"z and f must be arrays of equal length\",\n )\n errorif(method not in METHODS_3D, ValueError, f\"unknown method {method}\")\n\n fx = kwargs.pop(\"fx\", None)\n fy = kwargs.pop(\"fy\", None)\n fz = kwargs.pop(\"fz\", None)\n fxy = kwargs.pop(\"fxy\", None)\n fxz = kwargs.pop(\"fxz\", None)\n fyz = kwargs.pop(\"fyz\", None)\n fxyz = kwargs.pop(\"fxyz\", None)\n\n self.x = x\n self.y = y\n self.z = z\n self.f = f\n self.axis = axis\n self.method = method\n self.extrap = extrap\n self.period = period\n\n if fx is None:\n fx = approx_df(x, f, method, 0, **kwargs)\n if fy is None:\n fy = approx_df(y, f, method, 1, **kwargs)\n if fz is None:\n fz = approx_df(z, f, method, 2, **kwargs)\n if fxy is None:\n fxy = approx_df(y, fx, method, 1, **kwargs)\n if fxz is None:\n fxz = approx_df(z, fx, method, 2, **kwargs)\n if fyz is None:\n fyz = approx_df(z, fy, method, 2, **kwargs)\n if fxyz is None:\n fxyz = approx_df(z, fxy, method, 2, **kwargs)\n\n self.derivs = {\n \"fx\": fx,\n \"fy\": fy,\n \"fz\": fz,\n \"fxy\": fxy,\n \"fxz\": fxz,\n \"fyz\": fyz,\n \"fxyz\": fxyz,\n }\n\n def __call__(\n self,\n xq: jax.Array,\n yq: jax.Array,\n zq: jax.Array,\n dx: int = 0,\n dy: int = 0,\n dz: int = 0,\n ):\n \"\"\"Evaluate the interpolated function or its derivatives.\n\n Parameters\n ----------\n xq, yq, zq : ndarray, shape(Nq,)\n x, y, z query points where interpolation is desired\n dx, dy, dz : int >= 0\n Derivative to take in x, y, z directions.\n\n Returns\n -------\n fq : ndarray, shape(Nq, ...)\n Interpolated values.\n \"\"\"\n return interp3d(\n xq,\n yq,\n zq,\n self.x,\n self.y,\n self.z,\n self.f,\n self.method,\n (dx, dy, dz),\n self.extrap,\n self.period,\n **self.derivs,\n )" }, { "identifier": "interp1d", "path": "interpax/_spline.py", "snippet": "@partial(jit, static_argnames=\"method\")\ndef interp1d(\n xq: jax.Array,\n x: jax.Array,\n f: jax.Array,\n method: str = \"cubic\",\n derivative: int = 0,\n extrap: Union[bool, float, tuple] = False,\n period: Union[None, float] = None,\n **kwargs,\n):\n \"\"\"Interpolate a 1d function.\n\n Parameters\n ----------\n xq : ndarray, shape(Nq,)\n query points where interpolation is desired\n x : ndarray, shape(Nx,)\n coordinates of known function values (\"knots\")\n f : ndarray, shape(Nx,...)\n function values to interpolate\n method : str\n method of interpolation\n\n - ``'nearest'``: nearest neighbor interpolation\n - ``'linear'``: linear interpolation\n - ``'cubic'``: C1 cubic splines (aka local splines)\n - ``'cubic2'``: C2 cubic splines (aka natural splines)\n - ``'catmull-rom'``: C1 cubic centripetal \"tension\" splines\n - ``'cardinal'``: C1 cubic general tension splines. If used, can also pass\n keyword parameter ``c`` in float[0,1] to specify tension\n - ``'monotonic'``: C1 cubic splines that attempt to preserve monotonicity in the\n data, and will not introduce new extrema in the interpolated points\n - ``'monotonic-0'``: same as ``'monotonic'`` but with 0 first derivatives at\n both endpoints\n\n derivative : int >= 0\n derivative order to calculate\n extrap : bool, float, array-like\n whether to extrapolate values beyond knots (True) or return nan (False),\n or a specified value to return for query points outside the bounds. Can\n also be passed as a 2 element array or tuple to specify different conditions\n for xq<x[0] and x[-1]<xq\n period : float > 0, None\n periodicity of the function. If given, function is assumed to be periodic\n on the interval [0,period]. None denotes no periodicity\n\n Returns\n -------\n fq : ndarray, shape(Nq,...)\n function value at query points\n\n Notes\n -----\n For repeated interpolation given the same x, f data, recommend using Interpolator1D\n which caches the calculation of the derivatives and spline coefficients.\n\n \"\"\"\n xq, x, f = map(jnp.asarray, (xq, x, f))\n axis = kwargs.get(\"axis\", 0)\n fx = kwargs.pop(\"fx\", None)\n outshape = xq.shape + f.shape[1:]\n\n # Promote scalar query points to 1D array.\n # Note this is done after the computation of outshape\n # to make jax.grad work in the scalar case.\n xq = jnp.atleast_1d(xq)\n\n errorif(\n (len(x) != f.shape[axis]) or (jnp.ndim(x) != 1),\n ValueError,\n \"x and f must be arrays of equal length\",\n )\n errorif(method not in METHODS_1D, ValueError, f\"unknown method {method}\")\n\n lowx, highx = _parse_extrap(extrap, 1)\n\n if period is not None:\n xq, x, f, fx = _make_periodic(xq, x, period, axis, f, fx)\n lowx = highx = True\n\n if method == \"nearest\":\n\n def derivative0():\n i = jnp.argmin(jnp.abs(xq[:, np.newaxis] - x[np.newaxis]), axis=1)\n return f[i]\n\n def derivative1():\n return jnp.zeros((xq.size, *f.shape[1:]))\n\n fq = jax.lax.switch(derivative, [derivative0, derivative1])\n\n elif method == \"linear\":\n\n def derivative0():\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n df = jnp.take(f, i, axis) - jnp.take(f, i - 1, axis)\n dx = x[i] - x[i - 1]\n dxi = jnp.where(dx == 0, 0, 1 / dx)\n delta = xq - x[i - 1]\n fq = jnp.where(\n (dx == 0),\n jnp.take(f, i, axis).T,\n jnp.take(f, i - 1, axis).T + (delta * dxi * df.T),\n ).T\n return fq\n\n def derivative1():\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n df = jnp.take(f, i, axis) - jnp.take(f, i - 1, axis)\n dx = x[i] - x[i - 1]\n dxi = jnp.where(dx == 0, 0, 1 / dx)\n return (df.T * dxi).T\n\n def derivative2():\n return jnp.zeros((xq.size, *f.shape[1:]))\n\n fq = jax.lax.switch(derivative, [derivative0, derivative1, derivative2])\n\n elif method in (CUBIC_METHODS + (\"monotonic\", \"monotonic-0\")):\n\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n if fx is None:\n fx = approx_df(x, f, method, axis, **kwargs)\n assert fx.shape == f.shape\n\n dx = x[i] - x[i - 1]\n delta = xq - x[i - 1]\n dxi = jnp.where(dx == 0, 0, 1 / dx)\n t = delta * dxi\n\n f0 = jnp.take(f, i - 1, axis)\n f1 = jnp.take(f, i, axis)\n fx0 = (jnp.take(fx, i - 1, axis).T * dx).T\n fx1 = (jnp.take(fx, i, axis).T * dx).T\n\n F = jnp.stack([f0, f1, fx0, fx1], axis=0).T\n coef = jnp.vectorize(jnp.matmul, signature=\"(n,n),(n)->(n)\")(A_CUBIC, F).T\n ttx = _get_t_der(t, derivative, dxi)\n fq = jnp.einsum(\"ji...,ij->i...\", coef, ttx)\n\n fq = _extrap(xq, fq, x, lowx, highx)\n return fq.reshape(outshape)" }, { "identifier": "interp2d", "path": "interpax/_spline.py", "snippet": "@partial(jit, static_argnames=\"method\")\ndef interp2d( # noqa: C901 - FIXME: break this up into simpler pieces\n xq: jax.Array,\n yq: jax.Array,\n x: jax.Array,\n y: jax.Array,\n f: jax.Array,\n method: str = \"cubic\",\n derivative: int = 0,\n extrap: Union[bool, float, tuple] = False,\n period: Union[None, float, tuple] = None,\n **kwargs,\n):\n \"\"\"Interpolate a 2d function.\n\n Parameters\n ----------\n xq : ndarray, shape(Nq,)\n x query points where interpolation is desired\n yq : ndarray, shape(Nq,)\n y query points where interpolation is desired\n x : ndarray, shape(Nx,)\n x coordinates of known function values (\"knots\")\n y : ndarray, shape(Ny,)\n y coordinates of known function values (\"knots\")\n f : ndarray, shape(Nx,Ny,...)\n function values to interpolate\n method : str\n method of interpolation\n\n - ``'nearest'``: nearest neighbor interpolation\n - ``'linear'``: linear interpolation\n - ``'cubic'``: C1 cubic splines (aka local splines)\n - ``'cubic2'``: C2 cubic splines (aka natural splines)\n - ``'catmull-rom'``: C1 cubic centripetal \"tension\" splines\n - ``'cardinal'``: C1 cubic general tension splines. If used, can also pass\n keyword parameter ``c`` in float[0,1] to specify tension\n\n derivative : int >= 0 or array-like, shape(2,)\n derivative order to calculate in x, y. Use a single value for the same in both\n directions.\n extrap : bool, float, array-like\n whether to extrapolate values beyond knots (True) or return nan (False),\n or a specified value to return for query points outside the bounds. Can\n also be passed as an array or tuple to specify different conditions\n [[xlow, xhigh],[ylow,yhigh]]\n period : float > 0, None, array-like, shape(2,)\n periodicity of the function in x, y directions. None denotes no periodicity,\n otherwise function is assumed to be periodic on the interval [0,period]. Use a\n single value for the same in both directions.\n\n Returns\n -------\n fq : ndarray, shape(Nq,...)\n function value at query points\n\n Notes\n -----\n For repeated interpolation given the same x, y, f data, recommend using\n Interpolator2D which caches the calculation of the derivatives and spline\n coefficients.\n\n \"\"\"\n xq, yq, x, y, f = map(jnp.asarray, (xq, yq, x, y, f))\n fx = kwargs.pop(\"fx\", None)\n fy = kwargs.pop(\"fy\", None)\n fxy = kwargs.pop(\"fxy\", None)\n xq, yq = jnp.broadcast_arrays(xq, yq)\n outshape = xq.shape + f.shape[2:]\n\n # Promote scalar query points to 1D array.\n # Note this is done after the computation of outshape\n # to make jax.grad work in the scalar case.\n xq, yq = map(jnp.atleast_1d, (xq, yq))\n\n errorif(\n (len(x) != f.shape[0]) or (x.ndim != 1),\n ValueError,\n \"x and f must be arrays of equal length\",\n )\n errorif(\n (len(y) != f.shape[1]) or (y.ndim != 1),\n ValueError,\n \"y and f must be arrays of equal length\",\n )\n errorif(method not in METHODS_2D, ValueError, f\"unknown method {method}\")\n\n periodx, periody = _parse_ndarg(period, 2)\n derivative_x, derivative_y = _parse_ndarg(derivative, 2)\n lowx, highx, lowy, highy = _parse_extrap(extrap, 2)\n\n if periodx is not None:\n xq, x, f, fx, fy, fxy = _make_periodic(xq, x, periodx, 0, f, fx, fy, fxy)\n lowx = highx = True\n if periody is not None:\n yq, y, f, fx, fy, fxy = _make_periodic(yq, y, periody, 1, f, fx, fy, fxy)\n lowy = highy = True\n\n if method == \"nearest\":\n\n def derivative0():\n # because of the regular spaced grid we know that the nearest point\n # will be one of the 4 neighbors on the grid, so we first find those\n # and then take the nearest one among them.\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n j = jnp.clip(jnp.searchsorted(y, yq, side=\"right\"), 1, len(y) - 1)\n neighbors_x = jnp.array(\n [[x[i], x[i - 1], x[i], x[i - 1]], [y[j], y[j], y[j - 1], y[j - 1]]]\n )\n neighbors_f = jnp.array(\n [f[i, j].T, f[i - 1, j].T, f[i, j - 1].T, f[i - 1, j - 1].T]\n )\n xyq = jnp.array([xq, yq])\n dist = jnp.linalg.norm(neighbors_x - xyq[:, None, :], axis=0)\n idx = jnp.argmin(dist, axis=0)\n return jax.vmap(lambda a, b: jnp.take(a, b, axis=-1))(neighbors_f.T, idx)\n\n def derivative1():\n return jnp.zeros((xq.size, *f.shape[2:]))\n\n fq = jax.lax.cond(\n (derivative_x == 0) & (derivative_y == 0), derivative0, derivative1\n )\n\n elif method == \"linear\":\n\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n j = jnp.clip(jnp.searchsorted(y, yq, side=\"right\"), 1, len(y) - 1)\n\n f00 = f[i - 1, j - 1]\n f01 = f[i - 1, j]\n f10 = f[i, j - 1]\n f11 = f[i, j]\n x0 = x[i - 1]\n x1 = x[i]\n y0 = y[j - 1]\n y1 = y[j]\n dx = x1 - x0\n dxi = jnp.where(dx == 0, 0, 1 / dx)\n dy = y1 - y0\n dyi = jnp.where(dy == 0, 0, 1 / dy)\n\n dx0 = lambda: jnp.array([x1 - xq, xq - x0])\n dx1 = lambda: jnp.array([-jnp.ones_like(xq), jnp.ones_like(xq)])\n dx2 = lambda: jnp.zeros((2, xq.size))\n dy0 = lambda: jnp.array([y1 - yq, yq - y0])\n dy1 = lambda: jnp.array([-jnp.ones_like(yq), jnp.ones_like(yq)])\n dy2 = lambda: jnp.zeros((2, yq.size))\n\n tx = jax.lax.switch(derivative_x, [dx0, dx1, dx2])\n ty = jax.lax.switch(derivative_y, [dy0, dy1, dy2])\n F = jnp.array([[f00, f01], [f10, f11]])\n fq = (dxi * dyi * jnp.einsum(\"ijk...,ik,jk->k...\", F, tx, ty).T).T\n\n elif method in CUBIC_METHODS:\n if fx is None:\n fx = approx_df(x, f, method, 0, **kwargs)\n if fy is None:\n fy = approx_df(y, f, method, 1, **kwargs)\n if fxy is None:\n fxy = approx_df(y, fx, method, 1, **kwargs)\n assert fx.shape == fy.shape == fxy.shape == f.shape\n\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n j = jnp.clip(jnp.searchsorted(y, yq, side=\"right\"), 1, len(y) - 1)\n\n dx = x[i] - x[i - 1]\n deltax = xq - x[i - 1]\n dxi = jnp.where(dx == 0, 0, 1 / dx)\n tx = deltax * dxi\n dy = y[j] - y[j - 1]\n deltay = yq - y[j - 1]\n dyi = jnp.where(dy == 0, 0, 1 / dy)\n ty = deltay * dyi\n\n fs = OrderedDict()\n fs[\"f\"] = f\n fs[\"fx\"] = fx\n fs[\"fy\"] = fy\n fs[\"fxy\"] = fxy\n fsq = OrderedDict()\n for ff in fs.keys():\n for jj in [0, 1]:\n for ii in [0, 1]:\n s = ff + str(ii) + str(jj)\n fsq[s] = fs[ff][i - 1 + ii, j - 1 + jj]\n if \"x\" in ff:\n fsq[s] = (dx * fsq[s].T).T\n if \"y\" in ff:\n fsq[s] = (dy * fsq[s].T).T\n\n F = jnp.stack([foo for foo in fsq.values()], axis=0).T\n coef = jnp.vectorize(jnp.matmul, signature=\"(n,n),(n)->(n)\")(A_BICUBIC, F).T\n coef = jnp.moveaxis(coef.reshape((4, 4, *coef.shape[1:]), order=\"F\"), 2, 0)\n ttx = _get_t_der(tx, derivative_x, dxi)\n tty = _get_t_der(ty, derivative_y, dyi)\n fq = jnp.einsum(\"ijk...,ij,ik->i...\", coef, ttx, tty)\n\n fq = _extrap(xq, fq, x, lowx, highx)\n fq = _extrap(yq, fq, y, lowy, highy)\n\n return fq.reshape(outshape)" }, { "identifier": "interp3d", "path": "interpax/_spline.py", "snippet": "@partial(jit, static_argnames=\"method\")\ndef interp3d( # noqa: C901 - FIXME: break this up into simpler pieces\n xq: jax.Array,\n yq: jax.Array,\n zq: jax.Array,\n x: jax.Array,\n y: jax.Array,\n z: jax.Array,\n f: jax.Array,\n method: str = \"cubic\",\n derivative: int = 0,\n extrap: Union[bool, float, tuple] = False,\n period: Union[None, float, tuple] = None,\n **kwargs,\n):\n \"\"\"Interpolate a 3d function.\n\n Parameters\n ----------\n xq : ndarray, shape(Nq,)\n x query points where interpolation is desired\n yq : ndarray, shape(Nq,)\n y query points where interpolation is desired\n zq : ndarray, shape(Nq,)\n z query points where interpolation is desired\n x : ndarray, shape(Nx,)\n x coordinates of known function values (\"knots\")\n y : ndarray, shape(Ny,)\n y coordinates of known function values (\"knots\")\n z : ndarray, shape(Nz,)\n z coordinates of known function values (\"knots\")\n f : ndarray, shape(Nx,Ny,Nz,...)\n function values to interpolate\n method : str\n method of interpolation\n\n - ``'nearest'``: nearest neighbor interpolation\n - ``'linear'``: linear interpolation\n - ``'cubic'``: C1 cubic splines (aka local splines)\n - ``'cubic2'``: C2 cubic splines (aka natural splines)\n - ``'catmull-rom'``: C1 cubic centripetal \"tension\" splines\n - ``'cardinal'``: C1 cubic general tension splines. If used, can also pass\n keyword parameter ``c`` in float[0,1] to specify tension\n\n derivative : int >= 0, array-like, shape(3,)\n derivative order to calculate in x,y,z directions. Use a single value for the\n same in all directions.\n extrap : bool, float, array-like\n whether to extrapolate values beyond knots (True) or return nan (False),\n or a specified value to return for query points outside the bounds. Can\n also be passed as an array or tuple to specify different conditions for\n [[xlow, xhigh],[ylow,yhigh],[zlow,zhigh]]\n period : float > 0, None, array-like, shape(3,)\n periodicity of the function in x, y, z directions. None denotes no periodicity,\n otherwise function is assumed to be periodic on the interval [0,period]. Use a\n single value for the same in all directions.\n\n Returns\n -------\n fq : ndarray, shape(Nq,...)\n function value at query points\n\n Notes\n -----\n For repeated interpolation given the same x, y, z, f data, recommend using\n Interpolator3D which caches the calculation of the derivatives and spline\n coefficients.\n\n \"\"\"\n xq, yq, zq, x, y, z, f = map(jnp.asarray, (xq, yq, zq, x, y, z, f))\n errorif(\n (len(x) != f.shape[0]) or (x.ndim != 1),\n ValueError,\n \"x and f must be arrays of equal length\",\n )\n errorif(\n (len(y) != f.shape[1]) or (y.ndim != 1),\n ValueError,\n \"y and f must be arrays of equal length\",\n )\n errorif(\n (len(z) != f.shape[2]) or (z.ndim != 1),\n ValueError,\n \"z and f must be arrays of equal length\",\n )\n errorif(method not in METHODS_3D, ValueError, f\"unknown method {method}\")\n\n xq, yq, zq = jnp.broadcast_arrays(xq, yq, zq)\n outshape = xq.shape + f.shape[3:]\n\n # Promote scalar query points to 1D array.\n # Note this is done after the computation of outshape\n # to make jax.grad work in the scalar case.\n xq, yq, zq = map(jnp.atleast_1d, (xq, yq, zq))\n\n fx = kwargs.pop(\"fx\", None)\n fy = kwargs.pop(\"fy\", None)\n fz = kwargs.pop(\"fz\", None)\n fxy = kwargs.pop(\"fxy\", None)\n fxz = kwargs.pop(\"fxz\", None)\n fyz = kwargs.pop(\"fyz\", None)\n fxyz = kwargs.pop(\"fxyz\", None)\n\n periodx, periody, periodz = _parse_ndarg(period, 3)\n derivative_x, derivative_y, derivative_z = _parse_ndarg(derivative, 3)\n lowx, highx, lowy, highy, lowz, highz = _parse_extrap(extrap, 3)\n\n if periodx is not None:\n xq, x, f, fx, fy, fz, fxy, fxz, fyz, fxyz = _make_periodic(\n xq, x, periodx, 0, f, fx, fy, fz, fxy, fxz, fyz, fxyz\n )\n lowx = highx = True\n if periody is not None:\n yq, y, f, fx, fy, fz, fxy, fxz, fyz, fxyz = _make_periodic(\n yq, y, periody, 1, f, fx, fy, fz, fxy, fxz, fyz, fxyz\n )\n lowy = highy = True\n if periodz is not None:\n zq, z, f, fx, fy, fz, fxy, fxz, fyz, fxyz = _make_periodic(\n zq, z, periodz, 2, f, fx, fy, fz, fxy, fxz, fyz, fxyz\n )\n lowz = highz = True\n\n if method == \"nearest\":\n\n def derivative0():\n # because of the regular spaced grid we know that the nearest point\n # will be one of the 8 neighbors on the grid, so we first find those\n # and then take the nearest one among them.\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n j = jnp.clip(jnp.searchsorted(y, yq, side=\"right\"), 1, len(y) - 1)\n k = jnp.clip(jnp.searchsorted(z, zq, side=\"right\"), 1, len(z) - 1)\n neighbors_x = jnp.array(\n [\n [x[i], x[i - 1], x[i], x[i - 1], x[i], x[i - 1], x[i], x[i - 1]],\n [y[j], y[j], y[j - 1], y[j - 1], y[j], y[j], y[j - 1], y[j - 1]],\n [z[k], z[k], z[k], z[k], z[k - 1], z[k - 1], z[k - 1], z[k - 1]],\n ]\n )\n neighbors_f = jnp.array(\n [\n f[i, j, k].T,\n f[i - 1, j, k].T,\n f[i, j - 1, k].T,\n f[i - 1, j - 1, k].T,\n f[i, j, k - 1].T,\n f[i - 1, j, k - 1].T,\n f[i, j - 1, k - 1].T,\n f[i - 1, j - 1, k - 1].T,\n ]\n )\n xyzq = jnp.array([xq, yq, zq])\n dist = jnp.linalg.norm(neighbors_x - xyzq[:, None, :], axis=0)\n idx = jnp.argmin(dist, axis=0)\n return jax.vmap(lambda a, b: jnp.take(a, b, axis=-1))(neighbors_f.T, idx)\n\n def derivative1():\n return jnp.zeros((xq.size, *f.shape[3:]))\n\n fq = jax.lax.cond(\n (derivative_x == 0) & (derivative_y == 0) & (derivative_z == 0),\n derivative0,\n derivative1,\n )\n\n elif method == \"linear\":\n\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n j = jnp.clip(jnp.searchsorted(y, yq, side=\"right\"), 1, len(y) - 1)\n k = jnp.clip(jnp.searchsorted(z, zq, side=\"right\"), 1, len(z) - 1)\n\n f000 = f[i - 1, j - 1, k - 1]\n f001 = f[i - 1, j - 1, k]\n f010 = f[i - 1, j, k - 1]\n f100 = f[i, j - 1, k - 1]\n f110 = f[i, j, k - 1]\n f011 = f[i - 1, j, k]\n f101 = f[i, j - 1, k]\n f111 = f[i, j, k]\n x0 = x[i - 1]\n x1 = x[i]\n y0 = y[j - 1]\n y1 = y[j]\n z0 = z[k - 1]\n z1 = z[k]\n dx = x1 - x0\n dxi = jnp.where(dx == 0, 0, 1 / dx)\n dy = y1 - y0\n dyi = jnp.where(dy == 0, 0, 1 / dy)\n dz = z1 - z0\n dzi = jnp.where(dz == 0, 0, 1 / dz)\n\n dx0 = lambda: jnp.array([x1 - xq, xq - x0])\n dx1 = lambda: jnp.array([-jnp.ones_like(xq), jnp.ones_like(xq)])\n dx2 = lambda: jnp.zeros((2, xq.size))\n dy0 = lambda: jnp.array([y1 - yq, yq - y0])\n dy1 = lambda: jnp.array([-jnp.ones_like(yq), jnp.ones_like(yq)])\n dy2 = lambda: jnp.zeros((2, yq.size))\n dz0 = lambda: jnp.array([z1 - zq, zq - z0])\n dz1 = lambda: jnp.array([-jnp.ones_like(zq), jnp.ones_like(zq)])\n dz2 = lambda: jnp.zeros((2, zq.size))\n\n tx = jax.lax.switch(derivative_x, [dx0, dx1, dx2])\n ty = jax.lax.switch(derivative_y, [dy0, dy1, dy2])\n tz = jax.lax.switch(derivative_z, [dz0, dz1, dz2])\n\n F = jnp.array([[[f000, f001], [f010, f011]], [[f100, f101], [f110, f111]]])\n fq = (dxi * dyi * dzi * jnp.einsum(\"lijk...,lk,ik,jk->k...\", F, tx, ty, tz).T).T\n\n elif method in CUBIC_METHODS:\n if fx is None:\n fx = approx_df(x, f, method, 0, **kwargs)\n if fy is None:\n fy = approx_df(y, f, method, 1, **kwargs)\n if fz is None:\n fz = approx_df(z, f, method, 2, **kwargs)\n if fxy is None:\n fxy = approx_df(y, fx, method, 1, **kwargs)\n if fxz is None:\n fxz = approx_df(z, fx, method, 2, **kwargs)\n if fyz is None:\n fyz = approx_df(z, fy, method, 2, **kwargs)\n if fxyz is None:\n fxyz = approx_df(z, fxy, method, 2, **kwargs)\n assert (\n fx.shape\n == fy.shape\n == fz.shape\n == fxy.shape\n == fxz.shape\n == fyz.shape\n == fxyz.shape\n == f.shape\n )\n i = jnp.clip(jnp.searchsorted(x, xq, side=\"right\"), 1, len(x) - 1)\n j = jnp.clip(jnp.searchsorted(y, yq, side=\"right\"), 1, len(y) - 1)\n k = jnp.clip(jnp.searchsorted(z, zq, side=\"right\"), 1, len(z) - 1)\n\n dx = x[i] - x[i - 1]\n deltax = xq - x[i - 1]\n dxi = jnp.where(dx == 0, 0, 1 / dx)\n tx = deltax * dxi\n\n dy = y[j] - y[j - 1]\n deltay = yq - y[j - 1]\n dyi = jnp.where(dy == 0, 0, 1 / dy)\n ty = deltay * dyi\n\n dz = z[k] - z[k - 1]\n deltaz = zq - z[k - 1]\n dzi = jnp.where(dz == 0, 0, 1 / dz)\n tz = deltaz * dzi\n\n fs = OrderedDict()\n fs[\"f\"] = f\n fs[\"fx\"] = fx\n fs[\"fy\"] = fy\n fs[\"fz\"] = fz\n fs[\"fxy\"] = fxy\n fs[\"fxz\"] = fxz\n fs[\"fyz\"] = fyz\n fs[\"fxyz\"] = fxyz\n fsq = OrderedDict()\n for ff in fs.keys():\n for kk in [0, 1]:\n for jj in [0, 1]:\n for ii in [0, 1]:\n s = ff + str(ii) + str(jj) + str(kk)\n fsq[s] = fs[ff][i - 1 + ii, j - 1 + jj, k - 1 + kk]\n if \"x\" in ff:\n fsq[s] = (dx * fsq[s].T).T\n if \"y\" in ff:\n fsq[s] = (dy * fsq[s].T).T\n if \"z\" in ff:\n fsq[s] = (dz * fsq[s].T).T\n\n F = jnp.stack([foo for foo in fsq.values()], axis=0).T\n coef = jnp.vectorize(jnp.matmul, signature=\"(n,n),(n)->(n)\")(A_TRICUBIC, F).T\n coef = jnp.moveaxis(coef.reshape((4, 4, 4, *coef.shape[1:]), order=\"F\"), 3, 0)\n ttx = _get_t_der(tx, derivative_x, dxi)\n tty = _get_t_der(ty, derivative_y, dyi)\n ttz = _get_t_der(tz, derivative_z, dzi)\n fq = jnp.einsum(\"lijk...,li,lj,lk->l...\", coef, ttx, tty, ttz)\n\n fq = _extrap(xq, fq, x, lowx, highx)\n fq = _extrap(yq, fq, y, lowy, highy)\n fq = _extrap(zq, fq, z, lowz, highz)\n\n return fq.reshape(outshape)" } ]
import jax import jax.numpy as jnp import numpy as np import pytest from jax import config as jax_config from interpax import ( Interpolator1D, Interpolator2D, Interpolator3D, fft_interp1d, fft_interp2d, interp1d, interp2d, interp3d, )
14,725
xp = np.linspace(0, 2 * np.pi, 100) f = lambda x: np.sin(x) fp = f(xp) interp1 = lambda xq, *args, **kwargs: interp1d(xq, *args, **kwargs) interp2 = lambda xq, *args, **kwargs: Interpolator1D(*args, **kwargs)(xq) for interp in [interp1, interp2]: fq = interp(x, xp, fp, method="nearest") np.testing.assert_allclose(fq, f(x), rtol=1e-2, atol=1e-1) fq = interp(x, xp, fp, method="linear") np.testing.assert_allclose(fq, f(x), rtol=1e-4, atol=1e-3) fq = interp(x, xp, fp, method="cubic") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="cubic2") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="cardinal") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="catmull-rom") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="monotonic") np.testing.assert_allclose(fq, f(x), rtol=1e-4, atol=1e-3) fq = interp(x, xp, fp, method="monotonic-0") np.testing.assert_allclose(fq, f(x), rtol=1e-4, atol=1e-2) @pytest.mark.unit def test_interp1d_vector_valued(self): """Test for interpolating vector valued function.""" xp = np.linspace(0, 2 * np.pi, 100) x = np.linspace(0, 2 * np.pi, 300)[10:-10] f = lambda x: np.array([np.sin(x), np.cos(x)]) fp = f(xp).T fq = interp1d(x, xp, fp, method="nearest") np.testing.assert_allclose(fq, f(x).T, rtol=1e-2, atol=1e-1) fq = interp1d(x, xp, fp, method="linear") np.testing.assert_allclose(fq, f(x).T, rtol=1e-4, atol=1e-3) fq = interp1d(x, xp, fp, method="cubic") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="cubic2") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="cardinal") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="catmull-rom") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="monotonic") np.testing.assert_allclose(fq, f(x).T, rtol=1e-4, atol=1e-3) fq = interp1d(x, xp, fp, method="monotonic-0") np.testing.assert_allclose(fq, f(x).T, rtol=1e-4, atol=1e-2) @pytest.mark.unit def test_interp1d_extrap_periodic(self): """Test extrapolation and periodic BC of 1d interpolation.""" xp = np.linspace(0, 2 * np.pi, 200) x = np.linspace(-1, 2 * np.pi + 1, 10000) f = lambda x: np.sin(x) fp = f(xp) fq = interp1d(x, xp, fp, method="cubic", extrap=False) assert np.isnan(fq[0]) assert np.isnan(fq[-1]) fq = interp1d(x, xp, fp, method="cubic", extrap=True) assert not np.isnan(fq[0]) assert not np.isnan(fq[-1]) fq = interp1d(x, xp, fp, method="cubic", period=2 * np.pi) np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-2) @pytest.mark.unit def test_interp1d_monotonic(self): """Ensure monotonic interpolation is actually monotonic.""" # true function is just linear with a jump discontinuity at x=1.5 x = np.linspace(-4, 5, 10) f = np.heaviside(x - 1.5, 0) + 0.1 * x xq = np.linspace(-4, 5, 1000) dfc = interp1d(xq, x, f, derivative=1, method="cubic") dfm = interp1d(xq, x, f, derivative=1, method="monotonic") dfm0 = interp1d(xq, x, f, derivative=1, method="monotonic-0") assert dfc.min() < 0 # cubic interpolation undershoots, giving negative slope assert dfm.min() > 0 # monotonic interpolation doesn't assert dfm0.min() >= 0 # monotonic-0 doesn't overshoot either # ensure monotonic-0 has 0 slope at end points np.testing.assert_allclose(dfm0[np.array([0, -1])], 0, atol=1e-12) class TestInterp2D: """Tests for interp2d function.""" @pytest.mark.unit @pytest.mark.parametrize( "x, y", [ (np.linspace(0, 3 * np.pi, 1000), np.linspace(0, 2 * np.pi, 1000)), (0.0, 0.0), ], ) def test_interp2d(self, x, y): """Test accuracy of different 2d interpolation methods.""" xp = np.linspace(0, 3 * np.pi, 99) yp = np.linspace(0, 2 * np.pi, 40) xxp, yyp = np.meshgrid(xp, yp, indexing="ij") f = lambda x, y: np.sin(x) * np.cos(y) fp = f(xxp, yyp)
"""Tests for interpolation functions.""" jax_config.update("jax_enable_x64", True) class TestInterp1D: """Tests for interp1d function.""" @pytest.mark.unit @pytest.mark.parametrize( "x", [ np.linspace(0, 2 * np.pi, 10000), 0.0, ], ) def test_interp1d(self, x): """Test accuracy of different 1d interpolation methods.""" xp = np.linspace(0, 2 * np.pi, 100) f = lambda x: np.sin(x) fp = f(xp) interp1 = lambda xq, *args, **kwargs: interp1d(xq, *args, **kwargs) interp2 = lambda xq, *args, **kwargs: Interpolator1D(*args, **kwargs)(xq) for interp in [interp1, interp2]: fq = interp(x, xp, fp, method="nearest") np.testing.assert_allclose(fq, f(x), rtol=1e-2, atol=1e-1) fq = interp(x, xp, fp, method="linear") np.testing.assert_allclose(fq, f(x), rtol=1e-4, atol=1e-3) fq = interp(x, xp, fp, method="cubic") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="cubic2") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="cardinal") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="catmull-rom") np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-5) fq = interp(x, xp, fp, method="monotonic") np.testing.assert_allclose(fq, f(x), rtol=1e-4, atol=1e-3) fq = interp(x, xp, fp, method="monotonic-0") np.testing.assert_allclose(fq, f(x), rtol=1e-4, atol=1e-2) @pytest.mark.unit def test_interp1d_vector_valued(self): """Test for interpolating vector valued function.""" xp = np.linspace(0, 2 * np.pi, 100) x = np.linspace(0, 2 * np.pi, 300)[10:-10] f = lambda x: np.array([np.sin(x), np.cos(x)]) fp = f(xp).T fq = interp1d(x, xp, fp, method="nearest") np.testing.assert_allclose(fq, f(x).T, rtol=1e-2, atol=1e-1) fq = interp1d(x, xp, fp, method="linear") np.testing.assert_allclose(fq, f(x).T, rtol=1e-4, atol=1e-3) fq = interp1d(x, xp, fp, method="cubic") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="cubic2") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="cardinal") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="catmull-rom") np.testing.assert_allclose(fq, f(x).T, rtol=1e-6, atol=1e-5) fq = interp1d(x, xp, fp, method="monotonic") np.testing.assert_allclose(fq, f(x).T, rtol=1e-4, atol=1e-3) fq = interp1d(x, xp, fp, method="monotonic-0") np.testing.assert_allclose(fq, f(x).T, rtol=1e-4, atol=1e-2) @pytest.mark.unit def test_interp1d_extrap_periodic(self): """Test extrapolation and periodic BC of 1d interpolation.""" xp = np.linspace(0, 2 * np.pi, 200) x = np.linspace(-1, 2 * np.pi + 1, 10000) f = lambda x: np.sin(x) fp = f(xp) fq = interp1d(x, xp, fp, method="cubic", extrap=False) assert np.isnan(fq[0]) assert np.isnan(fq[-1]) fq = interp1d(x, xp, fp, method="cubic", extrap=True) assert not np.isnan(fq[0]) assert not np.isnan(fq[-1]) fq = interp1d(x, xp, fp, method="cubic", period=2 * np.pi) np.testing.assert_allclose(fq, f(x), rtol=1e-6, atol=1e-2) @pytest.mark.unit def test_interp1d_monotonic(self): """Ensure monotonic interpolation is actually monotonic.""" # true function is just linear with a jump discontinuity at x=1.5 x = np.linspace(-4, 5, 10) f = np.heaviside(x - 1.5, 0) + 0.1 * x xq = np.linspace(-4, 5, 1000) dfc = interp1d(xq, x, f, derivative=1, method="cubic") dfm = interp1d(xq, x, f, derivative=1, method="monotonic") dfm0 = interp1d(xq, x, f, derivative=1, method="monotonic-0") assert dfc.min() < 0 # cubic interpolation undershoots, giving negative slope assert dfm.min() > 0 # monotonic interpolation doesn't assert dfm0.min() >= 0 # monotonic-0 doesn't overshoot either # ensure monotonic-0 has 0 slope at end points np.testing.assert_allclose(dfm0[np.array([0, -1])], 0, atol=1e-12) class TestInterp2D: """Tests for interp2d function.""" @pytest.mark.unit @pytest.mark.parametrize( "x, y", [ (np.linspace(0, 3 * np.pi, 1000), np.linspace(0, 2 * np.pi, 1000)), (0.0, 0.0), ], ) def test_interp2d(self, x, y): """Test accuracy of different 2d interpolation methods.""" xp = np.linspace(0, 3 * np.pi, 99) yp = np.linspace(0, 2 * np.pi, 40) xxp, yyp = np.meshgrid(xp, yp, indexing="ij") f = lambda x, y: np.sin(x) * np.cos(y) fp = f(xxp, yyp)
interp1 = lambda xq, yq, *args, **kwargs: interp2d(xq, yq, *args, **kwargs)
6
2023-10-18 13:12:20+00:00
24k
amitfin/oref_alert
custom_components/oref_alert/coordinator.py
[ { "identifier": "CONF_ALERT_MAX_AGE", "path": "custom_components/oref_alert/const.py", "snippet": "CONF_ALERT_MAX_AGE: Final = \"alert_max_age\"" }, { "identifier": "CONF_POLL_INTERVAL", "path": "custom_components/oref_alert/const.py", "snippet": "CONF_POLL_INTERVAL: Final = \"poll_interval\"" }, { "identifier": "DEFAULT_POLL_INTERVAL", "path": "custom_components/oref_alert/const.py", "snippet": "DEFAULT_POLL_INTERVAL: Final = 2" }, { "identifier": "DOMAIN", "path": "custom_components/oref_alert/const.py", "snippet": "DOMAIN: Final = \"oref_alert\"" }, { "identifier": "IST", "path": "custom_components/oref_alert/const.py", "snippet": "IST = zoneinfo.ZoneInfo(\"Asia/Jerusalem\")" }, { "identifier": "LOGGER", "path": "custom_components/oref_alert/const.py", "snippet": "LOGGER = logging.getLogger(__package__)" }, { "identifier": "AREAS", "path": "custom_components/oref_alert/metadata/areas.py", "snippet": "AREAS = {\n \"אבו סנאן\",\n \"אבו קרינאת\",\n \"אבו תלול\",\n \"אבו-גוש\",\n \"אבטליון\",\n \"אביאל\",\n \"אביבים\",\n \"אביגדור\",\n \"אביחיל\",\n \"אביעזר\",\n \"אבירים\",\n \"אבן יהודה\",\n \"אבן מנחם\",\n \"אבן ספיר\",\n \"אבן שמואל\",\n \"אבני איתן\",\n \"אבני חפץ\",\n \"אבנת\",\n \"אבשלום\",\n \"אדורה\",\n \"אדוריים\",\n \"אדמית\",\n \"אדרת\",\n \"אודים\",\n \"אודם\",\n \"אום אל פחם\",\n \"אום אל קוטוף\",\n \"אום אל-גנם\",\n \"אום בטין\",\n \"אופקים\",\n \"אור הגנוז\",\n \"אור הנר\",\n \"אור יהודה\",\n \"אור עקיבא\",\n \"אורה\",\n \"אורון תעשייה ומסחר\",\n \"אורות\",\n \"אורטל\",\n \"אורים\",\n \"אורנים\",\n \"אורנית\",\n \"אושה\",\n \"אזור\",\n \"אזור תעשייה אכזיב מילואות\",\n \"אזור תעשייה אלון התבור\",\n \"אזור תעשייה אפק ולב הארץ\",\n \"אזור תעשייה באר טוביה\",\n \"אזור תעשייה בני יהודה\",\n \"אזור תעשייה בר-לב\",\n \"אזור תעשייה בראון\",\n \"אזור תעשייה ברוש\",\n \"אזור תעשייה דימונה\",\n \"אזור תעשייה הדרומי אשקלון\",\n \"אזור תעשייה הר טוב - צרעה\",\n \"אזור תעשייה חבל מודיעין\",\n \"אזור תעשייה חצור הגלילית\",\n \"אזור תעשייה טירה\",\n \"אזור תעשייה יקנעם עילית\",\n \"אזור תעשייה כנות\",\n \"אזור תעשייה כרמיאל\",\n \"אזור תעשייה מבוא כרמל\",\n \"אזור תעשייה מבואות הגלבוע\",\n \"אזור תעשייה מישור אדומים\",\n \"אזור תעשייה מיתרים\",\n \"אזור תעשייה נ.ע.מ\",\n \"אזור תעשייה ניר עציון\",\n \"אזור תעשייה נשר - רמלה\",\n \"אזור תעשייה עד הלום\",\n \"אזור תעשייה עידן הנגב\",\n \"אזור תעשייה עמק חפר\",\n \"אזור תעשייה צ.ח.ר\",\n \"אזור תעשייה צבאים\",\n \"אזור תעשייה ציפורית\",\n \"אזור תעשייה צמח\",\n \"אזור תעשייה צפוני אשקלון\",\n \"אזור תעשייה קדמת גליל\",\n \"אזור תעשייה קיסריה\",\n \"אזור תעשייה קריית גת\",\n \"אזור תעשייה רגבים\",\n \"אזור תעשייה רותם\",\n \"אזור תעשייה רמת דלתון\",\n \"אזור תעשייה שחורת\",\n \"אזור תעשייה שער בנימין\",\n \"אזור תעשייה שער נעמן\",\n \"אזור תעשייה תימורים\",\n \"אזור תעשייה תרדיון\",\n \"אחווה\",\n \"אחוזם\",\n \"אחוזת ברק\",\n \"אחיה\",\n \"אחיהוד\",\n \"אחיטוב\",\n \"אחיסמך\",\n \"אחיעזר\",\n \"איבטין\",\n \"אייל\",\n \"איילת השחר\",\n \"אילון\",\n \"אילות\",\n \"אילניה\",\n \"אילת\",\n \"אירוס\",\n \"איתמר\",\n \"איתן\",\n \"אכסאל\",\n \"אל סייד\",\n \"אל עזי\",\n \"אל עמארני, אל מסק\",\n \"אל עריאן\",\n \"אל פורעה\",\n \"אל רום\",\n \"אל-ח'וואלד מערב\",\n \"אלומה\",\n \"אלומות\",\n \"אלון\",\n \"אלון הגליל\",\n \"אלון מורה\",\n \"אלון שבות\",\n \"אלוני אבא\",\n \"אלוני הבשן\",\n \"אלוני יצחק\",\n \"אלונים\",\n \"אלי עד\",\n \"אליאב\",\n \"אליכין\",\n \"אליפז ומכרות תמנע\",\n \"אליפלט\",\n \"אליקים\",\n \"אלישיב\",\n \"אלישמע\",\n \"אלמגור\",\n \"אלמוג\",\n \"אלעד\",\n \"אלעזר\",\n \"אלפי מנשה\",\n \"אלקוש\",\n \"אלקנה\",\n \"אמונים\",\n \"אמירים\",\n \"אמנון\",\n \"אמץ\",\n \"אמציה\",\n \"אניעם\",\n \"אעבלין\",\n \"אפיק\",\n \"אפיקים\",\n \"אפק\",\n \"אפרת\",\n \"ארבל\",\n \"ארגמן\",\n \"ארז\",\n \"אריאל\",\n \"ארסוף\",\n \"אשבול\",\n \"אשבל\",\n \"אשדוד - א,ב,ד,ה\",\n \"אשדוד - איזור תעשייה צפוני\",\n \"אשדוד - ג,ו,ז\",\n \"אשדוד - ח,ט,י,יג,יד,טז\",\n \"אשדוד -יא,יב,טו,יז,מרינה,סיט\",\n \"אשדות יעקב איחוד\",\n \"אשדות יעקב מאוחד\",\n \"אשחר\",\n \"אשכולות\",\n \"אשל הנשיא\",\n \"אשלים\",\n \"אשקלון - דרום\",\n \"אשקלון - צפון\",\n \"אשרת\",\n \"אשתאול\",\n \"אתר דודאים\",\n \"אתר ההנצחה גולני\",\n \"באקה אל גרבייה\",\n \"באר אורה\",\n \"באר גנים\",\n \"באר טוביה\",\n \"באר יעקב\",\n \"באר מילכה\",\n \"באר שבע - דרום\",\n \"באר שבע - מזרח\",\n \"באר שבע - מערב\",\n \"באר שבע - צפון\",\n \"בארות יצחק\",\n \"בארותיים\",\n \"בארי\",\n \"בוסתן הגליל\",\n \"בועיינה-נוג'ידאת\",\n \"בוקעתא\",\n \"בורגתה\",\n \"בחן\",\n \"בטחה\",\n \"ביצרון\",\n \"ביר אלמכסור\",\n \"ביר הדאג'\",\n \"ביריה\",\n \"בית אורן\",\n \"בית אל\",\n \"בית אלעזרי\",\n \"בית אלפא וחפציבה\",\n \"בית אריה\",\n \"בית ברל\",\n \"בית ג'אן\",\n \"בית גוברין\",\n \"בית גמליאל\",\n \"בית דגן\",\n \"בית הגדי\",\n \"בית הלוי\",\n \"בית הלל\",\n \"בית העמק\",\n \"בית הערבה\",\n \"בית השיטה\",\n \"בית זית\",\n \"בית זרע\",\n \"בית חגי\",\n \"בית חורון\",\n \"בית חזון\",\n \"בית חלקיה\",\n \"בית חנן\",\n \"בית חנניה\",\n \"בית חרות\",\n \"בית חשמונאי\",\n \"בית יהושע\",\n \"בית יוסף\",\n \"בית ינאי\",\n \"בית יצחק - שער חפר\",\n \"בית ירח\",\n \"בית יתיר\",\n \"בית לחם הגלילית\",\n \"בית מאיר\",\n \"בית נחמיה\",\n \"בית ניר\",\n \"בית נקופה\",\n \"בית סוהר השרון\",\n \"בית סוהר מגידו\",\n \"בית סוהר נפחא\",\n \"בית סוהר צלמון\",\n \"בית סוהר קישון\",\n \"בית סוהר שיטה וגלבוע\",\n \"בית ספר אורט בנימינה\",\n \"בית ספר שדה מירון\",\n \"בית עובד\",\n \"בית עוזיאל\",\n \"בית עזרא\",\n \"בית עלמין תל רגב\",\n \"בית עריף\",\n \"בית צבי\",\n \"בית קמה\",\n \"בית קשת\",\n \"בית רימון\",\n \"בית שאן\",\n \"בית שמש\",\n \"בית שערים\",\n \"בית שקמה\",\n \"ביתן אהרן\",\n \"ביתר עילית\",\n \"בלפוריה\",\n \"בן זכאי\",\n \"בן עמי\",\n \"בן שמן\",\n \"בני ברק\",\n \"בני דקלים\",\n \"בני דרום\",\n \"בני דרור\",\n \"בני יהודה וגבעת יואב\",\n \"בני נצרים\",\n \"בני עטרות\",\n \"בני עי''ש\",\n \"בני ציון\",\n \"בני ראם\",\n \"בניה\",\n \"בנימינה\",\n 'בסמ\"ה',\n \"בסמת טבעון\",\n \"בענה\",\n \"בצרה\",\n \"בצת\",\n \"בקוע\",\n \"בקעות\",\n \"בר גיורא\",\n \"בר יוחאי\",\n \"ברוכין\",\n \"ברור חיל\",\n \"ברוש\",\n \"ברטעה\",\n \"ברכיה\",\n \"ברעם\",\n \"ברקאי\",\n \"ברקן\",\n \"ברקת\",\n \"בת הדר\",\n \"בת חן\",\n \"בת חפר\",\n \"בת עין\",\n \"בת שלמה\",\n \"בת-ים\",\n \"בתי מלון ים המלח\",\n \"ג'דידה מכר\",\n \"ג'וליס\",\n \"ג'לג'וליה\",\n \"ג'סר א-זרקא\",\n \"ג'ש - גוש חלב\",\n \"ג'ת\",\n \"גאולי תימן\",\n \"גאולים\",\n \"גאליה\",\n \"גבולות\",\n \"גבים, מכללת ספיר\",\n \"גבע בנימין\",\n \"גבע כרמל\",\n \"גבעון החדשה\",\n \"גבעות\",\n \"גבעות בר\",\n \"גבעות גורל\",\n \"גבעות עדן\",\n \"גבעת אבני\",\n \"גבעת אלה\",\n \"גבעת אסף\",\n \"גבעת ברנר\",\n \"גבעת הראל וגבעת הרואה\",\n \"גבעת השלושה\",\n \"גבעת וולפסון\",\n \"גבעת וושינגטון\",\n \"גבעת זאב\",\n \"גבעת חביבה\",\n \"גבעת חיים איחוד\",\n \"גבעת חיים מאוחד\",\n \"גבעת חן\",\n \"גבעת יערים\",\n \"גבעת ישעיהו\",\n \"גבעת כ''ח\",\n \"גבעת ניל''י\",\n \"גבעת עדה\",\n \"גבעת עוז\",\n \"גבעת שמואל\",\n \"גבעת שפירא\",\n \"גבעתי\",\n \"גבעתיים\",\n \"גברעם\",\n \"גבת\",\n \"גדות\",\n \"גדיש\",\n \"גדעונה\",\n \"גדרה\",\n \"גונן\",\n \"גורן\",\n \"גורנות הגליל\",\n \"גזית\",\n \"גזר\",\n \"גיאה\",\n \"גיבתון\",\n \"גיזו\",\n \"גילת\",\n \"גינוסר\",\n \"גינתון\",\n \"גיתה\",\n \"גיתית\",\n \"גלאון\",\n \"גלגל\",\n \"גלעד\",\n \"גמזו\",\n \"גן הדרום\",\n \"גן השומרון\",\n \"גן חיים\",\n \"גן יאשיה\",\n \"גן יבנה\",\n \"גן נר\",\n \"גן שורק\",\n \"גן שלמה\",\n \"גן שמואל\",\n \"גנות\",\n \"גנות הדר\",\n \"גני הדר\",\n \"גני טל\",\n \"גני יוחנן\",\n \"גני מודיעין\",\n \"גני עם\",\n \"גני תקווה\",\n \"גניגר\",\n \"געש\",\n \"געתון\",\n \"גפן\",\n \"גרופית\",\n \"גשור\",\n \"גשר\",\n \"גשר הזיו\",\n \"גת\",\n \"גת רימון\",\n \"דבוריה\",\n \"דביר\",\n \"דברת\",\n \"דגניה א\",\n \"דגניה ב\",\n \"דוב''ב\",\n \"דולב\",\n \"דור\",\n \"דורות\",\n \"דחי\",\n \"דימונה\",\n \"דיר אל-אסד\",\n \"דיר חנא\",\n \"דישון\",\n \"דליה\",\n \"דלית אל כרמל\",\n \"דלתון\",\n \"דמיידה\",\n \"דניאל\",\n \"דפנה\",\n \"דקל\",\n \"האון\",\n \"הבונים\",\n \"הגושרים\",\n \"הדר עם\",\n \"הוד השרון\",\n \"הודיה\",\n \"הודיות\",\n \"הושעיה\",\n \"הזורעים\",\n \"החותרים\",\n \"היוגב\",\n \"הילה\",\n \"המכללה האקדמית כנרת\",\n \"המעפיל\",\n \"המרכז האקדמי רופין\",\n \"הסוללים\",\n \"העוגן\",\n \"הר אדר\",\n \"הר ברכה\",\n \"הר גילה\",\n \"הר הנגב\",\n \"הר עמשא\",\n \"הר-חלוץ\",\n \"הראל\",\n \"הרדוף\",\n \"הרצליה - מערב\",\n \"הרצליה - מרכז וגליל ים\",\n \"הררית יחד\",\n \"ואדי אל חמאם\",\n \"ואדי אל נעם דרום\",\n \"ורד יריחו\",\n \"ורדון\",\n \"זבדיאל\",\n \"זוהר\",\n \"זיקים\",\n \"זיתן\",\n \"זכרון יעקב\",\n \"זכריה\",\n \"זמר\",\n \"זמרת, שובה\",\n \"זנוח\",\n \"זרועה\",\n \"זרזיר\",\n \"זרחיה\",\n \"זרעית\",\n \"ח'וואלד\",\n \"חבצלת השרון וצוקי ים\",\n \"חברון\",\n \"חג'אג'רה\",\n \"חגור\",\n \"חגלה\",\n \"חד נס\",\n \"חדיד\",\n \"חדרה - מזרח\",\n \"חדרה - מערב\",\n \"חדרה - מרכז\",\n \"חדרה - נווה חיים\",\n \"חוות גלעד\",\n \"חוות יאיר\",\n \"חוות עדן\",\n \"חוות ערנדל\",\n \"חוות שדה בר\",\n \"חוות שיקמים\",\n \"חולדה\",\n \"חולון\",\n \"חולית\",\n \"חולתה\",\n \"חוסן\",\n \"חוסנייה\",\n \"חופית\",\n \"חוקוק\",\n \"חורה\",\n \"חורפיש\",\n \"חורשים\",\n \"חזון\",\n \"חי-בר יטבתה\",\n \"חיבת ציון\",\n \"חיננית\",\n \"חיפה - כרמל ועיר תחתית\",\n \"חיפה - מערב\",\n \"חיפה - נווה שאנן ורמות כרמל\",\n \"חיפה - קריית חיים ושמואל\",\n \"חיפה-מפרץ\",\n \"חירן\",\n \"חלמיש\",\n \"חלץ\",\n \"חמד\",\n \"חמדיה\",\n \"חמדת\",\n \"חמרה\",\n \"חמת גדר\",\n \"חניאל\",\n \"חניתה\",\n \"חנתון\",\n \"חספין\",\n \"חפץ חיים\",\n \"חצב\",\n \"חצבה\",\n \"חצור\",\n \"חצור הגלילית\",\n \"חצרים\",\n \"חרב לאת\",\n \"חרוצים\",\n \"חרות\",\n \"חריש\",\n \"חרמש\",\n \"חרשה\",\n \"חרשים\",\n \"חשמונאים\",\n \"טבריה\",\n \"טובא זנגריה\",\n \"טורעאן\",\n \"טייבה\",\n \"טייבה בגלבוע\",\n \"טירה\",\n \"טירת יהודה\",\n \"טירת כרמל\",\n \"טירת צבי\",\n \"טל מנשה\",\n \"טל שחר\",\n \"טל-אל\",\n \"טללים\",\n \"טלמון\",\n \"טמרה\",\n \"טמרה בגלבוע\",\n \"טנא עומרים\",\n \"טפחות\",\n \"יבול\",\n \"יבנאל\",\n \"יבנה\",\n \"יגור\",\n \"יגל\",\n \"יד בנימין\",\n \"יד השמונה\",\n \"יד חנה\",\n \"יד מרדכי\",\n \"יד נתן\",\n \"יד רמב''ם\",\n \"יהוד-מונוסון\",\n \"יהל\",\n \"יובלים\",\n \"יודפת\",\n \"יונתן\",\n \"יושיביה\",\n \"יזרעאל\",\n \"יחיעם\",\n \"יטבתה\",\n \"ייט''ב\",\n \"יכיני\",\n \"ינוב\",\n \"ינוח-ג'ת\",\n \"ינון\",\n \"יסוד המעלה\",\n \"יסודות\",\n \"יסעור\",\n \"יעד\",\n \"יעף\",\n \"יערה\",\n \"יערות הכרמל\",\n \"יפיע\",\n \"יפית\",\n \"יפעת\",\n \"יפתח\",\n \"יצהר\",\n \"יציץ\",\n \"יקום\",\n \"יקיר\",\n \"יקנעם המושבה והזורע\",\n \"יקנעם עילית\",\n \"יראון\",\n \"ירדנה\",\n \"ירוחם\",\n \"ירושלים - אזור תעשייה עטרות\",\n \"ירושלים - דרום\",\n \"ירושלים - כפר עקב\",\n \"ירושלים - מזרח\",\n \"ירושלים - מערב\",\n \"ירושלים - מרכז\",\n \"ירושלים - צפון\",\n \"ירחיב\",\n \"ירכא\",\n \"ירקונה\",\n \"ישובי אומן\",\n \"ישובי יעל\",\n \"ישעי\",\n \"ישרש\",\n \"יתד\",\n \"כאבול\",\n \"כאוכב אבו אלהיג'א\",\n \"כברי\",\n \"כדורי\",\n \"כוכב השחר\",\n \"כוכב יאיר - צור יגאל\",\n \"כוכב יעקב\",\n \"כוכב מיכאל\",\n \"כורזים ורד הגליל\",\n \"כושי רמון\",\n \"כחל\",\n \"כינרת מושבה\",\n \"כינרת קבוצה\",\n \"כיסופים\",\n \"כיסרא סמיע\",\n \"כישור\",\n \"כלא דמון\",\n \"כליל\",\n \"כלנית\",\n \"כמהין\",\n \"כמון\",\n \"כנות\",\n \"כנף\",\n \"כסייפה\",\n \"כסלון\",\n \"כעביה\",\n \"כעביה טבאש\",\n \"כפר אביב\",\n \"כפר אדומים\",\n \"כפר אוריה\",\n \"כפר אחים\",\n \"כפר אלדד\",\n \"כפר ביאליק\",\n \"כפר ביל''ו\",\n \"כפר בלום\",\n \"כפר בן נון\",\n \"כפר ברא\",\n \"כפר ברוך\",\n \"כפר גדעון\",\n \"כפר גלים\",\n \"כפר גליקסון\",\n \"כפר גלעדי\",\n \"כפר גמילה מלכישוע\",\n \"כפר דניאל\",\n \"כפר האורנים\",\n \"כפר החורש\",\n \"כפר המכבי\",\n \"כפר הנגיד\",\n \"כפר הנוער ימין אורד\",\n \"כפר הנשיא\",\n \"כפר הס\",\n \"כפר הרא''ה\",\n \"כפר הרי''ף וצומת ראם\",\n \"כפר ויתקין\",\n \"כפר ורבורג\",\n \"כפר ורדים\",\n \"כפר זוהרים\",\n \"כפר זיתים\",\n \"כפר חב''ד\",\n \"כפר חיטים\",\n \"כפר חיים\",\n \"כפר חנניה\",\n \"כפר חסידים\",\n \"כפר חרוב\",\n \"כפר טבאש\",\n \"כפר טרומן\",\n \"כפר ידידיה\",\n \"כפר יהושע\",\n \"כפר יובל\",\n \"כפר יונה\",\n \"כפר יחזקאל\",\n \"כפר יסיף\",\n \"כפר יעבץ\",\n \"כפר כמא\",\n \"כפר כנא\",\n \"כפר מונש\",\n \"כפר מימון ותושיה\",\n \"כפר מל''ל\",\n \"כפר מנדא\",\n \"כפר מנחם\",\n \"כפר מסריק\",\n \"כפר מצר\",\n \"כפר מרדכי\",\n \"כפר נהר הירדן\",\n \"כפר נוער בן שמן\",\n \"כפר נטר\",\n \"כפר סאלד\",\n \"כפר סבא\",\n \"כפר סילבר\",\n \"כפר סירקין\",\n \"כפר עבודה\",\n \"כפר עזה\",\n \"כפר עציון\",\n \"כפר פינס\",\n \"כפר קאסם\",\n \"כפר קיש\",\n \"כפר קרע\",\n \"כפר רופין\",\n \"כפר רות\",\n \"כפר שמאי\",\n \"כפר שמואל\",\n \"כפר שמריהו\",\n \"כפר תבור\",\n \"כפר תפוח\",\n \"כפר תקווה\",\n \"כרכום\",\n \"כרם ביבנה\",\n \"כרם בן זמרה\",\n \"כרם בן שמן\",\n \"כרם מהר''ל\",\n \"כרם שלום\",\n \"כרמי יוסף\",\n \"כרמי צור\",\n \"כרמי קטיף\",\n \"כרמיאל\",\n \"כרמיה\",\n \"כרמים\",\n \"כרמית\",\n \"כרמל\",\n \"לבון\",\n \"לביא\",\n \"לבנים\",\n \"להב\",\n \"להבות הבשן\",\n \"להבות חביבה\",\n \"להבים\",\n \"לוד\",\n \"לוזית\",\n \"לוחמי הגטאות\",\n \"לוטם וחמדון\",\n \"לוטן\",\n \"לטרון\",\n \"לימן\",\n \"לכיש\",\n \"לפיד\",\n \"לפידות\",\n \"לקיה\",\n \"מאור\",\n \"מאיר שפיה\",\n \"מבוא ביתר\",\n \"מבוא דותן\",\n \"מבוא חורון\",\n \"מבוא חמה\",\n \"מבוא מודיעים\",\n \"מבואות יריחו\",\n \"מבועים\",\n \"מבטחים, עמיעוז, ישע\",\n \"מבקיעים\",\n \"מבשרת ציון\",\n \"מג'דל כרום\",\n \"מג'דל שמס\",\n \"מגדים\",\n \"מגדל\",\n \"מגדל העמק\",\n \"מגדל עוז\",\n \"מגדל תפן\",\n \"מגדלים\",\n \"מגל\",\n \"מגן\",\n \"מגן שאול\",\n \"מגרון\",\n \"מגשימים\",\n \"מדרך עוז\",\n \"מדרשת בן גוריון\",\n \"מודיעין\",\n \"מודיעין - ישפרו סנטר\",\n \"מודיעין - ליגד סנטר\",\n \"מודיעין עילית\",\n \"מולדת\",\n \"מועאוויה\",\n \"מוצא עילית\",\n \"מוקיבלה\",\n \"מורן\",\n \"מורשת\",\n \"מזור\",\n \"מזכרת בתיה\",\n \"מזרע\",\n \"מזרעה\",\n \"מחולה\",\n \"מחניים\",\n \"מחסיה\",\n \"מטווח ניר עם\",\n \"מטולה\",\n \"מטע\",\n \"מי עמי\",\n \"מייסר\",\n \"מיצד\",\n \"מיצר\",\n \"מירב\",\n \"מירון\",\n \"מישר\",\n \"מיתר\",\n \"מכון וינגייט\",\n \"מכורה\",\n \"מכמורת\",\n \"מכמנים\",\n \"מלאה\",\n \"מלונות ים המלח מרכז\",\n \"מלכיה\",\n \"ממשית\",\n \"מנוחה\",\n \"מנוף\",\n \"מנות\",\n \"מנחמיה\",\n \"מנחת מחניים\",\n \"מנרה\",\n \"מנשית זבדה\",\n \"מסד\",\n \"מסדה\",\n \"מסילות\",\n \"מסילת ציון\",\n \"מסלול\",\n \"מסעדה\",\n \"מע'אר\",\n \"מעברות\",\n \"מעגלים, גבעולים, מלילות\",\n \"מעגן\",\n \"מעגן מיכאל\",\n \"מעוז חיים\",\n \"מעון\",\n \"מעון צופיה\",\n \"מעונה\",\n \"מעיין ברוך\",\n \"מעיין צבי\",\n \"מעיליא\",\n \"מעלה אדומים\",\n \"מעלה אפרים\",\n \"מעלה גלבוע\",\n \"מעלה גמלא\",\n \"מעלה החמישה\",\n \"מעלה חבר\",\n \"מעלה לבונה\",\n \"מעלה מכמש\",\n \"מעלה עירון\",\n \"מעלה עמוס\",\n \"מעלה צביה\",\n \"מעלה רחבעם\",\n \"מעלה שומרון\",\n \"מעלות תרשיחא\",\n \"מענית\",\n \"מעש\",\n \"מפלסים\",\n \"מצדה\",\n \"מצובה\",\n \"מצוקי דרגות\",\n \"מצליח\",\n \"מצפה\",\n \"מצפה אבי''ב\",\n \"מצפה אילן\",\n \"מצפה יריחו\",\n \"מצפה נטופה\",\n \"מצפה רמון\",\n \"מצפה שלם\",\n \"מצר\",\n \"מקווה ישראל\",\n \"מרגליות\",\n \"מרום גולן\",\n \"מרחב עם\",\n \"מרחביה מושב\",\n \"מרחביה קיבוץ\",\n \"מרחצאות עין גדי\",\n \"מרכז אומן\",\n \"מרכז אזורי דרום השרון\",\n \"מרכז אזורי מבואות חרמון\",\n \"מרכז אזורי מגילות\",\n \"מרכז אזורי מרום גליל\",\n \"מרכז אזורי משגב\",\n \"מרכז חבר\",\n \"מרכז ימי קיסריה\",\n \"מרכז מיר''ב\",\n \"מרכז שפירא\",\n \"מרעית\",\n \"משאבי שדה\",\n \"משגב דב\",\n \"משגב עם\",\n \"משהד\",\n \"משואה\",\n \"משואות יצחק\",\n \"משכיות\",\n \"משמר איילון\",\n \"משמר דוד\",\n \"משמר הירדן\",\n \"משמר הנגב\",\n \"משמר העמק\",\n \"משמר השבעה\",\n \"משמר השרון\",\n \"משמרות\",\n \"משמרת\",\n \"משען\",\n \"מתחם בני דרום\",\n \"מתחם פי גלילות\",\n \"מתחם צומת שוקת\",\n \"מתן\",\n \"מתת\",\n \"מתתיהו\",\n \"נאות גולן\",\n \"נאות הכיכר\",\n \"נאות חובב\",\n \"נאות מרדכי\",\n \"נאות סמדר\",\n \"נבטים\",\n \"נבי סמואל\",\n \"נגבה\",\n \"נגוהות\",\n \"נהורה\",\n \"נהלל\",\n \"נהריה\",\n \"נוב\",\n \"נוגה\",\n \"נוה איתן\",\n \"נווה\",\n \"נווה אור\",\n \"נווה אטי''ב\",\n \"נווה אילן\",\n \"נווה דניאל\",\n \"נווה זוהר\",\n \"נווה זיו\",\n \"נווה חריף\",\n \"נווה ים\",\n \"נווה ימין\",\n \"נווה ירק\",\n \"נווה מבטח\",\n \"נווה מיכאל - רוגלית\",\n \"נווה שלום\",\n \"נועם\",\n \"נוף איילון\",\n \"נוף הגליל\",\n \"נופי נחמיה\",\n \"נופי פרת\",\n \"נופים\",\n \"נופית\",\n \"נופך\",\n \"נוקדים\",\n \"נורדיה\",\n \"נורית\",\n \"נחושה\",\n \"נחל עוז\",\n \"נחלה\",\n \"נחליאל\",\n \"נחלים\",\n \"נחם\",\n \"נחף\",\n \"נחשולים\",\n \"נחשון\",\n \"נחשונים\",\n \"נטועה\",\n \"נטור\",\n \"נטע\",\n \"נטעים\",\n \"נטף\",\n \"ניל''י\",\n \"נין\",\n \"ניצן\",\n \"ניצנה\",\n \"ניצני עוז\",\n \"ניצנים\",\n \"ניר אליהו\",\n \"ניר בנים\",\n \"ניר גלים\",\n \"ניר דוד\",\n \"ניר ח''ן\",\n \"ניר יפה\",\n \"ניר יצחק\",\n \"ניר ישראל\",\n \"ניר משה\",\n \"ניר עוז\",\n \"ניר עציון\",\n \"ניר עקיבא\",\n \"ניר צבי\",\n \"נירים\",\n \"נירית\",\n \"נמרוד\",\n \"נס הרים\",\n \"נס עמים\",\n \"נס ציונה\",\n \"נעורה\",\n \"נעורים\",\n \"נעלה\",\n \"נעמה\",\n \"נען\",\n \"נערן\",\n \"נצר חזני\",\n \"נצר סרני\",\n \"נצרת\",\n \"נריה\",\n \"נשר\",\n \"נתיב הגדוד\",\n \"נתיב הל''ה\",\n \"נתיב העשרה\",\n \"נתיב השיירה\",\n \"נתיבות\",\n \"נתניה - מזרח\",\n \"נתניה - מערב\",\n \"סאג'ור\",\n \"סאסא\",\n \"סביון\",\n \"סגולה\",\n \"סואעד חמירה\",\n \"סולם\",\n \"סוסיא\",\n \"סופה\",\n \"סינמה סיטי גלילות\",\n \"סכנין\",\n \"סלמה\",\n \"סלעית\",\n \"סמר\",\n \"סנדלה\",\n \"סנסנה\",\n \"סעד\",\n \"סעייה-מולדה\",\n \"סער\",\n \"ספיר\",\n \"ספסופה - כפר חושן\",\n \"סתריה\",\n \"ע'ג'ר\",\n \"עבדון\",\n \"עבדת\",\n \"עברון\",\n \"עגור\",\n \"עדי\",\n \"עדי עד\",\n \"עדנים\",\n \"עוזה\",\n \"עוזייר\",\n \"עולש\",\n \"עומר\",\n \"עופר\",\n \"עופרים\",\n \"עוצם\",\n \"עזוז\",\n \"עזר\",\n \"עזריאל\",\n \"עזריה\",\n \"עזריקם\",\n \"עטרת\",\n \"עידן\",\n \"עיינות\",\n \"עילבון\",\n \"עילוט\",\n \"עין איילה\",\n \"עין אל אסד\",\n \"עין אל-סהלה\",\n \"עין בוקק\",\n \"עין גב\",\n \"עין גדי\",\n \"עין דור\",\n \"עין הבשור\",\n \"עין הוד\",\n \"עין החורש\",\n \"עין המפרץ\",\n \"עין הנצי''ב\",\n \"עין העמק\",\n \"עין השופט\",\n \"עין השלושה\",\n \"עין ורד\",\n \"עין זיוון\",\n \"עין חוד\",\n \"עין חצבה\",\n \"עין חרוד\",\n \"עין חרוד איחוד\",\n \"עין יהב\",\n \"עין יעקב\",\n \"עין כמונים\",\n \"עין כרמל\",\n \"עין מאהל\",\n \"עין נקובא\",\n \"עין עירון\",\n \"עין צורים\",\n \"עין קנייא\",\n \"עין ראפה\",\n \"עין שמר\",\n \"עין שריד\",\n \"עין תמר\",\n \"עינבר\",\n \"עינת\",\n \"עיר אובות\",\n \"עכו\",\n \"עכו - אזור תעשייה\",\n \"עלומים\",\n \"עלי\",\n \"עלי זהב\",\n \"עלמה\",\n \"עלמון\",\n \"עמוקה\",\n \"עמיחי\",\n \"עמינדב\",\n \"עמיעד\",\n \"עמיקם\",\n \"עמיר\",\n \"עמנואל\",\n \"עמקה\",\n \"ענב\",\n \"עספיא\",\n \"עפולה\",\n \"עפרה\",\n \"עץ אפרים\",\n \"עצמון - שגב\",\n \"עראבה\",\n \"ערב אל עראמשה\",\n \"ערב אל-נעים\",\n \"ערד\",\n \"ערוגות\",\n \"ערערה\",\n \"ערערה בנגב\",\n \"עשאהל\",\n \"עשרת\",\n \"עתלית\",\n \"עתניאל\",\n \"פארן\",\n \"פארק תעשיות פלמחים\",\n \"פארק תעשייה ראם\",\n \"פדואל\",\n \"פדויים\",\n \"פדיה\",\n \"פוריה כפר עבודה\",\n \"פוריה נווה עובד\",\n \"פוריה עילית\",\n \"פוריידיס\",\n \"פורת\",\n \"פטיש\",\n \"פלך\",\n \"פלמחים\",\n \"פני קדם\",\n \"פנימיית עין כרם\",\n \"פסגות\",\n \"פסוטה\",\n \"פעמי תש''ז\",\n \"פצאל\",\n \"פקיעין\",\n \"פקיעין החדשה\",\n \"פרדס חנה-כרכור\",\n \"פרדסיה\",\n \"פרוד\",\n \"פרי גן\",\n \"פתח תקווה\",\n \"פתחיה\",\n \"צאלים\",\n \"צבעון\",\n \"צובה\",\n \"צוחר, אוהד\",\n \"צופים\",\n \"צופית\",\n \"צופר\",\n \"צוקים\",\n \"צור הדסה\",\n \"צור יצחק\",\n \"צור משה\",\n \"צור נתן\",\n \"צוריאל\",\n \"צורית גילון\",\n \"ציפורי\",\n \"צלפון\",\n \"צפריה\",\n \"צפרירים\",\n \"צפת\",\n \"צרופה\",\n \"צרעה\",\n \"קבוצת גבע\",\n \"קבוצת יבנה\",\n \"קדומים\",\n \"קדימה-צורן\",\n \"קדיתא\",\n \"קדמה\",\n \"קדמת צבי\",\n \"קדר\",\n \"קדרון\",\n \"קדרים\",\n \"קדש ברנע\",\n \"קוממיות\",\n \"קורנית\",\n \"קטורה\",\n \"קיבוץ דן\",\n \"קיבוץ מגידו\",\n \"קידה\",\n \"קיסריה\",\n \"קלחים\",\n \"קליה\",\n \"קלנסווה\",\n \"קלע\",\n \"קציר\",\n \"קצר-א-סיר\",\n \"קצרין\",\n \"קצרין - אזור תעשייה\",\n \"קריית אונו\",\n \"קריית אתא\",\n \"קריית ביאליק\",\n \"קריית גת, כרמי גת\",\n \"קריית חינוך מרחבים\",\n \"קריית טבעון-בית זייד\",\n \"קריית ים\",\n \"קריית יערים\",\n \"קריית מוצקין\",\n \"קריית מלאכי\",\n \"קריית נטפים\",\n \"קריית ענבים\",\n \"קריית עקרון\",\n \"קריית שמונה\",\n \"קרית ארבע\",\n \"קרני שומרון\",\n \"קשת\",\n \"ראמה\",\n \"ראס אל-עין\",\n \"ראס עלי\",\n \"ראש הנקרה\",\n \"ראש העין\",\n \"ראש פינה\",\n \"ראש צורים\",\n \"ראשון לציון - מזרח\",\n \"ראשון לציון - מערב\",\n \"רבבה\",\n \"רבדים\",\n \"רביבים\",\n \"רביד\",\n \"רגבה\",\n \"רגבים\",\n \"רהט\",\n \"רווחה\",\n \"רוויה\",\n \"רוחמה\",\n \"רומאנה\",\n \"רומת אל הייב\",\n \"רועי\",\n \"רותם\",\n \"רחוב\",\n \"רחובות\",\n \"רחלים\",\n \"רטורנו - גבעת שמש\",\n \"ריחאנייה\",\n \"ריחן\",\n \"ריינה\",\n \"רימונים\",\n \"רינתיה\",\n \"רכסים\",\n \"רם און\",\n \"רמות\",\n \"רמות השבים\",\n \"רמות מאיר\",\n \"רמות מנשה\",\n \"רמות נפתלי\",\n \"רמלה\",\n \"רמת גן - מזרח\",\n \"רמת גן - מערב\",\n \"רמת דוד\",\n \"רמת הכובש\",\n \"רמת הנדיב\",\n \"רמת השופט\",\n \"רמת השרון\",\n \"רמת יוחנן\",\n \"רמת ישי\",\n \"רמת מגשימים\",\n \"רמת צבי\",\n \"רמת רזיאל\",\n \"רמת רחל\",\n \"רנן\",\n \"רעים\",\n \"רעננה\",\n \"רקפת\",\n \"רשפון\",\n \"רשפים\",\n \"רתמים\",\n \"שאנטי במדבר\",\n \"שאר ישוב\",\n \"שבות רחל\",\n \"שבי דרום\",\n \"שבי ציון\",\n \"שבי שומרון\",\n \"שבלי\",\n \"שגב שלום\",\n \"שדה אברהם\",\n \"שדה אילן\",\n \"שדה אליהו\",\n \"שדה אליעזר\",\n \"שדה בוקר\",\n \"שדה דוד\",\n \"שדה ורבורג\",\n \"שדה יואב\",\n \"שדה יעקב\",\n \"שדה יצחק\",\n \"שדה משה\",\n \"שדה נחום\",\n \"שדה נחמיה\",\n \"שדה ניצן\",\n \"שדה עוזיהו\",\n \"שדה צבי\",\n \"שדות ים\",\n \"שדות מיכה\",\n \"שדי חמד\",\n \"שדי תרומות\",\n \"שדמה\",\n \"שדמות דבורה\",\n \"שדמות מחולה\",\n \"שדרות, איבים, ניר עם\",\n \"שהם\",\n \"שואבה\",\n \"שובל\",\n \"שומרה\",\n \"שומריה\",\n \"שומרת\",\n \"שוקדה\",\n \"שורש\",\n \"שורשים\",\n \"שושנת העמקים\",\n \"שזור\",\n \"שחר\",\n \"שחרות\",\n \"שיבולים\",\n \"שיטים\",\n \"שייח' דנון\",\n \"שילה\",\n \"שילת\",\n \"שכניה\",\n \"שלווה\",\n \"שלוחות\",\n \"שלומי\",\n \"שלומית\",\n \"שלפים\",\n \"שמיר\",\n \"שמעה\",\n \"שמשית\",\n \"שני ליבנה\",\n \"שניר\",\n \"שעב\",\n \"שעל\",\n \"שעלבים\",\n \"שער אפרים\",\n \"שער הגולן\",\n \"שער העמקים\",\n \"שער מנשה\",\n \"שערי תקווה\",\n \"שפיים\",\n \"שפיר\",\n \"שפר\",\n \"שפרעם\",\n \"שקד\",\n \"שקף\",\n \"שרונה\",\n \"שריגים - ליאון\",\n \"שריד\",\n \"שרשרת\",\n \"שתולה\",\n \"שתולים\",\n \"תארבין\",\n \"תאשור\",\n \"תדהר\",\n \"תובל\",\n \"תומר\",\n \"תחנת רכבת כפר יהושוע\",\n \"תחנת רכבת ראש העין\",\n \"תימורים\",\n \"תירוש\",\n \"תל אביב - דרום העיר ויפו\",\n \"תל אביב - מזרח\",\n \"תל אביב - מרכז העיר\",\n \"תל אביב - עבר הירקון\",\n \"תל חי\",\n \"תל יוסף\",\n \"תל יצחק\",\n \"תל מונד\",\n \"תל עדשים\",\n \"תל ערד\",\n \"תל ציון\",\n \"תל קציר\",\n \"תל שבע\",\n \"תל תאומים\",\n \"תלם\",\n \"תלמי אליהו\",\n \"תלמי אלעזר\",\n \"תלמי ביל''ו\",\n \"תלמי יוסף\",\n \"תלמי יחיאל\",\n \"תלמי יפה\",\n \"תלמים\",\n \"תמרת\",\n \"תנובות\",\n \"תעוז\",\n \"תעשיון חצב\",\n \"תעשיון צריפין\",\n \"תפרח\",\n \"תקומה\",\n \"תקומה וחוות יזרעם\",\n \"תקוע\",\n \"תרום\",\n}" } ]
import asyncio import homeassistant.util.dt as dt_util from dataclasses import dataclass from datetime import timedelta from functools import cmp_to_key from json import JSONDecodeError from typing import Any from aiohttp.client_exceptions import ContentTypeError from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from .const import ( CONF_ALERT_MAX_AGE, CONF_POLL_INTERVAL, DEFAULT_POLL_INTERVAL, DOMAIN, IST, LOGGER, ) from .metadata.areas import AREAS
17,913
"""DataUpdateCoordinator for oref_alert integration.""" OREF_ALERTS_URL = "https://www.oref.org.il/WarningMessages/alert/alerts.json" OREF_HISTORY_URL = "https://www.oref.org.il/WarningMessages/History/AlertsHistory.json" OREF_HEADERS = { "Referer": "https://www.oref.org.il/", "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json", } REQUEST_RETRIES = 3 REAL_TIME_ALERT_LOGIC_WINDOW = 2 @dataclass class OrefAlertCoordinatorData: """Class for holding coordinator data.""" alerts: list[Any] active_alerts: list[Any] def _sort_alerts(item1: dict[str, Any], item2: dict[str, Any]) -> int: """Sort by descending-order "date" and then ascending-order "name".""" if item1["alertDate"] < item2["alertDate"]: return 1 if item1["alertDate"] > item2["alertDate"]: return -1 if item1["data"] > item2["data"]: return 1 if item1["data"] < item2["data"]: return -1 return 0 def _compare_fields(alert: dict[str, Any], area: str, category: int) -> bool: """Compare an alert with area and category (time is ignored).""" return alert["data"] == area and alert["category"] == category class OrefAlertDataUpdateCoordinator(DataUpdateCoordinator[OrefAlertCoordinatorData]): """Class to manage fetching Oref Alert data.""" def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry): """Initialize global data updater.""" super().__init__( hass, LOGGER,
"""DataUpdateCoordinator for oref_alert integration.""" OREF_ALERTS_URL = "https://www.oref.org.il/WarningMessages/alert/alerts.json" OREF_HISTORY_URL = "https://www.oref.org.il/WarningMessages/History/AlertsHistory.json" OREF_HEADERS = { "Referer": "https://www.oref.org.il/", "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json", } REQUEST_RETRIES = 3 REAL_TIME_ALERT_LOGIC_WINDOW = 2 @dataclass class OrefAlertCoordinatorData: """Class for holding coordinator data.""" alerts: list[Any] active_alerts: list[Any] def _sort_alerts(item1: dict[str, Any], item2: dict[str, Any]) -> int: """Sort by descending-order "date" and then ascending-order "name".""" if item1["alertDate"] < item2["alertDate"]: return 1 if item1["alertDate"] > item2["alertDate"]: return -1 if item1["data"] > item2["data"]: return 1 if item1["data"] < item2["data"]: return -1 return 0 def _compare_fields(alert: dict[str, Any], area: str, category: int) -> bool: """Compare an alert with area and category (time is ignored).""" return alert["data"] == area and alert["category"] == category class OrefAlertDataUpdateCoordinator(DataUpdateCoordinator[OrefAlertCoordinatorData]): """Class to manage fetching Oref Alert data.""" def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry): """Initialize global data updater.""" super().__init__( hass, LOGGER,
name=DOMAIN,
3
2023-10-18 11:16:41+00:00
24k
RobertCsordas/moe
tasks/simple/language_model/transformer_lm_mixin.py
[ { "identifier": "TransformerLanguageModel", "path": "models/transformer_language_model.py", "snippet": "class TransformerLanguageModel(LoggingLayer, torch.nn.Module):\n def __init__(self, voc_size: int, embedding_size: Optional[int], state_size: int, dropout: float,\n tied_embedding: bool, layers: List[torch.nn.Module], n_prev_states: int,\n n_prev_states_test: Optional[int] = None, adaptive_cutoffs: List[int] = [],\n same_length_eval: bool = True, norm_before_output: bool = False,\n p_drop_layer: float = 0.0, use_last_state: bool = False, same_length: bool = False,\n output_mode: str = \"normal\"):\n\n super().__init__()\n\n self.embedding = torch.nn.Embedding(voc_size, embedding_size or state_size)\n # with torch.no_grad():\n # self.embedding.weight.uniform_(-0.1, 0.1)\n\n torch.nn.init.xavier_uniform_(self.embedding.weight)\n\n self.shared_layers = all([la is layers[0] for la in layers])\n\n if embedding_size is None:\n self.embedding_adapter = lambda x: x\n else:\n self.embedding_adapter = torch.nn.Linear(embedding_size, state_size)\n\n self.dropout = torch.nn.Dropout(dropout)\n self.layers = torch.nn.ModuleList(layers)\n self.output_adapter = lambda x: x\n self.n_prev_states = n_prev_states\n self.n_prev_states_test = n_prev_states_test or n_prev_states\n self.same_length_eval = same_length_eval\n self.embedding_scale = math.sqrt(state_size)\n self.p_drop_layer = p_drop_layer\n self.use_last_state = use_last_state\n self.same_length = same_length\n self.iter = 0\n self.output_mode = output_mode\n\n assert self.output_mode in {\"normal\", \"sum\", \"geometric\", \"sigmoid\"}\n\n if self.output_mode in {\"geometric\", \"sigmoid\"}:\n self.output_gate = torch.nn.Linear(state_size, 1)\n\n self.adaptive = bool(adaptive_cutoffs)\n\n out_proj_size = (embedding_size or state_size) if tied_embedding else state_size\n if self.adaptive:\n self.output = framework.layers.CustomAdaptiveLogSoftmaxWithLoss(\n out_proj_size, voc_size, adaptive_cutoffs, div_value=1,\n tied_to=self.embedding if tied_embedding else None)\n else:\n self.output = torch.nn.Linear(out_proj_size, voc_size)\n\n if norm_before_output or self.output_mode in {\"sum\", \"sigmoid\"}:\n self.out_norm = torch.nn.LayerNorm(state_size)\n else:\n self.out_norm = lambda x: x\n\n if tied_embedding:\n if not self.adaptive:\n self.output.weight = self.embedding.weight\n if embedding_size is not None:\n self.output_adapter = torch.nn.Linear(state_size, embedding_size)\n\n @staticmethod\n def generate_history_mask(sz: int, device: torch.device) -> torch.Tensor:\n return torch.tril(torch.ones(sz, sz, dtype=torch.bool, device=device), diagonal=-1)\n\n def gen_output(self, x: torch.Tensor, target: Optional[torch.Tensor]) -> torch.Tensor:\n net = self.out_norm(x)\n net = self.output_adapter(net)\n net = self.dropout(net)\n\n if self.adaptive:\n net = self.output(net.transpose(0, 1), target)\n else:\n net = self.output(net.transpose(0, 1))\n\n return net\n\n def accumulate_output(self, features: List[torch.Tensor]) -> torch.Tensor:\n if self.output_mode == \"sum\":\n return sum(features)\n elif self.output_mode in {\"geometric\", \"sigmoid\"}:\n # Must cast it to float16, otherwise pytorch will crash after a few hundred iterations with an\n # incomprehensible error in the gradient scaler\n gates = torch.sigmoid(torch.cat([self.output_gate(f).float() for f in features], -1))\n if self.output_mode == \"geometric\":\n ngates = torch.cumprod(1.0 - gates, -1)\n scores = torch.cat([gates[..., 0:1], gates[..., 1:] * ngates[..., :-1]], -1)\n else:\n scores = gates\n\n if self.iter % 100 == 0 and self.training:\n self.log(\"output_gate_mean\", framework.visualize.plot.Barplot(scores.flatten(end_dim=-2).mean(0)))\n # return sum(f * scores[..., i: i+1] for i, f in enumerate(features))\n f = scores.unsqueeze(-2) @ torch.stack(features, -2)\n return f.squeeze(-2)\n else:\n assert False, \"Invalid output mode\"\n\n def forward(self, x: torch.Tensor, target: Optional[torch.Tensor], state) -> Tuple[torch.Tensor, Any]:\n causality_mask = Transformer.generate_square_subsequent_mask(x.shape[0], x.device)\n\n net = self.dropout(self.embedding(x.T.long()))\n net = self.embedding_adapter(net)\n net = net * self.embedding_scale\n\n new_state = []\n features = [net]\n\n n_prev_states = self.n_prev_states if self.training else self.n_prev_states_test\n\n same_length = self.same_length or ((not self.training) and self.same_length_eval)\n if same_length and state is not None:\n causality_mask = [self.generate_history_mask(x.shape[0], x.device)] + \\\n [torch.zeros_like(causality_mask)] * (len(state[0]) - 1) + [causality_mask]\n causality_mask = torch.cat(causality_mask, -1)\n\n plot_cossim = (self.iter % 100 == 0 and self.training)\n for li, l in enumerate(self.layers):\n if n_prev_states > 0:\n if li == 0:\n # Pos offset should be constant for all layers\n pos_offset = sum(s.shape[1] for s in state[0]) if state is not None else 0\n\n # Concatenate the new state with the previous states\n li_r = 0 if self.use_last_state else li\n s = (state[li_r] + [net]) if state is not None else [net]\n attend_to = torch.cat(s, 1)\n\n if not self.use_last_state:\n s[-1] = s[-1].detach()\n new_state.append(s[-n_prev_states:])\n else:\n pos_offset = None\n attend_to = None\n\n net_o = l(net, mask=AttentionMask(None, causality_mask), attend_to=attend_to,\n pos_offset=pos_offset)\n\n if plot_cossim or self.output_mode != \"normal\":\n features.append(net_o)\n\n with torch.no_grad():\n ndiff = torch.norm(net_o - net, p=2, dim=-1)\n n_in = torch.norm(net, p=2, dim=-1)\n self.log(f\"activation_norm/abs_update_layer_{li}\", ndiff.mean())\n self.log(f\"activation_norm/in_layer_{li}\", n_in.mean())\n self.log(f\"activation_norm/rel_update_layer_{li}\", (ndiff/n_in.clamp(min=torch.finfo(n_in.dtype).eps)).mean())\n\n if self.training and self.p_drop_layer > 0.0:\n net = torch.where(torch.rand_like(net_o[..., 0:1]) < self.p_drop_layer, net, net_o)\n else:\n net = net_o\n\n if self.use_last_state and n_prev_states > 0:\n # If we carry over the last state, save it here\n new_state = [((state[0] if state is not None else []) + [net.detach()])[-n_prev_states:]]\n\n if self.output_mode != \"normal\":\n net = self.accumulate_output(features)\n\n if plot_cossim:\n with torch.no_grad():\n f_sample = [f.view(-1, f.shape[-1])[:1024] for f in features]\n f_sample_all = torch.stack(f_sample, -2)\n scores = framework.utils.cossim(f_sample_all, f_sample_all).mean(0)\n self.log(\"feature_cossim\", framework.visualize.plot.Heatmap(scores, range=(0, 1), textval=False))\n\n if self.output_mode != \"normal\":\n f_sample = [self.accumulate_output(f_sample[:i]) for i in range(1, len(f_sample)+1)]\n f_sample_all = torch.stack(f_sample, -2)\n\n outs = F.softmax(self.gen_output(f_sample_all, target).transpose(0, 1), -1)\n scores = framework.utils.cossim(outs, outs).mean(0)\n self.log(\"out_dist_cossim\", framework.visualize.plot.Heatmap(scores, range=(0, 1), textval=False))\n\n real_out = outs[:, -1]\n for i in range(outs.shape[-2] - 1):\n self.log(f\"out_diff_{i}\", (outs[:, i] - real_out).norm(dim=-1, p=1).mean())\n\n del outs\n del features\n\n net = self.gen_output(net, target)\n self.iter += 1\n\n return net, new_state" }, { "identifier": "task", "path": "tasks/task_db.py", "snippet": "def task(name: Optional[str] = None):\n def wrapper(cls):\n n = TASK_PREFIX + (name or camel_to_snake(cls.__name__))\n assert n not in TASKS, f\"Task {n} already exists\"\n TASKS[n] = cls\n return cls\n return wrapper" }, { "identifier": "args", "path": "tasks/task_db.py", "snippet": "def args(fn):\n global ARGS_REGISTERS\n ARGS_REGISTERS.append(fn)\n return fn" }, { "identifier": "RelativeTransformerEncoderLayer", "path": "layers/transformer/relative_transformer.py", "snippet": "class RelativeTransformerEncoderLayer(torch.nn.Module):\n def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu,\n attention_dropout=0, test_pos_clamp: Optional[int] = None, drop_expand: bool = True,\n head_projection_size: Optional[int] = None, ln_after_attention: bool = True):\n super().__init__()\n self.ln_after_attention = ln_after_attention\n self.self_attn = FixedRelativeMultiheadAttention(\n d_model, nhead, dropout=attention_dropout, test_pos_clamp=test_pos_clamp,\n projection_size=head_projection_size)\n self.linear1 = torch.nn.Linear(d_model, dim_feedforward)\n self.dropout = torch.nn.Dropout(dropout) if drop_expand else lambda x: x\n self.linear2 = torch.nn.Linear(dim_feedforward, d_model)\n\n if ln_after_attention:\n self.norm1 = torch.nn.LayerNorm(d_model)\n self.norm2 = torch.nn.LayerNorm(d_model)\n self.dropout1 = torch.nn.Dropout(dropout)\n self.dropout2 = torch.nn.Dropout(dropout)\n\n self.activation = activation\n self.reset_parameters()\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.self_attn(src, attend_to if attend_to is not None else src, mask, pos_offset=pos_offset)\n src = src + self.dropout1(src2)\n src = self.norm1(src) if self.ln_after_attention else src\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))\n src = src + self.dropout2(src2)\n src = self.norm2(src)\n return src\n\n def reset_parameters(self):\n torch.nn.init.xavier_normal_(self.linear1.weight, gain=torch.nn.init.calculate_gain('relu')\n if self.activation is F.relu else 1.0)\n torch.nn.init.xavier_uniform_(self.linear2.weight)" }, { "identifier": "PrelnRelativeTransformerEncoderLayer", "path": "layers/transformer/relative_preln_transformer.py", "snippet": "class PrelnRelativeTransformerEncoderLayer(RelativeTransformerEncoderLayer):\n is_preln = True\n\n def __init__(self, d_model, nhead, n_layers: int, dim_feedforward=2048, dropout=0.1,\n activation: ActivationFunction = F.relu, attention_dropout=0, test_pos_clamp: Optional[int] = None,\n drop_expand: bool = True, head_projection_size: Optional[int] = None):\n super().__init__(\n d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout,\n activation=activation, attention_dropout=attention_dropout, test_pos_clamp=test_pos_clamp,\n drop_expand=drop_expand, head_projection_size=head_projection_size)\n\n reset_prenorm_params(self, n_layers)\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.norm1(src)\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask,\n pos_offset=pos_offset)\n src = src + self.dropout1(src2)\n src2 = self.norm2(src)\n src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))\n src = src + self.dropout2(src2)\n return src" }, { "identifier": "PrelnRelativeKVMemTransformerEncoderLayer", "path": "layers/transformer/relative_preln_kvmem_transformer.py", "snippet": "class PrelnRelativeKVMemTransformerEncoderLayer(torch.nn.Module):\n def __init__(self, d_model, nhead, n_keys: Union[int, Tuple[int, int]], n_layers: int, dim_feedforward=2048,\n dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0,\n test_pos_clamp: Optional[int] = None, pkm_heads: int = 1, pkm_stochastic: bool = True,\n pkm_custom_init: int = 0, pkm_slice_values: bool = False,\n pkm_knn: int = 32, linproj: bool = False, head_merge_topk: bool = False, load_balance: bool = True,\n kvmem_dropout: str = \"none\", kvmem_randomize_indices: bool = False, kvmem_query_bias: bool = False,\n standard_parallel: bool = False, approx_topk: bool = False, factorize: bool = False,\n full_key: bool = False, key_redundancy_factor: int = 1, two_stage: bool = False,\n factors: Optional[List[int]] = None, head_exclusive: bool = False,\n head_projection_size: Optional[int] = None):\n super().__init__()\n self.self_attn = FixedRelativeMultiheadAttention(\n d_model, nhead, dropout=attention_dropout, test_pos_clamp=test_pos_clamp,\n projection_size=head_projection_size)\n\n self.pkm = LowrankApproximate2Layer(\n d_model, n_keys, pkm_heads, stochastic=pkm_stochastic, custom_init=pkm_custom_init,\n weight_scale=math.sqrt(2.0 / n_layers), slice_values=pkm_slice_values, knn=pkm_knn,\n head_merge_topk=head_merge_topk, load_balance=load_balance, dropout=dropout,\n query_proj=linproj, randomize_indices=kvmem_randomize_indices, dropout_mode=kvmem_dropout,\n query_bias=kvmem_query_bias, approx=approx_topk, factorize=factorize, full_key=full_key,\n key_redundancy_factor=key_redundancy_factor, two_stage=two_stage, factors=factors,\n head_exclusive=head_exclusive, activation=activation)\n\n self.norm1 = torch.nn.LayerNorm(d_model)\n self.norm2 = torch.nn.LayerNorm(d_model)\n self.dropout = torch.nn.Dropout(dropout)\n\n self.activation = activation\n self.standard_parallel = standard_parallel\n\n reset_prenorm_params(self, n_layers)\n\n if self.standard_parallel:\n self.linear1 = torch.nn.Linear(d_model, dim_feedforward, bias=False)\n self.linear2 = torch.nn.Linear(dim_feedforward, d_model, bias=False)\n\n initializer = self.pkm.get_custom_init()\n\n s_real = dim_feedforward + self.pkm.size\n # s_real = dim_feedforward + self.pkm.heads * self.pkm.knn\n initializer(self.linear2.weight, std=math.sqrt(2 / (n_layers * s_real)))\n initializer(self.pkm.values.weight, std=math.sqrt(2 / (n_layers * s_real)))\n initializer(self.linear1.weight, std=math.sqrt(2 / (n_layers * d_model)))\n\n if self.pkm.two_stage:\n initializer(self.pkm.full_keys, std=math.sqrt(2 / (n_layers * d_model)))\n\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.norm1(src)\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask,\n pos_offset=pos_offset)\n src = src + self.dropout(src2)\n src2 = self.norm2(src)\n src3 = self.pkm(src2)\n\n if self.standard_parallel:\n src3 = src3 + self.linear2(self.dropout(self.activation(self.linear1(src2))))\n\n src = src + self.dropout(src3)\n return src" }, { "identifier": "RelativeMoeTransformerEncoderLayer", "path": "layers/transformer/relative_moe_transformer.py", "snippet": "class RelativeMoeTransformerEncoderLayer(LoggingLayer, torch.nn.Module):\n def __init__(self, d_model, nhead, n_experts: int, expert_size: int, n_layers: int, dim_feedforward=2048,\n dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0,\n test_pos_clamp: Optional[int] = None, knn: int = 0,\n standard_parallel: bool = False, custom_init: int = 0,\n dropout_mode: str = \"none\", selection_mode: str = \"add\",\n perplexity_reg: float = 0.0, key_mode: str = \"moe\", half_key: bool = False,\n n_heads: int = 1, norm_keys: bool = False, perplexity_reg_mode: str=\"step\",\n n_random: int = 0, reg_type: str = \"normal\", std_correction: bool = False,\n topk_mode: str = \"full\", head_projection_size: Optional[int] = None,\n activation_after_topk: bool = False, weight_grouping: str = \"none\",\n kmeans_distance: str = \"cosine\", drop_parallel: bool = True, block_expert_sel_in_grad: bool = False,\n mlp_selection: bool = False, classification_target: str = \"sum\",\n normalize_expert_sel_init: bool = False, norm_key_init: bool = False, norm_value_init: bool = False,\n norm_standard_parallel_values: bool = False, identical_init: bool = False,\n topological_sel_reg: float = 0.0, topological_expert_reg: float = 0.0,\n gumbel_select_only: bool = False, topk_value_norm_compensation: bool = False,\n norm_expert_scores: bool = False, sel_input_cluster_init: bool = False,\n init_norm_mode: str = \"full\", sel_bias: bool = False,\n bias: bool = False, rescale_normed: bool = False, sel_norm: str = \"none\",\n rescale_grads: bool = False, gumbel_decay: int = 0, preln: bool = True, ln_affine: bool = True,\n sinkhorn_local: bool = False, sinkhorn_n_iters: int = 3, moe_dropout_factor: float = 1.0,\n drop_expert: float = 0.0, expert_size_init: bool = False, sync_distributed: bool = True,\n modulation_amplitude: float = 0.5, invisible_selection: bool = False,\n slope_multiplier: float = 1.0, moe_init_scale: float = 1.0):\n super().__init__()\n self.preln = preln\n self.i = 0\n self.self_attn = FixedRelativeMultiheadAttention(\n d_model, nhead, dropout=attention_dropout, test_pos_clamp=test_pos_clamp,\n projection_size=head_projection_size)\n\n std_scale = math.sqrt(2.0 / n_layers) if preln else 1.0\n std_scale *= math.sqrt(moe_init_scale)\n\n self.pkm = MoE(\n d_model, n_experts, expert_size, knn=knn, dropout=dropout * moe_dropout_factor, dropout_mode=dropout_mode,\n weight_scale=std_scale, custom_init=custom_init, selection_mode=selection_mode,\n perplexity_reg=perplexity_reg, key_mode=key_mode, half_key=half_key, n_heads=n_heads,\n norm_keys=norm_keys, perplexity_reg_mode=perplexity_reg_mode, n_random=n_random,\n reg_type=reg_type, std_correction=std_correction, topk_mode=topk_mode,\n activation_after_topk=activation_after_topk, weight_grouping=weight_grouping,\n kmeans_distance=kmeans_distance, activation=activation, block_expert_sel_in_grad=block_expert_sel_in_grad,\n mlp_selection=mlp_selection, classification_target=classification_target,\n normalize_expert_sel_init=normalize_expert_sel_init, norm_key_init=norm_key_init,\n norm_value_init=norm_value_init, identical_init=identical_init, topological_sel_reg=topological_sel_reg,\n topological_expert_reg=topological_expert_reg, gumbel_select_only=gumbel_select_only,\n topk_value_norm_compensation=topk_value_norm_compensation, norm_expert_scores=norm_expert_scores,\n sel_input_cluster_init=sel_input_cluster_init,\n n_parallel_expert_channels=dim_feedforward if standard_parallel else 0,\n init_norm_mode=init_norm_mode, sel_bias=sel_bias, bias=bias, rescale_normed=rescale_normed,\n sel_norm=sel_norm, rescale_grads=rescale_grads, gumbel_decay=gumbel_decay,\n sinkhorn_local=sinkhorn_local, sinkhorn_n_iters=sinkhorn_n_iters, expert_dropout=drop_expert,\n expert_size_init=expert_size_init, sync_distributed=sync_distributed,\n modulation_amplitude=modulation_amplitude, invisible_selection=invisible_selection,\n slope_multiplier=slope_multiplier)\n\n self.norm1 = torch.nn.LayerNorm(d_model, elementwise_affine=ln_affine)\n self.norm2 = torch.nn.LayerNorm(d_model, elementwise_affine=ln_affine)\n self.dropout = torch.nn.Dropout(dropout)\n\n self.activation = activation\n self.standard_parallel = standard_parallel\n self.drop_parallel = drop_parallel\n\n if preln:\n reset_prenorm_params(self, n_layers)\n\n if self.standard_parallel:\n self.linear1 = torch.nn.Linear(d_model, dim_feedforward, bias=bias)\n self.linear2 = torch.nn.Linear(dim_feedforward, d_model, bias=False)\n\n s_real = dim_feedforward + self.pkm.size\n # s_real = dim_feedforward + self.pkm.heads * self.pkm.knn\n\n init = self.pkm.get_initializer()\n\n init(self.linear1.weight, std=std_scale * math.sqrt(1.0 / d_model))\n init(self.linear2.weight, std=std_scale * math.sqrt(1.0 / s_real))\n\n if norm_standard_parallel_values:\n with torch.no_grad():\n self.linear2.weight.div_(self.linear2.weight.norm(dim=0, keepdim=True))\n\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n\n src2 = self.norm1(src) if self.preln else src\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask,\n pos_offset=pos_offset)\n src = src + self.dropout(src2)\n\n if self.preln:\n src2 = self.norm2(src)\n else:\n src = src2 = self.norm1(src)\n\n if self.i == 3:\n with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True) as prof:\n src3 = self.pkm(src2)\n prof.export_chrome_trace(\"trace.json\")\n assert False\n else:\n src3 = self.pkm(src2)\n\n # self.i += 1\n\n if self.standard_parallel:\n x = self.linear1(src2)\n with torch.no_grad():\n self.log(\"standard_parallel_relu_pass_rate\", (x > 0).flatten(end_dim=-2).float().mean().item())\n x = self.activation(x)\n if self.drop_parallel:\n x = self.dropout(x)\n src3 = src3 + self.linear2(x)\n\n src = src + self.dropout(src3)\n if not self.preln:\n src = self.norm2(src)\n\n return src" }, { "identifier": "TopkTransformer", "path": "layers/transformer/topk_transformer.py", "snippet": "class TopkTransformer(PrelnRelativeTransformerEncoderLayer, LoggingLayer):\n def __init__(self, d_model, nhead, n_layers: int, dim_feedforward=2048, dropout=0.1,\n activation: ActivationFunction = F.relu, attention_dropout=0,\n test_pos_clamp: Optional[int] = None, drop_expand: bool = True, k: int = 32,\n use_norm: bool = True, head_projection_size: Optional[int] = None):\n\n super().__init__(d_model, nhead, n_layers, dim_feedforward, dropout, activation, attention_dropout,\n test_pos_clamp, drop_expand, head_projection_size=head_projection_size)\n\n LoggingLayer.__init__(self)\n self.k = k\n self.use_norm = use_norm\n\n def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None,\n pos_offset: Optional[int] = None) -> torch.Tensor:\n src2 = self.norm1(src)\n src2 = self.self_attn(src2, self.norm1(attend_to) if attend_to is not None else src2, mask,\n pos_offset=pos_offset)\n src = src + self.dropout1(src2)\n src2 = self.norm2(src)\n\n middle = self.dropout(self.activation(self.linear1(src2)))\n\n with torch.no_grad():\n if self.use_norm:\n norms = self.linear2.weight.norm(dim=0)\n vals = - middle * norms\n else:\n vals = - middle\n mask = vals > vals.kthvalue(self.k, keepdim=True)[0]\n\n self.log(\"relu_pass_rate_before\", (middle > 0).float().mean())\n\n middle = middle.masked_fill(mask, 0)\n\n self.log(\"topk_positive_rate\", (middle > 0).float().sum(-1).mean()/self.k)\n\n src2 = self.linear2(middle)\n src = src + self.dropout2(src2)\n return src" }, { "identifier": "MoE", "path": "layers/moe_layer.py", "snippet": "class MoE(LoggingLayer, RegularizedLayer, OncePerIterLayer, torch.nn.Module):\n def __init__(self, dmodel: int, n_experts: int, expert_size: int, n_heads: int, knn: int = 0,\n dropout: float = 0, weight_scale: float = 1.0, custom_init: int = 0,\n dropout_mode: str = \"none\", selection_mode: str = \"add\", perplexity_reg: float = 0.0,\n key_mode: str = \"moe\", half_key: bool = False, norm_keys: bool = False,\n perplexity_reg_mode: str=\"step\", n_random: int = 0, reg_type: str = \"entropy\",\n std_correction: bool = False, topk_mode: str = \"full\", activation_after_topk: bool = False,\n weight_grouping: str = \"none\", kmeans_distance: str = \"cosine\",\n activation = lambda x: F.relu(x, inplace=True), block_expert_sel_in_grad: bool = False,\n mlp_selection: bool = False, classification_target: str = \"sum\",\n normalize_expert_sel_init: bool = False, norm_key_init: bool = False, norm_value_init: bool = False,\n identical_init: bool = False, topological_sel_reg: float = 0.0, topological_expert_reg: float = 0.0,\n gumbel_select_only: bool = False, topk_value_norm_compensation: bool = False,\n norm_expert_scores: bool = False, sel_input_cluster_init: bool = False,\n n_parallel_expert_channels: int = 0, init_norm_mode: str = \"full\", sel_bias: bool = False,\n bias: bool = False, rescale_normed: bool = False, sel_norm: str = \"none\",\n rescale_grads: bool = False, gumbel_decay: int = 0, v_dim: Optional[int] = None,\n sinkhorn_local: bool = False, sinkhorn_n_iters: int = 3, expert_dropout: float = 0.0,\n expert_size_init: bool = False, sync_distributed: bool = False,\n modulation_amplitude: float = 0.5, invisible_selection: bool = False,\n slope_multiplier: float = 1.0):\n\n super().__init__()\n self.custom_init = custom_init\n self.k_dim = dmodel\n self.v_dim = v_dim if v_dim is not None else dmodel\n self.n_experts = n_experts\n self.expert_size = expert_size\n self.size = self.n_experts * self.expert_size\n self.knn = knn\n self.dropout = dropout\n self.dropout_mode = dropout_mode\n self.selection_mode = selection_mode\n self.perplexity_reg = perplexity_reg\n self.half_key = half_key\n self.key_mode = key_mode\n self.k_vec_dim = self.k_dim // (2 if half_key else 1)\n self.n_heads = n_heads\n self.norm_keys = norm_keys\n self.perplexity_reg_mode = perplexity_reg_mode\n self.n_random = n_random\n self.reg_type = reg_type\n self.topk_mode = topk_mode\n self.activation_after_topk = activation_after_topk\n self.weight_grouping = weight_grouping\n self.kmeans_distance = kmeans_distance\n self.activation = activation\n self.block_expert_sel_in_grad = block_expert_sel_in_grad\n self.mlp_selection = mlp_selection\n self.classification_target = classification_target\n self.weight_scale = weight_scale\n self.normalize_expert_sel_init = normalize_expert_sel_init\n self.norm_key_init = norm_key_init\n self.norm_value_init = norm_value_init\n self.identical_init = identical_init\n self.topological_sel_reg = topological_sel_reg\n self.topological_expert_reg = topological_expert_reg\n self.gumbel_select_only = gumbel_select_only\n self.topk_value_norm_compensation = topk_value_norm_compensation\n self.norm_expert_scores = norm_expert_scores\n self.sel_input_cluster_init = sel_input_cluster_init\n self.iter = 0\n self.layer = 0\n self.initalized = False\n self.rescale_normed = rescale_normed\n self.sel_norm = sel_norm\n self.rescale_grads = rescale_grads\n self.gumbel_decay = gumbel_decay\n self.was_training = True\n self.sinkhorn_local = sinkhorn_local\n self.sinkhorn_n_iters = sinkhorn_n_iters\n self.expert_dropout = expert_dropout\n self.reg_counts = 0\n self.sync_distributed = sync_distributed and torch.distributed.is_initialized()\n self.modulation_amplitude = modulation_amplitude\n self.invisible_selection = invisible_selection\n self.slope_multiplier = slope_multiplier\n\n self.coocurence = None\n\n assert self.selection_mode in {\"add\", \"gate\", \"sigmoid\", \"gumbel\", \"hard_gumbel\", \"gumbel_sigmoid\", \"sinkhorn\", \"sinkhorn2\", \"sinkmoid\", \"sinkmax\", \"sinkhorn_local\", \"mul\", \"random\", \"sinkmoid2\", \"sinkmax2\", \"modulate\"}\n assert self.perplexity_reg_mode in {\"step\", \"global\", \"time\", \"global_time\"}\n assert self.dropout_mode in {\"none\", \"score\"}\n assert self.reg_type in {\"perplexity\", \"variance\", \"entropy\", \"l2\", \"switch\"}\n assert self.topk_mode in {\"full\", \"l1_approx\", \"approx\"}\n assert self.weight_grouping in {\"none\", \"keys_only\", \"keys_and_experts\"}\n assert self.classification_target in {\"sum\", \"max\"}\n assert self.sel_norm in {\"none\", \"cos\", \"input\", \"weights\"}\n\n if selection_mode in {\"mul\"} and activation_after_topk:\n raise ValueError(\"Activation after topk is not supported with mul selection\")\n\n if self.sel_norm != \"none\" and mlp_selection:\n raise ValueError(\"normalization not supported with mlp_selection\")\n\n if std_correction and self.selection_mode in {\"add\"}:\n if key_mode == \"both\":\n self.key_std_correction = math.sqrt(3)\n else:\n self.key_std_correction = math.sqrt(2)\n elif std_correction and self.selection_mode in {\"sigmoid\", \"sinkmoid\", \"sinkmoid2\"}:\n self.key_std_correction = 2.0\n else:\n self.key_std_correction = 1.0\n\n if self.key_mode in {\"moe\", \"both\"}:\n self.keys = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim, self.expert_size))\n self.get_initializer()(self.keys, std=dmodel ** -0.5 * weight_scale * self.key_std_correction)\n else:\n self.keys = None\n\n if bias:\n self.bias = torch.nn.Parameter(torch.zeros(self.n_experts, self.expert_size))\n self.o_bias = torch.nn.Parameter(torch.zeros(self.v_dim))\n else:\n self.bias = None\n self.o_bias = None\n\n if self.key_mode in {\"shared\", \"both\"}:\n self.shared_keys = torch.nn.Parameter(torch.empty(self.k_vec_dim, self.expert_size))\n self.get_initializer()(self.shared_keys, std=dmodel ** -0.5 * weight_scale * self.key_std_correction)\n else:\n self.shared_keys = None\n\n self.values = torch.nn.Parameter(torch.empty(self.n_experts, self.expert_size, self.v_dim))\n\n if self.mlp_selection:\n self.sel = torch.nn.Sequential(\n torch.nn.Linear(self.k_vec_dim, dmodel),\n torch.nn.ReLU(),\n torch.nn.Linear(dmodel, self.n_experts, bias=bias)\n )\n self.get_initializer()(self.sel[0].weight, std=self.k_vec_dim ** -0.5 * weight_scale * self.key_std_correction)\n self.get_initializer()(self.sel[-1].weight, std=dmodel ** -0.5 * weight_scale * self.key_std_correction)\n self.expert_sel = None\n else:\n self.sel = lambda x: F.linear(x, self.expert_sel, self.sel_bias)\n self.expert_sel = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim))\n self.sel_bias = torch.nn.Parameter(torch.zeros(self.n_experts)) if sel_bias else None\n\n self.get_initializer()(self.expert_sel, std=self.k_vec_dim ** -0.5 * weight_scale)\n\n if init_norm_mode == \"full\":\n real_size = self.size\n elif init_norm_mode == \"selected_experts\":\n real_size = self.expert_size * self.n_heads\n elif init_norm_mode == \"selected_channels\":\n real_size = self.knn\n elif init_norm_mode == \"expert_size\":\n real_size = self.expert_size\n else:\n raise ValueError(\"Unknown init_norm_mode\")\n\n real_size += n_parallel_expert_channels\n\n if expert_size_init:\n real_size = self.expert_size\n\n self.get_initializer()(self.values, std=real_size ** -0.5 * weight_scale)\n self.sel_hist = []\n self.index_sel_counts = 0\n self.index_sel_norm = 0\n\n self.index_sel_counts_100 = 0\n self.index_sel_norm_100 = 0\n\n self.sel_count_log = None\n\n self.register_buffer(\"kv_sel_counts\", torch.zeros(self.n_experts, self.expert_size), persistent=False)\n self.register_buffer(\"kv_sel_counts_100\", torch.zeros_like(self.kv_sel_counts))\n\n if self.rescale_normed and self.sel_norm != \"none\":\n self.sel_scale = torch.nn.Parameter(torch.ones([1]))\n else:\n self.sel_scale = 1.0\n\n if self.norm_expert_scores:\n self.expert_scale = torch.nn.Parameter(torch.full([1], math.sqrt(expert_size)))\n\n self.register_buffer(\"seq\", torch.arange(max(self.knn, self.n_heads, self.n_experts, self.k_dim, self.v_dim), dtype=torch.long), persistent=False)\n self.regroup_weights()\n\n def keys_to_logical_order(self, keys: torch.Tensor) -> torch.Tensor:\n k = keys.view(self.n_experts, self.k_vec_dim, self.expert_size)\n return k.permute(0, 2, 1).contiguous().view(-1, self.k_vec_dim)\n\n def keys_from_logical_order(self, keys: torch.Tensor) -> torch.Tensor:\n return keys.view(self.n_experts, self.expert_size, self.k_vec_dim).permute(0, 2, 1).contiguous().view(self.n_experts * self.k_vec_dim, self.expert_size)\n\n def init_sel(self, x: torch.Tensor):\n if not self.sel_input_cluster_init:\n return\n\n with torch.no_grad():\n from kmeans_pytorch import kmeans\n _, cluster_centers = kmeans(\n X=x, num_clusters=self.n_experts, distance=self.kmeans_distance, device=torch.device('cuda')\n )\n\n self.expert_sel.set_(cluster_centers.to(self.expert_sel.device).contiguous())\n if self.normalize_expert_sel_init:\n self.renorm_keep_std(self.expert_sel, dim=1)\n\n def renorm_keep_std(self, weight: torch.Tensor, dim: int = 0):\n with torch.no_grad():\n std = weight.std()\n weight.div_(weight.norm(dim=dim, keepdim=True))\n weight.mul_(std / weight.std())\n\n def regroup_weights(self) -> Optional[torch.Tensor]:\n with torch.no_grad():\n\n if self.norm_key_init:\n self.renorm_keep_std(self.keys.view(self.n_experts, self.k_vec_dim, self.expert_size), dim=1)\n\n if self.norm_value_init:\n self.renorm_keep_std(self.values, dim=1)\n\n if self.identical_init:\n k = self.keys.view(self.n_experts, self.k_vec_dim, self.expert_size)\n self.keys.set_(k[:1].expand_as(k).reshape_as(self.keys))\n\n v = self.values.view(self.n_experts, self.expert_size, self.v_dim)\n self.values.set_(v[:1].expand_as(v).reshape_as(self.values))\n\n ids = None\n if self.weight_grouping != \"none\":\n # self.n_experts * self.k_vec_dim, self.expert_size\n k = self.keys_to_logical_order(self.keys)\n\n from kmeans_pytorch import kmeans\n cluster_ids_x, cluster_centers = kmeans(\n X=k, num_clusters=self.n_experts, distance=self.kmeans_distance, device=torch.device('cuda')\n )\n\n _, ids = cluster_ids_x.sort()\n k = self.keys_from_logical_order(k[ids])\n\n self.keys.set_(k.contiguous())\n self.values.set_(self.values[ids].contiguous())\n if self.weight_grouping == \"keys_and_experts\":\n self.expert_sel.set_(cluster_centers.contiguous().to(self.expert_sel.device))\n else:\n self.get_initializer()(self.expert_sel, std=self.k_vec_dim ** -0.5 * self.weight_scale)\n\n if self.normalize_expert_sel_init:\n self.renorm_keep_std(self.expert_sel, dim=1)\n\n return ids\n\n def patch_optimizer_state(self, optimizer: torch.optim.AdamW, ids: torch.Tensor):\n if self.weight_grouping == \"none\":\n return\n\n with torch.no_grad():\n ks = optimizer.state[self.keys]\n vs = optimizer.state[self.values]\n\n for p in {\"exp_avg\", \"exp_avg_sq\"}:\n k = self.keys_to_logical_order(ks[p])\n ks[p].set_(self.keys_from_logical_order(k[ids]))\n\n vs[p].set_(vs[p][ids])\n\n es = optimizer.state[self.expert_sel]\n for p in {\"exp_avg\", \"exp_avg_sq\", 'step'}:\n es[p].zero_()\n\n def get_initializer(self):\n return torch.nn.init.normal_ if self.custom_init in {0} else utils.init.trunc_normal_\n\n def sparse_matmul(self, indices: torch.Tensor, values: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:\n return F.embedding_bag(indices, weight.type_as(values), per_sample_weights=values, mode=\"sum\", sparse=False)\n\n # def sparse_matmul(self, indices: torch.Tensor, values: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:\n # sin = torch.sparse_csr_tensor(\n # crow_indices=torch.arange(0, values.nelement() + 1, values.shape[-1], device=indices.device),\n # col_indices=indices.flatten(),\n # values=values.flatten(),\n # size=(values.shape[0], weight.shape[0])\n # )\n # return sin @ weight.type_as(values)\n\n def pre_train_forward(self):\n if self.norm_keys:\n with torch.no_grad():\n self.keys.div_(self.keys.norm(dim=-1, keepdim=True))\n\n if self.topk_value_norm_compensation:\n with torch.no_grad():\n self.value_norms = self.values.norm(2, dim=-1)\n\n def topoloss(self, x: torch.Tensor) -> torch.Tensor:\n return (F.mse_loss(x[1:], x[:-1], reduction='mean') +\n F.mse_loss(x[1:], x[:-1], reduction='mean'))\n\n def ani(self, x: torch.Tensor) -> torch.Tensor:\n assert x.ndim == 2\n chunk_size = 32\n\n xnorm = F.normalize(x, 2, dim=-1)\n\n accu = 0\n for i in range(0, x.shape[0], chunk_size):\n a = xnorm[i: i + chunk_size]\n sims = xnorm @ a.T\n sims[i : i + chunk_size].fill_diagonal_(0)\n accu += sims.sum()\n\n return accu / (x.shape[0] * (x.shape[0] - 1))\n\n def log_expert_sel_usage(self, prefix: str, channel_sel_counts: torch.Tensor):\n sel_nonzero = (channel_sel_counts != 0).type(torch.float).sum(axis=-1) / self.expert_size\n self.log(f\"{prefix}/mean\", sel_nonzero.mean())\n self.log(f\"{prefix}/min\", sel_nonzero.min())\n self.log(f\"{prefix}/max\", sel_nonzero.max())\n\n\n def post_train_forward(self):\n if self.training and self.rescale_grads:\n self.values.grad.view(self.n_experts, -1).mul_(self.rescale[:, None])\n self.keys.grad.view(self.n_experts, -1).mul_(self.rescale[:, None])\n self.expert_sel.grad.mul_(self.rescale[:, None])\n\n def pre_train_forward(self):\n if self.training and not self.was_training:\n sorted_counts = self.index_sel_counts.sort(descending=True).values\n self.log(\"test_exert_channel_usage\", framework.visualize.plot.Barplot(sorted_counts, xlabel=\"expert\", ylabel=\"usage count\"), drop_old=True)\n\n self.layer = 0\n if self.sel_hist:\n self.sel_hist = []\n self.index_sel_counts = 0\n self.index_sel_norm = 0\n self.reg_counts = 0\n\n def before_loss(self):\n if self.sel_hist:\n # Concatenate against time dimension. Important for the within-batch regularization\n sel = torch.cat(self.sel_hist, -2)\n self.add_perplexity_reg(sel)\n\n self.sel_hist = []\n\n if self.topological_sel_reg > 0:\n self.add_reg(lambda: self.topological_sel_reg * self.topoloss(self.expert_sel))\n\n if self.topological_expert_reg > 0:\n self.add_reg(lambda: self.topological_expert_reg * (\n self.topoloss(self.keys.view(self.n_experts, -1)) +\n self.topoloss(self.values.view(self.n_experts, -1))\n ))\n\n if self.rescale_grads:\n self.rescale = 1.0 / self.index_sel_counts.clamp(min=1)\n\n # json.dumps\n\n\n if self.index_sel_norm > 0:\n if self.training:\n with torch.no_grad():\n self.log(\"usag_rel_perplexity_all_layers\", utils.relative_perplexity(self.index_sel_counts / self.index_sel_norm))\n self.log(\"dead_expert_proportion_all_layers\", (self.index_sel_counts == 0).float().sum() / self.n_experts)\n\n self.log_expert_sel_usage(\"exert_channel_usage\", self.kv_sel_counts)\n\n self.kv_sel_counts_100.add_(self.kv_sel_counts)\n self.kv_sel_counts.zero_()\n\n self.index_sel_counts_100 = self.index_sel_counts_100 + self.index_sel_counts\n self.index_sel_norm_100 = self.index_sel_norm_100 + self.index_sel_norm\n\n if self.training and self.iter % 100 == 0:\n norm_cnt = self.index_sel_counts_100 / self.index_sel_norm_100\n self.log(\"usag_rel_perplexity_100\", utils.relative_perplexity(norm_cnt))\n self.log(\"dead_expert_proportion_100\", (self.index_sel_counts_100 == 0).float().sum() / self.n_experts)\n\n sorted_counts = self.index_sel_counts_100.sort(descending=True).values\n self.log(\"usage_counts_100\", framework.visualize.plot.Barplot(sorted_counts, xlabel=\"expert\", ylabel=\"usage count\"), drop_old=True)\n\n\n self.log_expert_sel_usage(\"exert_channel_usage_100\", self.kv_sel_counts_100)\n self.kv_sel_counts_100.zero_()\n\n self.index_sel_counts_100 = 0\n self.index_sel_norm_100 = 0\n\n self.log(\"ani/keys\", self.ani(self.keys_to_logical_order(self.keys)))\n self.log(\"ani/values\", self.ani(self.values.flatten(0, -2)))\n self.log(\"ani/expert_sel\", self.ani(self.expert_sel.T))\n\n if self.training:\n self.iter += 1\n\n def topk(self, x: torch.Tensor, k: int, approx: bool) -> Tuple[torch.Tensor, torch.Tensor]:\n if approx:\n x = x.view(*x.shape[:-1], k, -1)\n scores, ind = x.max(-1)\n return scores, self.seq[:k] * x.shape[-1] + ind\n else:\n return x.topk(k, dim=-1, sorted=False)\n\n def add_perplexity_reg(self, sel: torch.Tensor):\n sync_distributed = self.sync_distributed and (self.perplexity_reg_mode not in {\"time\", \"global_time\"})\n\n def log_mean(x: torch.Tensor, dim: int = 0):\n if sync_distributed:\n xlse = framework.utils.distributed_ops.logsumexp(x, dim=dim)\n\n # Normalize\n n = torch.tensor(x.shape[dim]).to(x.device)\n torch.distributed.all_reduce(n, op=torch.distributed.ReduceOp.SUM)\n return xlse - n.log()\n else:\n return x.logsumexp(dim) - math.log(x.shape[dim])\n\n if self.perplexity_reg_mode in {\"time\", \"global_time\"}:\n sel = sel.flatten(0, -3)\n else:\n sel = sel.flatten(0, -2)\n\n # Note: sel are raw logits, no matter what activation is used\n if self.perplexity_reg > 0:\n if self.reg_type == \"perplexity\":\n sel_d = F.log_softmax(sel, dim=-1)\n sel_d = log_mean(sel_d, -2)\n loss = lambda: self.perplexity_reg * ( - utils.relative_perplexity_l(sel_d).mean())\n elif self.reg_type == \"entropy\":\n sel_d = F.log_softmax(sel, dim=-1)\n sel_d = log_mean(sel_d, -2)\n loss = lambda: self.perplexity_reg * ( - utils.entropy_l(sel_d).mean())\n elif self.reg_type == \"variance\":\n if sync_distributed:\n raise NotImplementedError(\"Variance regularization is not supported in distributed mode\")\n avg_sel = sel.mean(-2)\n loss = lambda: self.perplexity_reg * avg_sel.var(-1).mean()\n elif self.reg_type == \"l2\":\n loss = lambda: self.perplexity_reg * sel.pow(2).mean()\n elif self.reg_type == \"switch\":\n if sync_distributed:\n torch.distributed.all_reduce(self.reg_counts, op=torch.distributed.ReduceOp.SUM)\n\n p_sel_real = self.reg_counts / self.reg_counts.sum(-1, keepdims=True)\n if self.perplexity_reg_mode in {\"time\", \"global_time\"}:\n p_sel_real = p_sel_real.unsqueeze(-2)\n\n loss = lambda: self.perplexity_reg * (F.softmax(sel, dim=-1) * p_sel_real).mean()\n self.reg_counts = 0\n else:\n assert False\n\n self.add_reg(loss, \"moe\")\n\n def compute_scores(self, input: torch.Tensor, index: CVMMSel, expert_scores: torch.Tensor, shared_score: Optional[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:\n if self.keys is not None:\n # scores = self.sparse_matmul(\n # (self.seq[:input.shape[-1]] + index[:, None] * (self.k_dim // (2 if self.half_key else 1))),\n # input,\n # self.keys\n # )\n scores = cvmm(input, index, self.keys)\n if self.shared_keys is not None:\n scores = scores + shared_score\n else:\n scores = shared_score\n\n if self.bias is not None:\n scores = scores + self.bias[index.raw_sel]\n\n if self.invisible_selection:\n unmodulated_scores = scores\n scores = scores.detach()\n\n if self.selection_mode in {\"add\"}:\n with torch.no_grad():\n self.log(\"expert_key_positive_rate\", (scores > 0).type_as(scores).mean())\n scores = scores + expert_scores[..., None]\n elif self.selection_mode in {\"mul\"}:\n scores = scores * expert_scores[..., None]\n elif self.selection_mode in {\"gate\", \"sigmoid\", \"gumbel\", \"gumbel_sigmoid\", \"sinkhorn\", \"sinkhorn2\", \"sinkmoid\", \"sinkmax\", \"random\", \"modulate\", \"sinkmoid2\"}:\n # Handle it later\n pass\n elif self.selection_mode == \"hard_gumbel\":\n s = (torch.ones_like(expert_scores) - expert_scores).detach() + expert_scores\n scores = scores * s[..., None]\n\n if self.invisible_selection and scores is not unmodulated_scores:\n scores = unmodulated_scores + scores - scores.detach()\n\n scores = self.activation(scores)\n\n if self.norm_expert_scores:\n scores = F.normalize(scores, 1, dim=-1) * self.expert_scale\n\n if self.selection_mode in {\"gate\", \"sigmoid\", \"gumbel\", \"gumbel_sigmoid\", \"sinkhorn\", \"sinkhorn2\", \"sinkmoid\", \"sinkmax\", \"modulate\", \"sinkmoid2\"}:\n if self.invisible_selection:\n unmodulated_scores = scores\n scores = scores.detach()\n scores = scores * expert_scores[..., None]\n if self.invisible_selection:\n scores = unmodulated_scores + scores - scores.detach()\n\n if self.train and self.iter % 10 == 0:\n with torch.no_grad():\n gt0 = (scores > 0).float()\n gt0_s = gt0.sum()\n if self.selection_mode in {\"add\"}:\n self.log(\"k1_vs_k2_magnitude\", (scores / expert_scores[..., None]).sum() / gt0_s - 1)\n\n self.log(\"relu_pass_rate\", gt0_s / scores.numel())\n\n self.kv_sel_counts.index_add_(0, index.raw_sel.flatten(), gt0.flatten(end_dim=-2))\n\n\n # elif self.selection_mode in {\"predict_rank\"}:\n # self.add_reg(lambda: self.rank_loss(expert_scores, scores.detach().sum(-1)))\n\n if self.dropout > 0 and self.dropout_mode != \"none\":\n scores = F.dropout(scores, self.dropout, training=self.training)\n\n # indices = torch.arange(0, scores.shape[-1], device=input.device) + index[:, None] * self.expert_size\n return scores\n\n def sel_activation(self, sel: torch.Tensor, seq_len: int) -> Tuple[torch.Tensor, torch.Tensor]:\n reg_sel = sel\n if self.selection_mode in {\"gumbel\", \"hard_gumbel\"}:\n if self.training:\n sel = F.gumbel_softmax(sel)\n else:\n sel = F.softmax(sel)\n elif self.selection_mode == \"gumbel_sigmoid\":\n if self.training and (self.gumbel_decay == 0 or self.gumbel_decay > self.iter):\n noise = gumbel_sigmoid_noise(sel)\n if self.gumbel_decay:\n noise = noise * (1 - self.iter / self.gumbel_decay)\n sel = sel + noise\n else:\n sel = F.sigmoid(sel)\n elif self.selection_mode in {\"sinkhorn\", \"sinkmoid\", \"sinkmax\"}:\n if self.training:\n if self.sinkhorn_local:\n sel = sel.view(-1, seq_len, sel.shape[-1])\n\n for _ in range(self.sinkhorn_n_iters):\n if self.sinkhorn_local or (not self.sync_distributed):\n sel = sel - torch.logsumexp(sel, -2, keepdim=True)\n else:\n sel = sel - framework.utils.distributed_ops.logsumexp(sel, -2, keepdim=True)\n\n sel = sel - torch.logsumexp(sel, -1, keepdim=True)\n reg_sel = sel\n\n if self.sinkhorn_local:\n sel = sel.flatten(end_dim=-2).exp()\n\n sel = sel.exp()\n elif self.selection_mode == \"sinkmoid\":\n sel = F.sigmoid(sel)\n else:\n sel = F.softmax(sel, dim=-1)\n elif self.selection_mode in {\"sinkhorn2\", \"sinkmoid2\", \"sinkmax2\"}:\n if self.training:\n sel = self.sinkhorn(sel, self.selection_mode != \"sinkmoid2\")\n elif self.selection_mode == \"sinkmoid\":\n sel = F.sigmoid(sel)\n else:\n sel = F.softmax(sel, dim=-1)\n elif self.selection_mode in {\"sigmoid\"}:\n sel = torch.sigmoid(sel)\n elif self.selection_mode in {\"modulate\"}:\n sel = torch.tanh(sel) * (self.modulation_amplitude / 0.5) + 1\n elif self.selection_mode in {\"add\"}:\n sel = sel\n elif self.selection_mode in {\"mul\"}:\n sel = sel.abs()\n reg_sel = sel\n elif self.selection_mode in {\"gate\"}:\n sel = F.softmax(sel, dim=-1)\n with torch.no_grad():\n self.log(\"expert_rel_perplexity_per_selection\", utils.relative_perplexity(sel).mean())\n else:\n assert False\n\n return sel, reg_sel\n\n def sinkhorn(self, x: torch.Tensor, normalize:bool = True) -> torch.Tensor:\n # Based on\n A, B = x.shape[-2:]\n\n a = torch.zeros_like(x[..., 0, :])\n b = torch.zeros_like(x[..., 0])\n\n for _ in range(self.sinkhorn_n_iters):\n b = math.log(A) - (x - a[..., None, :]).logsumexp(-1)\n if self.sync_distributed:\n a = math.log(B) - framework.utils.distributed_ops.logsumexp(x - b[..., None], -2)\n else:\n a = math.log(B) - (x - b[..., None]).logsumexp(-2)\n\n r = (a[..., None, :] + b[..., None] + x).exp()\n\n if normalize and self.sync_distributed:\n A = torch.tensor(A, device=x.device)\n A = torch.distributed.reduce_all(A, op=torch.distributed.ReduceOp.SUM)\n A = A.item()\n return (r / (A * B)) if normalize else r\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n if not self.initalized:\n self.init_sel(input)\n self.initalized = True\n\n out = 0\n\n if self.half_key:\n in1 = input[..., :self.k_dim // 2]\n in2 = input[..., self.k_dim // 2:]\n else:\n in1 = in2 = input\n\n if self.selection_mode != \"random\":\n if self.block_expert_sel_in_grad:\n in1 = in1.detach()\n\n sel = self.sel(in1) * self.slope_multiplier\n\n if self.sel_norm == \"cos\":\n sel = sel / (in1.norm(dim=-1, keepdim=True) * self.expert_sel.norm(dim=-1)[None]) * self.sel_scale\n elif self.sel_norm == \"weights\":\n sel = sel * (self.sel_scale / self.expert_sel.norm(dim=-1)[None])\n elif self.sel_norm == \"input\":\n sel = sel * (self.sel_scale / in1.norm(dim=-1, keepdim=True))\n\n sel_raw = reg_sel = sel\n\n inv_val = float(\"-inf\")\n\n if (not self.activation_after_topk) or self.selection_mode in {\"sinkhorn\", \"sinkhorn2\", \"gumbel\", \"hard_gumbel\", \"gumbel_sigmoid\", \"sinkmoid\", \"sinkmax\", \"mul\", \"sinkmoid2\"}:\n # Sinkhorn should be always applied before top-k\n sel, reg_sel = self.sel_activation(sel, input.shape[-2])\n if self.selection_mode not in {\"sinkmoid\", \"sinkmoid2\"}:\n inv_val = 0\n\n if self.training and self.expert_dropout > 0:\n if self.selection_mode not in {\"sigmoid\", \"modulate\", \"gate\", \"sinkmoid\", \"sinkmoid2\"}:\n raise ValueError(\"Expert dropout not supported in this mode\")\n\n mask = torch.rand_like(sel) < self.expert_dropout\n sel2 = sel.masked_fill(mask, inv_val)\n else:\n sel2 = sel\n\n sel_val, sel_index = self.topk(sel2, self.n_heads, self.topk_mode in {\"l1_approx\", \"approx\"})\n\n if self.activation_after_topk or (self.selection_mode in {\"sinkmoid\", \"sinkmax\", \"mul\", \"sinkmoid2\"}) or (self.gumbel_select_only and self.selection_mode in {\"gumbel\", \"hard_gumbel\", \"gumbel_sigmoid\", \"gumbel_sigmoid\", \"sinkmax\"}):\n sel_val = torch.gather(sel_raw, -1, sel_index)\n if self.selection_mode in {\"gumbel_sigmoid\", \"sinkmoid\", \"sinkmoid2\"}:\n sel_val = torch.sigmoid(sel_val)\n elif self.selection_mode in {\"sinkhorn\", \"sinkhorn2\"}:\n # In case of sinkhorn, simulate the effect of post-topk activation by renormalizing\n sel_val = F.normalize(sel_val, p=1, dim=-1)\n else:\n sel_val, reg_sel = self.sel_activation(sel_val, input.shape[-2])\n else:\n sel_index = torch.randint(0, self.n_experts, (*input.shape[:-1], self.n_heads), device=input.device)\n sel_val = torch.ones_like(sel_index, dtype=input.dtype, device=input.device)\n reg_sel = None\n\n\n record_counts_now = (self.training and self.iter % 10 == 0) or (not self.training)\n\n if not self.training:\n sel_index_flat = sel_index.flatten(end_dim=-2)\n if self.coocurence is None:\n self.coocurence = torch.zeros([self.n_experts, self.n_experts], device=sel_index_flat.device, dtype=torch.long)\n\n for h1 in range(self.n_heads):\n for h2 in range(self.n_heads):\n ind_flat = sel_index_flat[..., h1] * self.n_experts + sel_index_flat[..., h2]\n values = torch.tensor([1], device=self.coocurence.device, dtype=self.coocurence.dtype).expand_as(ind_flat)\n # values = sel_val[..., h2].flatten()\n self.coocurence.flatten().put_(ind_flat, values, accumulate=True)\n # self.coocurence[sel_index_flat[..., h1], sel_index_flat[..., h2]] += 1\n\n if record_counts_now or self.reg_type == \"switch\":\n reg_counts = F.one_hot(sel_index, self.n_experts).type_as(input)\n\n if self.reg_type == \"switch\":\n reg_counts2 = reg_counts.view(*input.shape[:-2], input.shape[-2] * self.n_heads, self.n_experts)\n if self.perplexity_reg_mode == \"time\":\n reg_counts2 = reg_counts2.sum(-2)\n else:\n reg_counts2 = reg_counts2.flatten(end_dim=-2).sum(0)\n\n self.reg_counts = self.reg_counts + reg_counts2\n\n if record_counts_now:\n with torch.no_grad():\n sel_counts = reg_counts.flatten(end_dim=-2).sum(0)\n cnt = sel_index.nelement()\n\n p_expert_sel = sel_counts / cnt\n\n self.index_sel_counts = self.index_sel_counts + sel_counts\n self.index_sel_norm = self.index_sel_norm + cnt\n\n if self.training:\n self.log(\"min_sel_score\", sel_val.min(dim=-1).values.mean())\n self.log(\"max_sel_score\", sel_val.max(dim=-1).values.mean())\n\n sel_oh = F.one_hot(sel_index, self.n_experts).sum(-2).bool()\n if self.layer >= 1 and self.training:\n self.log(f\"layer_sel_overlap_{self.layer}\", ((self.prev_sel_oh & sel_oh).sum(-1).float() / self.n_heads).mean())\n\n self.prev_sel_oh = sel_oh\n\n ppl = utils.relative_perplexity(p_expert_sel)\n self.log(\"usage_rel_perplexity\", ppl)\n self.log(\"dead_expert_proportion\", (p_expert_sel == 0).float().sum() / self.n_experts)\n\n if self.perplexity_reg_mode in {\"step\", \"time\"}:\n self.add_perplexity_reg(reg_sel)\n elif self.perplexity_reg > 0 and self.training:\n self.sel_hist.append(reg_sel)\n\n shared_score = (in2 @ self.shared_keys) if self.shared_keys is not None else None\n\n scores_l = []\n\n sel_indices = [cvmm_prepare_sel(sel_index[..., h].int(), self.n_experts) for h in range(sel_index.shape[-1])]\n\n for h in range(sel_index.shape[-1]):\n hi = sel_indices[h]\n\n scores = self.compute_scores(in2, hi, sel_val[..., h], shared_score)\n scores_l.append(scores)\n\n if self.knn > 0 or self.selection_mode == \"classify\":\n with torch.no_grad():\n scores = torch.cat(scores_l, -1)\n\n if self.knn > 0:\n with torch.no_grad():\n tresh = scores.kthvalue(scores.shape[-1] - self.knn, -1).values\n\n scores_l = [s.masked_fill_(s < tresh[:, None], 0) for s in scores_l]\n\n out = 0\n for (hi, scores) in zip(sel_indices, scores_l):\n out = out + cvmm(scores, hi, self.values)\n\n # indices = torch.cat(ind_l, dim=-1)\n # scores = torch.cat(scores_l, dim=-1)\n\n if self.selection_mode == \"classify\":\n self.add_reg(lambda: self.cls_loss(sel_val, scores))\n\n # if self.knn > 0:\n # if self.topk_value_norm_compensation:\n # norms = self.value_norms[None].expand(indices.shape[0], -1).gather(-1, indices)\n # scores2 = scores * norms\n # _, ind2 = self.topk(scores2, self.knn, self.topk_mode == \"approx\")\n # indices = indices.gather(-1, ind2)\n # scores = scores.gather(-1, ind2)\n # else:\n # scores, ind2 = self.topk(scores, self.knn, self.topk_mode == \"approx\")\n # indices = indices.gather(-1, ind2)\n\n # if self.n_random > 0 and self.selection_mode not in {\"predict\", \"classify\"}:\n # with torch.no_grad():\n # rind = torch.arange(0, self.n_experts, device=input.device)\n # rind = torch.masked_select(rind, ~F.one_hot(sel_index, self.n_experts).sum(-2).bool()).view(in_flat.shape[0],-1)\n # rind = rind.gather(-1, torch.randint(0, rind.shape[-1], size=[*rind.shape[:-1], self.n_random], device=rind.device))\n\n # ind_l = [indices]\n # scores_l = [scores]\n # for i in range(self.n_random):\n # hi = rind[..., i]\n # indices, scores = self.compute_scores(in2, hi, sel.gather(-1, hi[:, None]).squeeze(), shared_score)\n\n # ind_l.append(indices)\n # scores_l.append(scores)\n\n # indices = torch.cat(ind_l, dim=-1)\n # scores = torch.cat(scores_l, dim=-1)\n\n # out = self.sparse_matmul(indices, scores, self.values)\n\n self.layer += 1\n\n self.was_training = self.training\n res = out.view(*input.shape[:-1], self.v_dim)\n if self.o_bias is not None:\n res = res + self.o_bias\n return res\n\n def dump_logs(self, save_dir: str):\n if self.coocurence is not None:\n os.makedirs(save_dir, exist_ok=True)\n torch.save(self.coocurence, os.path.join(save_dir, \"coocurence.pt\"))\n\n def get_logs(self) -> Dict[str, Any]:\n res = super().get_logs()\n\n if self.coocurence is not None:\n coo = self.coocurence / self.coocurence.diagonal().clamp(min=1)[:, None]\n res[\"expert_coocurence\"] = framework.visualize.plot.Heatmap(coo, xlabel=\"expert\", ylabel=\"expert\", textval=False)\n self.coocurence = None\n return res" }, { "identifier": "Result", "path": "interfaces/result.py", "snippet": "class Result:\n outputs: torch.Tensor\n loss: torch.Tensor\n\n batch_dim = 0\n\n def plot(self) -> Dict[str, Any]:\n return {}\n\n @property\n def batch_size(self) -> int:\n return self.outputs.shape[self.batch_dim]\n\n @staticmethod\n def merge(l: List, batch_weights: Optional[List[float]] = None):\n if len(l) == 1:\n return l[0]\n batch_weights = batch_weights if batch_weights is not None else [1] * len(l)\n loss = sum([r.loss * w for r, w in zip(l, batch_weights)]) / sum(batch_weights)\n out = torch.stack([r.outputs for r in l], l[0].batch_dim)\n return l[0].__class__(out, loss)" } ]
import framework import torch import torch.nn import torch.nn.functional as F import torch.utils.data import math from typing import List, Tuple, Dict, Any from models import TransformerLanguageModel from ... import task, args from layers.transformer import RelativeTransformerEncoderLayer, PrelnRelativeTransformerEncoderLayer from layers.transformer.relative_preln_kvmem_transformer import PrelnRelativeKVMemTransformerEncoderLayer from layers.transformer.relative_moe_transformer import RelativeMoeTransformerEncoderLayer from layers.transformer.topk_transformer import TopkTransformer from layers.moe_layer import MoE from interfaces import Result
19,197
parser.add_argument("-moe.topk_value_norm_compensation", default=False) parser.add_argument("-moe.norm_expert_scores", default=False) parser.add_argument("-moe.sel_input_cluster_init", default=False) parser.add_argument("-moe.init_norm_mode", default="full") parser.add_argument("-moe.bias", default=False) parser.add_argument("-moe.sel_bias", default=False) parser.add_argument("-moe.rescale_normed", default=False) parser.add_argument("-moe.sel_norm", default="none", choice=["none", "cos", "input", "weights"]) parser.add_argument("-moe.rescale_grads", default=False) parser.add_argument("-moe.gumbel_decay", default=0) parser.add_argument("-moe.sinkhorn_local", default=False) parser.add_argument("-moe.sinkhron_n_iters", default=3) parser.add_argument("-moe.dropout_factor", default=1.0) parser.add_argument("-moe.drop_expert", default=0.0) parser.add_argument("-moe.expert_size_init", default=False) parser.add_argument("-moe.sync_distributed", default=True) parser.add_argument("-moe.modulation_amplitude", default=0.5) parser.add_argument("-moe.invisible_selection", default=False) parser.add_argument("-moe.slope_multiplier", default=1.0) parser.add_argument("-moe.init_scale", default=1.0) parser.add_argument("-kvmem.linproj", default=False) parser.add_argument("-kvmem.head_merge_topk", default=False) parser.add_argument("-kvmem.load_balance", default=False) parser.add_argument("-kvmem.dropout", default="none", choice=["none", "early", "late", "weight", "score"]) parser.add_argument("-kvmem.randomize_indices", default=False) parser.add_argument("-kvmem.standard_parallel", default=False) parser.add_argument("-kvmem.query_bias", default=False) parser.add_argument("-kvmem.approx_topk", default=False) parser.add_argument("-kvmem.norm_values", default=False) parser.add_argument("-kvmem.factorize", default=False) parser.add_argument("-kvmem.full_key", default=False) parser.add_argument("-kvmem.key_redundancy_factor", default=1) parser.add_argument("-kvmem.two_stage", default=False) parser.add_argument("-kvmem.head_exclusive", default=False) parser.add_argument("-transformer.topk_value", default=32) parser.add_argument("-transformer.universal.nonshared", default=0) parser.add_argument("-transformer.topk_use_norm", default=True) parser.add_argument("-transformer.activation", default="relu", choice=["relu", "topk", "gelu", "identity", "sigmoid", "softmax"]) parser.add_argument("-transformer.p_drop_layer", default=0.0) parser.add_argument("-transformer.head_projection_size", default="none", parser=parser.int_or_none_parser) parser.add_argument("-transformer.ln_affine", default=True) parser.add_argument("-transformer.ln_after_attention", default=True) parser.add_argument("-transformer.output_mode", default="normal", choice=["normal", "sum", "geometric", "sigmoid"]) @task() class TransformerLMMixin: helper: framework.helpers.TrainingHelper def is_preln(self) -> bool: return "preln" in self.helper.args.transformer.variant def topk_activation(self, x: torch.Tensor) -> torch.Tensor: nx = -x return torch.masked_fill(x, nx <= nx.kthvalue(self.helper.args.transformer.topk_value, keepdim=True)[0], 0) def get_layers(self) -> List[torch.nn.Module]: # pyright: reportOptionalMemberAccess=false if self.helper.args.transformer.activation == "relu": activation = F.relu elif self.helper.args.transformer.activation == "topk": activation = self.topk_activation elif self.helper.args.transformer.activation == "identity": activation = lambda x: x elif self.helper.args.transformer.activation == "sigmoid": activation = torch.sigmoid elif self.helper.args.transformer.activation == "gelu": activation = F.gelu elif self.helper.args.transformer.activation == "softmax": activation = lambda x: F.softmax(x, dim=-1) else: raise ValueError(f"Invalid activation: {self.helper.args.transformer.activation}") base_args = dict( d_model=self.helper.args.state_size, nhead=self.helper.args.transformer.n_heads, dim_feedforward=int(self.helper.args.state_size * self.helper.args.transformer.ff_multiplier), dropout=self.helper.args.dropout, activation=activation ) extra_args = {} if not self.helper.args.transformer.variant.endswith("_gelu") else { "activation": F.gelu, "drop_expand": False } if self.helper.args.transformer.variant in {"preln_relative"}: mklayer = lambda: PrelnRelativeTransformerEncoderLayer( **base_args, **extra_args, test_pos_clamp=self.helper.args.lm.trafo.test_pos_clamp, n_layers=self.helper.args.transformer.encoder_n_layers, head_projection_size=self.helper.args.transformer.head_projection_size,) elif self.helper.args.transformer.variant in {"preln_topk"}: mklayer = lambda: TopkTransformer( **base_args, **extra_args, test_pos_clamp=self.helper.args.lm.trafo.test_pos_clamp, n_layers=self.helper.args.transformer.encoder_n_layers, k=self.helper.args.transformer.topk_value, use_norm=self.helper.args.transformer.topk_use_norm, head_projection_size=self.helper.args.transformer.head_projection_size,) elif self.helper.args.transformer.variant in {"preln_kvmem"}: mklayer = lambda: PrelnRelativeKVMemTransformerEncoderLayer( **base_args, **extra_args, test_pos_clamp=self.helper.args.lm.trafo.test_pos_clamp, n_layers=self.helper.args.transformer.encoder_n_layers, n_keys=self.helper.args.pkm.n_keys, pkm_stochastic=self.helper.args.pkm.stochastic, pkm_heads=self.helper.args.pkm.n_heads, pkm_custom_init=self.helper.args.pkm.custom_init, pkm_slice_values=self.helper.args.pkm.slice_values, pkm_knn=self.helper.args.pkm.knn, linproj=self.helper.args.kvmem.linproj, head_merge_topk=self.helper.args.kvmem.head_merge_topk, load_balance=self.helper.args.kvmem.load_balance, kvmem_dropout=self.helper.args.kvmem.dropout, kvmem_randomize_indices=self.helper.args.kvmem.randomize_indices, kvmem_query_bias=self.helper.args.kvmem.query_bias, standard_parallel=self.helper.args.kvmem.standard_parallel, approx_topk=self.helper.args.kvmem.approx_topk, factorize=self.helper.args.kvmem.factorize, full_key=self.helper.args.kvmem.full_key, key_redundancy_factor=self.helper.args.kvmem.key_redundancy_factor, two_stage=self.helper.args.kvmem.two_stage, head_exclusive=self.helper.args.kvmem.head_exclusive, head_projection_size=self.helper.args.transformer.head_projection_size,) elif self.helper.args.transformer.variant in {"preln_moe", "preln_moe_universal", "moe", "moe_universal"}: # def __init__(self, d_model, nhead, n_bins: int, bin_size: int, n_layers: int, dim_feedforward=2048,
@args def a(parser: framework.helpers.ArgumentParser): parser.add_argument("-lm.trafo.context_blocks", default=1) parser.add_argument("-lm.trafo.test_context_blocks", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.trafo.test_pos_clamp", default="none", parser=parser.int_or_none_parser) parser.add_argument("-lm.trafo.same_length_eval", default=False) parser.add_argument("-lm.trafo.same_length", default=False) parser.add_argument("-lm.trafo.last_layer_context", default=False) parser.add_argument("-lm.trafo.xl_init", default=False) parser.add_argument("-lm.trafo.embedding_mode_init", default="default", choice=["default", "scale_to_sqrt_dmodel", "init_to_sqrt_dmodel", "one_and_scale_to_sqrt_dmodel", "like_preln"]) parser.add_argument("-pkm.n_keys", default="128", parser=parser.int_list_parser) parser.add_argument("-pkm.n_heads", default=1) parser.add_argument("-pkm.knn", default=32) parser.add_argument("-pkm.stochastic", default=False) parser.add_argument("-pkm.query_batchnorm", default=False) parser.add_argument("-pkm.custom_init", default=0) parser.add_argument("-pkm.slice_values", default=False) parser.add_argument("-pkm.slice_proj", default=False) parser.add_argument("-pkm.sample_smallest", default=False) parser.add_argument("-moe.n_experts", default=128) parser.add_argument("-moe.expert_size", default=128) parser.add_argument("-moe.selection_mode", default="add", choice=["add", "gate", "sigmoid", "gumbel", "hard_gumbel", "predict", "predict_mlp", "classify", "gumbel_sigmoid", "sinkhorn", "sinkhorn2", "sinkmoid", "sinkmax", "moe", "mul", "random", "sinkmoid2", "sinkmax2", "modulate"]) parser.add_argument("-moe.perplexity_reg", default=0.0) parser.add_argument("-moe.perplexity_reg_mode", default="step", choice=["step", "global", "time", "global_time"]) parser.add_argument("-moe.reg_type", default="entropy", choice=["perplexity", "variance", "entropy", "l2", "switch", "normal"]) parser.add_argument("-moe.key_mode", default="moe", choice=["moe", "both", "shared"]) parser.add_argument("-moe.half_key", default=False) parser.add_argument("-moe.norm_keys", default=False) parser.add_argument("-moe.kmeans_distance", default='cosine', choice=['cosine', 'euclidean']) parser.add_argument("-moe.n_random", default=0) parser.add_argument("-moe.std_correction", default=False) parser.add_argument("-moe.topk_mode", default="full", choice=["full", "l1_approx", "approx"]) parser.add_argument("-moe.activation_after_topk", default=False) parser.add_argument("-moe.weight_grouping", default="none", choice=["none", "keys_only", "keys_and_experts"]) parser.add_argument("-moe.drop_parallel", default=True) parser.add_argument("-moe.mlp_selection", default=False) parser.add_argument("-moe.block_expert_sel_in_grad", default=False) parser.add_argument("-moe.classification_target", default="sum", choice=["sum", "max"]) parser.add_argument("-moe.recluster_steps", default="", parser=parser.int_list_parser) parser.add_argument("-moe.norm_key_init", default=False) parser.add_argument("-moe.norm_value_init", default=False) parser.add_argument("-moe.norm_expert_sel_init", default=False) parser.add_argument("-moe.norm_standard_parallel_values", default=False) parser.add_argument("-moe.identical_init", default=False) parser.add_argument("-moe.topological_sel_reg", default=0.0) parser.add_argument("-moe.topological_expert_reg", default=0.0) parser.add_argument("-moe.sel_lr_multipler", default=1.0) parser.add_argument("-moe.expert_lr_multipler", default=1.0) parser.add_argument("-moe.gumbel_select_only", default=False) parser.add_argument("-moe.topk_value_norm_compensation", default=False) parser.add_argument("-moe.norm_expert_scores", default=False) parser.add_argument("-moe.sel_input_cluster_init", default=False) parser.add_argument("-moe.init_norm_mode", default="full") parser.add_argument("-moe.bias", default=False) parser.add_argument("-moe.sel_bias", default=False) parser.add_argument("-moe.rescale_normed", default=False) parser.add_argument("-moe.sel_norm", default="none", choice=["none", "cos", "input", "weights"]) parser.add_argument("-moe.rescale_grads", default=False) parser.add_argument("-moe.gumbel_decay", default=0) parser.add_argument("-moe.sinkhorn_local", default=False) parser.add_argument("-moe.sinkhron_n_iters", default=3) parser.add_argument("-moe.dropout_factor", default=1.0) parser.add_argument("-moe.drop_expert", default=0.0) parser.add_argument("-moe.expert_size_init", default=False) parser.add_argument("-moe.sync_distributed", default=True) parser.add_argument("-moe.modulation_amplitude", default=0.5) parser.add_argument("-moe.invisible_selection", default=False) parser.add_argument("-moe.slope_multiplier", default=1.0) parser.add_argument("-moe.init_scale", default=1.0) parser.add_argument("-kvmem.linproj", default=False) parser.add_argument("-kvmem.head_merge_topk", default=False) parser.add_argument("-kvmem.load_balance", default=False) parser.add_argument("-kvmem.dropout", default="none", choice=["none", "early", "late", "weight", "score"]) parser.add_argument("-kvmem.randomize_indices", default=False) parser.add_argument("-kvmem.standard_parallel", default=False) parser.add_argument("-kvmem.query_bias", default=False) parser.add_argument("-kvmem.approx_topk", default=False) parser.add_argument("-kvmem.norm_values", default=False) parser.add_argument("-kvmem.factorize", default=False) parser.add_argument("-kvmem.full_key", default=False) parser.add_argument("-kvmem.key_redundancy_factor", default=1) parser.add_argument("-kvmem.two_stage", default=False) parser.add_argument("-kvmem.head_exclusive", default=False) parser.add_argument("-transformer.topk_value", default=32) parser.add_argument("-transformer.universal.nonshared", default=0) parser.add_argument("-transformer.topk_use_norm", default=True) parser.add_argument("-transformer.activation", default="relu", choice=["relu", "topk", "gelu", "identity", "sigmoid", "softmax"]) parser.add_argument("-transformer.p_drop_layer", default=0.0) parser.add_argument("-transformer.head_projection_size", default="none", parser=parser.int_or_none_parser) parser.add_argument("-transformer.ln_affine", default=True) parser.add_argument("-transformer.ln_after_attention", default=True) parser.add_argument("-transformer.output_mode", default="normal", choice=["normal", "sum", "geometric", "sigmoid"]) @task() class TransformerLMMixin: helper: framework.helpers.TrainingHelper def is_preln(self) -> bool: return "preln" in self.helper.args.transformer.variant def topk_activation(self, x: torch.Tensor) -> torch.Tensor: nx = -x return torch.masked_fill(x, nx <= nx.kthvalue(self.helper.args.transformer.topk_value, keepdim=True)[0], 0) def get_layers(self) -> List[torch.nn.Module]: # pyright: reportOptionalMemberAccess=false if self.helper.args.transformer.activation == "relu": activation = F.relu elif self.helper.args.transformer.activation == "topk": activation = self.topk_activation elif self.helper.args.transformer.activation == "identity": activation = lambda x: x elif self.helper.args.transformer.activation == "sigmoid": activation = torch.sigmoid elif self.helper.args.transformer.activation == "gelu": activation = F.gelu elif self.helper.args.transformer.activation == "softmax": activation = lambda x: F.softmax(x, dim=-1) else: raise ValueError(f"Invalid activation: {self.helper.args.transformer.activation}") base_args = dict( d_model=self.helper.args.state_size, nhead=self.helper.args.transformer.n_heads, dim_feedforward=int(self.helper.args.state_size * self.helper.args.transformer.ff_multiplier), dropout=self.helper.args.dropout, activation=activation ) extra_args = {} if not self.helper.args.transformer.variant.endswith("_gelu") else { "activation": F.gelu, "drop_expand": False } if self.helper.args.transformer.variant in {"preln_relative"}: mklayer = lambda: PrelnRelativeTransformerEncoderLayer( **base_args, **extra_args, test_pos_clamp=self.helper.args.lm.trafo.test_pos_clamp, n_layers=self.helper.args.transformer.encoder_n_layers, head_projection_size=self.helper.args.transformer.head_projection_size,) elif self.helper.args.transformer.variant in {"preln_topk"}: mklayer = lambda: TopkTransformer( **base_args, **extra_args, test_pos_clamp=self.helper.args.lm.trafo.test_pos_clamp, n_layers=self.helper.args.transformer.encoder_n_layers, k=self.helper.args.transformer.topk_value, use_norm=self.helper.args.transformer.topk_use_norm, head_projection_size=self.helper.args.transformer.head_projection_size,) elif self.helper.args.transformer.variant in {"preln_kvmem"}: mklayer = lambda: PrelnRelativeKVMemTransformerEncoderLayer( **base_args, **extra_args, test_pos_clamp=self.helper.args.lm.trafo.test_pos_clamp, n_layers=self.helper.args.transformer.encoder_n_layers, n_keys=self.helper.args.pkm.n_keys, pkm_stochastic=self.helper.args.pkm.stochastic, pkm_heads=self.helper.args.pkm.n_heads, pkm_custom_init=self.helper.args.pkm.custom_init, pkm_slice_values=self.helper.args.pkm.slice_values, pkm_knn=self.helper.args.pkm.knn, linproj=self.helper.args.kvmem.linproj, head_merge_topk=self.helper.args.kvmem.head_merge_topk, load_balance=self.helper.args.kvmem.load_balance, kvmem_dropout=self.helper.args.kvmem.dropout, kvmem_randomize_indices=self.helper.args.kvmem.randomize_indices, kvmem_query_bias=self.helper.args.kvmem.query_bias, standard_parallel=self.helper.args.kvmem.standard_parallel, approx_topk=self.helper.args.kvmem.approx_topk, factorize=self.helper.args.kvmem.factorize, full_key=self.helper.args.kvmem.full_key, key_redundancy_factor=self.helper.args.kvmem.key_redundancy_factor, two_stage=self.helper.args.kvmem.two_stage, head_exclusive=self.helper.args.kvmem.head_exclusive, head_projection_size=self.helper.args.transformer.head_projection_size,) elif self.helper.args.transformer.variant in {"preln_moe", "preln_moe_universal", "moe", "moe_universal"}: # def __init__(self, d_model, nhead, n_bins: int, bin_size: int, n_layers: int, dim_feedforward=2048,
mklayer = lambda: RelativeMoeTransformerEncoderLayer(
6
2023-10-16 11:26:45+00:00
24k
boppreh/hello_tls
src/hello_tls/scan.py
[ { "identifier": "ClientHello", "path": "src/hello_tls/protocol.py", "snippet": "class ScanError(Exception):\nclass ServerAlertError(ScanError):\nclass BadServerResponse(ScanError):\nclass ServerHello:\nclass ClientHello:\n def __init__(self, level: AlertLevel, description: AlertDescription):\ndef _make_stream_parser(packets: Iterable[bytes]) -> Tuple[Callable[[int], bytes], Callable[[], int]]:\n def read_next(length: int) -> bytes:\ndef _bytes_to_int(b: bytes) -> int:\ndef parse_server_hello(packets: Iterable[bytes]) -> ServerHello:\ndef make_client_hello(client_hello: ClientHello) -> bytes:\n def prefix_length(block_name: str, width_bytes: int = 2) -> Iterator[None]:" }, { "identifier": "AlertDescription", "path": "src/hello_tls/names_and_numbers.py", "snippet": "class AlertDescription(Enum):\n \"\"\" Different alert messages that can be sent by the server. \"\"\"\n close_notify = b'\\x00'\n unexpected_message = b'\\x0a'\n bad_record_mac = b'\\x14'\n record_overflow = b'\\x16'\n handshake_failure = b'\\x28'\n bad_certificate = b'\\x2a'\n unsupported_certificate = b'\\x2b'\n certificate_revoked = b'\\x2c'\n certificate_expired = b'\\x2d'\n certificate_unknown = b'\\x2e'\n illegal_parameter = b'\\x2f'\n unknown_ca = b'\\x30'\n access_denied = b'\\x31'\n decode_error = b'\\x32'\n decrypt_error = b'\\x33'\n protocol_version = b'\\x46'\n insufficient_security = b'\\x47'\n internal_error = b'\\x50'\n inappropriate_fallback = b'\\x56'\n user_canceled = b'\\x5a'\n missing_extension = b'\\x6d'\n unsupported_extension = b'\\x6e'\n unrecognized_name = b'\\x70'\n bad_certificate_status_response = b'\\x71'\n unknown_psk_identity = b'\\x73'\n certificate_required = b'\\x74'\n no_application_protocol = b'\\x78'" }, { "identifier": "CipherSuite", "path": "src/hello_tls/names_and_numbers.py", "snippet": "class CipherSuite(Enum):\n def __repr__(self):\n return self.name\n def __new__(cls, value, *rest, **kwds):\n obj = object.__new__(cls)\n obj._value_ = value\n return obj\n # Annotate each cipher suite with the protocols it's supported at.\n # Default to all but TLS 1.3, because that's the most common.\n def __init__(self, _: bytes, protocols: Sequence[Protocol] = (Protocol.SSLv3, Protocol.TLS1_0, Protocol.TLS1_1, Protocol.TLS1_2)):\n self.protocols = protocols\n\n # Pseudo cipher suite, not actually picked.\n #TLS_EMPTY_RENEGOTIATION_INFO_SCSV = b\"\\x00\\xff\"\n\n # TLS 1.3 cipher suites.\n TLS_AES_128_GCM_SHA256 = b\"\\x13\\x01\", (Protocol.TLS1_3,)\n TLS_AES_256_GCM_SHA384 = b\"\\x13\\x02\", (Protocol.TLS1_3,)\n TLS_CHACHA20_POLY1305_SHA256 = b\"\\x13\\x03\", (Protocol.TLS1_3,)\n TLS_AES_128_CCM_SHA256 = b\"\\x13\\x04\", (Protocol.TLS1_3,)\n TLS_AES_128_CCM_8_SHA256 = b\"\\x13\\x05\", (Protocol.TLS1_3,)\n\n # Cipher suite that had its number reassigned.\n OLD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = b'\\xcc\\x13'\n \n # Cipher suites adapted from IANA assignments:\n # https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4\n TLS_AEGIS_128L_SHA256 = b'\\x13\\x07' # [draft-irtf-cfrg-aegis-aead-00]\n TLS_AEGIS_256_SHA384 = b'\\x13\\x06' # [draft-irtf-cfrg-aegis-aead-00]\n TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = b'\\x00\\x19' # [RFC4346]\n TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = b'\\x00\\x17' # [RFC4346][RFC6347]\n TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x1B' # [RFC5246]\n TLS_DH_anon_WITH_AES_128_CBC_SHA = b'\\x00\\x34' # [RFC5246]\n TLS_DH_anon_WITH_AES_128_CBC_SHA256 = b'\\x00\\x6C' # [RFC5246]\n TLS_DH_anon_WITH_AES_128_GCM_SHA256 = b'\\x00\\xA6' # [RFC5288]\n TLS_DH_anon_WITH_AES_256_CBC_SHA = b'\\x00\\x3A' # [RFC5246]\n TLS_DH_anon_WITH_AES_256_CBC_SHA256 = b'\\x00\\x6D' # [RFC5246]\n TLS_DH_anon_WITH_AES_256_GCM_SHA384 = b'\\x00\\xA7' # [RFC5288]\n TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x46' # [RFC6209]\n TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x5A' # [RFC6209]\n TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x47' # [RFC6209]\n TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x5B' # [RFC6209]\n TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA = b'\\x00\\x46' # [RFC5932]\n TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 = b'\\x00\\xBF' # [RFC5932]\n TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x84' # [RFC6367]\n TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA = b'\\x00\\x89' # [RFC5932]\n TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 = b'\\x00\\xC5' # [RFC5932]\n TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x85' # [RFC6367]\n TLS_DH_anon_WITH_DES_CBC_SHA = b'\\x00\\x1A' # [RFC8996]\n TLS_DH_anon_WITH_RC4_128_MD5 = b'\\x00\\x18' # [RFC5246][RFC6347]\n TLS_DH_anon_WITH_SEED_CBC_SHA = b'\\x00\\x9B' # [RFC4162]\n TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = b'\\x00\\x0B' # [RFC4346]\n TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x0D' # [RFC5246]\n TLS_DH_DSS_WITH_AES_128_CBC_SHA = b'\\x00\\x30' # [RFC5246]\n TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = b'\\x00\\x3E' # [RFC5246]\n TLS_DH_DSS_WITH_AES_128_GCM_SHA256 = b'\\x00\\xA4' # [RFC5288]\n TLS_DH_DSS_WITH_AES_256_CBC_SHA = b'\\x00\\x36' # [RFC5246]\n TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = b'\\x00\\x68' # [RFC5246]\n TLS_DH_DSS_WITH_AES_256_GCM_SHA384 = b'\\x00\\xA5' # [RFC5288]\n TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x3E' # [RFC6209]\n TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x58' # [RFC6209]\n TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x3F' # [RFC6209]\n TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x59' # [RFC6209]\n TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA = b'\\x00\\x42' # [RFC5932]\n TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 = b'\\x00\\xBB' # [RFC5932]\n TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x82' # [RFC6367]\n TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA = b'\\x00\\x85' # [RFC5932]\n TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 = b'\\x00\\xC1' # [RFC5932]\n TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x83' # [RFC6367]\n TLS_DH_DSS_WITH_DES_CBC_SHA = b'\\x00\\x0C' # [RFC8996]\n TLS_DH_DSS_WITH_SEED_CBC_SHA = b'\\x00\\x97' # [RFC4162]\n TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = b'\\x00\\x0E' # [RFC4346]\n TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x10' # [RFC5246]\n TLS_DH_RSA_WITH_AES_128_CBC_SHA = b'\\x00\\x31' # [RFC5246]\n TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = b'\\x00\\x3F' # [RFC5246]\n TLS_DH_RSA_WITH_AES_128_GCM_SHA256 = b'\\x00\\xA0' # [RFC5288]\n TLS_DH_RSA_WITH_AES_256_CBC_SHA = b'\\x00\\x37' # [RFC5246]\n TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = b'\\x00\\x69' # [RFC5246]\n TLS_DH_RSA_WITH_AES_256_GCM_SHA384 = b'\\x00\\xA1' # [RFC5288]\n TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x40' # [RFC6209]\n TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x54' # [RFC6209]\n TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x41' # [RFC6209]\n TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x55' # [RFC6209]\n TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA = b'\\x00\\x43' # [RFC5932]\n TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = b'\\x00\\xBC' # [RFC5932]\n TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x7E' # [RFC6367]\n TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA = b'\\x00\\x86' # [RFC5932]\n TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 = b'\\x00\\xC2' # [RFC5932]\n TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x7F' # [RFC6367]\n TLS_DH_RSA_WITH_DES_CBC_SHA = b'\\x00\\x0F' # [RFC8996]\n TLS_DH_RSA_WITH_SEED_CBC_SHA = b'\\x00\\x98' # [RFC4162]\n TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = b'\\x00\\x11' # [RFC4346]\n TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x13' # [RFC5246]\n TLS_DHE_DSS_WITH_AES_128_CBC_SHA = b'\\x00\\x32' # [RFC5246]\n TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = b'\\x00\\x40' # [RFC5246]\n TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = b'\\x00\\xA2' # [RFC5288]\n TLS_DHE_DSS_WITH_AES_256_CBC_SHA = b'\\x00\\x38' # [RFC5246]\n TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = b'\\x00\\x6A' # [RFC5246]\n TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = b'\\x00\\xA3' # [RFC5288]\n TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x42' # [RFC6209]\n TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x56' # [RFC6209]\n TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x43' # [RFC6209]\n TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x57' # [RFC6209]\n TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA = b'\\x00\\x44' # [RFC5932]\n TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 = b'\\x00\\xBD' # [RFC5932]\n TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x80' # [RFC6367]\n TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA = b'\\x00\\x87' # [RFC5932]\n TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 = b'\\x00\\xC3' # [RFC5932]\n TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x81' # [RFC6367]\n TLS_DHE_DSS_WITH_DES_CBC_SHA = b'\\x00\\x12' # [RFC8996]\n TLS_DHE_DSS_WITH_SEED_CBC_SHA = b'\\x00\\x99' # [RFC4162]\n TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x8F' # [RFC4279]\n TLS_DHE_PSK_WITH_AES_128_CBC_SHA = b'\\x00\\x90' # [RFC4279]\n TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = b'\\x00\\xB2' # [RFC5487]\n TLS_DHE_PSK_WITH_AES_128_CCM = b'\\xC0\\xA6' # [RFC6655]\n TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 = b'\\x00\\xAA' # [RFC5487]\n TLS_DHE_PSK_WITH_AES_256_CBC_SHA = b'\\x00\\x91' # [RFC4279]\n TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = b'\\x00\\xB3' # [RFC5487]\n TLS_DHE_PSK_WITH_AES_256_CCM = b'\\xC0\\xA7' # [RFC6655]\n TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 = b'\\x00\\xAB' # [RFC5487]\n TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x66' # [RFC6209]\n TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x6C' # [RFC6209]\n TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x67' # [RFC6209]\n TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x6D' # [RFC6209]\n TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x96' # [RFC6367]\n TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x90' # [RFC6367]\n TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x97' # [RFC6367]\n TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x91' # [RFC6367]\n TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = b'\\xCC\\xAD' # [RFC7905]\n TLS_DHE_PSK_WITH_NULL_SHA = b'\\x00\\x2D' # [RFC4785]\n TLS_DHE_PSK_WITH_NULL_SHA256 = b'\\x00\\xB4' # [RFC5487]\n TLS_DHE_PSK_WITH_NULL_SHA384 = b'\\x00\\xB5' # [RFC5487]\n TLS_DHE_PSK_WITH_RC4_128_SHA = b'\\x00\\x8E' # [RFC4279][RFC6347]\n TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = b'\\x00\\x14' # [RFC4346]\n TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x16' # [RFC5246]\n TLS_DHE_RSA_WITH_AES_128_CBC_SHA = b'\\x00\\x33' # [RFC5246]\n TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = b'\\x00\\x67' # [RFC5246]\n TLS_DHE_RSA_WITH_AES_128_CCM = b'\\xC0\\x9E' # [RFC6655]\n TLS_DHE_RSA_WITH_AES_128_CCM_8 = b'\\xC0\\xA2' # [RFC6655]\n TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = b'\\x00\\x9E' # [RFC5288]\n TLS_DHE_RSA_WITH_AES_256_CBC_SHA = b'\\x00\\x39' # [RFC5246]\n TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = b'\\x00\\x6B' # [RFC5246]\n TLS_DHE_RSA_WITH_AES_256_CCM = b'\\xC0\\x9F' # [RFC6655]\n TLS_DHE_RSA_WITH_AES_256_CCM_8 = b'\\xC0\\xA3' # [RFC6655]\n TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = b'\\x00\\x9F' # [RFC5288]\n TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x44' # [RFC6209]\n TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x52' # [RFC6209]\n TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x45' # [RFC6209]\n TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x53' # [RFC6209]\n TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA = b'\\x00\\x45' # [RFC5932]\n TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = b'\\x00\\xBE' # [RFC5932]\n TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x7C' # [RFC6367]\n TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA = b'\\x00\\x88' # [RFC5932]\n TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = b'\\x00\\xC4' # [RFC5932]\n TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x7D' # [RFC6367]\n TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = b'\\xCC\\xAA' # [RFC7905]\n TLS_DHE_RSA_WITH_DES_CBC_SHA = b'\\x00\\x15' # [RFC8996]\n TLS_DHE_RSA_WITH_SEED_CBC_SHA = b'\\x00\\x9A' # [RFC4162]\n TLS_ECCPWD_WITH_AES_128_CCM_SHA256 = b'\\xC0\\xB2' # [RFC8492]\n TLS_ECCPWD_WITH_AES_128_GCM_SHA256 = b'\\xC0\\xB0' # [RFC8492]\n TLS_ECCPWD_WITH_AES_256_CCM_SHA384 = b'\\xC0\\xB3' # [RFC8492]\n TLS_ECCPWD_WITH_AES_256_GCM_SHA384 = b'\\xC0\\xB1' # [RFC8492]\n TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x17' # [RFC8422]\n TLS_ECDH_anon_WITH_AES_128_CBC_SHA = b'\\xC0\\x18' # [RFC8422]\n TLS_ECDH_anon_WITH_AES_256_CBC_SHA = b'\\xC0\\x19' # [RFC8422]\n TLS_ECDH_anon_WITH_NULL_SHA = b'\\xC0\\x15' # [RFC8422]\n TLS_ECDH_anon_WITH_RC4_128_SHA = b'\\xC0\\x16' # [RFC8422][RFC6347]\n TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x03' # [RFC8422]\n TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = b'\\xC0\\x04' # [RFC8422]\n TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = b'\\xC0\\x25' # [RFC5289]\n TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = b'\\xC0\\x2D' # [RFC5289]\n TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = b'\\xC0\\x05' # [RFC8422]\n TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = b'\\xC0\\x26' # [RFC5289]\n TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = b'\\xC0\\x2E' # [RFC5289]\n TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x4A' # [RFC6209]\n TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x5E' # [RFC6209]\n TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x4B' # [RFC6209]\n TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x5F' # [RFC6209]\n TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x74' # [RFC6367]\n TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x88' # [RFC6367]\n TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x75' # [RFC6367]\n TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x89' # [RFC6367]\n TLS_ECDH_ECDSA_WITH_NULL_SHA = b'\\xC0\\x01' # [RFC8422]\n TLS_ECDH_ECDSA_WITH_RC4_128_SHA = b'\\xC0\\x02' # [RFC8422][RFC6347]\n TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x0D' # [RFC8422]\n TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = b'\\xC0\\x0E' # [RFC8422]\n TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = b'\\xC0\\x29' # [RFC5289]\n TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = b'\\xC0\\x31' # [RFC5289]\n TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = b'\\xC0\\x0F' # [RFC8422]\n TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = b'\\xC0\\x2A' # [RFC5289]\n TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = b'\\xC0\\x32' # [RFC5289]\n TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x4E' # [RFC6209]\n TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x62' # [RFC6209]\n TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x4F' # [RFC6209]\n TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x63' # [RFC6209]\n TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x78' # [RFC6367]\n TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x8C' # [RFC6367]\n TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x79' # [RFC6367]\n TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x8D' # [RFC6367]\n TLS_ECDH_RSA_WITH_NULL_SHA = b'\\xC0\\x0B' # [RFC8422]\n TLS_ECDH_RSA_WITH_RC4_128_SHA = b'\\xC0\\x0C' # [RFC8422][RFC6347]\n TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x08' # [RFC8422]\n TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = b'\\xC0\\x09' # [RFC8422]\n TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = b'\\xC0\\x23' # [RFC5289]\n TLS_ECDHE_ECDSA_WITH_AES_128_CCM = b'\\xC0\\xAC' # [RFC7251]\n TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = b'\\xC0\\xAE' # [RFC7251]\n TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = b'\\xC0\\x2B' # [RFC5289]\n TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = b'\\xC0\\x0A' # [RFC8422]\n TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = b'\\xC0\\x24' # [RFC5289]\n TLS_ECDHE_ECDSA_WITH_AES_256_CCM = b'\\xC0\\xAD' # [RFC7251]\n TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = b'\\xC0\\xAF' # [RFC7251]\n TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = b'\\xC0\\x2C' # [RFC5289]\n TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x48' # [RFC6209]\n TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x5C' # [RFC6209]\n TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x49' # [RFC6209]\n TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x5D' # [RFC6209]\n TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x72' # [RFC6367]\n TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x86' # [RFC6367]\n TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x73' # [RFC6367]\n TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x87' # [RFC6367]\n TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = b'\\xCC\\xA9' # [RFC7905]\n TLS_ECDHE_ECDSA_WITH_NULL_SHA = b'\\xC0\\x06' # [RFC8422]\n TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = b'\\xC0\\x07' # [RFC8422][RFC6347]\n TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x34' # [RFC5489]\n TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA = b'\\xC0\\x35' # [RFC5489]\n TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 = b'\\xC0\\x37' # [RFC5489]\n TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256 = b'\\xD0\\x03' # [RFC8442]\n TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 = b'\\xD0\\x05' # [RFC8442]\n TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 = b'\\xD0\\x01' # [RFC8442]\n TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA = b'\\xC0\\x36' # [RFC5489]\n TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 = b'\\xC0\\x38' # [RFC5489]\n TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384 = b'\\xD0\\x02' # [RFC8442]\n TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x70' # [RFC6209]\n TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x71' # [RFC6209]\n TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x9A' # [RFC6367]\n TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x9B' # [RFC6367]\n TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = b'\\xCC\\xAC' # [RFC7905]\n TLS_ECDHE_PSK_WITH_NULL_SHA = b'\\xC0\\x39' # [RFC5489]\n TLS_ECDHE_PSK_WITH_NULL_SHA256 = b'\\xC0\\x3A' # [RFC5489]\n TLS_ECDHE_PSK_WITH_NULL_SHA384 = b'\\xC0\\x3B' # [RFC5489]\n TLS_ECDHE_PSK_WITH_RC4_128_SHA = b'\\xC0\\x33' # [RFC5489][RFC6347]\n TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x12' # [RFC8422]\n TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = b'\\xC0\\x13' # [RFC8422]\n TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = b'\\xC0\\x27' # [RFC5289]\n TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = b'\\xC0\\x2F' # [RFC5289]\n TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = b'\\xC0\\x14' # [RFC8422]\n TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = b'\\xC0\\x28' # [RFC5289]\n TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = b'\\xC0\\x30' # [RFC5289]\n TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x4C' # [RFC6209]\n TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x60' # [RFC6209]\n TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x4D' # [RFC6209]\n TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x61' # [RFC6209]\n TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x76' # [RFC6367]\n TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x8A' # [RFC6367]\n TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x77' # [RFC6367]\n TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x8B' # [RFC6367]\n TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = b'\\xCC\\xA8' # [RFC7905]\n TLS_ECDHE_RSA_WITH_NULL_SHA = b'\\xC0\\x10' # [RFC8422]\n TLS_ECDHE_RSA_WITH_RC4_128_SHA = b'\\xC0\\x11' # [RFC8422][RFC6347]\n TLS_GOSTR341112_256_WITH_28147_CNT_IMIT = b'\\xC1\\x02' # [RFC9189]\n TLS_GOSTR341112_256_WITH_KUZNYECHIK_CTR_OMAC = b'\\xC1\\x00' # [RFC9189]\n TLS_GOSTR341112_256_WITH_KUZNYECHIK_MGM_L = b'\\xC1\\x03' # [RFC9367]\n TLS_GOSTR341112_256_WITH_KUZNYECHIK_MGM_S = b'\\xC1\\x05' # [RFC9367]\n TLS_GOSTR341112_256_WITH_MAGMA_CTR_OMAC = b'\\xC1\\x01' # [RFC9189]\n TLS_GOSTR341112_256_WITH_MAGMA_MGM_L = b'\\xC1\\x04' # [RFC9367]\n TLS_GOSTR341112_256_WITH_MAGMA_MGM_S = b'\\xC1\\x06' # [RFC9367]\n TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 = b'\\x00\\x29' # [RFC2712]\n TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA = b'\\x00\\x26' # [RFC2712]\n TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 = b'\\x00\\x2A' # [RFC2712]\n TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA = b'\\x00\\x27' # [RFC2712]\n TLS_KRB5_EXPORT_WITH_RC4_40_MD5 = b'\\x00\\x2B' # [RFC2712][RFC6347]\n TLS_KRB5_EXPORT_WITH_RC4_40_SHA = b'\\x00\\x28' # [RFC2712][RFC6347]\n TLS_KRB5_WITH_3DES_EDE_CBC_MD5 = b'\\x00\\x23' # [RFC2712]\n TLS_KRB5_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x1F' # [RFC2712]\n TLS_KRB5_WITH_DES_CBC_MD5 = b'\\x00\\x22' # [RFC2712]\n TLS_KRB5_WITH_DES_CBC_SHA = b'\\x00\\x1E' # [RFC2712]\n TLS_KRB5_WITH_IDEA_CBC_MD5 = b'\\x00\\x25' # [RFC2712]\n TLS_KRB5_WITH_IDEA_CBC_SHA = b'\\x00\\x21' # [RFC2712]\n TLS_KRB5_WITH_RC4_128_MD5 = b'\\x00\\x24' # [RFC2712][RFC6347]\n TLS_KRB5_WITH_RC4_128_SHA = b'\\x00\\x20' # [RFC2712][RFC6347]\n TLS_NULL_WITH_NULL_NULL = b'\\x00\\x00' # [RFC5246]\n TLS_PSK_DHE_WITH_AES_128_CCM_8 = b'\\xC0\\xAA' # [RFC6655]\n TLS_PSK_DHE_WITH_AES_256_CCM_8 = b'\\xC0\\xAB' # [RFC6655]\n TLS_PSK_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x8B' # [RFC4279]\n TLS_PSK_WITH_AES_128_CBC_SHA = b'\\x00\\x8C' # [RFC4279]\n TLS_PSK_WITH_AES_128_CBC_SHA256 = b'\\x00\\xAE' # [RFC5487]\n TLS_PSK_WITH_AES_128_CCM = b'\\xC0\\xA4' # [RFC6655]\n TLS_PSK_WITH_AES_128_CCM_8 = b'\\xC0\\xA8' # [RFC6655]\n TLS_PSK_WITH_AES_128_GCM_SHA256 = b'\\x00\\xA8' # [RFC5487]\n TLS_PSK_WITH_AES_256_CBC_SHA = b'\\x00\\x8D' # [RFC4279]\n TLS_PSK_WITH_AES_256_CBC_SHA384 = b'\\x00\\xAF' # [RFC5487]\n TLS_PSK_WITH_AES_256_CCM = b'\\xC0\\xA5' # [RFC6655]\n TLS_PSK_WITH_AES_256_CCM_8 = b'\\xC0\\xA9' # [RFC6655]\n TLS_PSK_WITH_AES_256_GCM_SHA384 = b'\\x00\\xA9' # [RFC5487]\n TLS_PSK_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x64' # [RFC6209]\n TLS_PSK_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x6A' # [RFC6209]\n TLS_PSK_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x65' # [RFC6209]\n TLS_PSK_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x6B' # [RFC6209]\n TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x94' # [RFC6367]\n TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x8E' # [RFC6367]\n TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x95' # [RFC6367]\n TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x8F' # [RFC6367]\n TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 = b'\\xCC\\xAB' # [RFC7905]\n TLS_PSK_WITH_NULL_SHA = b'\\x00\\x2C' # [RFC4785]\n TLS_PSK_WITH_NULL_SHA256 = b'\\x00\\xB0' # [RFC5487]\n TLS_PSK_WITH_NULL_SHA384 = b'\\x00\\xB1' # [RFC5487]\n TLS_PSK_WITH_RC4_128_SHA = b'\\x00\\x8A' # [RFC4279][RFC6347]\n TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = b'\\x00\\x08' # [RFC4346]\n TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = b'\\x00\\x06' # [RFC4346]\n TLS_RSA_EXPORT_WITH_RC4_40_MD5 = b'\\x00\\x03' # [RFC4346][RFC6347]\n TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x93' # [RFC4279]\n TLS_RSA_PSK_WITH_AES_128_CBC_SHA = b'\\x00\\x94' # [RFC4279]\n TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 = b'\\x00\\xB6' # [RFC5487]\n TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 = b'\\x00\\xAC' # [RFC5487]\n TLS_RSA_PSK_WITH_AES_256_CBC_SHA = b'\\x00\\x95' # [RFC4279]\n TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 = b'\\x00\\xB7' # [RFC5487]\n TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 = b'\\x00\\xAD' # [RFC5487]\n TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x68' # [RFC6209]\n TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x6E' # [RFC6209]\n TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x69' # [RFC6209]\n TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x6F' # [RFC6209]\n TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 = b'\\xC0\\x98' # [RFC6367]\n TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x92' # [RFC6367]\n TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 = b'\\xC0\\x99' # [RFC6367]\n TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x93' # [RFC6367]\n TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 = b'\\xCC\\xAE' # [RFC7905]\n TLS_RSA_PSK_WITH_NULL_SHA = b'\\x00\\x2E' # [RFC4785]\n TLS_RSA_PSK_WITH_NULL_SHA256 = b'\\x00\\xB8' # [RFC5487]\n TLS_RSA_PSK_WITH_NULL_SHA384 = b'\\x00\\xB9' # [RFC5487]\n TLS_RSA_PSK_WITH_RC4_128_SHA = b'\\x00\\x92' # [RFC4279][RFC6347]\n TLS_RSA_WITH_3DES_EDE_CBC_SHA = b'\\x00\\x0A' # [RFC5246]\n TLS_RSA_WITH_AES_128_CBC_SHA = b'\\x00\\x2F' # [RFC5246]\n TLS_RSA_WITH_AES_128_CBC_SHA256 = b'\\x00\\x3C' # [RFC5246]\n TLS_RSA_WITH_AES_128_CCM = b'\\xC0\\x9C' # [RFC6655]\n TLS_RSA_WITH_AES_128_CCM_8 = b'\\xC0\\xA0' # [RFC6655]\n TLS_RSA_WITH_AES_128_GCM_SHA256 = b'\\x00\\x9C' # [RFC5288]\n TLS_RSA_WITH_AES_256_CBC_SHA = b'\\x00\\x35' # [RFC5246]\n TLS_RSA_WITH_AES_256_CBC_SHA256 = b'\\x00\\x3D' # [RFC5246]\n TLS_RSA_WITH_AES_256_CCM = b'\\xC0\\x9D' # [RFC6655]\n TLS_RSA_WITH_AES_256_CCM_8 = b'\\xC0\\xA1' # [RFC6655]\n TLS_RSA_WITH_AES_256_GCM_SHA384 = b'\\x00\\x9D' # [RFC5288]\n TLS_RSA_WITH_ARIA_128_CBC_SHA256 = b'\\xC0\\x3C' # [RFC6209]\n TLS_RSA_WITH_ARIA_128_GCM_SHA256 = b'\\xC0\\x50' # [RFC6209]\n TLS_RSA_WITH_ARIA_256_CBC_SHA384 = b'\\xC0\\x3D' # [RFC6209]\n TLS_RSA_WITH_ARIA_256_GCM_SHA384 = b'\\xC0\\x51' # [RFC6209]\n TLS_RSA_WITH_CAMELLIA_128_CBC_SHA = b'\\x00\\x41' # [RFC5932]\n TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 = b'\\x00\\xBA' # [RFC5932]\n TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 = b'\\xC0\\x7A' # [RFC6367]\n TLS_RSA_WITH_CAMELLIA_256_CBC_SHA = b'\\x00\\x84' # [RFC5932]\n TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 = b'\\x00\\xC0' # [RFC5932]\n TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 = b'\\xC0\\x7B' # [RFC6367]\n TLS_RSA_WITH_DES_CBC_SHA = b'\\x00\\x09' # [RFC8996]\n TLS_RSA_WITH_IDEA_CBC_SHA = b'\\x00\\x07' # [RFC8996]\n TLS_RSA_WITH_NULL_MD5 = b'\\x00\\x01' # [RFC5246]\n TLS_RSA_WITH_NULL_SHA = b'\\x00\\x02' # [RFC5246]\n TLS_RSA_WITH_NULL_SHA256 = b'\\x00\\x3B' # [RFC5246]\n TLS_RSA_WITH_RC4_128_MD5 = b'\\x00\\x04' # [RFC5246][RFC6347]\n TLS_RSA_WITH_RC4_128_SHA = b'\\x00\\x05' # [RFC5246][RFC6347]\n TLS_RSA_WITH_SEED_CBC_SHA = b'\\x00\\x96' # [RFC4162]\n TLS_SHA256_SHA256 = b'\\xC0\\xB4' # [RFC9150]\n TLS_SHA384_SHA384 = b'\\xC0\\xB5' # [RFC9150]\n TLS_SM4_CCM_SM3 = b'\\x00\\xC7' # [RFC8998]\n TLS_SM4_GCM_SM3 = b'\\x00\\xC6' # [RFC8998]\n TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x1C' # [RFC5054]\n TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA = b'\\xC0\\x1F' # [RFC5054]\n TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA = b'\\xC0\\x22' # [RFC5054]\n TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x1B' # [RFC5054]\n TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = b'\\xC0\\x1E' # [RFC5054]\n TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = b'\\xC0\\x21' # [RFC5054]\n TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = b'\\xC0\\x1A' # [RFC5054]\n TLS_SRP_SHA_WITH_AES_128_CBC_SHA = b'\\xC0\\x1D' # [RFC5054]\n TLS_SRP_SHA_WITH_AES_256_CBC_SHA = b'\\xC0\\x20' # [RFC5054]" }, { "identifier": "Group", "path": "src/hello_tls/names_and_numbers.py", "snippet": "class Group(Enum):\n def __new__(cls, value, *rest, **kwds):\n obj = object.__new__(cls)\n obj._value_ = value\n return obj\n # Annotate each group with whether it's a PQ group.\n def __init__(self, _: bytes, is_pq: bool = False):\n self.is_pq = is_pq\n def __repr__(self):\n return self.name\n \n sect163k1 = b'\\x00\\x01'\n sect163r1 = b'\\x00\\x02'\n sect163r2 = b'\\x00\\x03'\n sect193r1 = b'\\x00\\x04'\n sect193r2 = b'\\x00\\x05'\n sect233k1 = b'\\x00\\x06'\n sect233r1 = b'\\x00\\x07'\n sect239k1 = b'\\x00\\x08'\n sect283k1 = b'\\x00\\x09'\n sect283r1 = b'\\x00\\x0a'\n sect409k1 = b'\\x00\\x0b'\n sect409r1 = b'\\x00\\x0c'\n sect571k1 = b'\\x00\\x0d'\n sect571r1 = b'\\x00\\x0e'\n secp160k1 = b'\\x00\\x0f'\n secp160r1 = b'\\x00\\x10'\n secp160r2 = b'\\x00\\x11'\n secp192k1 = b'\\x00\\x12'\n secp192r1 = b'\\x00\\x13'\n secp224k1 = b'\\x00\\x14'\n secp224r1 = b'\\x00\\x15'\n secp256k1 = b'\\x00\\x16'\n secp256r1 = b'\\x00\\x17'\n secp384r1 = b'\\x00\\x18'\n secp521r1 = b'\\x00\\x19'\n brainpoolP256r1 = b'\\x00\\x1a'\n brainpoolP384r1 = b'\\x00\\x1b'\n brainpoolP512r1 = b'\\x00\\x1c'\n x25519 = b'\\x00\\x1d'\n x448 = b'\\x00\\x1e'\n brainpoolP256r1tls13 = b'\\x00\\x1f'\n brainpoolP384r1tls13 = b'\\x00\\x20'\n brainpoolP512r1tls13 = b'\\x00\\x21'\n GC256A = b'\\x00\\x22'\n GC256B = b'\\x00\\x23'\n GC256C = b'\\x00\\x24'\n GC256D = b'\\x00\\x25'\n GC512A = b'\\x00\\x26'\n GC512B = b'\\x00\\x27'\n GC512C = b'\\x00\\x28'\n curveSM2 = b'\\x00\\x29'\n ffdhe2048 = b'\\x01\\x00'\n ffdhe3072 = b'\\x01\\x01'\n ffdhe4096 = b'\\x01\\x02'\n ffdhe6144 = b'\\x01\\x03'\n ffdhe8192 = b'\\x01\\x04'\n arbitrary_explicit_prime_curves = b'\\xff\\x01'\n arbitrary_explicit_char2_curves = b'\\xff\\x02'\n\n # Somewhat common post-quantum groups, not yet standardized:\n X25519Kyber768Draft00 = b'\\x63\\x99', True\n X25519Kyber768Draft00_obsolete = b'\\xfe\\x31', True\n X25519Kyber512Draft00 = b'\\xfe\\x30', True\n SecP256r1Kyber768Draft00 = b'\\x63\\x9a', True\n\n # Long list of unusual post-quantum groups from liboqs:\n # https://github.com/open-quantum-safe/oqs-provider/blob/main/ALGORITHMS.md?plain=1#L13\n frodo640aes = b'\\x02\\x00', True\n p256_frodo640aes = b'\\x2F\\x00', True\n x25519_frodo640aes = b'\\x2F\\x80', True\n frodo640shake = b'\\x02\\x01', True\n p256_frodo640shake = b'\\x2F\\x01', True\n x25519_frodo640shake = b'\\x2F\\x81', True\n frodo976aes = b'\\x02\\x02', True\n p384_frodo976aes = b'\\x2F\\x02', True\n x448_frodo976aes = b'\\x2F\\x82', True\n frodo976shake = b'\\x02\\x03', True\n p384_frodo976shake = b'\\x2F\\x03', True\n x448_frodo976shake = b'\\x2F\\x83', True\n frodo1344aes = b'\\x02\\x04', True\n p521_frodo1344aes = b'\\x2F\\x04', True\n frodo1344shake = b'\\x02\\x05', True\n p521_frodo1344shake = b'\\x2F\\x05', True\n kyber512 = b'\\x02\\x3A', True\n p256_kyber512 = b'\\x2F\\x3A', True\n x25519_kyber512 = b'\\x2F\\x39', True\n kyber768 = b'\\x02\\x3C', True\n p384_kyber768 = b'\\x2F\\x3C', True\n x448_kyber768 = b'\\x2F\\x90', True\n kyber1024 = b'\\x02\\x3D', True\n p521_kyber1024 = b'\\x2F\\x3D', True\n bikel1 = b'\\x02\\x41', True\n p256_bikel1 = b'\\x2F\\x41', True\n x25519_bikel1 = b'\\x2F\\xAE', True\n bikel3 = b'\\x02\\x42', True\n p384_bikel3 = b'\\x2F\\x42', True\n x448_bikel3 = b'\\x2F\\xAF', True\n bikel5 = b'\\x02\\x43', True\n p521_bikel5 = b'\\x2F\\x43', True\n hqc128 = b'\\x02\\x2C', True\n p256_hqc128 = b'\\x2F\\x2C', True\n x25519_hqc128 = b'\\x2F\\xAC', True\n hqc192 = b'\\x02\\x2D', True\n p384_hqc192 = b'\\x2F\\x2D', True\n x448_hqc192 = b'\\x2F\\xAD', True\n hqc256 = b'\\x02\\x2E', True\n p521_hqc256 = b'\\x2F\\x2E', True\n dilithium2 = b'\\xfe\\xa0', True\n p256_dilithium2 = b'\\xfe\\xa1', True\n rsa3072_dilithium2 = b'\\xfe\\xa2', True\n dilithium3 = b'\\xfe\\xa3', True\n p384_dilithium3 = b'\\xfe\\xa4', True\n dilithium5 = b'\\xfe\\xa5', True\n p521_dilithium5 = b'\\xfe\\xa6', True\n falcon512 = b'\\xfe\\xae', True\n p256_falcon512 = b'\\xfe\\xaf', True\n rsa3072_falcon512 = b'\\xfe\\xb0', True\n falcon1024 = b'\\xfe\\xb1', True\n p521_falcon1024 = b'\\xfe\\xb2', True\n sphincssha2128fsimple = b'\\xfe\\xb3', True\n p256_sphincssha2128fsimple = b'\\xfe\\xb4', True\n rsa3072_sphincssha2128fsimple = b'\\xfe\\xb5', True\n sphincssha2128ssimple = b'\\xfe\\xb6', True\n p256_sphincssha2128ssimple = b'\\xfe\\xb7', True\n rsa3072_sphincssha2128ssimple = b'\\xfe\\xb8', True\n sphincssha2192fsimple = b'\\xfe\\xb9', True\n p384_sphincssha2192fsimple = b'\\xfe\\xba', True\n sphincssha2192ssimple = b'\\xfe\\xbb', True\n p384_sphincssha2192ssimple = b'\\xfe\\xbc', True\n sphincssha2256fsimple = b'\\xfe\\xbd', True\n p521_sphincssha2256fsimple = b'\\xfe\\xbe', True\n sphincssha2256ssimple = b'\\xfe\\xc0', True\n p521_sphincssha2256ssimple = b'\\xfe\\xc1', True\n sphincsshake128fsimple = b'\\xfe\\xc2', True\n p256_sphincsshake128fsimple = b'\\xfe\\xc3', True\n rsa3072_sphincsshake128fsimple = b'\\xfe\\xc4', True\n sphincsshake128ssimple = b'\\xfe\\xc5', True\n p256_sphincsshake128ssimple = b'\\xfe\\xc6', True\n rsa3072_sphincsshake128ssimple = b'\\xfe\\xc7', True\n sphincsshake192fsimple = b'\\xfe\\xc8', True\n p384_sphincsshake192fsimple = b'\\xfe\\xc9', True\n sphincsshake192ssimple = b'\\xfe\\xca', True\n p384_sphincsshake192ssimple = b'\\xfe\\xcb', True\n sphincsshake256fsimple = b'\\xfe\\xcc', True\n p521_sphincsshake256fsimple = b'\\xfe\\xcd', True\n sphincsshake256ssimple = b'\\xfe\\xce', True\n p521_sphincsshake256ssimple = b'\\xfe\\xcf', True" }, { "identifier": "Protocol", "path": "src/hello_tls/names_and_numbers.py", "snippet": "class Protocol(Enum):\n # Keep protocols in order of preference.\n TLS1_3 = b\"\\x03\\x04\"\n TLS1_2 = b\"\\x03\\x03\"\n TLS1_1 = b\"\\x03\\x02\"\n TLS1_0 = b\"\\x03\\x01\"\n SSLv3 = b\"\\x03\\x00\"\n\n def __repr__(self):\n return self.name\n def __lt__(self, other):\n if self.__class__ != other.__class__:\n return NotImplemented\n return self.value < other.value" }, { "identifier": "CompressionMethod", "path": "src/hello_tls/names_and_numbers.py", "snippet": "class CompressionMethod(Enum):\n NULL = b'\\x00'\n DEFLATE = b'\\x01'" } ]
from enum import Enum from multiprocessing.pool import ThreadPool from typing import Iterable, Union, List, Optional, Iterator, Callable, Any from urllib.parse import urlparse from datetime import datetime, timezone from .protocol import ClientHello, ScanError, make_client_hello, parse_server_hello, ServerAlertError, BadServerResponse, ServerHello, logger from .names_and_numbers import AlertDescription, CipherSuite, Group, Protocol, CompressionMethod from OpenSSL import SSL, crypto import socket import re import dataclasses import ssl, select
15,190
if not settings.proxy.startswith('http://'): raise ProxyError("Only HTTP proxies are supported at the moment.", settings.proxy) socket_host, socket_port = parse_target(settings.proxy, 80) sock = socket.create_connection((socket_host, socket_port), timeout=settings.timeout_in_seconds) sock.send(f"CONNECT {settings.host}:{settings.port} HTTP/1.1\r\nhost:{socket_host}\r\n\r\n".encode('utf-8')) sock_file = sock.makefile('r', newline='\r\n') line = sock_file.readline() if not re.fullmatch(r'HTTP/1\.[01] 200 Connection [Ee]stablished\r\n', line): sock_file.close() sock.close() raise ProxyError("Proxy refused the connection: ", line) while True: if sock_file.readline() == '\r\n': break return sock except TimeoutError as e: raise ConnectionError(f"Connection to {socket_host}:{socket_port} timed out after {settings.timeout_in_seconds} seconds") from e except socket.gaierror as e: raise ConnectionError(f"Could not resolve host {socket_host}") from e except socket.error as e: raise ConnectionError(f"Could not connect to {socket_host}:{socket_port}") from e def send_hello(connection_settings: ConnectionSettings, client_hello: ClientHello) -> ServerHello: """ Sends a Client Hello to the server, and returns the parsed ServerHello. Raises exceptions for the different alert messages the server can send. """ sock = make_socket(connection_settings) sock.send(make_client_hello(client_hello)) packet_stream = iter(lambda: sock.recv(4096), b'') server_hello = parse_server_hello(packet_stream) if server_hello.version not in client_hello.protocols: # Server picked a protocol we didn't ask for. logger.info(f"Server attempted to downgrade protocol to unsupported version {server_hello.version}") raise DowngradeError(f"Server attempted to downgrade from {client_hello.protocols} to {server_hello.version}") return server_hello def _iterate_server_option(connection_settings: ConnectionSettings, client_hello: ClientHello, request_option: str, response_option: str, on_response: Callable[[ServerHello], None] = lambda s: None) -> Iterator[Any]: """ Continually sends Client Hello packets to the server, removing the `response_option` from the list of options each time, until the server rejects the handshake. """ # We'll be mutating the list of options, so make a copy. options_to_test = list(getattr(client_hello, request_option)) # TODO: figure out how to have mypy accept this line. client_hello = dataclasses.replace(client_hello, **{request_option: options_to_test}) # type: ignore logger.info(f"Enumerating server {response_option} with {len(options_to_test)} options and protocols {client_hello.protocols}") while options_to_test: try: logger.debug(f"Offering {len(options_to_test)} {response_option} over {client_hello.protocols}: {options_to_test}") server_hello = send_hello(connection_settings, client_hello) on_response(server_hello) except DowngradeError: break except ServerAlertError as error: if error.description in [AlertDescription.protocol_version, AlertDescription.handshake_failure]: break raise accepted_option = getattr(server_hello, response_option) if accepted_option is None or accepted_option not in options_to_test: # When enumerating groups, the server can refuse all groups and still accept the handshake (group=None), # or accept a group that we didn't offer (e.g. Caddy 2.7.5 with group x25519). break options_to_test.remove(accepted_option) yield accepted_option def enumerate_server_cipher_suites(connection_settings: ConnectionSettings, client_hello: ClientHello, on_response: Callable[[ServerHello], None] = lambda s: None) -> List[CipherSuite]: """ Given a list of cipher suites to test, sends a sequence of Client Hello packets to the server, removing the accepted cipher suite from the list each time. Returns a list of all cipher suites the server accepted. """ return list(_iterate_server_option(connection_settings, client_hello, 'cipher_suites', 'cipher_suite', on_response)) def enumerate_server_groups(connection_settings: ConnectionSettings, client_hello: ClientHello, on_response: Callable[[ServerHello], None] = lambda s: None) -> Optional[List[Group]]: """ Given a list of groups to test, sends a sequence of Client Hello packets to the server, removing the accepted group from the list each time. Returns a list of all groups the server accepted. """ return list(_iterate_server_option(connection_settings, client_hello, 'groups', 'group', on_response)) @dataclasses.dataclass class Certificate: """ Represents an X509 certificate in a chain sent by the server. """ serial_number: str fingerprint_sha256: str subject: dict[str, str] issuer: dict[str, str] subject_alternative_names: list[str] key_type: str key_length_in_bits: int all_key_usage: list[str] not_before: datetime not_after: datetime is_expired: bool days_until_expiration: int signature_algorithm: str extensions: dict[str, str] def get_server_certificate_chain(connection_settings: ConnectionSettings, client_hello: ClientHello) -> Iterable[Certificate]: """ Use socket and pyOpenSSL to get the server certificate chain. """ def _x509_name_to_dict(x509_name: crypto.X509Name) -> dict[str, str]: return {name.decode('utf-8'): value.decode('utf-8') for name, value in x509_name.get_components()} def _x509_time_to_datetime(x509_time: Optional[bytes]) -> datetime: if x509_time is None:
# Default number of workers/threads/concurrent connections to use. DEFAULT_MAX_WORKERS: int = 6 # Default socket connection timeout, in seconds. DEFAULT_TIMEOUT: float = 2 class DowngradeError(ScanError): """ Error for servers that attempt to downgrade beyond supported versions. """ pass class ConnectionError(ScanError): """ Class for error in resolving or connecting to a server. """ pass class ProxyError(ConnectionError): """ Class for errors in connecting through a proxy. """ pass @dataclasses.dataclass class ConnectionSettings: """ Settings for a connection to a server, including the host, port, and proxy. """ host: str port: int = 443 proxy: Optional[str] = None timeout_in_seconds: Optional[float] = DEFAULT_TIMEOUT date: datetime = dataclasses.field(default_factory=lambda: datetime.now(tz=timezone.utc).replace(microsecond=0)) def make_socket(settings: ConnectionSettings) -> socket.socket: """ Creates and connects a socket to the target server, through the chosen proxy if any. """ socket_host, socket_port = None, None # To appease the type checker. try: if not settings.proxy: socket_host, socket_port = settings.host, settings.port return socket.create_connection((socket_host, socket_port), timeout=settings.timeout_in_seconds) if not settings.proxy.startswith('http://'): raise ProxyError("Only HTTP proxies are supported at the moment.", settings.proxy) socket_host, socket_port = parse_target(settings.proxy, 80) sock = socket.create_connection((socket_host, socket_port), timeout=settings.timeout_in_seconds) sock.send(f"CONNECT {settings.host}:{settings.port} HTTP/1.1\r\nhost:{socket_host}\r\n\r\n".encode('utf-8')) sock_file = sock.makefile('r', newline='\r\n') line = sock_file.readline() if not re.fullmatch(r'HTTP/1\.[01] 200 Connection [Ee]stablished\r\n', line): sock_file.close() sock.close() raise ProxyError("Proxy refused the connection: ", line) while True: if sock_file.readline() == '\r\n': break return sock except TimeoutError as e: raise ConnectionError(f"Connection to {socket_host}:{socket_port} timed out after {settings.timeout_in_seconds} seconds") from e except socket.gaierror as e: raise ConnectionError(f"Could not resolve host {socket_host}") from e except socket.error as e: raise ConnectionError(f"Could not connect to {socket_host}:{socket_port}") from e def send_hello(connection_settings: ConnectionSettings, client_hello: ClientHello) -> ServerHello: """ Sends a Client Hello to the server, and returns the parsed ServerHello. Raises exceptions for the different alert messages the server can send. """ sock = make_socket(connection_settings) sock.send(make_client_hello(client_hello)) packet_stream = iter(lambda: sock.recv(4096), b'') server_hello = parse_server_hello(packet_stream) if server_hello.version not in client_hello.protocols: # Server picked a protocol we didn't ask for. logger.info(f"Server attempted to downgrade protocol to unsupported version {server_hello.version}") raise DowngradeError(f"Server attempted to downgrade from {client_hello.protocols} to {server_hello.version}") return server_hello def _iterate_server_option(connection_settings: ConnectionSettings, client_hello: ClientHello, request_option: str, response_option: str, on_response: Callable[[ServerHello], None] = lambda s: None) -> Iterator[Any]: """ Continually sends Client Hello packets to the server, removing the `response_option` from the list of options each time, until the server rejects the handshake. """ # We'll be mutating the list of options, so make a copy. options_to_test = list(getattr(client_hello, request_option)) # TODO: figure out how to have mypy accept this line. client_hello = dataclasses.replace(client_hello, **{request_option: options_to_test}) # type: ignore logger.info(f"Enumerating server {response_option} with {len(options_to_test)} options and protocols {client_hello.protocols}") while options_to_test: try: logger.debug(f"Offering {len(options_to_test)} {response_option} over {client_hello.protocols}: {options_to_test}") server_hello = send_hello(connection_settings, client_hello) on_response(server_hello) except DowngradeError: break except ServerAlertError as error: if error.description in [AlertDescription.protocol_version, AlertDescription.handshake_failure]: break raise accepted_option = getattr(server_hello, response_option) if accepted_option is None or accepted_option not in options_to_test: # When enumerating groups, the server can refuse all groups and still accept the handshake (group=None), # or accept a group that we didn't offer (e.g. Caddy 2.7.5 with group x25519). break options_to_test.remove(accepted_option) yield accepted_option def enumerate_server_cipher_suites(connection_settings: ConnectionSettings, client_hello: ClientHello, on_response: Callable[[ServerHello], None] = lambda s: None) -> List[CipherSuite]: """ Given a list of cipher suites to test, sends a sequence of Client Hello packets to the server, removing the accepted cipher suite from the list each time. Returns a list of all cipher suites the server accepted. """ return list(_iterate_server_option(connection_settings, client_hello, 'cipher_suites', 'cipher_suite', on_response)) def enumerate_server_groups(connection_settings: ConnectionSettings, client_hello: ClientHello, on_response: Callable[[ServerHello], None] = lambda s: None) -> Optional[List[Group]]: """ Given a list of groups to test, sends a sequence of Client Hello packets to the server, removing the accepted group from the list each time. Returns a list of all groups the server accepted. """ return list(_iterate_server_option(connection_settings, client_hello, 'groups', 'group', on_response)) @dataclasses.dataclass class Certificate: """ Represents an X509 certificate in a chain sent by the server. """ serial_number: str fingerprint_sha256: str subject: dict[str, str] issuer: dict[str, str] subject_alternative_names: list[str] key_type: str key_length_in_bits: int all_key_usage: list[str] not_before: datetime not_after: datetime is_expired: bool days_until_expiration: int signature_algorithm: str extensions: dict[str, str] def get_server_certificate_chain(connection_settings: ConnectionSettings, client_hello: ClientHello) -> Iterable[Certificate]: """ Use socket and pyOpenSSL to get the server certificate chain. """ def _x509_name_to_dict(x509_name: crypto.X509Name) -> dict[str, str]: return {name.decode('utf-8'): value.decode('utf-8') for name, value in x509_name.get_components()} def _x509_time_to_datetime(x509_time: Optional[bytes]) -> datetime: if x509_time is None:
raise BadServerResponse('Timestamp cannot be None')
0
2023-10-21 02:00:13+00:00
24k
zhaojw1998/AccoMontage-3
arrangement_utils.py
[ { "identifier": "split_phrases", "path": "piano_arranger/acc_utils.py", "snippet": "def split_phrases(segmentation):\n \"\"\"Split a phrase label string into individual phrase meta info\"\"\"\n if '\\n' not in segmentation:\n segmentation += '\\n'\n phrases = []\n lengths = []\n current = 0\n while segmentation[current] != '\\n':\n if segmentation[current].isalpha():\n j = 1\n while not (segmentation[current + j].isalpha() or segmentation[current + j] == '\\n'):\n j += 1\n phrases.append(segmentation[current])\n lengths.append(int(segmentation[current+1: current+j]))\n current += j\n return [(phrases[i], lengths[i], sum(lengths[:i])) for i in range(len(phrases))] " }, { "identifier": "DisentangleVAE", "path": "piano_arranger/models/Poly_Dis.py", "snippet": "class DisentangleVAE(PytorchModel):\n\n def __init__(self, name, device, chd_encoder, rhy_encoder, decoder,\n chd_decoder):\n super(DisentangleVAE, self).__init__(name, device)\n self.chd_encoder = chd_encoder\n self.rhy_encoder = rhy_encoder\n self.decoder = decoder\n self.num_step = self.decoder.num_step\n self.chd_decoder = chd_decoder\n\n def confuse_prmat(self, pr_mat):\n non_zero_ent = torch.nonzero(pr_mat.long())\n eps = torch.randint(0, 2, (non_zero_ent.size(0),))\n eps = ((2 * eps) - 1).long()\n confuse_ent = torch.clamp(non_zero_ent[:, 2] + eps, min=0, max=127)\n pr_mat[non_zero_ent[:, 0], non_zero_ent[:, 1], confuse_ent] = \\\n pr_mat[non_zero_ent[:, 0], non_zero_ent[:, 1], non_zero_ent[:, 2]]\n return pr_mat\n\n def get_chroma(self, pr_mat):\n bs = pr_mat.size(0)\n pad = torch.zeros(bs, 32, 4).to(self.device)\n pr_mat = torch.cat([pr_mat, pad], dim=-1)\n c = pr_mat.view(bs, 32, -1, 12).contiguous()\n c = c.sum(dim=-2) # (bs, 32, 12)\n c = c.view(bs, 8, 4, 12)\n c = c.sum(dim=-2).float()\n c = torch.log(c + 1)\n return c.to(self.device)\n\n def run(self, x, c, pr_mat, tfr1, tfr2, tfr3, confuse=True):\n embedded_x, lengths = self.decoder.emb_x(x)\n # cc = self.get_chroma(pr_mat)\n dist_chd = self.chd_encoder(c)\n # pr_mat = self.confuse_prmat(pr_mat)\n dist_rhy = self.rhy_encoder(pr_mat)\n z_chd, z_rhy = get_zs_from_dists([dist_chd, dist_rhy], True)\n dec_z = torch.cat([z_chd, z_rhy], dim=-1)\n pitch_outs, dur_outs = self.decoder(dec_z, False, embedded_x,\n lengths, tfr1, tfr2)\n recon_root, recon_chroma, recon_bass = self.chd_decoder(z_chd, False,\n tfr3, c)\n return pitch_outs, dur_outs, dist_chd, dist_rhy, recon_root, \\\n recon_chroma, recon_bass\n\n def loss_function(self, x, c, recon_pitch, recon_dur, dist_chd,\n dist_rhy, recon_root, recon_chroma, recon_bass,\n beta, weights, weighted_dur=False):\n recon_loss, pl, dl = self.decoder.recon_loss(x, recon_pitch, recon_dur,\n weights, weighted_dur)\n kl_loss, kl_chd, kl_rhy = self.kl_loss(dist_chd, dist_rhy)\n chord_loss, root, chroma, bass = self.chord_loss(c, recon_root,\n recon_chroma,\n recon_bass)\n loss = recon_loss + beta * kl_loss + chord_loss\n return loss, recon_loss, pl, dl, kl_loss, kl_chd, kl_rhy, chord_loss, \\\n root, chroma, bass\n\n def chord_loss(self, c, recon_root, recon_chroma, recon_bass):\n loss_fun = nn.CrossEntropyLoss()\n root = c[:, :, 0: 12].max(-1)[-1].view(-1).contiguous()\n chroma = c[:, :, 12: 24].long().view(-1).contiguous()\n bass = c[:, :, 24:].max(-1)[-1].view(-1).contiguous()\n\n recon_root = recon_root.view(-1, 12).contiguous()\n recon_chroma = recon_chroma.view(-1, 2).contiguous()\n recon_bass = recon_bass.view(-1, 12).contiguous()\n root_loss = loss_fun(recon_root, root)\n chroma_loss = loss_fun(recon_chroma, chroma)\n bass_loss = loss_fun(recon_bass, bass)\n chord_loss = root_loss + chroma_loss + bass_loss\n return chord_loss, root_loss, chroma_loss, bass_loss\n\n def kl_loss(self, *dists):\n # kl = kl_with_normal(dists[0])\n kl_chd = kl_with_normal(dists[0])\n kl_rhy = kl_with_normal(dists[1])\n kl_loss = kl_chd + kl_rhy\n return kl_loss, kl_chd, kl_rhy\n\n def loss(self, x, c, pr_mat, dt_x, tfr1=0., tfr2=0., tfr3=0., beta=0.1, weights=(1, 0.5)):\n #print(pr_mat.shape, dt_x.shape)\n outputs = self.run(x, c, pr_mat, tfr1, tfr2, tfr3)\n loss = self.loss_function(x, c, *outputs, beta, weights)\n return loss\n\n # def inference(self, c, pr_mat):\n # self.eval()\n # with torch.no_grad():\n # dist_chd = self.chd_encoder(c)\n # # pr_mat = self.confuse_prmat(pr_mat)\n # dist_rhy = self.rhy_encoder(pr_mat)\n # z_chd, z_rhy = get_zs_from_dists([dist_chd, dist_rhy], True)\n # dec_z = torch.cat([z_chd, z_rhy], dim=-1)\n # pitch_outs, dur_outs = self.decoder(dec_z, True, None,\n # None, 0., 0.)\n # est_x, _, _ = self.decoder.output_to_numpy(pitch_outs, dur_outs)\n # return est_x\n #\n # def swap(self, c1, c2, pr_mat1, pr_mat2, fix_rhy, fix_chd):\n # pr_mat = pr_mat1 if fix_rhy else pr_mat2\n # c = c1 if fix_chd else c2\n # est_x = self.inference(c, pr_mat)\n # return est_x\n\n def inference_encode(self, pr_mat, c):\n self.eval()\n with torch.no_grad():\n dist_chd = self.chd_encoder(c)\n dist_rhy = self.rhy_encoder(pr_mat)\n return dist_chd, dist_rhy\n\n def inference_decode(self, z_chd, z_rhy):\n self.eval()\n with torch.no_grad():\n dec_z = torch.cat([z_chd, z_rhy], dim=-1)\n pitch_outs, dur_outs = self.decoder(dec_z, True, None,\n None, 0., 0.)\n est_x, _, _ = self.decoder.output_to_numpy(pitch_outs, dur_outs)\n return est_x\n\n def inference(self, pr_mat, c, sample):\n self.eval()\n with torch.no_grad():\n dist_chd = self.chd_encoder(c)\n dist_rhy = self.rhy_encoder(pr_mat)\n z_chd, z_rhy = get_zs_from_dists([dist_chd, dist_rhy], sample)\n dec_z = torch.cat([z_chd, z_rhy], dim=-1)\n pitch_outs, dur_outs = self.decoder(dec_z, True, None,\n None, 0., 0.)\n est_x, _, _ = self.decoder.output_to_numpy(pitch_outs, dur_outs)\n return est_x\n\n def swap(self, pr_mat1, pr_mat2, c1, c2, fix_rhy, fix_chd):\n pr_mat = pr_mat1 if fix_rhy else pr_mat2\n c = c1 if fix_chd else c2\n est_x = self.inference(pr_mat, c, sample=False)\n return est_x\n\n def posterior_sample(self, pr_mat, c, scale=None, sample_chd=True,\n sample_txt=True):\n if scale is None and sample_chd and sample_txt:\n est_x = self.inference(pr_mat, c, sample=True)\n else:\n dist_chd, dist_rhy = self.inference_encode(pr_mat, c)\n if scale is not None:\n mean_chd = dist_chd.mean\n mean_rhy = dist_rhy.mean\n # std_chd = torch.ones_like(dist_chd.mean) * scale\n # std_rhy = torch.ones_like(dist_rhy.mean) * scale\n std_chd = dist_chd.scale * scale\n std_rhy = dist_rhy.scale * scale\n dist_rhy = Normal(mean_rhy, std_rhy)\n dist_chd = Normal(mean_chd, std_chd)\n z_chd, z_rhy = get_zs_from_dists([dist_chd, dist_rhy], True)\n if not sample_chd:\n z_chd = dist_chd.mean\n if not sample_txt:\n z_rhy = dist_rhy.mean\n est_x = self.inference_decode(z_chd, z_rhy)\n return est_x\n\n def prior_sample(self, x, c, sample_chd=False, sample_rhy=False,\n scale=1.):\n dist_chd, dist_rhy = self.inference_encode(x, c)\n mean = torch.zeros_like(dist_rhy.mean)\n loc = torch.ones_like(dist_rhy.mean) * scale\n if sample_chd:\n dist_chd = Normal(mean, loc)\n if sample_rhy:\n dist_rhy = Normal(mean, loc)\n z_chd, z_rhy = get_zs_from_dists([dist_chd, dist_rhy], True)\n return self.inference_decode(z_chd, z_rhy)\n\n def gt_sample(self, x):\n out = x[:, :, 1:].numpy()\n return out\n\n def interp(self, pr_mat1, c1, pr_mat2, c2, interp_chd=False,\n interp_rhy=False, int_count=10):\n dist_chd1, dist_rhy1 = self.inference_encode(pr_mat1, c1)\n dist_chd2, dist_rhy2 = self.inference_encode(pr_mat2, c2)\n [z_chd1, z_rhy1, z_chd2, z_rhy2] = \\\n get_zs_from_dists([dist_chd1, dist_rhy1, dist_chd2, dist_rhy2],\n False)\n if interp_chd:\n z_chds = self.interp_z(z_chd1, z_chd2, int_count)\n else:\n z_chds = z_chd1.unsqueeze(1).repeat(1, int_count, 1)\n if interp_rhy:\n z_rhys = self.interp_z(z_rhy1, z_rhy2, int_count)\n else:\n z_rhys = z_rhy1.unsqueeze(1).repeat(1, int_count, 1)\n bs = z_chds.size(0)\n z_chds = z_chds.view(bs * int_count, -1).contiguous()\n z_rhys = z_rhys.view(bs * int_count, -1).contiguous()\n estxs = self.inference_decode(z_chds, z_rhys)\n return estxs.reshape((bs, int_count, 32, 15, -1))\n\n def interp_z(self, z1, z2, int_count=10):\n z1 = z1.numpy()\n z2 = z2.numpy()\n zs = torch.stack([self.interp_path(zz1, zz2, int_count)\n for zz1, zz2 in zip(z1, z2)], dim=0)\n return zs\n\n def interp_path(self, z1, z2, interpolation_count=10):\n result_shape = z1.shape\n z1 = z1.reshape(-1)\n z2 = z2.reshape(-1)\n\n def slerp2(p0, p1, t):\n omega = np.arccos(\n np.dot(p0 / np.linalg.norm(p0), p1 / np.linalg.norm(p1)))\n so = np.sin(omega)\n return np.sin((1.0 - t) * omega)[:, None] / so * p0[\n None] + np.sin(\n t * omega)[:, None] / so * p1[None]\n\n percentages = np.linspace(0.0, 1.0, interpolation_count)\n\n normalized_z1 = z1 / np.linalg.norm(z1)\n normalized_z2 = z2 / np.linalg.norm(z2)\n dirs = slerp2(normalized_z1, normalized_z2, percentages)\n length = np.linspace(np.log(np.linalg.norm(z1)),\n np.log(np.linalg.norm(z2)),\n interpolation_count)\n out = (dirs * np.exp(length[:, None])).reshape(\n [interpolation_count] + list(result_shape))\n # out = np.array([(1 - t) * z1 + t * z2 for t in percentages])\n return torch.from_numpy(out).to(self.device).float()\n\n @staticmethod\n def init_model(device=None, chd_size=256, txt_size=256, num_channel=10):\n name = 'disvae'\n if device is None:\n device = torch.device('cuda' if torch.cuda.is_available()\n else 'cpu')\n # chd_encoder = RnnEncoder(36, 1024, 256)\n chd_encoder = RnnEncoder(36, 1024, chd_size)\n # rhy_encoder = TextureEncoder(256, 1024, 256)\n rhy_encoder = TextureEncoder(256, 1024, txt_size, num_channel)\n # pt_encoder = PtvaeEncoder(device=device, z_size=152)\n # chd_decoder = RnnDecoder(z_dim=256)\n chd_decoder = RnnDecoder(z_dim=chd_size)\n # pt_decoder = PtvaeDecoder(note_embedding=None,\n # dec_dur_hid_size=64, z_size=512)\n pt_decoder = PtvaeDecoder(note_embedding=None,\n dec_dur_hid_size=64,\n z_size=chd_size + txt_size)\n\n model = DisentangleVAE(name, device, chd_encoder,\n rhy_encoder, pt_decoder, chd_decoder)\n return model" }, { "identifier": "find_by_length", "path": "piano_arranger/AccoMontage.py", "snippet": "def find_by_length(melody_data, acc_data, chord_data, velocity_data, cc_data, length):\n \"\"\"Search from POP909 phrase data for a certain phrase length.\"\"\"\n melody_record = []\n acc_record = []\n chord_record = []\n velocity_record = []\n cc_record = []\n song_reference = []\n for song_idx in range(acc_data.shape[0]):\n for phrase_idx in range(len(acc_data[song_idx])):\n melody = melody_data[song_idx][phrase_idx]\n if not melody.shape[0] == length * 16:\n continue\n if np.sum(melody[:, :128]) <= 2:\n continue\n melody_record.append(melody)\n acc = acc_data[song_idx][phrase_idx]\n acc_record.append(acc)\n chord = chord_data[song_idx][phrase_idx]\n chord_record.append(chord)\n velocity = velocity_data[song_idx][phrase_idx]\n velocity_record.append(velocity)\n cc = cc_data[song_idx][phrase_idx]\n cc_record.append(cc)\n song_reference.append((song_idx, phrase_idx))\n return np.array(melody_record), np.array(acc_record), np.array(chord_record), np.array(velocity_record), np.array(cc_record), song_reference" }, { "identifier": "dp_search", "path": "piano_arranger/AccoMontage.py", "snippet": "def dp_search(query_phrases, seg_query, acc_pool, edge_weights, texture_filter=None, filter_id=None, spotlights=None, randomness=0):\n \"\"\"Search for texture donors based on dynamic programming.\n * query_phrases: lead sheet in segmented phrases. Shape of each phrase: (T, 142), quantized at 1/4-beat level. This format is defined in R. Yang et al., \"Deep music analogy via latent representation disentanglement,\" ISMIR 2019.\n * seg_query: phrase annotation for the lead sheet. Format of each phrase: (label, length, start). For example, seg_query=[('A', 8, 0), ('A', 8, 8), ('B', 4, 16)].\n * acc_pool: search space for piano texture donors.\n * edge_weights: pre-computed transition scores for texture donor i to i+1.\n * texture_filter: filter on voice number (VN) and rhythmic density (RD).\n * filter_id: specified VN abd RD to filter for the first phrase.\n * spotlights: specified a preference for certain songs and/or artists for the search process.\n * randomness: degree of randomness tobe introduced to the search process.\n \"\"\"\n seg_query = [item[0] + str(item[1]) for item in seg_query] #['A8', 'A8', 'B8', 'B8']\n #Searching for phrase 1\n query_length = [query_phrases[i].shape[0]//16 for i in range(len(query_phrases))]\n mel, acc, chord, _, _, song_ref = acc_pool[query_length[0]]\n mel_set = mel\n rhy_set = np.concatenate((np.sum(mel_set[:, :, :128], axis=-1, keepdims=True), mel_set[:, :, 128: 130]), axis=-1)\n query_rhy = np.concatenate((np.sum(query_phrases[0][:, : 128], axis=-1, keepdims=True), query_phrases[0][:, 128: 130]), axis=-1)[np.newaxis, :, :]\n rhythm_result = cosine_rhy(query_rhy+1e-5, rhy_set+1e-5)\n\n chord_set = chord\n chord_set, num_total, shift_const = chord_shift(chord_set)\n chord_set_TIV = computeTIV(chord_set)\n query_chord = query_phrases[0][:, 130:][::4]\n query_chord_TIV = computeTIV(query_chord)[np.newaxis, :, :]\n chord_score, arg_chord = cosine(query_chord_TIV, chord_set_TIV)\n\n score = .5*rhythm_result + .5*chord_score\n score += randomness * np.random.normal(0, 1, size=len(score)) #to introduce some randomness\n if spotlights is not None:\n for spot_idx in spotlights:\n for ref_idx, ref_item in enumerate(song_ref):\n if ref_item[0] == spot_idx: \n score[ref_idx] += 1\n if filter_id is not None:\n mask = texture_filter[query_length[0]][0][filter_id[0]] * texture_filter[query_length[0]][1][filter_id[1]] - 1\n score += mask\n\n path = [[(i, score[i])] for i in range(acc.shape[0])]\n shift = [[shift_const[i]] for i in arg_chord]\n melody_record = np.argmax(mel_set, axis=-1)\n record = []\n\n #Searching for phrase 2, 3, ...\n for i in tqdm(range(1, len(query_length))):\n mel, acc, chord, _, _, song_ref = acc_pool[query_length[i]]\n weight_key = f\"l_{str(query_length[i-1]).zfill(2)}_{str(query_length[i]).zfill(2)}\"\n contras_result = edge_weights[weight_key]\n if query_length[i-1] == query_length[i]:\n for j in range(contras_result.shape[0]):\n contras_result[j, j] = -1 #the ith phrase does not transition to itself at i+1\n for k in range(j-1, -1, -1):\n if song_ref[k][0] != song_ref[j][0]:\n break\n contras_result[j, k] = -1 #ith phrase does not transition to its ancestors in the same song.\n if i > 1:\n contras_result = contras_result[[item[-1][1] for item in record]]\n if spotlights is not None:\n for spot_idx in spotlights:\n for ref_idx, ref_item in enumerate(song_ref):\n if ref_item[0] == spot_idx:\n contras_result[:, ref_idx] += 1\n mel_set = mel\n rhy_set = np.concatenate((np.sum(mel_set[:, :, :128], axis=-1, keepdims=True), mel_set[:, :, 128: 130]), axis=-1)\n query_rhy = np.concatenate((np.sum(query_phrases[i][:, : 128], axis=-1, keepdims=True), query_phrases[i][:, 128: 130]), axis=-1)[np.newaxis, :, :]\n rhythm_result = cosine_rhy(query_rhy, rhy_set)\n chord_set = chord\n chord_set, num_total, shift_const = chord_shift(chord_set)\n chord_set_TIV = computeTIV(chord_set)\n query_chord = query_phrases[i][:, 130:][::4]\n query_chord_TIV = computeTIV(query_chord)[np.newaxis, :, :]\n chord_score, arg_chord = cosine(query_chord_TIV, chord_set_TIV)\n sim_this_layer = .5*rhythm_result + .5*chord_score\n sim_this_layer += randomness * np.random.normal(0, 1, size=len(sim_this_layer))\n if spotlights is not None:\n for spot_idx in spotlights:\n for ref_idx, ref_item in enumerate(song_ref):\n if ref_item[0] == spot_idx: \n sim_this_layer[ref_idx] += 1\n score_this_layer = .7*contras_result + .3*np.tile(sim_this_layer[np.newaxis, :], (contras_result.shape[0], 1)) + np.tile(score[:, np.newaxis], (1, contras_result.shape[1]))\n melody_flat = np.argmax(mel_set, axis=-1)\n if seg_query[i] == seg_query[i-1]:\n melody_pre = melody_record\n matrix = np.matmul(melody_pre, np.transpose(melody_flat, (1, 0))) / (np.linalg.norm(melody_pre, axis=-1)[:, np.newaxis]*(np.linalg.norm(np.transpose(melody_flat, (1, 0)), axis=0))[np.newaxis, :])\n if i == 1:\n for k in range(matrix.shape[1]):\n matrix[k, :k] = -1\n else:\n for k in range(len(record)):\n matrix[k, :record[k][-1][1]] = -1\n matrix = (matrix > 0.99) * 1.\n score_this_layer += matrix\n topk = 1\n args = np.argsort(score_this_layer, axis=0)[::-1, :][:topk, :]\n record = []\n for j in range(args.shape[-1]):\n for k in range(args.shape[0]):\n record.append((score_this_layer[args[k, j], j], (args[k, j], j)))\n shift_this_layer = [[shift_const[k]] for k in arg_chord]\n new_path = [path[item[-1][0]] + [(item[-1][1], sim_this_layer[item[-1][1]])] for item in record]\n new_shift = [shift[item[-1][0]] + shift_this_layer[item[-1][1]] for item in record]\n melody_record = melody_flat[[item[-1][1] for item in record]]\n path = new_path\n shift = new_shift\n score = np.array([item[0] for item in record])\n\n arg = score.argsort()[::-1]\n return [path[arg[i]] for i in range(topk)], [shift[arg[i]] for i in range(topk)]" }, { "identifier": "re_harmonization", "path": "piano_arranger/AccoMontage.py", "snippet": "def re_harmonization(lead_sheet, chord_table, query_phrases, indices, shifts, acc_pool, model, get_est=True, tempo=120):\n \"\"\"Re-harmonize the accompaniment texture donors and save in MIDI.\n * lead_sheet: the conditional lead sheet. Its melody track will be taken. Shape: (T, 142), quantized at 1-beat level. This format is defined in R. Yang et al., \"Deep music analogy via latent representation disentanglement,\" ISMIR 2019.\n * chord_table: the conditional chord progression from the lead sheet. Shape: (T', 36), quantized at 1-beat level. This format is defined in Z. Wang et al., \"Learning interpretable representation for controllable polyphonic music generation,\" ISMIR 2020.\n * seg_query: phrase annotation for the lead sheet. Format of each phrase: (label, length, start). For example, seg_query=[('A', 8, 0), ('A', 8, 8), ('B', 4, 16)].\n * indices: the indices of selected texture donor phrases in the acc_pool.\n * shifts: pitch transposition of each selected phrase.\n * acc_pool: search space for piano texture donors.\n * tempo: the tempo to render the piece.\n \"\"\"\n acc_roll = np.empty((0, 128))\n vel_roll = []\n phrase_mean_vel = []\n cc_roll = np.empty((0, 128))\n #retrive texture donor data of the corrresponding indices from the acc_pool\n for i, idx in enumerate(indices):\n length = query_phrases[i][-2]\n shift = shifts[i]\n # notes\n acc_matrix = np.roll(acc_pool[length][1][idx[0]], shift, axis=-1)\n acc_roll = np.concatenate((acc_roll, acc_matrix), axis=0)\n #MIDI velocity\n vel_matrix = np.roll(acc_pool[length][3][idx[0]], shift, axis=-1)\n phrase_mean_vel.append(np.mean(np.ma.masked_equal(vel_matrix, value=0)))\n vel_roll.append(vel_matrix)\n #MIDI control messages (mainly for pedals)\n cc_matrix = acc_pool[length][4][idx[0]]\n cc_roll = np.concatenate((cc_roll, cc_matrix), axis=0)\n # normalize the scale of velocity across different retrieved phrases\n global_mean_vel = np.mean(np.ma.masked_equal(np.concatenate(vel_roll, axis=0), value=0))\n for i in range(len(vel_roll)):\n vel_roll[i][vel_roll[i] > 0] += (global_mean_vel - phrase_mean_vel[i])\n vel_roll = np.concatenate(vel_roll, axis=0)\n #re-harmonization\n if len(acc_roll) % 32 != 0:\n pad_len = (len(acc_roll)//32+1)*32 - len(acc_roll)\n acc_roll = np.pad(acc_roll, ((0, pad_len), (0, 0)))\n vel_roll = np.pad(vel_roll, ((0, pad_len), (0, 0)))\n cc_roll = np.pad(cc_roll, ((0, pad_len), (0, 0)), mode='constant', constant_values=-1)\n chord_table = np.pad(chord_table, ((0, pad_len//4), (0, 0)))\n chord_table[-pad_len:, 0] = -1\n chord_table[-pad_len:, -1] = -1\n acc_roll = acc_roll.reshape(-1, 32, 128)\n chord_table = chord_table.reshape(-1, 8, 36)\n acc_roll = torch.from_numpy(acc_roll).float().cuda()\n acc_roll = torch.clip(acc_roll, min=0, max=31)\n gt_chord = torch.from_numpy(chord_table).float().cuda()\n est_x = model.inference(acc_roll, gt_chord, sample=False)\n acc_roll = cvt.grid2pr(est_x.reshape(-1, 15, 6))\n #interpolate MIDI velocity\n adapt_vel_roll = np.zeros(vel_roll.shape)\n masked_dyn_matrix = np.ma.masked_equal(vel_roll, value=0)\n mean = np.mean(masked_dyn_matrix, axis=-1)\n onsets = np.nonzero(mean.data)\n dynamic = mean.data[onsets]\n onsets = onsets[0].tolist()\n dynamic = dynamic.tolist()\n if not 0 in onsets:\n onsets = [0] + onsets\n dynamic = [dynamic[0]] + dynamic\n if not len(vel_roll)-1 in onsets:\n onsets = onsets + [len(vel_roll)-1]\n dynamic = dynamic + [dynamic[-1]]\n dyn_curve = interp1d(onsets, dynamic)\n for t, p in zip(*np.nonzero(acc_roll)):\n adapt_vel_roll[t, p] = dyn_curve(t)\n adapt_vel_roll = np.clip(adapt_vel_roll, a_min=0, a_max=127)\n #reconstruct MIDI\n accompaniment = np.stack([acc_roll, adapt_vel_roll, cc_roll], axis=-1)[np.newaxis, :, :, :]\n midi_recon = cvt.matrix2midi_with_dynamics(accompaniment, programs=[0], init_tempo=tempo)\n melody_track = cvt.melody_matrix2data(melody_matrix=lead_sheet[:, :130], tempo=tempo)\n midi_recon.instruments = [melody_track] + midi_recon.instruments\n if get_est:\n return midi_recon, est_x\n else:\n return midi_recon" }, { "identifier": "get_texture_filter", "path": "piano_arranger/AccoMontage.py", "snippet": "def get_texture_filter(acc_pool):\n \"\"\"Divide accompaniment texture donors into fifths in terms of voice number (VN) and rhythmic density (RD).\"\"\"\n texture_filter = {}\n for key in acc_pool:\n acc_track = acc_pool[key][1]\n # CALCULATE HORIZONTAL DENSITY (rhythmic density)\n onset_positions = (np.sum(acc_track, axis=-1) > 0) * 1.\n HD = np.sum(onset_positions, axis=-1) / acc_track.shape[1] #(N)\n # CALCULATE VERTICAL DENSITY (voice number)\n beat_positions = acc_track[:, ::4, :]\n downbeat_positions = acc_track[:, ::16, :]\n upbeat_positions = acc_track[:, 2::4, :]\n\n simu_notes_on_beats = np.sum((beat_positions > 0) * 1., axis=-1) #N*T\n simu_notes_on_downbeats = np.sum((downbeat_positions > 0) * 1., axis=-1)\n simu_notes_on_upbeats = np.sum((upbeat_positions > 0) * 1., axis=-1)\n\n VD_beat = np.sum(simu_notes_on_beats, axis=-1) / (np.sum((simu_notes_on_beats > 0) * 1., axis=-1) + 1e-10)\n VD_upbeat = np.sum(simu_notes_on_upbeats, axis=-1) / (np.sum((simu_notes_on_upbeats > 0) * 1., axis=-1) + 1e-10)\n\n VD = np.max(np.stack((VD_beat, VD_upbeat), axis=-1), axis=-1)\n #get five-equal-divident-points of HD\n dst = np.sort(HD)\n HD_anchors = [dst[len(dst) // 5], dst[len(dst) // 5 * 2], dst[len(dst) // 5 * 3], dst[len(dst) // 5 * 4]]\n HD_Bins = [\n HD < HD_anchors[0],\n (HD >= HD_anchors[0]) * (HD < HD_anchors[1]),\n (HD >= HD_anchors[1]) * (HD < HD_anchors[2]),\n (HD >= HD_anchors[2]) * (HD < HD_anchors[3]),\n HD >= HD_anchors[3]\n ]\n #get five-equal-divident-points of VD\n dst = np.sort(VD)\n VD_anchors = [dst[len(dst) // 5], dst[len(dst) // 5 * 2], dst[len(dst) // 5 * 3], dst[len(dst) // 5 * 4]]\n VD_Bins = [\n VD < VD_anchors[0],\n (VD >= VD_anchors[0]) * (VD < VD_anchors[1]),\n (VD >= VD_anchors[1]) * (VD < VD_anchors[2]),\n (VD >= VD_anchors[2]) * (VD < VD_anchors[3]),\n VD >= VD_anchors[3]\n ]\n texture_filter[key] = (HD_Bins, VD_Bins) #((5, N), (5, N))\n return texture_filter" }, { "identifier": "ref_spotlight", "path": "piano_arranger/AccoMontage.py", "snippet": "def ref_spotlight(ref_name_list, reference_check):\n \"\"\"convert spotlight song/artist names into the indices of corresponding pieces in the dataset.\"\"\"\n if ref_name_list is None:\n return None\n check_idx = []\n #POP909 song_id\n for name in ref_name_list:\n line = reference_check[reference_check.song_id == name]\n if not line.empty:\n check_idx.append(line.index)#read by pd, neglect first row, index starts from 0.\n #song name\n for name in ref_name_list:\n line = reference_check[reference_check.name == name]\n if not line.empty:\n check_idx.append(line.index)#read by pd, neglect first row, index starts from 0.\n #artist name\n for name in ref_name_list:\n line = reference_check[reference_check.artist == name]\n if not line.empty:\n check_idx += list(line.index)#read by pd, neglect first row, index starts from 0\n return check_idx" }, { "identifier": "Slakh2100_Pop909_Dataset", "path": "orchestrator/QA_dataset.py", "snippet": "class Slakh2100_Pop909_Dataset(Dataset):\n def __init__(self, slakh_dir, pop909_dir, sample_len=SAMPLE_LEN, hop_len=BAR_HOP_LEN, debug_mode=False, split='train', mode='train', with_dynamics=False, merge_pop909=0):\n super(Slakh2100_Pop909_Dataset, self).__init__()\n self.split = split\n self.mode = mode\n self.debug_mode = debug_mode\n\n self.with_dynamics = with_dynamics\n self.merge_pop909 = merge_pop909\n\n self.memory = dict({'tracks': [],\n 'programs': [],\n 'dynamics': [],\n 'dir': []\n })\n self.anchor_list = []\n self.sample_len = sample_len\n \n if slakh_dir is not None:\n print('loading Slakh2100 Dataset ...')\n self.load_data(slakh_dir, sample_len, hop_len)\n if pop909_dir is not None:\n print('loading Pop909 Dataset ...')\n self.load_data(pop909_dir, sample_len, hop_len)\n\n def __len__(self):\n return len(self.anchor_list)\n \n def __getitem__(self, idx):\n song_id, start = self.anchor_list[idx]\n\n if self.mode == 'train': \n tracks_sample = self.memory['tracks'][song_id][:, start: start+self.sample_len]\n program_sample = self.memory['programs'][song_id]\n #delete empty tracks if any\n non_empty = np.nonzero(np.sum(tracks_sample, axis=(1, 2)))[0]\n tracks_sample = tracks_sample[non_empty]\n program_sample = program_sample[non_empty]\n\n elif (self.mode == 'test') or (self.mode == 'inference'): \n tracks_sample = self.memory['tracks'][song_id][:, start:]\n program_sample = self.memory['programs'][song_id]\n\n if ((len(program_sample) <= 3) and (program_sample == 0).all()):\n #merge pop909 into a single piano track at certain probability\n if np.random.rand() < self.merge_pop909: \n tracks_sample = np.max(tracks_sample, axis=0, keepdims=True)\n program_sample = np.array([0])\n\n if self.with_dynamics:\n dynamics = self.memory['dynamics'][song_id][:, start: start+self.sample_len]\n else: \n dynamics = None\n \n return tracks_sample, program_sample, dynamics, self.memory['dir'][song_id]\n\n\n def slakh_program_mapping(self, programs):\n return np.array([EMBED_PROGRAM_MAPPING[SLAKH_PROGRAM_MAPPING[program]] for program in programs])\n\n\n def load_data(self, data_dir, sample_len, hop_len):\n song_list = [os.path.join(data_dir, self.split, item) for item in os.listdir(os.path.join(data_dir, self.split))]\n if self.debug_mode:\n song_list = song_list[: 10]\n for song_dir in tqdm(song_list):\n song_data = np.load(song_dir)\n tracks = song_data['tracks'] #(n_track, time, 128)\n if 'programs' in song_data:\n programs = song_data['programs'] #(n_track, )\n else:\n programs = np.array([0]*len(tracks))\n\n center_pitch = compute_center_pitch(tracks)\n pitch_sort = np.argsort(center_pitch)[::-1]\n tracks = tracks[pitch_sort]\n programs = programs[pitch_sort]\n\n \"\"\"clipping\"\"\" \n if self.mode == 'train':\n if self.split =='validation':\n # during model training, no overlapping for validation set\n for i in range(0, tracks.shape[1], sample_len):\n if i + sample_len >= tracks.shape[1]:\n break\n self.anchor_list.append((len(self.memory['tracks']), i)) #(song_id, start, total_length)\n else:\n # otherwise, hop size is 1-bar\n downbeats = np.nonzero(song_data['db_indicator'])[0]\n for i in range(0, len(downbeats), hop_len):\n if downbeats[i] + sample_len >= tracks.shape[1]:\n break\n self.anchor_list.append((len(self.memory['tracks']), downbeats[i])) #(song_id, start)\n\n elif (self.mode == 'test') or (self.mode == 'inference'):\n start = np.nonzero(song_data['db_indicator'])[0][0]\n end = start + (tracks.shape[1] - start) // sample_len * sample_len\n if end < tracks.shape[1]:\n pad_len = end + sample_len - tracks.shape[1]\n end += sample_len\n tracks = np.pad(tracks, ((0, 0), (0, pad_len), (0, 0)), mode='constant', constant_values=(0,))\n tracks = tracks[:, start: end]\n self.anchor_list.append((len(self.memory['tracks']), start))\n\n self.memory['tracks'].append(tracks)\n self.memory['programs'].append(self.slakh_program_mapping(programs))\n self.memory['dir'].append(song_dir)\n\n if self.with_dynamics:\n self.memory['dynamics'].append(song_data['dynamics'])" }, { "identifier": "collate_fn", "path": "orchestrator/QA_dataset.py", "snippet": "def collate_fn(batch, device, pitch_shift=True):\n #print(batch)\n max_tracks = max([max(len(item[0]), 1) for item in batch])\n\n tracks = [] \n mixture = []\n instrument = []\n aux_feature = []\n mask = [] #track-wise pad mask\n function = []\n\n if pitch_shift:\n aug_p = AUG_P / AUG_P.sum()\n aug_shift = np.random.choice(np.arange(-6, 6), 1, p=aug_p)[0]\n else:\n aug_shift = 0\n\n for pr, programs, _, _ in batch:\n pr = pr_mat_pitch_shift(pr, aug_shift)\n aux, _, func = compute_pr_feat(pr)\n mask.append([0]*len(pr) + [1]*(max_tracks-len(pr)))\n\n pr = np.pad(pr, ((0, max_tracks-len(pr)), (0, 0), (0, 0)), mode='constant', constant_values=(0,))\n programs = np.pad(programs, (0, max_tracks-len(programs)), mode='constant', constant_values=(NUM_INSTR_CLASS,))\n aux = np.pad(aux, ((0, max_tracks-len(aux)), (0, 0), (0, 0)), mode='constant', constant_values=(0,))\n func = np.pad(func, ((0, max_tracks-len(func)), (0, 0)), mode='constant', constant_values=(0,))\n\n mix = pr2grid(np.max(pr, axis=0), max_note_count=32)\n grid = np.array([pr2grid(matrix) for matrix in pr])\n\n tracks.append(grid)\n mixture.append(mix)\n instrument.append(programs)\n aux_feature.append(aux)\n function.append(func)\n\n return torch.from_numpy(np.array(mixture)).long().to(device), \\\n torch.from_numpy(np.array(instrument)).to(device), \\\n torch.from_numpy(np.array(function)).float().to(device),\\\n torch.from_numpy(np.array(tracks)).long().to(device), \\\n torch.from_numpy(np.array(aux_feature)).float().to(device), \\\n torch.BoolTensor(mask).to(device)" }, { "identifier": "compute_pr_feat", "path": "orchestrator/QA_dataset.py", "snippet": "def compute_pr_feat(pr):\n #pr: (track, time, 128)\n onset = (np.sum(pr, axis=-1) > 0) * 1. #(track, time)\n rhy_intensity = np.clip(np.sum((pr > 0) * 1., axis=-1) / 14, a_min=None, a_max=1) #(track, time)\n\n weight = np.sum(pr, axis=-1)\n weight[weight==0] = 1\n pitch_center = np.sum(np.arange(0, 128)[np.newaxis, np.newaxis, :] * pr, axis=-1) / weight / 128\n\n feature = np.stack((onset, rhy_intensity, pitch_center), axis=-1)\n\n func_pitch = np.sum((pr > 0) * 1., axis=-2) / 32\n\n func_time = rhy_intensity.copy()\n \n return feature, func_pitch, func_time" }, { "identifier": "EMBED_PROGRAM_MAPPING", "path": "orchestrator/QA_dataset.py", "snippet": "EMBED_PROGRAM_MAPPING = dict({\n 0: 0, 4: 1, 8: 2, 16: 3, 24: 4, 26: 5, 29: 6, 32: 7,\\\n 33: 8, 40: 9, 41: 10, 42: 11, 43: 12, 46: 13, 47: 14, 48: 15,\\\n 50: 16, 52: 17, 55: 18, 56: 19, 57: 20, 58: 21, 60: 22, 61: 23, \n 64: 24, 66: 25, 67: 26, 68: 27, 69: 28, 70: 29, 71: 30, 72: 31,\\\n 80: 32, 88: 33})" }, { "identifier": "Prior", "path": "orchestrator/prior_model.py", "snippet": "class Prior(nn.Module):\n def __init__(self, mixture_encoder=None,\n function_encoder=None,\n context_enc_layer=12, \n function_dec_layer=12, \n d_model=256, \n nhead=8, \n dim_feedforward=1024, \n dropout=.1, \n function_resolution=8,\n inference=False,\n QA_model=None,\n DEVICE='cuda:0'):\n super(Prior, self).__init__()\n\n # embeddings\n self.func_embedding = nn.Embedding(num_embeddings=NUM_TIME_CODE+1, embedding_dim=d_model, padding_idx=NUM_TIME_CODE)\n self.prog_embedding = nn.Embedding(num_embeddings=NUM_INSTR_CLASS+1, embedding_dim=d_model, padding_idx=NUM_INSTR_CLASS)\n self.total_len_embedding = nn.Embedding(num_embeddings=len(TOTAL_LEN_BIN)+1, embedding_dim=d_model, padding_idx=len(TOTAL_LEN_BIN))\n self.abs_pos_embedding = nn.Embedding(num_embeddings=len(ABS_POS_BIN)+1, embedding_dim=d_model, padding_idx=len(ABS_POS_BIN))\n self.rel_pos_embedding = nn.Embedding(num_embeddings=len(REL_POS_BIN)+1, embedding_dim=d_model, padding_idx=len(REL_POS_BIN))\n\n self.start_embedding = nn.Parameter(torch.empty(NUM_INSTR_CLASS+1, d_model))\n nn.init.normal_(self.start_embedding)\n with torch.no_grad():\n self.start_embedding[NUM_INSTR_CLASS].fill_(0)\n\n #pre-trained encoders\n if not inference:\n self.mixture_encoder = mixture_encoder\n for param in self.mixture_encoder.parameters():\n param.requires_grad = False\n self.function_encoder = function_encoder\n for param in self.function_encoder.parameters():\n param.requires_grad = False\n else:\n self.QA_model = QA_model\n self.mixture_encoder = self.QA_model.mixture_enc\n self.function_encoder = self.QA_model.function_enc\n\n \n self.context_enc = nn.TransformerEncoder(\n nn.TransformerEncoderLayer(d_model=d_model, \n nhead=nhead, \n dim_feedforward=dim_feedforward, \n dropout=dropout, \n activation=F.gelu, \n batch_first=True, \n norm_first=True,\n device=DEVICE),\n num_layers=context_enc_layer)\n #multi-track Transformer\n self.mt_trf = nn.ModuleDict({})\n for layer in range(function_dec_layer):\n self.mt_trf[f'track_layer_{layer}'] = TransformerEncoderLayerRPE(d_model=d_model, \n nhead=nhead, \n dim_feedforward=dim_feedforward, \n dropout=dropout, \n norm_first=True,\n max_len=18).to(DEVICE)\n self.mt_trf[f'time_layer_{layer}'] = nn.TransformerDecoderLayer(d_model=d_model, \n nhead=nhead, \n dim_feedforward=dim_feedforward, \n dropout=dropout, \n activation=F.gelu, \n batch_first=True, \n norm_first=True,\n device=DEVICE)\n \n #positional encoding\n self.max_len = 1000\n position = torch.arange(self.max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))\n pe = torch.zeros(1, self.max_len, d_model)\n pe[0, :, 0::2] = torch.sin(position * div_term)\n pe[0, :, 1::2] = torch.cos(position * div_term)\n pe = pe.to(DEVICE)\n self.register_buffer('pe', pe)\n \n #decoder output module \n self.func_out_linear = nn.Linear(d_model, NUM_TIME_CODE)\n\n #constants\n self.d_model = d_model\n self.function_dec_layer = function_dec_layer\n self.func_res = function_resolution\n\n #loss function\n self.criterion = nn.CrossEntropyLoss(reduction='mean')\n\n\n def generate_square_subsequent_mask(self, sz=15):\n return torch.triu(torch.ones(sz, sz), diagonal=1).bool()\n\n\n def func_get_next_token(self, token, gt=None):\n #token: (batch, codebook_size)\n #gt: (bs,)\n if gt is None:\n idx = token.max(-1)[1]\n else:\n idx = gt\n token = torch.zeros_like(token, device=token.device)\n arange = torch.arange(token.shape[0], device=token.device).long()\n token[arange, idx] = 1\n return token.unsqueeze(1) #one-hot shaoe (batch, 1, ft_codebook_size)\n\n \n\n\n def run(self, mix, prog, function, tm_mask, tk_mask, total_len, abs_pos, rel_pos, inference=False):\n #mix: (batch, max_time, 256)\n #prog: (batch, max_track)\n #function: (batch, max_time, max_track, 8)\n #tm_mask: (batch, max_time)\n #tk_mask: (batch, max_track)\n #total_len: (batch, max_time)\n #abs_pos: (batch, max_time)\n #rel_pos: (batch, max_time)\n batch, max_time, _ = mix.shape\n _, max_track = prog.shape\n \n mix = mix + self.pe[:, :self.func_res*mix.shape[1], :][:, ::self.func_res]\n mix = mix + self.total_len_embedding(total_len)\n mix = mix + self.abs_pos_embedding(abs_pos)\n mix = mix + self.rel_pos_embedding(rel_pos)\n \n mix = self.context_enc(mix) #(batch, max_time, 256)\n mix = mix.unsqueeze(1) + self.prog_embedding(prog).unsqueeze(2) #(batch, max_track, max_time, 256)\n mix = mix.reshape(-1, max_time, self.d_model)\n\n function = function.permute(0, 1, 3, 2).reshape(batch, -1, max_track)\n func = self.func_embedding(function)#(batch, 8*max_time, max_track, d_model)\n \n func = torch.cat([\n self.start_embedding[prog].unsqueeze(1), #(batch, 1, max_track, d_model)\n func[:, :-1]], \n dim=1) #batch, 8*max_time, max_track, d_model\n\n func = func + self.prog_embedding(prog).unsqueeze(1) \n\n func = func + self.pe[:, :func.shape[1], :].unsqueeze(2)\n func = func + self.total_len_embedding(total_len).repeat_interleave(self.func_res, dim=1).unsqueeze(2)\n func = func + self.abs_pos_embedding(abs_pos).repeat_interleave(self.func_res, dim=1).unsqueeze(2)\n func = func + self.rel_pos_embedding(rel_pos).repeat_interleave(self.func_res, dim=1).unsqueeze(2)\n\n for layer in range(self.function_dec_layer):\n func = func.reshape(-1, max_track, self.d_model)\n func = self.mt_trf[f'track_layer_{layer}'](src=func, \n src_key_padding_mask=tk_mask.unsqueeze(1).repeat(1, self.func_res*max_time, 1).reshape(-1, max_track))\n func = func.reshape(batch, -1, max_track, self.d_model).permute(0, 2, 1, 3).reshape(-1, self.func_res*max_time, self.d_model)\n func = self.mt_trf[f'time_layer_{layer}'](tgt=func,\n tgt_mask=self.generate_square_subsequent_mask(self.func_res*max_time).to(func.device),\n tgt_key_padding_mask=tm_mask.unsqueeze(1).repeat(1, max_track, 1).reshape(-1, max_time).repeat_interleave(self.func_res, dim=-1),\n memory=mix) \n func = func.reshape(batch, max_track, -1, self.d_model).permute(0, 2, 1, 3) #(batch, 8*max_time, max_track, d_model)\n\n function_recon = self.func_out_linear(func)\n\n return function_recon, function\n\n \n\n def loss_function(self, function_recon, function_gt, tm_mask, tk_mask):\n\n mask = torch.logical_or(tm_mask.repeat_interleave(8, dim=-1).unsqueeze(-1), tk_mask.unsqueeze(1)) #(batch, 8*max_time, track) \n unmask = torch.logical_not(mask)\n\n function_loss = self.criterion(function_recon[unmask].reshape(-1, NUM_TIME_CODE), \n function_gt[unmask].reshape(-1))\n return function_loss\n \n\n def loss(self, mix, prog, function, tm_mask, tk_mask, total_len, abs_pos, rel_pos):\n output = self.run(mix, prog, function, tm_mask, tk_mask, total_len, abs_pos, rel_pos, inference=False)\n return self.loss_function(*output, tm_mask, tk_mask)\n \n\n def forward(self, mode, *input, **kwargs):\n if mode in [\"run\", 0]:\n return self.run(*input, **kwargs)\n elif mode in ['loss', 'train', 1]:\n return self.loss(*input, **kwargs)\n elif mode in ['inference', 'eval', 'val', 2]:\n return self.inference(*input, **kwargs)\n else:\n raise NotImplementedError\n\n\n def run_autoregressive_greedy(self, mix, prog, function, total_len, abs_pos, rel_pos, blur=.5):\n #mix: (batch, num2bar, bar_resolution, max_simu_note, 6)\n #prog: (batch, max_track)\n #function: (batch, 1, max_track, 32)\n #total_len: (batch, num2bar)\n #abs_pos: (batch, num2bar)\n #rel_pos: (batch, num2bar)\n batch, num_2bar, time, max_simu_note, _ = mix.shape\n _, max_track = prog.shape\n\n mix = mix.reshape(-1, time, max_simu_note, 6)\n mix = self.mixture_encoder(mix)[0].mean.reshape(batch, num_2bar, -1) #(batch, num_2bar, 256)\n mix_ = (1-blur)*mix.clone() + blur*torch.empty(mix.shape, device=mix.device).normal_(mean=0, std=1) \n \n mix_ = mix_ + self.pe[:, :self.func_res*mix.shape[1], :][:, ::self.func_res]\n mix_ = mix_ + self.total_len_embedding(total_len)\n mix_ = mix_ + self.abs_pos_embedding(abs_pos)\n mix_ = mix_ + self.rel_pos_embedding(rel_pos)\n\n mix_ = self.context_enc(mix_) #(batch, num_bar, 256)\n mix_ = mix_.unsqueeze(1) + self.prog_embedding(prog).unsqueeze(2) #(batch, max_track, num_bar, 256)\n mix_ = mix_.reshape(-1, num_2bar, self.d_model)\n \n function = function.reshape(-1, 32)\n function = self.function_encoder.get_code_indices(function).reshape(batch, max_track, self.func_res)\n\n\n for idx in range(self.func_res, self.func_res*num_2bar):\n func = self.func_embedding(function) #*batch, max_track, 8, d_model\n func = func.permute(0, 2, 1, 3).reshape(batch, -1, max_track, self.d_model)\n\n func = func + self.prog_embedding(prog).unsqueeze(1)\n func = func + self.pe[:, :func.shape[1], :].unsqueeze(2)\n\n func = func + self.total_len_embedding(total_len).repeat_interleave(self.func_res, dim=1)[:, :func.shape[1]].unsqueeze(2)\n func = func + self.abs_pos_embedding(abs_pos).repeat_interleave(self.func_res, dim=1)[:, :func.shape[1]].unsqueeze(2)\n func = func + self.rel_pos_embedding(rel_pos).repeat_interleave(self.func_res, dim=1)[:, :func.shape[1]].unsqueeze(2)\n\n for layer in range(self.function_dec_layer):\n \n func = func.reshape(-1, max_track, self.d_model)\n func = self.mt_trf[f'track_layer_{layer}'](src=func)\n func = func.reshape(batch, -1, max_track, self.d_model).permute(0, 2, 1, 3).reshape(-1, idx, self.d_model)\n func = self.mt_trf[f'time_layer_{layer}'](tgt=func,\n tgt_mask=self.generate_square_subsequent_mask(sz=idx).to(func.device),\n memory=mix_) \n func = func.reshape(batch, max_track, -1, self.d_model).permute(0, 2, 1, 3) #(batch, num2bar-1, max_track, d_model)\n\n \n func_pred = self.func_out_linear(func[:, -1,]).max(-1)[1].unsqueeze(-1)\n\n function = torch.cat([function, func_pred], dim=-1)\n if function.shape[1] == self.func_res*num_2bar:\n break\n \n function = function.reshape(batch, max_track, num_2bar, self.func_res).permute(0, 2, 1, 3)\n z_func = self.function_encoder.infer_by_codes(function)\n return self.QA_model.infer_with_function_codes(mix[0], prog[0].repeat(num_2bar, 1), z_func[0])\n \n\n def run_autoregressive_nucleus(self, mix, prog, func_prompt, total_len, abs_pos, rel_pos, blur=.5, p=.1, t=1):\n #mix: (batch, num2bar, bar_resolution, max_simu_note, 6)\n #prog: (batch, max_track)\n #func_prompt: (batch, 1, max_track, 32)\n #total_len: (batch, num2bar)\n #abs_pos: (batch, num2bar)\n #rel_pos: (batch, num2bar)\n\n batch, num_2bar, time, max_simu_note, _ = mix.shape\n _, max_track = prog.shape\n\n mix = mix.reshape(-1, time, max_simu_note, 6)\n mix = self.mixture_encoder(mix)[0].mean.reshape(batch, num_2bar, -1) #(batch, num_2bar, 256)\n mix_ = (1-blur)*mix.clone() + blur*torch.empty(mix.shape, device=mix.device).normal_(mean=0, std=1) \n \n mix_ = mix_ + self.pe[:, :self.func_res*mix.shape[1], :][:, ::self.func_res]\n mix_ = mix_ + self.total_len_embedding(total_len)\n mix_ = mix_ + self.abs_pos_embedding(abs_pos)\n mix_ = mix_ + self.rel_pos_embedding(rel_pos)\n\n mix_ = self.context_enc(mix_) #(batch, num_bar, 256)\n mix_ = mix_.unsqueeze(1) + self.prog_embedding(prog).unsqueeze(2) #(batch, max_track, num_bar, 256)\n mix_ = mix_.reshape(-1, num_2bar, self.d_model)\n \n start = self.start_embedding[prog].unsqueeze(1) #(batch, 1, max_track, dmodel)\n\n if func_prompt is not None:\n func_prompt = func_prompt.reshape(-1, 32)\n func_prompt = self.function_encoder.get_code_indices(func_prompt).reshape(batch, max_track, self.func_res).permute(0, 2, 1) #(batch, 8, max_track)\n #else:\n function = torch.empty((batch, 0, max_track)).long().to(mix.device)\n\n for idx in range(self.func_res*num_2bar):\n if (idx < self.func_res) and (func_prompt is not None):\n start = torch.cat([start, self.func_embedding(function[:, idx-1: idx, :])], dim=1)\n function = torch.cat([function, func_prompt[:, idx: idx+1, :]], dim=1) \n continue\n else:\n func = torch.cat([start, self.func_embedding(function[:, idx-1: idx, :])], dim=1)\n\n func = func + self.prog_embedding(prog).unsqueeze(1)\n func = func + self.pe[:, :func.shape[1], :].unsqueeze(2)\n\n func = func + self.total_len_embedding(total_len).repeat_interleave(self.func_res, dim=1)[:, :func.shape[1]].unsqueeze(2)\n func = func + self.abs_pos_embedding(abs_pos).repeat_interleave(self.func_res, dim=1)[:, :func.shape[1]].unsqueeze(2)\n func = func + self.rel_pos_embedding(rel_pos).repeat_interleave(self.func_res, dim=1)[:, :func.shape[1]].unsqueeze(2)\n\n for layer in range(self.function_dec_layer):\n \n func = func.reshape(-1, max_track, self.d_model)\n func = self.mt_trf[f'track_layer_{layer}'](src=func)\n func = func.reshape(batch, -1, max_track, self.d_model).permute(0, 2, 1, 3).reshape(-1, idx+1, self.d_model)\n func = self.mt_trf[f'time_layer_{layer}'](tgt=func,\n tgt_mask=self.generate_square_subsequent_mask(sz=idx+1).to(func.device),\n memory=mix_) \n func = func.reshape(batch, max_track, -1, self.d_model).permute(0, 2, 1, 3)#(batch, num2bar-1, max_track, d_model)\n \n start = torch.cat([start, self.func_embedding(function[:, idx-1: idx, :])], dim=1)\n\n func_logits = self.func_out_linear(func[:, -1,]) / t\n filtered_func_logits = self.nucleus_filter(func_logits, p)\n func_probability = F.softmax(filtered_func_logits, dim=-1)\n func_pred = torch.multinomial(func_probability.reshape(-1, NUM_TIME_CODE), 1).reshape(func_probability.shape[:-1]).unsqueeze(1)\n\n function = torch.cat([function, func_pred], dim=1)\n if function.shape[1] == self.func_res*num_2bar:\n break\n \n\n \n function = function.reshape(batch, num_2bar, self.func_res, max_track).permute(0, 1, 3, 2)\n z_func = self.function_encoder.infer_by_codes(function)\n return self.QA_model.infer_with_function_codes(mix[0], prog[0].repeat(num_2bar, 1), z_func[0])\n \n def nucleus_filter(self, logits, p):\n #sorted_logits, sorted_indices = torch.sort(logits, descending=True)\n sorted_logits, sorted_indices = torch.sort(logits, dim=-1, descending=True)\n #cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)\n cum_sum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)\n\n # Remove tokens with cumulative probability above the threshold\n #sorted_indices_to_remove = cumulative_probs > p\n nucleus = cum_sum_probs < p\n # Shift the indices to the right to keep also the first token above the threshold\n #sorted_indices_to_remove = torch.cat([sorted_indices_to_remove.new_zeros(sorted_indices_to_remove.shape[:-1] + (1,)), sorted_indices_to_remove[..., :-1]], dim=-1)\n nucleus = torch.cat([nucleus.new_ones(nucleus.shape[:-1] + (1,)), nucleus[..., :-1]], dim=-1)\n nucleus = nucleus.gather(-1, sorted_indices.argsort(-1))\n\n logits[~nucleus] = float('-inf')\n return logits\n \n\n\n @classmethod\n def init_model(cls, pretrain_model_path=None, DEVICE='cuda:0'):\n \"\"\"Fast model initialization.\"\"\"\n vqQaA = Query_and_reArrange(name='pretrain', trf_layers=2, device=DEVICE)\n if pretrain_model_path is not None:\n vqQaA.load_state_dict(torch.load(pretrain_model_path, map_location=torch.device('cpu')))\n vqQaA.eval()\n model = cls(vqQaA.mixture_enc, vqQaA.function_enc, DEVICE=DEVICE).to(DEVICE)\n return model\n \n @classmethod\n def init_inference_model(cls, prior_model_path, QA_model_path, DEVICE='cuda:0'):\n \"\"\"Fast model initialization.\"\"\"\n vqQaA = Query_and_reArrange(name='pretrain', trf_layers=2, device=DEVICE)\n vqQaA.load_state_dict(torch.load(QA_model_path, map_location=torch.device('cpu')))\n vqQaA.eval()\n model = cls(inference=True, QA_model=vqQaA, DEVICE=DEVICE).to(DEVICE)\n model.load_state_dict(torch.load(prior_model_path), strict=False)\n return model" }, { "identifier": "SLAKH_CLASS_PROGRAMS", "path": "orchestrator/QA_dataset.py", "snippet": "SLAKH_CLASS_PROGRAMS = dict({\n 0: 'Acoustic Piano', #0\n 4: 'Electric Piano', #1\n 8: 'Chromatic Percussion',#2\n 16: 'Organ', #3\n 24: 'Acoustic Guitar', #4\n 26: 'Clean Electric Guitar', #5\n 29: 'Distorted Electric Guitar', #6\n 32: 'Acoustic Bass', #7\n 33: 'Electric Bass', #8\n 40: 'Violin', #9\n 41: 'Viola', #10\n 42: 'Cello', #11\n 43: 'Contrabass', #12\n 46: 'Orchestral Harp', #13\n 47: 'Timpani', #14\n 48: 'String Ensemble', #15\n 50: 'Synth Strings', #16\n 52: 'Choir and Voice', #17\n 55: 'Orchestral Hit', #18\n 56: 'Trumpet', #19\n 57: 'Trombone', #20\n 58: 'Tuba', #21\n 60: 'French Horn', #22\n 61: 'Brass Section', #23\n 64: 'Soprano/Alto Sax', #24\n 66: 'Tenor Sax', #25\n 67: 'Baritone Sax', #26\n 68: 'Oboe', #27\n 69: 'English Horn', #28\n 70: 'Bassoon', #29\n 71: 'Clarinet', #30\n 72: 'Pipe', #31\n 80: 'Synth Lead', #32\n 88: 'Synth Pad' #33\n})" }, { "identifier": "grid2pr", "path": "orchestrator/utils/format_convert.py", "snippet": "def grid2pr(grid, max_note_count=16, min_pitch=0, pitch_eos_ind=129):\n #grid: (time, max_simu_note, 6)\n if grid.shape[1] == max_note_count:\n grid = grid[:, 1:]\n pr = np.zeros((grid.shape[0], 128), dtype=int)\n for t in range(grid.shape[0]):\n for n in range(grid.shape[1]):\n note = grid[t, n]\n if note[0] == pitch_eos_ind:\n break\n pitch = note[0] + min_pitch\n dur = int(''.join([str(_) for _ in note[1:]]), 2) + 1\n pr[t, pitch] = dur\n return pr" }, { "identifier": "pr2grid", "path": "orchestrator/utils/format_convert.py", "snippet": "def pr2grid(pr_mat, max_note_count=16, max_pitch=127, min_pitch=0,\n pitch_pad_ind=130, dur_pad_ind=2,\n pitch_sos_ind=128, pitch_eos_ind=129):\n pr_mat3d = np.ones((len(pr_mat), max_note_count, 6), dtype=int) * dur_pad_ind\n pr_mat3d[:, :, 0] = pitch_pad_ind\n pr_mat3d[:, 0, 0] = pitch_sos_ind\n cur_idx = np.ones(len(pr_mat), dtype=int)\n for t, p in zip(*np.where(pr_mat != 0)):\n pr_mat3d[t, cur_idx[t], 0] = p - min_pitch\n binary = np.binary_repr(min(int(pr_mat[t, p]), 32) - 1, width=5)\n pr_mat3d[t, cur_idx[t], 1: 6] = \\\n np.fromstring(' '.join(list(binary)), dtype=int, sep=' ')\n if cur_idx[t] == max_note_count-1:\n continue\n cur_idx[t] += 1\n #print(cur_idx)\n pr_mat3d[np.arange(0, len(pr_mat)), cur_idx, 0] = pitch_eos_ind\n return pr_mat3d" }, { "identifier": "matrix2midi", "path": "orchestrator/utils/format_convert.py", "snippet": "def matrix2midi(matrices, programs, init_tempo=120, time_start=0):\n \"\"\"\n Reconstruct a multi-track midi from a 3D matrix of shape (Track. Time, 128).\n \"\"\"\n ACC = 16\n tracks = []\n for program in programs:\n track_recon = pyd.Instrument(program=int(program), is_drum=False, name=pyd.program_to_instrument_name(int(program)))\n tracks.append(track_recon)\n\n indices_track, indices_onset, indices_pitch = np.nonzero(matrices)\n alpha = 1 / (ACC // 4) * 60 / init_tempo #timetep between each quntization bin\n for idx in range(len(indices_track)):\n track_id = indices_track[idx]\n onset = indices_onset[idx]\n pitch = indices_pitch[idx]\n\n start = onset * alpha\n duration = matrices[track_id, onset, pitch] * alpha\n velocity = 100\n\n note_recon = pyd.Note(velocity=int(velocity), pitch=int(pitch), start=time_start + start, end=time_start + start + duration)\n tracks[track_id].notes.append(note_recon)\n \n midi_recon = pyd.PrettyMIDI(initial_tempo=init_tempo)\n midi_recon.instruments = tracks\n return midi_recon" }, { "identifier": "midi2matrix", "path": "orchestrator/utils/format_convert.py", "snippet": "def midi2matrix(midi, quaver):\n pr_matrices = []\n programs = []\n for track in midi.instruments:\n programs.append(track.program)\n pr_matrix = np.zeros((len(quaver), 128))\n for note in track.notes:\n note_start = np.argmin(np.abs(quaver - note.start))\n note_end = np.argmin(np.abs(quaver - note.end))\n if note_end == note_start:\n note_end = min(note_start + 1, len(quaver) - 1)\n pr_matrix[note_start, note.pitch] = note_end - note_start\n pr_matrices.append(pr_matrix)\n return np.array(pr_matrices), np.array(programs)" }, { "identifier": "TOTAL_LEN_BIN", "path": "orchestrator/prior_dataset.py", "snippet": "TOTAL_LEN_BIN = np.array([4, 7, 12, 15, 20, 23, 28, 31, 36, 39, 44, 47, 52, 55, 60, 63, 68, 71, 76, 79, 84, 87, 92, 95, 100, 103, 108, 111, 116, 119, 124, 127, 132])" }, { "identifier": "ABS_POS_BIN", "path": "orchestrator/prior_dataset.py", "snippet": "ABS_POS_BIN = np.arange(129)" }, { "identifier": "REL_POS_BIN", "path": "orchestrator/prior_dataset.py", "snippet": "REL_POS_BIN = np.arange(128)" } ]
import os import pretty_midi as pyd import numpy as np import torch import piano_arranger.format_converter as cvt from torch.utils.data import DataLoader from scipy.interpolate import interp1d from tqdm import tqdm from piano_arranger.acc_utils import split_phrases from piano_arranger.models import DisentangleVAE from piano_arranger.AccoMontage import find_by_length, dp_search, re_harmonization, get_texture_filter, ref_spotlight from orchestrator import Slakh2100_Pop909_Dataset, collate_fn, compute_pr_feat, EMBED_PROGRAM_MAPPING, Prior from orchestrator.QA_dataset import SLAKH_CLASS_PROGRAMS from orchestrator.utils import grid2pr, pr2grid, matrix2midi, midi2matrix from orchestrator.prior_dataset import TOTAL_LEN_BIN, ABS_POS_BIN, REL_POS_BIN
18,249
SLAKH_CLASS_MAPPING = {v: k for k, v in EMBED_PROGRAM_MAPPING.items()} def load_premise(DATA_FILE_ROOT, DEVICE): """Load AccoMontage Search Space""" print('Loading AccoMontage piano texture search space. This may take 1 or 2 minutes ...') data = np.load(os.path.join(DATA_FILE_ROOT, 'phrase_data.npz'), allow_pickle=True) melody = data['melody'] acc = data['acc'] chord = data['chord'] vel = data['velocity'] cc = data['cc'] acc_pool = {} for LEN in tqdm(range(2, 13)): (mel, acc_, chord_, vel_, cc_, song_reference) = find_by_length(melody, acc, chord, vel, cc, LEN) acc_pool[LEN] = (mel, acc_, chord_, vel_, cc_, song_reference) texture_filter = get_texture_filter(acc_pool) edge_weights=np.load(os.path.join(DATA_FILE_ROOT, 'edge_weights.npz'), allow_pickle=True) """Load Q&A Prompt Search Space""" print('loading orchestration prompt search space ...') slakh_dir = os.path.join(DATA_FILE_ROOT, 'Slakh2100_inference_set') dataset = Slakh2100_Pop909_Dataset(slakh_dir=slakh_dir, pop909_dir=None, debug_mode=False, split='validation', mode='train') loader = DataLoader(dataset, batch_size=1, shuffle=True, collate_fn=lambda b:collate_fn(b, DEVICE)) REF = [] REF_PROG = [] REF_MIX = [] for (_, prog, function, _, _, _) in loader: prog = prog[0, :] REF.extend([batch for batch in function]) REF_PROG.extend([prog for _ in range(len(function))]) REF_MIX.append(torch.sum(function, dim=1)) REF_MIX = torch.cat(REF_MIX, dim=0) """Initialize orchestration model (Prior + Q&A)""" print('Initialize model ...') prior_model_path = os.path.join(DATA_FILE_ROOT, 'params_prior.pt') QaA_model_path = os.path.join(DATA_FILE_ROOT, 'params_qa.pt') orchestrator = Prior.init_inference_model(prior_model_path, QaA_model_path, DEVICE=DEVICE) orchestrator.to(DEVICE) orchestrator.eval() piano_arranger = DisentangleVAE.init_model(torch.device('cuda')).cuda() piano_arranger.load_state_dict(torch.load(os.path.join(DATA_FILE_ROOT, 'params_reharmonizer.pt'))) print('Finished.') return piano_arranger, orchestrator, (acc_pool, edge_weights, texture_filter), (REF, REF_PROG, REF_MIX) def read_lead_sheet(DEMO_ROOT, SONG_NAME, SEGMENTATION, NOTE_SHIFT, melody_track_ID=0): melody_roll, chord_roll = cvt.leadsheet2matrix(os.path.join(DEMO_ROOT, SONG_NAME, 'lead sheet.mid'), melody_track_ID) assert(len(melody_roll == len(chord_roll))) if NOTE_SHIFT != 0: melody_roll = melody_roll[int(NOTE_SHIFT*4):, :] chord_roll = chord_roll[int(NOTE_SHIFT*4):, :] if len(melody_roll) % 16 != 0: pad_len = (len(melody_roll)//16+1)*16-len(melody_roll) melody_roll = np.pad(melody_roll, ((0, pad_len), (0, 0))) melody_roll[-pad_len:, -1] = 1 chord_roll = np.pad(chord_roll, ((0, pad_len), (0, 0))) chord_roll[-pad_len:, 0] = -1 chord_roll[-pad_len:, -1] = -1 CHORD_TABLE = np.stack([cvt.expand_chord(chord) for chord in chord_roll[::4]], axis=0) LEADSHEET = np.concatenate((melody_roll, chord_roll[:, 1: -1]), axis=-1) #T*142, quantized at 16th
SLAKH_CLASS_MAPPING = {v: k for k, v in EMBED_PROGRAM_MAPPING.items()} def load_premise(DATA_FILE_ROOT, DEVICE): """Load AccoMontage Search Space""" print('Loading AccoMontage piano texture search space. This may take 1 or 2 minutes ...') data = np.load(os.path.join(DATA_FILE_ROOT, 'phrase_data.npz'), allow_pickle=True) melody = data['melody'] acc = data['acc'] chord = data['chord'] vel = data['velocity'] cc = data['cc'] acc_pool = {} for LEN in tqdm(range(2, 13)): (mel, acc_, chord_, vel_, cc_, song_reference) = find_by_length(melody, acc, chord, vel, cc, LEN) acc_pool[LEN] = (mel, acc_, chord_, vel_, cc_, song_reference) texture_filter = get_texture_filter(acc_pool) edge_weights=np.load(os.path.join(DATA_FILE_ROOT, 'edge_weights.npz'), allow_pickle=True) """Load Q&A Prompt Search Space""" print('loading orchestration prompt search space ...') slakh_dir = os.path.join(DATA_FILE_ROOT, 'Slakh2100_inference_set') dataset = Slakh2100_Pop909_Dataset(slakh_dir=slakh_dir, pop909_dir=None, debug_mode=False, split='validation', mode='train') loader = DataLoader(dataset, batch_size=1, shuffle=True, collate_fn=lambda b:collate_fn(b, DEVICE)) REF = [] REF_PROG = [] REF_MIX = [] for (_, prog, function, _, _, _) in loader: prog = prog[0, :] REF.extend([batch for batch in function]) REF_PROG.extend([prog for _ in range(len(function))]) REF_MIX.append(torch.sum(function, dim=1)) REF_MIX = torch.cat(REF_MIX, dim=0) """Initialize orchestration model (Prior + Q&A)""" print('Initialize model ...') prior_model_path = os.path.join(DATA_FILE_ROOT, 'params_prior.pt') QaA_model_path = os.path.join(DATA_FILE_ROOT, 'params_qa.pt') orchestrator = Prior.init_inference_model(prior_model_path, QaA_model_path, DEVICE=DEVICE) orchestrator.to(DEVICE) orchestrator.eval() piano_arranger = DisentangleVAE.init_model(torch.device('cuda')).cuda() piano_arranger.load_state_dict(torch.load(os.path.join(DATA_FILE_ROOT, 'params_reharmonizer.pt'))) print('Finished.') return piano_arranger, orchestrator, (acc_pool, edge_weights, texture_filter), (REF, REF_PROG, REF_MIX) def read_lead_sheet(DEMO_ROOT, SONG_NAME, SEGMENTATION, NOTE_SHIFT, melody_track_ID=0): melody_roll, chord_roll = cvt.leadsheet2matrix(os.path.join(DEMO_ROOT, SONG_NAME, 'lead sheet.mid'), melody_track_ID) assert(len(melody_roll == len(chord_roll))) if NOTE_SHIFT != 0: melody_roll = melody_roll[int(NOTE_SHIFT*4):, :] chord_roll = chord_roll[int(NOTE_SHIFT*4):, :] if len(melody_roll) % 16 != 0: pad_len = (len(melody_roll)//16+1)*16-len(melody_roll) melody_roll = np.pad(melody_roll, ((0, pad_len), (0, 0))) melody_roll[-pad_len:, -1] = 1 chord_roll = np.pad(chord_roll, ((0, pad_len), (0, 0))) chord_roll[-pad_len:, 0] = -1 chord_roll[-pad_len:, -1] = -1 CHORD_TABLE = np.stack([cvt.expand_chord(chord) for chord in chord_roll[::4]], axis=0) LEADSHEET = np.concatenate((melody_roll, chord_roll[:, 1: -1]), axis=-1) #T*142, quantized at 16th
query_phrases = split_phrases(SEGMENTATION) #[('A', 8, 0), ('A', 8, 8), ('B', 8, 16), ('B', 8, 24)]
0
2023-10-23 12:36:57+00:00
24k
liuqidong07/MOELoRA-peft
src/MLoRA/peft/peft_model.py
[ { "identifier": "PeftConfig", "path": "src/MLoRA/peft/utils/config.py", "snippet": "class PeftConfig(PeftConfigMixin):\n \"\"\"\n This is the base configuration class to store the configuration of a [`PeftModel`].\n\n Args:\n peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use.\n task_type (Union[[`~peft.utils.config.TaskType`], `str`]): The type of task to perform.\n inference_mode (`bool`, defaults to `False`): Whether to use the Peft model in inference mode.\n \"\"\"\n\n base_model_name_or_path: str = field(default=None, metadata={\"help\": \"The name of the base model to use.\"})\n peft_type: Union[str, PeftType] = field(default=None, metadata={\"help\": \"Peft type\"})\n task_type: Union[str, TaskType] = field(default=None, metadata={\"help\": \"Task type\"})\n inference_mode: bool = field(default=False, metadata={\"help\": \"Whether to use inference mode\"})" }, { "identifier": "Gate", "path": "src/MLoRA/peft/shared.py", "snippet": "class Gate(nn.Module):\n \"\"\"Gate\"\"\"\n def __init__(self, peft_config: PeftConfig, adapter_name=\"default\"):\n\n super().__init__()\n\n self.expert_num = peft_config.expert_num\n self.task_num = peft_config.task_num\n self.te_dim = peft_config.task_embedding_dim\n\n #self.lora_task_embedding = nn.Embedding(self.task_num+1, self.te_dim)# 使用embedding来代替线性层\n self.GateL = nn.Linear(self.te_dim, self.expert_num, bias=False)\n self.act = nn.Softmax(dim=1) # 第0维为batch size\n \n def forward(self, task_em):\n\n #task_em = self.lora_task_embedding(x)\n y = self.GateL(task_em)\n y = self.act(y)\n\n return y" }, { "identifier": "GateN", "path": "src/MLoRA/peft/shared.py", "snippet": "class GateN(nn.Module):\n \"\"\"Gate New Function\"\"\"\n def __init__(self, expert_num, task_embedding_dim):\n\n super().__init__()\n\n self.expert_num = expert_num\n self.te_dim = task_embedding_dim\n\n self.GateL = nn.Linear(self.te_dim, self.expert_num, bias=False)\n self.act = nn.Softmax(dim=1) # 第0维为batch size\n \n def forward(self, task_em):\n\n #task_em = self.lora_task_embedding(x)\n y = self.GateL(task_em)\n y = self.act(y)\n\n return y" }, { "identifier": "AdaptionPromptModel", "path": "src/MLoRA/peft/tuners/adaption_prompt.py", "snippet": "class AdaptionPromptModel(nn.Module):\n \"\"\"\n Implements adaption prompts as described in https://arxiv.org/pdf/2303.16199.pdf.\n\n The top L attention modules are replaced with AdaptedAttention modules that wrap the original ones, but insert\n trainable prompts with gates (for zero init).\n\n Notes on the multi-adapter pattern:\n - We store the states of different adapters by keeping a dictionary of AdaptedAttention modules indexed by adapter\n name.\n - Every time we switch adapters, we remove the modules of the currently active adapter from the model, store them\n in the dictionary, and replace them with the modules of the new adapter.\n - To avoid duplicated and potentially inconsistent state, the currently active adapter is always removed from the\n dictionary.\n - Disabling the adapter would also result in the modules being removed from the model.\n \"\"\"\n\n def __init__(self, model, configs: Dict, adapter_name: str):\n super().__init__()\n self.model = model\n # Store adapter configs by name.\n self._configs: Dict[str, AdaptionPromptConfig] = {}\n # Store lists of the parents of the affected attention modules by adapter name.\n # We keep references to the parents so we can swap the adapters in-and-out of the model.\n self._parents: Dict[str, List[nn.Module]] = {}\n # Store lists of cached AdaptedAttention modules by name.\n self._cached_adapters: Dict[str, List] = {}\n # The name of the currently active adapter.\n self._active_adapter = None\n # Whether the adapter is enabled.\n self._enabled = True\n self.forward = self.model.forward\n self.add_adapter(adapter_name, configs[adapter_name])\n self._mark_only_adaption_prompts_as_trainable()\n\n def add_adapter(self, adapter_name: str, config: AdaptionPromptConfig) -> None:\n \"\"\"Add an adapter with the given name and config.\"\"\"\n config = prepare_config(config, self.model)\n if adapter_name in self._configs:\n raise ValueError(f\"Adapter with name '{adapter_name}' already exists.\")\n\n parents = []\n for name, _ in self.model.named_modules():\n if name.endswith(config.target_modules):\n par, _, _ = _get_submodules(self.model, name)\n parents.append(par)\n if len(parents) < config.adapter_layers:\n raise ValueError(\n f\"Config specifies more adapter layers '{config.adapter_layers}'\"\n f\" than the model has '{len(parents)}'.\"\n )\n # Note that if the target modules are not in Sequential, ModuleList, or\n # some other PyTorch ordered container, the behavior is undefined as we\n # assume here that the order of the modules is the same as the order of\n # the transformer decoder layers.\n parents = parents[-config.adapter_layers :]\n self._parents[adapter_name] = parents\n\n # It is only None during initialization.\n # If it is disabled, we don't have to remove the modules.\n if self._active_adapter is not None and self._enabled:\n self._remove_adapted_attentions(self._active_adapter)\n self._active_adapter = adapter_name\n self._configs[adapter_name] = config\n self._create_adapted_attentions(config, parents)\n if not self._enabled:\n self._remove_adapted_attentions(self._active_adapter)\n\n if config.inference_mode:\n _freeze_adapter(self.model, adapter_name)\n\n def set_adapter(self, adapter_name: str) -> None:\n \"\"\"Set the model to use the adapter with the given name.\"\"\"\n if self._active_adapter == adapter_name:\n return\n if adapter_name not in self._configs:\n raise ValueError(f\"Adapter with name '{adapter_name}' does not exist.\")\n\n if self._enabled:\n self._remove_adapted_attentions(self._active_adapter)\n self._set_adapted_attentions(adapter_name)\n\n self._active_adapter = adapter_name\n\n def enable_adapter_layers(self):\n \"\"\"Enable adapter layers by swapping in cached AdaptedAttention modules.\"\"\"\n self._enabled = True\n self._set_adapted_attentions(self._active_adapter)\n\n def disable_adapter_layers(self):\n \"\"\"Disable adapter layers by swapping out AdaptedAttention modules.\"\"\"\n self._enabled = False\n self._remove_adapted_attentions(self._active_adapter)\n\n def _create_adapted_attentions(self, config: AdaptionPromptConfig, parents: List[nn.Module]) -> None:\n \"\"\"Wrap LlamaAttention modules with newly created AdaptedAttention modules.\"\"\"\n for par in parents:\n attn = AdaptedAttention(\n model_type=self.model.config.model_type,\n adapter_len=config.adapter_len,\n model=getattr(par, config.target_modules),\n )\n setattr(par, config.target_modules, attn)\n\n def _set_adapted_attentions(self, adapter_name: str) -> None:\n \"\"\"Replace LlamaAttention modules with cached AdaptedAttention modules.\"\"\"\n cached = self._cached_adapters[adapter_name]\n del self._cached_adapters[adapter_name]\n config = self._configs[adapter_name]\n for i, par in enumerate(self._parents[adapter_name]):\n setattr(par, config.target_modules, cached[i])\n\n def _remove_adapted_attentions(self, adapter_name: str) -> None:\n \"\"\"Remove AdaptedAttention modules from the model and store them in the cache.\"\"\"\n config = self._configs[adapter_name]\n adapted_attentions = []\n for par in self._parents[adapter_name]:\n attn = getattr(par, config.target_modules)\n adapted_attentions.append(attn)\n setattr(par, config.target_modules, attn.model)\n self._cached_adapters[adapter_name] = adapted_attentions\n\n def _mark_only_adaption_prompts_as_trainable(self) -> None:\n \"\"\"Freeze all parameters of the model except the adaption prompts.\"\"\"\n for n, p in self.model.named_parameters():\n if not is_adaption_prompt_trainable(n):\n p.requires_grad = False\n\n def __getattr__(self, name: str):\n \"\"\"Forward missing attributes to the wrapped module.\"\"\"\n try:\n return super().__getattr__(name) # defer to nn.Module's logic\n except AttributeError:\n # This is necessary as e.g. causal models have various methods that we\n # don't want to re-implement here.\n return getattr(self.model, name)" }, { "identifier": "LoraModel", "path": "src/MLoRA/peft/tuners/lora.py", "snippet": "class LoraModel(torch.nn.Module):\n \"\"\"\n Creates Low Rank Adapter (Lora) model from a pretrained transformers model.\n\n Args:\n model ([`~transformers.PreTrainedModel`]): The model to be adapted.\n config ([`LoraConfig`]): The configuration of the Lora model.\n\n Returns:\n `torch.nn.Module`: The Lora model.\n\n Example:\n\n ```py\n >>> from transformers import AutoModelForSeq2SeqLM, LoraConfig\n >>> from peft import LoraModel, LoraConfig\n\n >>> config = LoraConfig(\n ... peft_type=\"LORA\",\n ... task_type=\"SEQ_2_SEQ_LM\",\n ... r=8,\n ... lora_alpha=32,\n ... target_modules=[\"q\", \"v\"],\n ... lora_dropout=0.01,\n ... )\n\n >>> model = AutoModelForSeq2SeqLM.from_pretrained(\"t5-base\")\n >>> lora_model = LoraModel(config, model)\n ```\n\n **Attributes**:\n - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.\n - **peft_config** ([`LoraConfig`]): The configuration of the Lora model.\n \"\"\"\n\n def __init__(self, model, config, adapter_name):\n super().__init__()\n self.model = model\n self.forward = self.model.forward\n self.peft_config = config\n self.add_adapter(adapter_name, self.peft_config[adapter_name])\n\n def add_adapter(self, adapter_name, config=None):\n if config is not None:\n model_config = self.model.config.to_dict() if hasattr(self.model.config, \"to_dict\") else self.model.config\n config = self._prepare_lora_config(config, model_config)\n self.peft_config[adapter_name] = config\n self._find_and_replace(adapter_name)\n if len(self.peft_config) > 1 and self.peft_config[adapter_name].bias != \"none\":\n raise ValueError(\n \"LoraModel supports only 1 adapter with bias. When using multiple adapters, set bias to 'none' for all adapters.\"\n )\n mark_only_lora_as_trainable(self.model, self.peft_config[adapter_name].bias) # freeze all layers except for lora layer\n if self.peft_config[adapter_name].inference_mode: # if inference, also freeze lora layer\n _freeze_adapter(self.model, adapter_name)\n\n def _find_and_replace(self, adapter_name):\n \"\"\"Replace the target `Linear` module with LoRA layer (Linear+LoRA)\"\"\"\n lora_config = self.peft_config[adapter_name]\n loaded_in_8bit = getattr(self.model, \"is_loaded_in_8bit\", False)\n if loaded_in_8bit and not is_bnb_available():\n raise ImportError(\n \"To use Lora with 8-bit quantization, please install the `bitsandbytes` package. \"\n \"You can install it with `pip install bitsandbytes`.\"\n )\n is_target_modules_in_base_model = False\n kwargs = {\n \"r\": lora_config.r,\n \"lora_alpha\": lora_config.lora_alpha,\n \"lora_dropout\": lora_config.lora_dropout,\n \"fan_in_fan_out\": lora_config.fan_in_fan_out,\n \"init_lora_weights\": lora_config.init_lora_weights,\n }\n key_list = [key for key, _ in self.model.named_modules()]\n for key in key_list:\n if isinstance(lora_config.target_modules, str):\n target_module_found = re.fullmatch(lora_config.target_modules, key)\n else:\n target_module_found = any(key.endswith(target_key) for target_key in lora_config.target_modules)\n if target_module_found:\n if not is_target_modules_in_base_model:\n is_target_modules_in_base_model = True\n parent, target, target_name = _get_submodules(self.model, key) # parent: the parent mudle of target (e.g., SelfAttention), target: target module (e.g., nn.Linear()), target name: the name of target module (e.g., query_key_value)\n bias = target.bias is not None\n if isinstance(target, LoraLayer): # if the target is LoraLayer, only need to update the parameters\n target.update_layer(\n adapter_name,\n lora_config.r,\n lora_config.lora_alpha,\n lora_config.lora_dropout,\n lora_config.init_lora_weights,\n )\n else: # if not, get the lora parameter for create.\n if loaded_in_8bit and isinstance(target, bnb.nn.Linear8bitLt):\n eightbit_kwargs = kwargs.copy()\n eightbit_kwargs.update(\n {\n \"has_fp16_weights\": target.state.has_fp16_weights,\n \"memory_efficient_backward\": target.state.memory_efficient_backward,\n \"threshold\": target.state.threshold,\n \"index\": target.index,\n }\n )\n new_module = Linear8bitLt(\n adapter_name, target.in_features, target.out_features, bias=bias, **eightbit_kwargs\n )\n else: # create based on the original module type\n if isinstance(target, torch.nn.Linear):\n in_features, out_features = target.in_features, target.out_features\n if kwargs[\"fan_in_fan_out\"]:\n warnings.warn(\n \"fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. \"\n \"Setting fan_in_fan_out to False.\"\n )\n kwargs[\"fan_in_fan_out\"] = lora_config.fan_in_fan_out = False\n elif isinstance(target, Conv1D):\n in_features, out_features = (\n target.weight.ds_shape if hasattr(target.weight, \"ds_shape\") else target.weight.shape\n )\n if not kwargs[\"fan_in_fan_out\"]:\n warnings.warn(\n \"fan_in_fan_out is set to False but the target module is `Conv1D`. \"\n \"Setting fan_in_fan_out to True.\"\n )\n kwargs[\"fan_in_fan_out\"] = lora_config.fan_in_fan_out = True\n else:\n raise ValueError(\n f\"Target module {target} is not supported. \"\n f\"Currently, only `torch.nn.Linear` and `Conv1D` are supported.\"\n )\n new_module = Linear(adapter_name, in_features, out_features, bias=bias, **kwargs) # create the lora module, here is not the raw nn.Linear, but the lora layer\n\n self._replace_module(parent, target_name, new_module, target)\n if not is_target_modules_in_base_model:\n raise ValueError(\n f\"Target modules {lora_config.target_modules} not found in the base model. \"\n f\"Please check the target modules and try again.\"\n )\n\n def _replace_module(self, parent_module, child_name, new_module, old_module):\n \"\"\"substitute the original nn.Linear to new Linear (nn.Linear+LoRA block)\"\"\"\n setattr(parent_module, child_name, new_module)\n new_module.weight = old_module.weight\n if old_module.bias is not None:\n new_module.bias = old_module.bias\n if getattr(old_module, \"state\", None) is not None: # synchronize the state and device\n new_module.state = old_module.state\n new_module.to(old_module.weight.device)\n\n # dispatch to correct device\n for name, module in new_module.named_modules():\n if \"lora_\" in name:\n module.to(old_module.weight.device)\n\n def __getattr__(self, name: str):\n \"\"\"Forward missing attributes to the wrapped module.\"\"\"\n try:\n return super().__getattr__(name) # defer to nn.Module's logic\n except AttributeError:\n return getattr(self.model, name)\n\n def get_peft_config_as_dict(self, inference: bool = False):\n config_dict = {}\n for key, value in self.peft_config.items():\n config = {k: v.value if isinstance(v, Enum) else v for k, v in asdict(value).items()}\n if inference:\n config[\"inference_mode\"] = True\n config_dict[key] = config\n return config\n\n def _set_adapter_layers(self, enabled=True):\n for module in self.model.modules():\n if isinstance(module, LoraLayer):\n module.disable_adapters = False if enabled else True\n\n def enable_adapter_layers(self):\n self._set_adapter_layers(enabled=True)\n\n def disable_adapter_layers(self):\n self._set_adapter_layers(enabled=False)\n\n def set_adapter(self, adapter_name):\n for module in self.model.modules():\n if isinstance(module, LoraLayer):\n if module.merged:\n warnings.warn(\"Adapter cannot be set when the model is merged. Unmerging the model first.\")\n module.unmerge()\n module.active_adapter = adapter_name\n\n def merge_adapter(self):\n for module in self.model.modules():\n if isinstance(module, LoraLayer):\n module.merge()\n\n def unmerge_adapter(self):\n for module in self.model.modules():\n if isinstance(module, LoraLayer):\n module.unmerge()\n\n @staticmethod\n def _prepare_lora_config(peft_config, model_config):\n if peft_config.target_modules is None:\n if model_config[\"model_type\"] not in TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING:\n raise ValueError(\"Please specify `target_modules` in `peft_config`\")\n peft_config.target_modules = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING[model_config[\"model_type\"]]\n if peft_config.inference_mode:\n peft_config.merge_weights = True\n return peft_config\n\n def merge_and_unload(self):\n r\"\"\"\n This method merges the LoRa layers into the base model. This is needed if someone wants to use the base model\n as a standalone model.\n \"\"\"\n if getattr(self.config, \"model_type\", None) == \"gpt2\":\n raise ValueError(\"GPT2 models are not supported for merging LORA layers\")\n\n if getattr(self.model, \"is_loaded_in_8bit\", False):\n raise ValueError(\"Cannot merge LORA layers when the model is loaded in 8-bit mode\")\n\n key_list = [key for key, _ in self.model.named_modules() if \"lora\" not in key]\n for key in key_list:\n try:\n parent, target, target_name = _get_submodules(self.model, key)\n except AttributeError:\n continue\n if isinstance(target, LoraLayer):\n bias = target.bias is not None\n new_module = torch.nn.Linear(target.in_features, target.out_features, bias=bias)\n target.merge()\n self._replace_module(parent, target_name, new_module, target)\n\n # save any additional trainable modules part of `modules_to_save`\n if isinstance(target, ModulesToSaveWrapper):\n setattr(parent, target_name, target.modules_to_save[target.active_adapter])\n\n return self.model\n\n def add_weighted_adapter(self, adapters, weights, adapter_name):\n if len({self.peft_config[adapter].r for adapter in adapters}) != 1:\n raise ValueError(\"All adapters must have the same r value\")\n self.peft_config[adapter_name] = self.peft_config[adapters[0]]\n self.peft_config[adapter_name].lora_alpha = self.peft_config[adapters[0]].r\n self._find_and_replace(adapter_name)\n mark_only_lora_as_trainable(self.model, self.peft_config[adapter_name].bias)\n _freeze_adapter(self.model, adapter_name)\n key_list = [key for key, _ in self.model.named_modules() if \"lora\" not in key]\n for key in key_list:\n _, target, _ = _get_submodules(self.model, key)\n if isinstance(target, LoraLayer):\n target.lora_A[adapter_name].weight.data = target.lora_A[adapter_name].weight.data * 0.0\n target.lora_B[adapter_name].weight.data = target.lora_B[adapter_name].weight.data * 0.0\n for adapter, weight in zip(adapters, weights):\n if adapter not in target.lora_A:\n continue\n target.lora_A[adapter_name].weight.data += (\n target.lora_A[adapter].weight.data * weight * target.scaling[adapter]\n )\n target.lora_B[adapter_name].weight.data += target.lora_B[adapter].weight.data * weight" }, { "identifier": "AdaLoraModel", "path": "src/MLoRA/peft/tuners/adalora.py", "snippet": "class AdaLoraModel(LoraModel):\n \"\"\"\n Creates AdaLoRA (Adaptive LoRA) model from a pretrained transformers model. Paper:\n https://openreview.net/pdf?id=lq62uWRJjiY\n\n Args:\n model ([`transformers.PreTrainedModel`]): The model to be adapted.\n config ([`AdaLoraConfig`]): The configuration of the AdaLora model.\n\n Returns:\n `torch.nn.Module`: The AdaLora model.\n\n Example::\n\n >>> from transformers import AutoModelForSeq2SeqLM, LoraConfig >>> from peft import AdaLoraModel, AdaLoraConfig\n >>> config = AdaLoraConfig(\n peft_type=\"ADALORA\", task_type=\"SEQ_2_SEQ_LM\", r=8, lora_alpha=32, target_modules=[\"q\", \"v\"],\n lora_dropout=0.01,\n )\n >>> model = AutoModelForSeq2SeqLM.from_pretrained(\"t5-base\") >>> model = AdaLoraModel(config, model)\n\n **Attributes**:\n - **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted.\n - **peft_config** ([`AdaLoraConfig`]): The configuration of the AdaLora model.\n \"\"\"\n\n def __init__(self, model, config, adapter_name):\n nn.Module.__init__(self)\n self.model = model\n self.peft_config = config\n self.add_adapter(adapter_name, self.peft_config[adapter_name])\n\n def add_adapter(self, adapter_name, config=None):\n if config is not None:\n model_config = self.model.config.to_dict() if hasattr(self.model.config, \"to_dict\") else self.model.config\n config = self._prepare_adalora_config(config, model_config)\n self.peft_config[adapter_name] = config\n self._find_and_replace(adapter_name)\n if len(self.peft_config) > 1 and self.peft_config[adapter_name].bias != \"none\":\n raise ValueError(\n \"AdaLoraModel supports only 1 adapter with bias. When using multiple adapters, set bias to 'none' for all adapters.\"\n )\n traininable_mode_counter = 0\n for config in self.peft_config.values():\n if not config.inference_mode:\n traininable_mode_counter += 1\n\n if traininable_mode_counter > 1:\n raise ValueError(\n \"AdaLoraModel supports only 1 trainable adapter. \"\n \"When using multiple adapters, set inference_mode to True for all adapters except the one you want to train.\"\n )\n\n mark_only_lora_as_trainable(self.model, self.peft_config[adapter_name].bias)\n if self.peft_config[adapter_name].inference_mode:\n _freeze_adapter(self.model, adapter_name)\n else:\n self.trainable_adapter_name = adapter_name\n self.rankallocator = RankAllocator(self.model, self.peft_config[adapter_name], self.trainable_adapter_name)\n\n def _find_and_replace(self, adapter_name):\n lora_config = self.peft_config[adapter_name]\n loaded_in_8bit = getattr(self.model, \"is_loaded_in_8bit\", False)\n if loaded_in_8bit and not is_bnb_available():\n raise ImportError(\n \"To use Lora with 8-bit quantization, please install the `bitsandbytes` package. \"\n \"You can install it with `pip install bitsandbytes`.\"\n )\n is_target_modules_in_base_model = False\n kwargs = {\n \"r\": lora_config.init_r,\n \"lora_alpha\": lora_config.lora_alpha,\n \"lora_dropout\": lora_config.lora_dropout,\n \"fan_in_fan_out\": lora_config.fan_in_fan_out,\n \"init_lora_weights\": lora_config.init_lora_weights,\n }\n key_list = [key for key, _ in self.model.named_modules()]\n for key in key_list:\n if isinstance(lora_config.target_modules, str):\n target_module_found = re.fullmatch(lora_config.target_modules, key)\n else:\n target_module_found = any(key.endswith(target_key) for target_key in lora_config.target_modules)\n if target_module_found:\n if not is_target_modules_in_base_model:\n is_target_modules_in_base_model = True\n parent, target, target_name = _get_submodules(self.model, key)\n bias = target.bias is not None\n if isinstance(target, LoraLayer):\n target.update_layer(\n adapter_name,\n lora_config.init_r,\n lora_config.lora_alpha,\n lora_config.lora_dropout,\n lora_config.init_lora_weights,\n )\n else:\n if loaded_in_8bit and isinstance(target, bnb.nn.Linear8bitLt):\n kwargs.update(\n {\n \"has_fp16_weights\": target.state.has_fp16_weights,\n \"memory_efficient_backward\": target.state.memory_efficient_backward,\n \"threshold\": target.state.threshold,\n \"index\": target.index,\n }\n )\n new_module = SVDLinear8bitLt(\n adapter_name, target.in_features, target.out_features, bias=bias, **kwargs\n )\n else:\n if isinstance(target, torch.nn.Linear):\n in_features, out_features = target.in_features, target.out_features\n if kwargs[\"fan_in_fan_out\"]:\n warnings.warn(\n \"fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. \"\n \"Setting fan_in_fan_out to False.\"\n )\n kwargs[\"fan_in_fan_out\"] = lora_config.fan_in_fan_out = False\n elif isinstance(target, Conv1D):\n in_features, out_features = (\n target.weight.ds_shape if hasattr(target.weight, \"ds_shape\") else target.weight.shape\n )\n if not kwargs[\"fan_in_fan_out\"]:\n warnings.warn(\n \"fan_in_fan_out is set to False but the target module is `Conv1D`. \"\n \"Setting fan_in_fan_out to True.\"\n )\n kwargs[\"fan_in_fan_out\"] = lora_config.fan_in_fan_out = True\n else:\n raise ValueError(\n f\"Target module {target} is not supported. \"\n f\"Currently, only `torch.nn.Linear` and `Conv1D` are supported.\"\n )\n new_module = SVDLinear(adapter_name, in_features, out_features, bias=bias, **kwargs)\n\n self._replace_module(parent, target_name, new_module, target)\n if not is_target_modules_in_base_model:\n raise ValueError(\n f\"Target modules {lora_config.target_modules} not found in the base model. \"\n f\"Please check the target modules and try again.\"\n )\n\n def __getattr__(self, name: str):\n \"\"\"Forward missing attributes to the wrapped module.\"\"\"\n try:\n return super().__getattr__(name) # defer to nn.Module's logic\n except AttributeError:\n return getattr(self.model, name)\n\n def forward(self, *args, **kwargs):\n outputs = self.model.forward(*args, **kwargs)\n\n # Calculate the orthogonal regularization\n orth_reg_weight = self.peft_config[self.trainable_adapter_name].orth_reg_weight\n assert orth_reg_weight > 0\n\n if hasattr(outputs, \"loss\"):\n regu_loss = 0\n num_param = 0\n for n, p in self.model.named_parameters():\n if (\"lora_A\" in n or \"lora_B\" in n) and self.trainable_adapter_name in n:\n para_cov = p @ p.T if \"lora_A\" in n else p.T @ p\n I = torch.eye(*para_cov.size(), out=torch.empty_like(para_cov))\n I.requires_grad = False\n num_param += 1\n regu_loss += torch.norm(para_cov - I, p=\"fro\")\n regu_loss = regu_loss / num_param\n outputs.loss += orth_reg_weight * regu_loss\n return outputs\n\n def resize_modules_by_rank_pattern(self, rank_pattern, adapter_name):\n lora_config = self.peft_config[adapter_name]\n for name, rank_idx in rank_pattern.items():\n if isinstance(rank_idx, list):\n rank = sum(rank_idx)\n elif isinstance(rank_idx, torch.Tensor):\n rank_idx = rank_idx.view(-1)\n rank = rank_idx.sum().item()\n else:\n raise ValueError(\"Unexcepted type of rank_idx\")\n key = \".\".join(name.split(\".\")[0:-2]) if adapter_name in name else \".\".join(name.split(\".\")[0:-1])\n _, target, _ = _get_submodules(self.model, key)\n lora_E_weights = target.lora_E[adapter_name][rank_idx]\n lora_A_weights = target.lora_A[adapter_name][rank_idx]\n lora_B_weights = target.lora_B[adapter_name][:, rank_idx]\n ranknum = target.ranknum[adapter_name]\n target.update_layer(\n adapter_name,\n rank,\n lora_config.lora_alpha,\n lora_config.lora_dropout,\n lora_config.init_lora_weights,\n )\n with torch.no_grad():\n if rank > 0:\n target.lora_E[adapter_name].copy_(lora_E_weights)\n target.lora_A[adapter_name].copy_(lora_A_weights)\n target.lora_B[adapter_name].copy_(lora_B_weights)\n # The scaling is exactly as the previous\n target.ranknum[adapter_name].copy_(ranknum)\n\n def resize_state_dict_by_rank_pattern(self, rank_pattern, state_dict, adapter_name):\n for name, rank_idx in rank_pattern.items():\n rank = sum(rank_idx)\n prefix = \".\".join(name.split(\".\")[0:-2]) if adapter_name in name else \".\".join(name.split(\".\")[0:-1])\n for layer in [\"lora_E\", \"lora_A\", \"lora_B\"]:\n key = f\"base_model.model.{prefix}.{layer}.{adapter_name}\"\n if layer != \"lora_B\":\n state_dict[key] = (\n state_dict[key][rank_idx] if rank != state_dict[key].shape[0] else state_dict[key]\n )\n else:\n state_dict[key] = (\n state_dict[key][:, rank_idx] if rank != state_dict[key].shape[1] else state_dict[key]\n )\n return state_dict\n\n def update_and_allocate(self, global_step):\n lora_config = self.peft_config[self.trainable_adapter_name]\n # Update the importance score and allocate the budget\n if global_step < lora_config.total_step - lora_config.tfinal:\n _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step)\n if rank_pattern:\n lora_config.rank_pattern = rank_pattern\n # Finalize the budget allocation\n elif global_step == lora_config.total_step - lora_config.tfinal:\n _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step, force_mask=True)\n # for some reason, this freezes the trainable parameters and nothing gets updates\n # self.resize_modules_by_rank_pattern(rank_pattern, self.trainable_adapter_name)\n lora_config.rank_pattern = rank_pattern\n self.rankallocator.reset_ipt()\n # Currently using inefficient way to mask the unimportant weights using the rank pattern\n # due to problem mentioned above\n elif global_step > lora_config.total_step - lora_config.tfinal:\n self.rankallocator.mask_using_rank_pattern(self.model, lora_config.rank_pattern)\n # Pass the function and do forward propagation\n else:\n return None\n\n @staticmethod\n def _prepare_adalora_config(peft_config, model_config):\n if peft_config.target_modules is None:\n if model_config[\"model_type\"] not in TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING:\n raise ValueError(\"Please specify `target_modules` in `peft_config`\")\n peft_config.target_modules = TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING[\n model_config[\"model_type\"]\n ]\n if peft_config.inference_mode:\n peft_config.merge_weights = True\n return peft_config" }, { "identifier": "PromptEncoder", "path": "src/MLoRA/peft/tuners/p_tuning.py", "snippet": "class PromptEncoder(torch.nn.Module):\n \"\"\"\n The prompt encoder network that is used to generate the virtual token embeddings for p-tuning.\n\n Args:\n config ([`PromptEncoderConfig`]): The configuration of the prompt encoder.\n\n Example:\n\n ```py\n >>> from peft import PromptEncoder, PromptEncoderConfig\n\n >>> config = PromptEncoderConfig(\n ... peft_type=\"P_TUNING\",\n ... task_type=\"SEQ_2_SEQ_LM\",\n ... num_virtual_tokens=20,\n ... token_dim=768,\n ... num_transformer_submodules=1,\n ... num_attention_heads=12,\n ... num_layers=12,\n ... encoder_reparameterization_type=\"MLP\",\n ... encoder_hidden_size=768,\n ... )\n\n >>> prompt_encoder = PromptEncoder(config)\n ```\n\n **Attributes**:\n - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt encoder.\n - **mlp_head** (`torch.nn.Sequential`) -- The MLP head of the prompt encoder if `inference_mode=False`.\n - **lstm_head** (`torch.nn.LSTM`) -- The LSTM head of the prompt encoder if `inference_mode=False` and\n `encoder_reparameterization_type=\"LSTM\"`.\n - **token_dim** (`int`) -- The hidden embedding dimension of the base transformer model.\n - **input_size** (`int`) -- The input size of the prompt encoder.\n - **output_size** (`int`) -- The output size of the prompt encoder.\n - **hidden_size** (`int`) -- The hidden size of the prompt encoder.\n - **total_virtual_tokens** (`int`): The total number of virtual tokens of the\n prompt encoder.\n - **encoder_type** (Union[[`PromptEncoderReparameterizationType`], `str`]): The encoder type of the prompt\n encoder.\n\n\n Input shape: (`batch_size`, `total_virtual_tokens`)\n\n Output shape: (`batch_size`, `total_virtual_tokens`, `token_dim`)\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.token_dim = config.token_dim\n self.input_size = self.token_dim\n self.output_size = self.token_dim\n self.hidden_size = config.encoder_hidden_size\n self.total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules\n self.encoder_type = config.encoder_reparameterization_type\n\n # embedding\n self.embedding = torch.nn.Embedding(self.total_virtual_tokens, self.token_dim)\n if not config.inference_mode:\n if self.encoder_type == PromptEncoderReparameterizationType.LSTM:\n lstm_dropout = config.encoder_dropout\n num_layers = config.encoder_num_layers\n # LSTM\n self.lstm_head = torch.nn.LSTM(\n input_size=self.input_size,\n hidden_size=self.hidden_size,\n num_layers=num_layers,\n dropout=lstm_dropout,\n bidirectional=True,\n batch_first=True,\n )\n\n self.mlp_head = torch.nn.Sequential(\n torch.nn.Linear(self.hidden_size * 2, self.hidden_size * 2),\n torch.nn.ReLU(),\n torch.nn.Linear(self.hidden_size * 2, self.output_size),\n )\n\n elif self.encoder_type == PromptEncoderReparameterizationType.MLP:\n warnings.warn(\n f\"for {self.encoder_type}, the `encoder_num_layers` is ignored. Exactly 2 MLP layers are used.\"\n )\n layers = [\n torch.nn.Linear(self.input_size, self.hidden_size),\n torch.nn.ReLU(),\n torch.nn.Linear(self.hidden_size, self.hidden_size),\n torch.nn.ReLU(),\n torch.nn.Linear(self.hidden_size, self.output_size),\n ]\n self.mlp_head = torch.nn.Sequential(*layers)\n\n else:\n raise ValueError(\"Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.\")\n\n def forward(self, indices):\n input_embeds = self.embedding(indices)\n if self.encoder_type == PromptEncoderReparameterizationType.LSTM:\n output_embeds = self.mlp_head(self.lstm_head(input_embeds)[0])\n elif self.encoder_type == PromptEncoderReparameterizationType.MLP:\n output_embeds = self.mlp_head(input_embeds)\n else:\n raise ValueError(\"Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.\")\n\n return output_embeds" }, { "identifier": "PrefixEncoder", "path": "src/MLoRA/peft/tuners/prefix_tuning.py", "snippet": "class PrefixEncoder(torch.nn.Module):\n r\"\"\"\n The `torch.nn` model to encode the prefix.\n\n Args:\n config ([`PrefixTuningConfig`]): The configuration of the prefix encoder.\n\n Example:\n\n ```py\n >>> from peft import PrefixEncoder, PrefixTuningConfig\n\n >>> config = PrefixTuningConfig(\n ... peft_type=\"PREFIX_TUNING\",\n ... task_type=\"SEQ_2_SEQ_LM\",\n ... num_virtual_tokens=20,\n ... token_dim=768,\n ... num_transformer_submodules=1,\n ... num_attention_heads=12,\n ... num_layers=12,\n ... encoder_hidden_size=768,\n ... )\n >>> prefix_encoder = PrefixEncoder(config)\n ```\n\n **Attributes**:\n - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prefix encoder.\n - **transform** (`torch.nn.Sequential`) -- The two-layer MLP to transform the prefix embeddings if\n `prefix_projection` is `True`.\n - **prefix_projection** (`bool`) -- Whether to project the prefix embeddings.\n\n Input shape: (`batch_size`, `num_virtual_tokens`)\n\n Output shape: (`batch_size`, `num_virtual_tokens`, `2*layers*hidden`)\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.prefix_projection = config.prefix_projection\n token_dim = config.token_dim\n num_layers = config.num_layers\n encoder_hidden_size = config.encoder_hidden_size\n num_virtual_tokens = config.num_virtual_tokens\n if self.prefix_projection and not config.inference_mode:\n # Use a two-layer MLP to encode the prefix\n self.embedding = torch.nn.Embedding(num_virtual_tokens, token_dim)\n self.transform = torch.nn.Sequential(\n torch.nn.Linear(token_dim, encoder_hidden_size),\n torch.nn.Tanh(),\n torch.nn.Linear(encoder_hidden_size, num_layers * 2 * token_dim),\n )\n else:\n self.embedding = torch.nn.Embedding(num_virtual_tokens, num_layers * 2 * token_dim)\n\n def forward(self, prefix: torch.Tensor):\n if self.prefix_projection:\n prefix_tokens = self.embedding(prefix)\n past_key_values = self.transform(prefix_tokens)\n else:\n past_key_values = self.embedding(prefix)\n return past_key_values" }, { "identifier": "PromptEmbedding", "path": "src/MLoRA/peft/tuners/prompt_tuning.py", "snippet": "class PromptEmbedding(torch.nn.Module):\n \"\"\"\n The model to encode virtual tokens into prompt embeddings.\n\n Args:\n config ([`PromptTuningConfig`]): The configuration of the prompt embedding.\n word_embeddings (`torch.nn.Module`): The word embeddings of the base transformer model.\n\n **Attributes**:\n - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt embedding.\n\n Example:\n\n ```py\n >>> from peft import PromptEmbedding, PromptTuningConfig\n\n >>> config = PromptTuningConfig(\n ... peft_type=\"PROMPT_TUNING\",\n ... task_type=\"SEQ_2_SEQ_LM\",\n ... num_virtual_tokens=20,\n ... token_dim=768,\n ... num_transformer_submodules=1,\n ... num_attention_heads=12,\n ... num_layers=12,\n ... prompt_tuning_init=\"TEXT\",\n ... prompt_tuning_init_text=\"Predict if sentiment of this review is positive, negative or neutral\",\n ... tokenizer_name_or_path=\"t5-base\",\n ... )\n\n >>> # t5_model.shared is the word embeddings of the base model\n >>> prompt_embedding = PromptEmbedding(config, t5_model.shared)\n ```\n\n Input Shape: (`batch_size`, `total_virtual_tokens`)\n\n Output Shape: (`batch_size`, `total_virtual_tokens`, `token_dim`)\n \"\"\"\n\n def __init__(self, config, word_embeddings):\n super().__init__()\n\n total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules\n self.embedding = torch.nn.Embedding(total_virtual_tokens, config.token_dim)\n if config.prompt_tuning_init == PromptTuningInit.TEXT:\n from transformers import AutoTokenizer\n\n tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name_or_path)\n init_text = config.prompt_tuning_init_text\n init_token_ids = tokenizer(init_text)[\"input_ids\"]\n # Trim or iterate until num_text_tokens matches total_virtual_tokens\n num_text_tokens = len(init_token_ids)\n if num_text_tokens > total_virtual_tokens:\n init_token_ids = init_token_ids[:total_virtual_tokens]\n elif num_text_tokens < total_virtual_tokens:\n num_reps = math.ceil(total_virtual_tokens / num_text_tokens)\n init_token_ids = init_token_ids * num_reps\n init_token_ids = init_token_ids[:total_virtual_tokens]\n\n word_embedding_weights = word_embeddings(torch.LongTensor(init_token_ids)).detach().clone()\n word_embedding_weights = word_embedding_weights.to(torch.float32)\n self.embedding.weight = torch.nn.Parameter(word_embedding_weights)\n\n def forward(self, indices):\n # Just get embeddings\n prompt_embeddings = self.embedding(indices)\n return prompt_embeddings" }, { "identifier": "MMOELoraModelS", "path": "src/MLoRA/peft/tuners/mmoeloraS.py", "snippet": "class MMOELoraModelS(MMOELoraModel):\n\n def __init__(self, model, config, adapter_name):\n\n super().__init__(model, config, adapter_name)\n\n\n\n def _find_and_replace(self, adapter_name):\n \"\"\"Replace the target `Linear` module with LoRA layer (Linear+LoRA)\"\"\"\n lora_config = self.peft_config[adapter_name]\n loaded_in_8bit = getattr(self.model, \"is_loaded_in_8bit\", False)\n if loaded_in_8bit and not is_bnb_available():\n raise ImportError(\n \"To use Lora with 8-bit quantization, please install the `bitsandbytes` package. \"\n \"You can install it with `pip install bitsandbytes`.\"\n )\n is_target_modules_in_base_model = False\n kwargs = {\n \"r\": lora_config.r,\n \"lora_alpha\": lora_config.lora_alpha,\n \"lora_dropout\": lora_config.lora_dropout,\n \"fan_in_fan_out\": lora_config.fan_in_fan_out,\n \"init_lora_weights\": lora_config.init_lora_weights,\n \"task_num\": lora_config.task_num,\n \"task_embedding_dim\": lora_config.task_embedding_dim,\n \"expert_num\": lora_config.expert_num,\n }\n key_list = [key for key, _ in self.model.named_modules()] # all module in raw model\n for key in key_list:\n # find the corresponding modules. target module has been split into list.\n if isinstance(lora_config.target_modules, str):\n target_module_found = re.fullmatch(lora_config.target_modules, key)\n else:\n target_module_found = any(key.endswith(target_key) for target_key in lora_config.target_modules)\n if target_module_found:\n if not is_target_modules_in_base_model:\n is_target_modules_in_base_model = True\n parent, target, target_name = _get_submodules(self.model, key)\n bias = target.bias is not None\n if isinstance(target, MMOELoraLayer):\n target.update_layer(\n adapter_name,\n lora_config.init_r,\n lora_config.lora_alpha,\n lora_config.lora_dropout,\n lora_config.init_lora_weights,\n )\n else:\n if loaded_in_8bit and isinstance(target, bnb.nn.Linear8bitLt):\n raise NotImplementedError\n else:\n if isinstance(target, torch.nn.Linear):\n in_features, out_features = target.in_features, target.out_features\n if kwargs[\"fan_in_fan_out\"]:\n warnings.warn(\n \"fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. \"\n \"Setting fan_in_fan_out to False.\"\n )\n kwargs[\"fan_in_fan_out\"] = lora_config.fan_in_fan_out = False\n elif isinstance(target, Conv1D):\n in_features, out_features = (\n target.weight.ds_shape if hasattr(target.weight, \"ds_shape\") else target.weight.shape\n )\n if not kwargs[\"fan_in_fan_out\"]:\n warnings.warn(\n \"fan_in_fan_out is set to False but the target module is `Conv1D`. \"\n \"Setting fan_in_fan_out to True.\"\n )\n kwargs[\"fan_in_fan_out\"] = lora_config.fan_in_fan_out = True\n else:\n raise ValueError(\n f\"Target module {target} is not supported. \"\n f\"Currently, only `torch.nn.Linear` and `Conv1D` are supported.\"\n )\n new_module = MMOELoraLinearS(adapter_name, in_features, out_features, \n bias=bias, **kwargs)\n\n self._replace_module(parent, target_name, new_module, target)\n if not is_target_modules_in_base_model:\n raise ValueError(\n f\"Target modules {lora_config.target_modules} not found in the base model. \"\n f\"Please check the target modules and try again.\"\n )" }, { "identifier": "PeftConfig", "path": "src/MLoRA/peft/utils/config.py", "snippet": "class PeftConfig(PeftConfigMixin):\n \"\"\"\n This is the base configuration class to store the configuration of a [`PeftModel`].\n\n Args:\n peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use.\n task_type (Union[[`~peft.utils.config.TaskType`], `str`]): The type of task to perform.\n inference_mode (`bool`, defaults to `False`): Whether to use the Peft model in inference mode.\n \"\"\"\n\n base_model_name_or_path: str = field(default=None, metadata={\"help\": \"The name of the base model to use.\"})\n peft_type: Union[str, PeftType] = field(default=None, metadata={\"help\": \"Peft type\"})\n task_type: Union[str, TaskType] = field(default=None, metadata={\"help\": \"Task type\"})\n inference_mode: bool = field(default=False, metadata={\"help\": \"Whether to use inference mode\"})" }, { "identifier": "PeftType", "path": "src/MLoRA/peft/utils/config.py", "snippet": "class PeftType(str, enum.Enum):\n PROMPT_TUNING = \"PROMPT_TUNING\"\n P_TUNING = \"P_TUNING\"\n PREFIX_TUNING = \"PREFIX_TUNING\"\n LORA = \"LORA\"\n ADALORA = \"ADALORA\"\n ADAPTION_PROMPT = \"ADAPTION_PROMPT\"\n MMOELORAS = \"MMOELORAS\"" }, { "identifier": "PromptLearningConfig", "path": "src/MLoRA/peft/utils/config.py", "snippet": "class PromptLearningConfig(PeftConfig):\n \"\"\"\n This is the base configuration class to store the configuration of [`PrefixTuning`], [`PromptEncoder`], or\n [`PromptTuning`].\n\n Args:\n num_virtual_tokens (`int`): The number of virtual tokens to use.\n token_dim (`int`): The hidden embedding dimension of the base transformer model.\n num_transformer_submodules (`int`): The number of transformer submodules in the base transformer model.\n num_attention_heads (`int`): The number of attention heads in the base transformer model.\n num_layers (`int`): The number of layers in the base transformer model.\n \"\"\"\n\n num_virtual_tokens: int = field(default=None, metadata={\"help\": \"Number of virtual tokens\"})\n token_dim: int = field(\n default=None, metadata={\"help\": \"The hidden embedding dimension of the base transformer model\"}\n )\n num_transformer_submodules: Optional[int] = field(\n default=None, metadata={\"help\": \"Number of transformer submodules\"}\n )\n num_attention_heads: Optional[int] = field(default=None, metadata={\"help\": \"Number of attention heads\"})\n num_layers: Optional[int] = field(default=None, metadata={\"help\": \"Number of transformer layers\"})" }, { "identifier": "TaskType", "path": "src/MLoRA/peft/utils/config.py", "snippet": "class TaskType(str, enum.Enum):\n SEQ_CLS = \"SEQ_CLS\"\n SEQ_2_SEQ_LM = \"SEQ_2_SEQ_LM\"\n CAUSAL_LM = \"CAUSAL_LM\"\n TOKEN_CLS = \"TOKEN_CLS\"\n CAUSAL_LMS = \"CAUSAL_LMS\"" }, { "identifier": "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", "path": "src/MLoRA/peft/utils/other.py", "snippet": "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING = {\n \"bloom\": bloom_model_postprocess_past_key_value,\n}" }, { "identifier": "WEIGHTS_NAME", "path": "src/MLoRA/peft/utils/other.py", "snippet": "WEIGHTS_NAME = \"adapter_model.bin\"" }, { "identifier": "_set_trainable", "path": "src/MLoRA/peft/utils/other.py", "snippet": "def _set_trainable(model, adapter_name):\n key_list = [key for key, _ in model.named_modules()]\n for key in key_list:\n target_module_found = any(key.endswith(target_key) for target_key in model.modules_to_save)\n if target_module_found:\n parent, target, target_name = _get_submodules(model, key)\n if isinstance(target, ModulesToSaveWrapper):\n target.update(adapter_name)\n else:\n for param in target.parameters():\n param.requires_grad = True\n setattr(parent, target_name, ModulesToSaveWrapper(target, adapter_name))" }, { "identifier": "shift_tokens_right", "path": "src/MLoRA/peft/utils/other.py", "snippet": "def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):\n \"\"\"\n Shift input ids one token to the right.\n\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): input ids\n pad_token_id (`int`): The id of the `padding` token.\n decoder_start_token_id (`int`): The id of the `start` token.\n \"\"\"\n shifted_input_ids = input_ids.new_zeros(input_ids.shape)\n shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()\n shifted_input_ids[:, 0] = decoder_start_token_id\n\n if pad_token_id is None:\n raise ValueError(\"self.model.config.pad_token_id has to be defined.\")\n # replace possible -100 values in labels by `pad_token_id`\n shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)\n\n return shifted_input_ids" }, { "identifier": "_set_adapter", "path": "src/MLoRA/peft/utils/other.py", "snippet": "def _set_adapter(model, adapter_name):\n for module in model.modules():\n if isinstance(module, ModulesToSaveWrapper):\n module.active_adapter = adapter_name" }, { "identifier": "get_peft_model_state_dict", "path": "src/MLoRA/peft/utils/save_and_load.py", "snippet": "def get_peft_model_state_dict(model, state_dict=None, adapter_name=\"default\"):\n \"\"\"\n Get the state dict of the Peft model.\n\n Args:\n model ([`PeftModel`]): The Peft model. When using torch.nn.DistributedDataParallel, DeepSpeed or FSDP,\n the model should be the underlying model/unwrapped model (i.e. model.module).\n state_dict (`dict`, *optional*, defaults to `None`):\n The state dict of the model. If not provided, the state dict of the model\n will be used.\n \"\"\"\n config = model.peft_config[adapter_name]\n if state_dict is None:\n state_dict = model.state_dict()\n if config.peft_type in (PeftType.LORA, PeftType.ADALORA,\n PeftType.MMOELORAS):\n # to_return = lora_state_dict(model, bias=model.peft_config.bias)\n # adapted from `https://github.com/microsoft/LoRA/blob/main/loralib/utils.py`\n # to be used directly with the state dict which is necessary when using DeepSpeed or FSDP\n bias = config.bias\n if bias == \"none\": # filter out all lora parameters\n to_return = {k: state_dict[k] for k in state_dict if \"lora_\" in k}\n elif bias == \"all\":\n to_return = {k: state_dict[k] for k in state_dict if \"lora_\" in k or \"bias\" in k}\n elif bias == \"lora_only\":\n to_return = {}\n for k in state_dict:\n if \"lora_\" in k:\n to_return[k] = state_dict[k]\n bias_name = k.split(\"lora_\")[0] + \"bias\"\n if bias_name in state_dict:\n to_return[bias_name] = state_dict[bias_name]\n else:\n raise NotImplementedError\n to_return = {k: v for k, v in to_return.items() if ((\"lora_\" in k and adapter_name in k) or (\"bias\" in k))}\n\n if config.peft_type == PeftType.ADALORA:\n rank_pattern = config.rank_pattern\n if rank_pattern is not None:\n rank_pattern = {k.replace(f\".{adapter_name}\", \"\"): v for k, v in rank_pattern.items()}\n config.rank_pattern = rank_pattern\n to_return = model.resize_state_dict_by_rank_pattern(rank_pattern, to_return, adapter_name)\n\n elif config.peft_type == PeftType.ADAPTION_PROMPT:\n to_return = {k: state_dict[k] for k in state_dict if k.split(\".\")[-1].startswith(\"adaption_\")}\n elif isinstance(config, PromptLearningConfig):\n to_return = {}\n if config.inference_mode:\n prompt_embeddings = model.prompt_encoder[adapter_name].embedding.weight\n else:\n prompt_embeddings = model.get_prompt_embedding_to_save(adapter_name)\n to_return[\"prompt_embeddings\"] = prompt_embeddings\n else:\n raise NotImplementedError\n if model.modules_to_save is not None:\n for key, value in state_dict.items():\n if any(f\"{module_name}.modules_to_save.{adapter_name}\" in key for module_name in model.modules_to_save):\n to_return[key.replace(\"modules_to_save.\", \"\")] = value\n\n to_return = {k.replace(f\".{adapter_name}\", \"\"): v for k, v in to_return.items()}\n return to_return" }, { "identifier": "set_peft_model_state_dict", "path": "src/MLoRA/peft/utils/save_and_load.py", "snippet": "def set_peft_model_state_dict(model, peft_model_state_dict, adapter_name=\"default\"):\n \"\"\"\n Set the state dict of the Peft model.\n\n Args:\n model ([`PeftModel`]): The Peft model.\n peft_model_state_dict (`dict`): The state dict of the Peft model.\n \"\"\"\n config = model.peft_config[adapter_name]\n state_dict = {}\n if model.modules_to_save is not None:\n for key, value in peft_model_state_dict.items():\n if any(module_name in key for module_name in model.modules_to_save):\n for module_name in model.modules_to_save:\n if module_name in key:\n key = key.replace(module_name, f\"{module_name}.modules_to_save.{adapter_name}\")\n break\n state_dict[key] = value\n else:\n state_dict = peft_model_state_dict\n\n if config.peft_type in (PeftType.LORA, PeftType.ADALORA,\n PeftType.MMOELORAS):\n peft_model_state_dict = {}\n for k, v in state_dict.items():\n if \"lora_\" in k:\n suffix = k.split(\"lora_\")[1]\n if \".\" in suffix:\n suffix_to_replace = \".\".join(suffix.split(\".\")[1:])\n k = k.replace(suffix_to_replace, f\"{adapter_name}.{suffix_to_replace}\")\n else:\n k = f\"{k}.{adapter_name}\"\n peft_model_state_dict[k] = v\n else:\n peft_model_state_dict[k] = v\n if config.peft_type == PeftType.ADALORA:\n rank_pattern = config.rank_pattern\n if rank_pattern is not None:\n model.resize_modules_by_rank_pattern(rank_pattern, adapter_name)\n elif isinstance(config, PromptLearningConfig) or config.peft_type == PeftType.ADAPTION_PROMPT:\n peft_model_state_dict = state_dict\n else:\n raise NotImplementedError\n\n model.load_state_dict(peft_model_state_dict, strict=False)\n if isinstance(config, PromptLearningConfig):\n model.prompt_encoder[adapter_name].embedding.load_state_dict(\n {\"weight\": peft_model_state_dict[\"prompt_embeddings\"]}, strict=True\n )" } ]
import inspect import os import warnings import torch import torch.nn as nn from contextlib import contextmanager from accelerate import dispatch_model, infer_auto_device_map from accelerate.hooks import AlignDevicesHook, add_hook_to_module, remove_hook_from_submodules from accelerate.utils import get_balanced_memory from huggingface_hub import hf_hub_download from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers import PreTrainedModel from transformers.modeling_outputs import SequenceClassifierOutput, TokenClassifierOutput from transformers.utils import PushToHubMixin from .utils import PeftConfig from .shared import Gate, GateN from .tuners import ( AdaLoraModel, AdaptionPromptModel, LoraModel, PrefixEncoder, PromptEmbedding, PromptEncoder, MMOELoraModelS, ) from .utils import ( TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, WEIGHTS_NAME, PeftConfig, PeftType, PromptLearningConfig, TaskType, _set_adapter, _set_trainable, get_peft_model_state_dict, set_peft_model_state_dict, shift_tokens_right, ) from .mapping import MODEL_TYPE_TO_PEFT_MODEL_MAPPING, PEFT_TYPE_TO_CONFIG_MAPPING from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING
14,470
# coding=utf-8 # Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. PEFT_TYPE_TO_MODEL_MAPPING = { PeftType.LORA: LoraModel, PeftType.PROMPT_TUNING: PromptEmbedding, PeftType.P_TUNING: PromptEncoder,
# coding=utf-8 # Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. PEFT_TYPE_TO_MODEL_MAPPING = { PeftType.LORA: LoraModel, PeftType.PROMPT_TUNING: PromptEmbedding, PeftType.P_TUNING: PromptEncoder,
PeftType.PREFIX_TUNING: PrefixEncoder,
7
2023-10-19 10:55:50+00:00
24k
YuroFR/freqtrade-modded-crypto-trading-bot
freqtrade/exchange/exchange.py
[ { "identifier": "DEFAULT_AMOUNT_RESERVE_PERCENT", "path": "freqtrade/constants.py", "snippet": "DOCS_LINK = \"https://www.freqtrade.io/en/stable\"\nDEFAULT_CONFIG = 'config.json'\nPROCESS_THROTTLE_SECS = 5 # sec\nHYPEROPT_EPOCH = 100 # epochs\nRETRY_TIMEOUT = 30 # sec\nTIMEOUT_UNITS = ['minutes', 'seconds']\nEXPORT_OPTIONS = ['none', 'trades', 'signals']\nDEFAULT_DB_PROD_URL = 'sqlite:///tradesv3.sqlite'\nDEFAULT_DB_DRYRUN_URL = 'sqlite:///tradesv3.dryrun.sqlite'\nUNLIMITED_STAKE_AMOUNT = 'unlimited'\nDEFAULT_AMOUNT_RESERVE_PERCENT = 0.05\nREQUIRED_ORDERTIF = ['entry', 'exit']\nREQUIRED_ORDERTYPES = ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']\nPRICING_SIDES = ['ask', 'bid', 'same', 'other']\nORDERTYPE_POSSIBILITIES = ['limit', 'market']\n_ORDERTIF_POSSIBILITIES = ['GTC', 'FOK', 'IOC', 'PO']\nORDERTIF_POSSIBILITIES = _ORDERTIF_POSSIBILITIES + [t.lower() for t in _ORDERTIF_POSSIBILITIES]\nSTOPLOSS_PRICE_TYPES = [p for p in PriceType]\nHYPEROPT_LOSS_BUILTIN = ['ShortTradeDurHyperOptLoss', 'OnlyProfitHyperOptLoss',\n 'SharpeHyperOptLoss', 'SharpeHyperOptLossDaily',\n 'SortinoHyperOptLoss', 'SortinoHyperOptLossDaily',\n 'CalmarHyperOptLoss',\n 'MaxDrawDownHyperOptLoss', 'MaxDrawDownRelativeHyperOptLoss',\n 'ProfitDrawDownHyperOptLoss']\nAVAILABLE_PAIRLISTS = ['StaticPairList', 'VolumePairList', 'ProducerPairList', 'RemotePairList',\n 'AgeFilter', \"FullTradesFilter\", 'OffsetFilter', 'PerformanceFilter',\n 'PrecisionFilter', 'PriceFilter', 'RangeStabilityFilter',\n 'ShuffleFilter', 'SpreadFilter', 'VolatilityFilter']\nAVAILABLE_PROTECTIONS = ['CooldownPeriod',\n 'LowProfitPairs', 'MaxDrawdown', 'StoplossGuard']\nAVAILABLE_DATAHANDLERS = ['json', 'jsongz', 'hdf5', 'feather', 'parquet']\nBACKTEST_BREAKDOWNS = ['day', 'week', 'month']\nBACKTEST_CACHE_AGE = ['none', 'day', 'week', 'month']\nBACKTEST_CACHE_DEFAULT = 'day'\nDRY_RUN_WALLET = 1000\nDATETIME_PRINT_FORMAT = '%Y-%m-%d %H:%M:%S'\nMATH_CLOSE_PREC = 1e-14 # Precision used for float comparisons\nDEFAULT_DATAFRAME_COLUMNS = ['date', 'open', 'high', 'low', 'close', 'volume']\nDEFAULT_TRADES_COLUMNS = ['timestamp', 'id', 'type', 'side', 'price', 'amount', 'cost']\nTRADES_DTYPES = {\n 'timestamp': 'int64',\n 'id': 'str',\n 'type': 'str',\n 'side': 'str',\n 'price': 'float64',\n 'amount': 'float64',\n 'cost': 'float64',\n}\nTRADING_MODES = ['spot', 'margin', 'futures']\nMARGIN_MODES = ['cross', 'isolated', '']\nLAST_BT_RESULT_FN = '.last_result.json'\nFTHYPT_FILEVERSION = 'fthypt_fileversion'\nUSERPATH_HYPEROPTS = 'hyperopts'\nUSERPATH_STRATEGIES = 'strategies'\nUSERPATH_NOTEBOOKS = 'notebooks'\nUSERPATH_FREQAIMODELS = 'freqaimodels'\nTELEGRAM_SETTING_OPTIONS = ['on', 'off', 'silent']\nWEBHOOK_FORMAT_OPTIONS = ['form', 'json', 'raw']\nFULL_DATAFRAME_THRESHOLD = 100\nCUSTOM_TAG_MAX_LENGTH = 255\nDL_DATA_TIMEFRAMES = ['1m', '5m']\nENV_VAR_PREFIX = 'FREQTRADE__'\nCANCELED_EXCHANGE_STATES = ('cancelled', 'canceled', 'expired')\nNON_OPEN_EXCHANGE_STATES = CANCELED_EXCHANGE_STATES + ('closed',)\nDECIMAL_PER_COIN_FALLBACK = 3 # Should be low to avoid listing all possible FIAT's\nDECIMALS_PER_COIN = {\n 'BTC': 8,\n 'ETH': 5,\n}\nDUST_PER_COIN = {\n 'BTC': 0.0001,\n 'ETH': 0.01\n}\nUSER_DATA_FILES = {\n 'sample_strategy.py': USERPATH_STRATEGIES,\n 'sample_hyperopt_loss.py': USERPATH_HYPEROPTS,\n 'strategy_analysis_example.ipynb': USERPATH_NOTEBOOKS,\n}\nSUPPORTED_FIAT = [\n \"AUD\", \"BRL\", \"CAD\", \"CHF\", \"CLP\", \"CNY\", \"CZK\", \"DKK\",\n \"EUR\", \"GBP\", \"HKD\", \"HUF\", \"IDR\", \"ILS\", \"INR\", \"JPY\",\n \"KRW\", \"MXN\", \"MYR\", \"NOK\", \"NZD\", \"PHP\", \"PKR\", \"PLN\",\n \"RUB\", \"UAH\", \"SEK\", \"SGD\", \"THB\", \"TRY\", \"TWD\", \"ZAR\",\n \"USD\", \"BTC\", \"ETH\", \"XRP\", \"LTC\", \"BCH\"\n]\nMINIMAL_CONFIG = {\n \"stake_currency\": \"\",\n \"dry_run\": True,\n \"exchange\": {\n \"name\": \"\",\n \"key\": \"\",\n \"secret\": \"\",\n \"pair_whitelist\": [],\n \"ccxt_async_config\": {\n }\n }\n}\n__MESSAGE_TYPE_DICT: Dict[str, Dict[str, str]] = {x: {'type': 'object'} for x in RPCMessageType}\nCONF_SCHEMA = {\n 'type': 'object',\n 'properties': {\n 'max_open_trades': {'type': ['integer', 'number'], 'minimum': -1},\n 'new_pairs_days': {'type': 'integer', 'default': 30},\n 'timeframe': {'type': 'string'},\n 'stake_currency': {'type': 'string'},\n 'stake_amount': {\n 'type': ['number', 'string'],\n 'minimum': 0.0001,\n 'pattern': UNLIMITED_STAKE_AMOUNT\n },\n 'tradable_balance_ratio': {\n 'type': 'number',\n 'minimum': 0.0,\n 'maximum': 1,\n 'default': 0.99\n },\n 'available_capital': {\n 'type': 'number',\n 'minimum': 0,\n },\n 'amend_last_stake_amount': {'type': 'boolean', 'default': False},\n 'last_stake_amount_min_ratio': {\n 'type': 'number', 'minimum': 0.0, 'maximum': 1.0, 'default': 0.5\n },\n 'fiat_display_currency': {'type': 'string', 'enum': SUPPORTED_FIAT},\n 'dry_run': {'type': 'boolean'},\n 'dry_run_wallet': {'type': 'number', 'default': DRY_RUN_WALLET},\n 'cancel_open_orders_on_exit': {'type': 'boolean', 'default': False},\n 'process_only_new_candles': {'type': 'boolean'},\n 'minimal_roi': {\n 'type': 'object',\n 'patternProperties': {\n '^[0-9.]+$': {'type': 'number'}\n },\n },\n 'amount_reserve_percent': {'type': 'number', 'minimum': 0.0, 'maximum': 0.5},\n 'stoploss': {'type': 'number', 'maximum': 0, 'exclusiveMaximum': True},\n 'trailing_stop': {'type': 'boolean'},\n 'trailing_stop_positive': {'type': 'number', 'minimum': 0, 'maximum': 1},\n 'trailing_stop_positive_offset': {'type': 'number', 'minimum': 0, 'maximum': 1},\n 'trailing_only_offset_is_reached': {'type': 'boolean'},\n 'use_exit_signal': {'type': 'boolean'},\n 'exit_profit_only': {'type': 'boolean'},\n 'exit_profit_offset': {'type': 'number'},\n 'ignore_roi_if_entry_signal': {'type': 'boolean'},\n 'ignore_buying_expired_candle_after': {'type': 'number'},\n 'trading_mode': {'type': 'string', 'enum': TRADING_MODES},\n 'margin_mode': {'type': 'string', 'enum': MARGIN_MODES},\n 'reduce_df_footprint': {'type': 'boolean', 'default': False},\n 'minimum_trade_amount': {'type': 'number', 'default': 10},\n 'targeted_trade_amount': {'type': 'number', 'default': 20},\n 'lookahead_analysis_exportfilename': {'type': 'string'},\n 'startup_candle': {\n 'type': 'array',\n 'uniqueItems': True,\n 'default': [199, 399, 499, 999, 1999],\n },\n 'liquidation_buffer': {'type': 'number', 'minimum': 0.0, 'maximum': 0.99},\n 'backtest_breakdown': {\n 'type': 'array',\n 'items': {'type': 'string', 'enum': BACKTEST_BREAKDOWNS}\n },\n 'bot_name': {'type': 'string'},\n 'unfilledtimeout': {\n 'type': 'object',\n 'properties': {\n 'entry': {'type': 'number', 'minimum': 1},\n 'exit': {'type': 'number', 'minimum': 1},\n 'exit_timeout_count': {'type': 'number', 'minimum': 0, 'default': 0},\n 'unit': {'type': 'string', 'enum': TIMEOUT_UNITS, 'default': 'minutes'}\n }\n },\n 'entry_pricing': {\n 'type': 'object',\n 'properties': {\n 'price_last_balance': {\n 'type': 'number',\n 'minimum': 0,\n 'maximum': 1,\n 'exclusiveMaximum': False,\n },\n 'price_side': {'type': 'string', 'enum': PRICING_SIDES, 'default': 'same'},\n 'use_order_book': {'type': 'boolean'},\n 'order_book_top': {'type': 'integer', 'minimum': 1, 'maximum': 50, },\n 'check_depth_of_market': {\n 'type': 'object',\n 'properties': {\n 'enabled': {'type': 'boolean'},\n 'bids_to_ask_delta': {'type': 'number', 'minimum': 0},\n }\n },\n },\n 'required': ['price_side']\n },\n 'exit_pricing': {\n 'type': 'object',\n 'properties': {\n 'price_side': {'type': 'string', 'enum': PRICING_SIDES, 'default': 'same'},\n 'price_last_balance': {\n 'type': 'number',\n 'minimum': 0,\n 'maximum': 1,\n 'exclusiveMaximum': False,\n },\n 'use_order_book': {'type': 'boolean'},\n 'order_book_top': {'type': 'integer', 'minimum': 1, 'maximum': 50, },\n },\n 'required': ['price_side']\n },\n 'custom_price_max_distance_ratio': {\n 'type': 'number', 'minimum': 0.0\n },\n 'order_types': {\n 'type': 'object',\n 'properties': {\n 'entry': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},\n 'exit': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},\n 'force_exit': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},\n 'force_entry': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},\n 'emergency_exit': {\n 'type': 'string',\n 'enum': ORDERTYPE_POSSIBILITIES,\n 'default': 'market'},\n 'stoploss': {'type': 'string', 'enum': ORDERTYPE_POSSIBILITIES},\n 'stoploss_on_exchange': {'type': 'boolean'},\n 'stoploss_price_type': {'type': 'string', 'enum': STOPLOSS_PRICE_TYPES},\n 'stoploss_on_exchange_interval': {'type': 'number'},\n 'stoploss_on_exchange_limit_ratio': {'type': 'number', 'minimum': 0.0,\n 'maximum': 1.0}\n },\n 'required': ['entry', 'exit', 'stoploss', 'stoploss_on_exchange']\n },\n 'order_time_in_force': {\n 'type': 'object',\n 'properties': {\n 'entry': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES},\n 'exit': {'type': 'string', 'enum': ORDERTIF_POSSIBILITIES}\n },\n 'required': REQUIRED_ORDERTIF\n },\n 'exchange': {'$ref': '#/definitions/exchange'},\n 'edge': {'$ref': '#/definitions/edge'},\n 'freqai': {'$ref': '#/definitions/freqai'},\n 'external_message_consumer': {'$ref': '#/definitions/external_message_consumer'},\n 'experimental': {\n 'type': 'object',\n 'properties': {\n 'block_bad_exchanges': {'type': 'boolean'}\n }\n },\n 'pairlists': {\n 'type': 'array',\n 'items': {\n 'type': 'object',\n 'properties': {\n 'method': {'type': 'string', 'enum': AVAILABLE_PAIRLISTS},\n },\n 'required': ['method'],\n }\n },\n 'protections': {\n 'type': 'array',\n 'items': {\n 'type': 'object',\n 'properties': {\n 'method': {'type': 'string', 'enum': AVAILABLE_PROTECTIONS},\n 'stop_duration': {'type': 'number', 'minimum': 0.0},\n 'stop_duration_candles': {'type': 'number', 'minimum': 0},\n 'trade_limit': {'type': 'number', 'minimum': 1},\n 'lookback_period': {'type': 'number', 'minimum': 1},\n 'lookback_period_candles': {'type': 'number', 'minimum': 1},\n },\n 'required': ['method'],\n }\n },\n 'telegram': {\n 'type': 'object',\n 'properties': {\n 'enabled': {'type': 'boolean'},\n 'token': {'type': 'string'},\n 'chat_id': {'type': 'string'},\n 'allow_custom_messages': {'type': 'boolean', 'default': True},\n 'balance_dust_level': {'type': 'number', 'minimum': 0.0},\n 'notification_settings': {\n 'type': 'object',\n 'default': {},\n 'properties': {\n 'status': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},\n 'warning': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},\n 'startup': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},\n 'entry': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},\n 'entry_fill': {\n 'type': 'string',\n 'enum': TELEGRAM_SETTING_OPTIONS,\n 'default': 'off'\n },\n 'entry_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS, },\n 'exit': {\n 'type': ['string', 'object'],\n 'additionalProperties': {\n 'type': 'string',\n 'enum': TELEGRAM_SETTING_OPTIONS\n }\n },\n 'exit_fill': {\n 'type': 'string',\n 'enum': TELEGRAM_SETTING_OPTIONS,\n 'default': 'on'\n },\n 'exit_cancel': {'type': 'string', 'enum': TELEGRAM_SETTING_OPTIONS},\n 'protection_trigger': {\n 'type': 'string',\n 'enum': TELEGRAM_SETTING_OPTIONS,\n 'default': 'on'\n },\n 'protection_trigger_global': {\n 'type': 'string',\n 'enum': TELEGRAM_SETTING_OPTIONS,\n 'default': 'on'\n },\n 'show_candle': {\n 'type': 'string',\n 'enum': ['off', 'ohlc'],\n 'default': 'off'\n },\n 'strategy_msg': {\n 'type': 'string',\n 'enum': TELEGRAM_SETTING_OPTIONS,\n 'default': 'on'\n },\n }\n },\n 'reload': {'type': 'boolean'},\n },\n 'required': ['enabled', 'token', 'chat_id'],\n },\n 'webhook': {\n 'type': 'object',\n 'properties': {\n 'enabled': {'type': 'boolean'},\n 'url': {'type': 'string'},\n 'format': {'type': 'string', 'enum': WEBHOOK_FORMAT_OPTIONS, 'default': 'form'},\n 'retries': {'type': 'integer', 'minimum': 0},\n 'retry_delay': {'type': 'number', 'minimum': 0},\n **__MESSAGE_TYPE_DICT,\n # **{x: {'type': 'object'} for x in RPCMessageType},\n # Below -> Deprecated\n 'webhookentry': {'type': 'object'},\n 'webhookentrycancel': {'type': 'object'},\n 'webhookentryfill': {'type': 'object'},\n 'webhookexit': {'type': 'object'},\n 'webhookexitcancel': {'type': 'object'},\n 'webhookexitfill': {'type': 'object'},\n 'webhookstatus': {'type': 'object'},\n },\n },\n 'discord': {\n 'type': 'object',\n 'properties': {\n 'enabled': {'type': 'boolean'},\n 'webhook_url': {'type': 'string'},\n \"exit_fill\": {\n 'type': 'array', 'items': {'type': 'object'},\n 'default': [\n {\"Trade ID\": \"{trade_id}\"},\n {\"Exchange\": \"{exchange}\"},\n {\"Pair\": \"{pair}\"},\n {\"Direction\": \"{direction}\"},\n {\"Open rate\": \"{open_rate}\"},\n {\"Close rate\": \"{close_rate}\"},\n {\"Amount\": \"{amount}\"},\n {\"Open date\": \"{open_date:%Y-%m-%d %H:%M:%S}\"},\n {\"Close date\": \"{close_date:%Y-%m-%d %H:%M:%S}\"},\n {\"Profit\": \"{profit_amount} {stake_currency}\"},\n {\"Profitability\": \"{profit_ratio:.2%}\"},\n {\"Enter tag\": \"{enter_tag}\"},\n {\"Exit Reason\": \"{exit_reason}\"},\n {\"Strategy\": \"{strategy}\"},\n {\"Timeframe\": \"{timeframe}\"},\n ]\n },\n \"entry_fill\": {\n 'type': 'array', 'items': {'type': 'object'},\n 'default': [\n {\"Trade ID\": \"{trade_id}\"},\n {\"Exchange\": \"{exchange}\"},\n {\"Pair\": \"{pair}\"},\n {\"Direction\": \"{direction}\"},\n {\"Open rate\": \"{open_rate}\"},\n {\"Amount\": \"{amount}\"},\n {\"Open date\": \"{open_date:%Y-%m-%d %H:%M:%S}\"},\n {\"Enter tag\": \"{enter_tag}\"},\n {\"Strategy\": \"{strategy} {timeframe}\"},\n ]\n },\n }\n },\n 'api_server': {\n 'type': 'object',\n 'properties': {\n 'enabled': {'type': 'boolean'},\n 'listen_ip_address': {'format': 'ipv4'},\n 'listen_port': {\n 'type': 'integer',\n 'minimum': 1024,\n 'maximum': 65535\n },\n 'username': {'type': 'string'},\n 'password': {'type': 'string'},\n 'ws_token': {'type': ['string', 'array'], 'items': {'type': 'string'}},\n 'jwt_secret_key': {'type': 'string'},\n 'CORS_origins': {'type': 'array', 'items': {'type': 'string'}},\n 'verbosity': {'type': 'string', 'enum': ['error', 'info']},\n },\n 'required': ['enabled', 'listen_ip_address', 'listen_port', 'username', 'password']\n },\n 'db_url': {'type': 'string'},\n 'export': {'type': 'string', 'enum': EXPORT_OPTIONS, 'default': 'trades'},\n 'disableparamexport': {'type': 'boolean'},\n 'initial_state': {'type': 'string', 'enum': ['running', 'stopped']},\n 'force_entry_enable': {'type': 'boolean'},\n 'disable_dataframe_checks': {'type': 'boolean'},\n 'internals': {\n 'type': 'object',\n 'default': {},\n 'properties': {\n 'process_throttle_secs': {'type': 'integer'},\n 'interval': {'type': 'integer'},\n 'sd_notify': {'type': 'boolean'},\n }\n },\n 'dataformat_ohlcv': {\n 'type': 'string',\n 'enum': AVAILABLE_DATAHANDLERS,\n 'default': 'feather'\n },\n 'dataformat_trades': {\n 'type': 'string',\n 'enum': AVAILABLE_DATAHANDLERS,\n 'default': 'feather'\n },\n 'position_adjustment_enable': {'type': 'boolean'},\n 'max_entry_position_adjustment': {'type': ['integer', 'number'], 'minimum': -1},\n },\n 'definitions': {\n 'exchange': {\n 'type': 'object',\n 'properties': {\n 'name': {'type': 'string'},\n 'key': {'type': 'string', 'default': ''},\n 'secret': {'type': 'string', 'default': ''},\n 'password': {'type': 'string', 'default': ''},\n 'uid': {'type': 'string'},\n 'pair_whitelist': {\n 'type': 'array',\n 'items': {\n 'type': 'string',\n },\n 'uniqueItems': True\n },\n 'pair_blacklist': {\n 'type': 'array',\n 'items': {\n 'type': 'string',\n },\n 'uniqueItems': True\n },\n 'unknown_fee_rate': {'type': 'number'},\n 'outdated_offset': {'type': 'integer', 'minimum': 1},\n 'markets_refresh_interval': {'type': 'integer'},\n 'ccxt_config': {'type': 'object'},\n 'ccxt_async_config': {'type': 'object'}\n },\n 'required': ['name']\n },\n 'edge': {\n 'type': 'object',\n 'properties': {\n 'enabled': {'type': 'boolean'},\n 'process_throttle_secs': {'type': 'integer', 'minimum': 600},\n 'calculate_since_number_of_days': {'type': 'integer'},\n 'allowed_risk': {'type': 'number'},\n 'stoploss_range_min': {'type': 'number'},\n 'stoploss_range_max': {'type': 'number'},\n 'stoploss_range_step': {'type': 'number'},\n 'minimum_winrate': {'type': 'number'},\n 'minimum_expectancy': {'type': 'number'},\n 'min_trade_number': {'type': 'number'},\n 'max_trade_duration_minute': {'type': 'integer'},\n 'remove_pumps': {'type': 'boolean'}\n },\n 'required': ['process_throttle_secs', 'allowed_risk']\n },\n 'external_message_consumer': {\n 'type': 'object',\n 'properties': {\n 'enabled': {'type': 'boolean', 'default': False},\n 'producers': {\n 'type': 'array',\n 'items': {\n 'type': 'object',\n 'properties': {\n 'name': {'type': 'string'},\n 'host': {'type': 'string'},\n 'port': {\n 'type': 'integer',\n 'default': 8080,\n 'minimum': 0,\n 'maximum': 65535\n },\n 'secure': {'type': 'boolean', 'default': False},\n 'ws_token': {'type': 'string'},\n },\n 'required': ['name', 'host', 'ws_token']\n }\n },\n 'wait_timeout': {'type': 'integer', 'minimum': 0},\n 'sleep_time': {'type': 'integer', 'minimum': 0},\n 'ping_timeout': {'type': 'integer', 'minimum': 0},\n 'remove_entry_exit_signals': {'type': 'boolean', 'default': False},\n 'initial_candle_limit': {\n 'type': 'integer',\n 'minimum': 0,\n 'maximum': 1500,\n 'default': 1500\n },\n 'message_size_limit': { # In megabytes\n 'type': 'integer',\n 'minimum': 1,\n 'maxmium': 20,\n 'default': 8,\n }\n },\n 'required': ['producers']\n },\n \"freqai\": {\n \"type\": \"object\",\n \"properties\": {\n \"enabled\": {\"type\": \"boolean\", \"default\": False},\n \"keras\": {\"type\": \"boolean\", \"default\": False},\n \"write_metrics_to_disk\": {\"type\": \"boolean\", \"default\": False},\n \"purge_old_models\": {\"type\": [\"boolean\", \"number\"], \"default\": 2},\n \"conv_width\": {\"type\": \"integer\", \"default\": 1},\n \"train_period_days\": {\"type\": \"integer\", \"default\": 0},\n \"backtest_period_days\": {\"type\": \"number\", \"default\": 7},\n \"identifier\": {\"type\": \"string\", \"default\": \"example\"},\n \"feature_parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"include_corr_pairlist\": {\"type\": \"array\"},\n \"include_timeframes\": {\"type\": \"array\"},\n \"label_period_candles\": {\"type\": \"integer\"},\n \"include_shifted_candles\": {\"type\": \"integer\", \"default\": 0},\n \"DI_threshold\": {\"type\": \"number\", \"default\": 0},\n \"weight_factor\": {\"type\": \"number\", \"default\": 0},\n \"principal_component_analysis\": {\"type\": \"boolean\", \"default\": False},\n \"use_SVM_to_remove_outliers\": {\"type\": \"boolean\", \"default\": False},\n \"plot_feature_importances\": {\"type\": \"integer\", \"default\": 0},\n \"svm_params\": {\"type\": \"object\",\n \"properties\": {\n \"shuffle\": {\"type\": \"boolean\", \"default\": False},\n \"nu\": {\"type\": \"number\", \"default\": 0.1}\n },\n },\n \"shuffle_after_split\": {\"type\": \"boolean\", \"default\": False},\n \"buffer_train_data_candles\": {\"type\": \"integer\", \"default\": 0}\n },\n \"required\": [\"include_timeframes\", \"include_corr_pairlist\", ]\n },\n \"data_split_parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"test_size\": {\"type\": \"number\"},\n \"random_state\": {\"type\": \"integer\"},\n \"shuffle\": {\"type\": \"boolean\", \"default\": False}\n },\n },\n \"model_training_parameters\": {\n \"type\": \"object\"\n },\n \"rl_config\": {\n \"type\": \"object\",\n \"properties\": {\n \"drop_ohlc_from_features\": {\"type\": \"boolean\", \"default\": False},\n \"train_cycles\": {\"type\": \"integer\"},\n \"max_trade_duration_candles\": {\"type\": \"integer\"},\n \"add_state_info\": {\"type\": \"boolean\", \"default\": False},\n \"max_training_drawdown_pct\": {\"type\": \"number\", \"default\": 0.02},\n \"cpu_count\": {\"type\": \"integer\", \"default\": 1},\n \"model_type\": {\"type\": \"string\", \"default\": \"PPO\"},\n \"policy_type\": {\"type\": \"string\", \"default\": \"MlpPolicy\"},\n \"net_arch\": {\"type\": \"array\", \"default\": [128, 128]},\n \"randomize_starting_position\": {\"type\": \"boolean\", \"default\": False},\n \"progress_bar\": {\"type\": \"boolean\", \"default\": True},\n \"model_reward_parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"rr\": {\"type\": \"number\", \"default\": 1},\n \"profit_aim\": {\"type\": \"number\", \"default\": 0.025}\n }\n }\n },\n },\n },\n \"required\": [\n \"enabled\",\n \"train_period_days\",\n \"backtest_period_days\",\n \"identifier\",\n \"feature_parameters\",\n \"data_split_parameters\"\n ]\n },\n },\n}\nSCHEMA_TRADE_REQUIRED = [\n 'exchange',\n 'timeframe',\n 'max_open_trades',\n 'stake_currency',\n 'stake_amount',\n 'tradable_balance_ratio',\n 'last_stake_amount_min_ratio',\n 'dry_run',\n 'dry_run_wallet',\n 'exit_pricing',\n 'entry_pricing',\n 'stoploss',\n 'minimal_roi',\n 'internals',\n 'dataformat_ohlcv',\n 'dataformat_trades',\n]\nSCHEMA_BACKTEST_REQUIRED = [\n 'exchange',\n 'stake_currency',\n 'stake_amount',\n 'dry_run_wallet',\n 'dataformat_ohlcv',\n 'dataformat_trades',\n]\nSCHEMA_BACKTEST_REQUIRED_FINAL = SCHEMA_BACKTEST_REQUIRED + [\n 'stoploss',\n 'minimal_roi',\n 'max_open_trades'\n]\nSCHEMA_MINIMAL_REQUIRED = [\n 'exchange',\n 'dry_run',\n 'dataformat_ohlcv',\n 'dataformat_trades',\n]\nSCHEMA_MINIMAL_WEBSERVER = SCHEMA_MINIMAL_REQUIRED + [\n 'api_server',\n]\nCANCEL_REASON = {\n \"TIMEOUT\": \"cancelled due to timeout\",\n \"PARTIALLY_FILLED_KEEP_OPEN\": \"partially filled - keeping order open\",\n \"PARTIALLY_FILLED\": \"partially filled\",\n \"FULLY_CANCELLED\": \"fully cancelled\",\n \"ALL_CANCELLED\": \"cancelled (all unfilled and partially filled open orders cancelled)\",\n \"CANCELLED_ON_EXCHANGE\": \"cancelled on exchange\",\n \"FORCE_EXIT\": \"forcesold\",\n \"REPLACE\": \"cancelled to be replaced by new limit order\",\n \"REPLACE_FAILED\": \"failed to replace order, deleting Trade\",\n \"USER_CANCEL\": \"user requested order cancel\"\n}" }, { "identifier": "clean_ohlcv_dataframe", "path": "freqtrade/data/converter/converter.py", "snippet": "def clean_ohlcv_dataframe(data: DataFrame, timeframe: str, pair: str, *,\n fill_missing: bool, drop_incomplete: bool) -> DataFrame:\n \"\"\"\n Cleanse a OHLCV dataframe by\n * Grouping it by date (removes duplicate tics)\n * dropping last candles if requested\n * Filling up missing data (if requested)\n :param data: DataFrame containing candle (OHLCV) data.\n :param timeframe: timeframe (e.g. 5m). Used to fill up eventual missing data\n :param pair: Pair this data is for (used to warn if fillup was necessary)\n :param fill_missing: fill up missing candles with 0 candles\n (see ohlcv_fill_up_missing_data for details)\n :param drop_incomplete: Drop the last candle of the dataframe, assuming it's incomplete\n :return: DataFrame\n \"\"\"\n # group by index and aggregate results to eliminate duplicate ticks\n data = data.groupby(by='date', as_index=False, sort=True).agg({\n 'open': 'first',\n 'high': 'max',\n 'low': 'min',\n 'close': 'last',\n 'volume': 'max',\n })\n # eliminate partial candle\n if drop_incomplete:\n data.drop(data.tail(1).index, inplace=True)\n logger.debug('Dropping last candle')\n\n if fill_missing:\n return ohlcv_fill_up_missing_data(data, timeframe, pair)\n else:\n return data" }, { "identifier": "ohlcv_to_dataframe", "path": "freqtrade/data/converter/converter.py", "snippet": "def ohlcv_to_dataframe(ohlcv: list, timeframe: str, pair: str, *,\n fill_missing: bool = True, drop_incomplete: bool = True) -> DataFrame:\n \"\"\"\n Converts a list with candle (OHLCV) data (in format returned by ccxt.fetch_ohlcv)\n to a Dataframe\n :param ohlcv: list with candle (OHLCV) data, as returned by exchange.async_get_candle_history\n :param timeframe: timeframe (e.g. 5m). Used to fill up eventual missing data\n :param pair: Pair this data is for (used to warn if fillup was necessary)\n :param fill_missing: fill up missing candles with 0 candles\n (see ohlcv_fill_up_missing_data for details)\n :param drop_incomplete: Drop the last candle of the dataframe, assuming it's incomplete\n :return: DataFrame\n \"\"\"\n logger.debug(f\"Converting candle (OHLCV) data to dataframe for pair {pair}.\")\n cols = DEFAULT_DATAFRAME_COLUMNS\n df = DataFrame(ohlcv, columns=cols)\n\n df['date'] = to_datetime(df['date'], unit='ms', utc=True)\n\n # Some exchanges return int values for Volume and even for OHLC.\n # Convert them since TA-LIB indicators used in the strategy assume floats\n # and fail with exception...\n df = df.astype(dtype={'open': 'float', 'high': 'float', 'low': 'float', 'close': 'float',\n 'volume': 'float'})\n return clean_ohlcv_dataframe(df, timeframe, pair,\n fill_missing=fill_missing,\n drop_incomplete=drop_incomplete)" }, { "identifier": "trades_dict_to_list", "path": "freqtrade/data/converter/trade_converter.py", "snippet": "def trades_dict_to_list(trades: List[Dict]) -> TradeList:\n \"\"\"\n Convert fetch_trades result into a List (to be more memory efficient).\n :param trades: List of trades, as returned by ccxt.fetch_trades.\n :return: List of Lists, with constants.DEFAULT_TRADES_COLUMNS as columns\n \"\"\"\n return [[t[col] for col in DEFAULT_TRADES_COLUMNS] for t in trades]" }, { "identifier": "CandleType", "path": "freqtrade/enums/candletype.py", "snippet": "class CandleType(str, Enum):\n \"\"\"Enum to distinguish candle types\"\"\"\n SPOT = \"spot\"\n FUTURES = \"futures\"\n MARK = \"mark\"\n INDEX = \"index\"\n PREMIUMINDEX = \"premiumIndex\"\n\n # TODO: Could take up less memory if these weren't a CandleType\n FUNDING_RATE = \"funding_rate\"\n # BORROW_RATE = \"borrow_rate\" # * unimplemented\n\n def __str__(self):\n return f\"{self.name.lower()}\"\n\n @staticmethod\n def from_string(value: str) -> 'CandleType':\n if not value:\n # Default to spot\n return CandleType.SPOT\n return CandleType(value)\n\n @staticmethod\n def get_default(trading_mode: str) -> 'CandleType':\n if trading_mode == 'futures':\n return CandleType.FUTURES\n return CandleType.SPOT" }, { "identifier": "MarginMode", "path": "freqtrade/enums/marginmode.py", "snippet": "class MarginMode(str, Enum):\n \"\"\"\n Enum to distinguish between\n cross margin/futures margin_mode and\n isolated margin/futures margin_mode\n \"\"\"\n CROSS = \"cross\"\n ISOLATED = \"isolated\"\n NONE = ''" }, { "identifier": "PriceType", "path": "freqtrade/enums/pricetype.py", "snippet": "class PriceType(str, Enum):\n \"\"\"Enum to distinguish possible trigger prices for stoplosses\"\"\"\n LAST = \"last\"\n MARK = \"mark\"\n INDEX = \"index\"" }, { "identifier": "OPTIMIZE_MODES", "path": "freqtrade/enums/runmode.py", "snippet": "OPTIMIZE_MODES = [RunMode.BACKTEST, RunMode.EDGE, RunMode.HYPEROPT]" }, { "identifier": "TradingMode", "path": "freqtrade/enums/tradingmode.py", "snippet": "class TradingMode(str, Enum):\n \"\"\"\n Enum to distinguish between\n spot, margin, futures or any other trading method\n \"\"\"\n SPOT = \"spot\"\n MARGIN = \"margin\"\n FUTURES = \"futures\"" }, { "identifier": "DDosProtection", "path": "freqtrade/exceptions.py", "snippet": "class DDosProtection(TemporaryError):\n \"\"\"\n Temporary error caused by DDOS protection.\n Bot will wait for a second and then retry.\n \"\"\"" }, { "identifier": "ExchangeError", "path": "freqtrade/exceptions.py", "snippet": "class ExchangeError(DependencyException):\n \"\"\"\n Error raised out of the exchange.\n Has multiple Errors to determine the appropriate error.\n \"\"\"" }, { "identifier": "InsufficientFundsError", "path": "freqtrade/exceptions.py", "snippet": "class InsufficientFundsError(InvalidOrderException):\n \"\"\"\n This error is used when there are not enough funds available on the exchange\n to create an order.\n \"\"\"" }, { "identifier": "InvalidOrderException", "path": "freqtrade/exceptions.py", "snippet": "class InvalidOrderException(ExchangeError):\n \"\"\"\n This is returned when the order is not valid. Example:\n If stoploss on exchange order is hit, then trying to cancel the order\n should return this exception.\n \"\"\"" }, { "identifier": "OperationalException", "path": "freqtrade/exceptions.py", "snippet": "class OperationalException(FreqtradeException):\n \"\"\"\n Requires manual intervention and will stop the bot.\n Most of the time, this is caused by an invalid Configuration.\n \"\"\"" }, { "identifier": "PricingError", "path": "freqtrade/exceptions.py", "snippet": "class PricingError(DependencyException):\n \"\"\"\n Subclass of DependencyException.\n Indicates that the price could not be determined.\n Implicitly a buy / sell operation.\n \"\"\"" }, { "identifier": "RetryableOrderError", "path": "freqtrade/exceptions.py", "snippet": "class RetryableOrderError(InvalidOrderException):\n \"\"\"\n This is returned when the order is not found.\n This Error will be repeated with increasing backoff (in line with DDosError).\n \"\"\"" }, { "identifier": "TemporaryError", "path": "freqtrade/exceptions.py", "snippet": "class TemporaryError(ExchangeError):\n \"\"\"\n Temporary network or exchange related error.\n This could happen when an exchange is congested, unavailable, or the user\n has networking problems. Usually resolves itself after a time.\n \"\"\"" }, { "identifier": "API_FETCH_ORDER_RETRY_COUNT", "path": "freqtrade/exchange/common.py", "snippet": "API_FETCH_ORDER_RETRY_COUNT = 5" }, { "identifier": "remove_exchange_credentials", "path": "freqtrade/exchange/common.py", "snippet": "def remove_exchange_credentials(exchange_config: ExchangeConfig, dry_run: bool) -> None:\n \"\"\"\n Removes exchange keys from the configuration and specifies dry-run\n Used for backtesting / hyperopt / edge and utils.\n Modifies the input dict!\n \"\"\"\n if dry_run:\n exchange_config['key'] = ''\n exchange_config['apiKey'] = ''\n exchange_config['secret'] = ''\n exchange_config['password'] = ''\n exchange_config['uid'] = ''" }, { "identifier": "retrier", "path": "freqtrade/exchange/common.py", "snippet": "@overload\ndef retrier(_func: F) -> F:\n ..." }, { "identifier": "retrier_async", "path": "freqtrade/exchange/common.py", "snippet": "def retrier_async(f):\n async def wrapper(*args, **kwargs):\n count = kwargs.pop('count', API_RETRY_COUNT)\n kucoin = args[0].name == \"KuCoin\" # Check if the exchange is KuCoin.\n try:\n return await f(*args, **kwargs)\n except TemporaryError as ex:\n msg = f'{f.__name__}() returned exception: \"{ex}\". '\n if count > 0:\n msg += f'Retrying still for {count} times.'\n count -= 1\n kwargs['count'] = count\n if isinstance(ex, DDosProtection):\n if kucoin and \"429000\" in str(ex):\n # Temporary fix for 429000 error on kucoin\n # see https://github.com/freqtrade/freqtrade/issues/5700 for details.\n _get_logging_mixin().log_once(\n f\"Kucoin 429 error, avoid triggering DDosProtection backoff delay. \"\n f\"{count} tries left before giving up\", logmethod=logger.warning)\n # Reset msg to avoid logging too many times.\n msg = ''\n else:\n backoff_delay = calculate_backoff(count + 1, API_RETRY_COUNT)\n logger.info(f\"Applying DDosProtection backoff delay: {backoff_delay}\")\n await asyncio.sleep(backoff_delay)\n if msg:\n logger.warning(msg)\n return await wrapper(*args, **kwargs)\n else:\n logger.warning(msg + 'Giving up.')\n raise ex\n return wrapper" }, { "identifier": "ROUND", "path": "freqtrade/exchange/exchange_utils.py", "snippet": "def is_exchange_known_ccxt(\n exchange_name: str, ccxt_module: Optional[CcxtModuleType] = None) -> bool:\ndef ccxt_exchanges(ccxt_module: Optional[CcxtModuleType] = None) -> List[str]:\ndef available_exchanges(ccxt_module: Optional[CcxtModuleType] = None) -> List[str]:\ndef validate_exchange(exchange: str) -> Tuple[bool, str]:\ndef _build_exchange_list_entry(\n exchange_name: str, exchangeClasses: Dict[str, Any]) -> ValidExchangesType:\ndef list_available_exchanges(all_exchanges: bool) -> List[ValidExchangesType]:\ndef timeframe_to_seconds(timeframe: str) -> int:\ndef timeframe_to_minutes(timeframe: str) -> int:\ndef timeframe_to_msecs(timeframe: str) -> int:\ndef timeframe_to_prev_date(timeframe: str, date: Optional[datetime] = None) -> datetime:\ndef timeframe_to_next_date(timeframe: str, date: Optional[datetime] = None) -> datetime:\ndef date_minus_candles(\n timeframe: str, candle_count: int, date: Optional[datetime] = None) -> datetime:\ndef market_is_active(market: Dict) -> bool:\ndef amount_to_contracts(amount: float, contract_size: Optional[float]) -> float:\ndef contracts_to_amount(num_contracts: float, contract_size: Optional[float]) -> float:\ndef amount_to_precision(amount: float, amount_precision: Optional[float],\n precisionMode: Optional[int]) -> float:\ndef amount_to_contract_precision(\n amount, amount_precision: Optional[float], precisionMode: Optional[int],\n contract_size: Optional[float]) -> float:\ndef __price_to_precision_significant_digits(\n price: float,\n price_precision: float,\n *,\n rounding_mode: int = ROUND,\n) -> float:\ndef price_to_precision(\n price: float,\n price_precision: Optional[float],\n precisionMode: Optional[int],\n *,\n rounding_mode: int = ROUND,\n) -> float:" }, { "identifier": "OHLCVResponse", "path": "freqtrade/exchange/types.py", "snippet": "class Ticker(TypedDict):\nclass OrderBook(TypedDict):" }, { "identifier": "chunks", "path": "freqtrade/misc.py", "snippet": "def chunks(lst: List[Any], n: int) -> Iterator[List[Any]]:\n \"\"\"\n Split lst into chunks of the size n.\n :param lst: list to split into chunks\n :param n: number of max elements per chunk\n :return: None\n \"\"\"\n for chunk in range(0, len(lst), n):\n yield (lst[chunk:chunk + n])" }, { "identifier": "deep_merge_dicts", "path": "freqtrade/misc.py", "snippet": "def deep_merge_dicts(source, destination, allow_null_overrides: bool = True):\n \"\"\"\n Values from Source override destination, destination is returned (and modified!!)\n Sample:\n >>> a = { 'first' : { 'rows' : { 'pass' : 'dog', 'number' : '1' } } }\n >>> b = { 'first' : { 'rows' : { 'fail' : 'cat', 'number' : '5' } } }\n >>> merge(b, a) == { 'first' : { 'rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }\n True\n \"\"\"\n for key, value in source.items():\n if isinstance(value, dict):\n # get node or create one\n node = destination.setdefault(key, {})\n deep_merge_dicts(value, node, allow_null_overrides)\n elif value is not None or allow_null_overrides:\n destination[key] = value\n\n return destination" }, { "identifier": "file_dump_json", "path": "freqtrade/misc.py", "snippet": "def file_dump_json(filename: Path, data: Any, is_zip: bool = False, log: bool = True) -> None:\n \"\"\"\n Dump JSON data into a file\n :param filename: file to create\n :param is_zip: if file should be zip\n :param data: JSON Data to save\n :return:\n \"\"\"\n\n if is_zip:\n if filename.suffix != '.gz':\n filename = filename.with_suffix('.gz')\n if log:\n logger.info(f'dumping json to \"{filename}\"')\n\n with gzip.open(filename, 'w') as fpz:\n rapidjson.dump(data, fpz, default=str, number_mode=rapidjson.NM_NATIVE)\n else:\n if log:\n logger.info(f'dumping json to \"{filename}\"')\n with filename.open('w') as fp:\n rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)\n\n logger.debug(f'done json to \"{filename}\"')" }, { "identifier": "file_load_json", "path": "freqtrade/misc.py", "snippet": "def file_load_json(file: Path):\n\n if file.suffix != \".gz\":\n gzipfile = file.with_suffix(file.suffix + '.gz')\n else:\n gzipfile = file\n # Try gzip file first, otherwise regular json file.\n if gzipfile.is_file():\n logger.debug(f\"Loading historical data from file {gzipfile}\")\n with gzip.open(gzipfile) as datafile:\n pairdata = json_load(datafile)\n elif file.is_file():\n logger.debug(f\"Loading historical data from file {file}\")\n with file.open() as datafile:\n pairdata = json_load(datafile)\n else:\n return None\n return pairdata" }, { "identifier": "safe_value_fallback2", "path": "freqtrade/misc.py", "snippet": "def safe_value_fallback2(dict1: dictMap, dict2: dictMap, key1: str, key2: str, default_value=None):\n \"\"\"\n Search a value in dict1, return this if it's not None.\n Fall back to dict2 - return key2 from dict2 if it's not None.\n Else falls back to None.\n\n \"\"\"\n if key1 in dict1 and dict1[key1] is not None:\n return dict1[key1]\n else:\n if key2 in dict2 and dict2[key2] is not None:\n return dict2[key2]\n return default_value" }, { "identifier": "expand_pairlist", "path": "freqtrade/plugins/pairlist/pairlist_helpers.py", "snippet": "def expand_pairlist(wildcardpl: List[str], available_pairs: List[str],\n keep_invalid: bool = False) -> List[str]:\n \"\"\"\n Expand pairlist potentially containing wildcards based on available markets.\n This will implicitly filter all pairs in the wildcard-list which are not in available_pairs.\n :param wildcardpl: List of Pairlists, which may contain regex\n :param available_pairs: List of all available pairs (`exchange.get_markets().keys()`)\n :param keep_invalid: If sets to True, drops invalid pairs silently while expanding regexes\n :return: expanded pairlist, with Regexes from wildcardpl applied to match all available pairs.\n :raises: ValueError if a wildcard is invalid (like '*/BTC' - which should be `.*/BTC`)\n \"\"\"\n result = []\n if keep_invalid:\n for pair_wc in wildcardpl:\n try:\n comp = re.compile(pair_wc, re.IGNORECASE)\n result_partial = [\n pair for pair in available_pairs if re.fullmatch(comp, pair)\n ]\n # Add all matching pairs.\n # If there are no matching pairs (Pair not on exchange) keep it.\n result += result_partial or [pair_wc]\n except re.error as err:\n raise ValueError(f\"Wildcard error in {pair_wc}, {err}\")\n\n result = [element for element in result if re.fullmatch(r'^[A-Za-z0-9:/-]+$', element)]\n\n else:\n for pair_wc in wildcardpl:\n try:\n comp = re.compile(pair_wc, re.IGNORECASE)\n result += [\n pair for pair in available_pairs if re.fullmatch(comp, pair)\n ]\n except re.error as err:\n raise ValueError(f\"Wildcard error in {pair_wc}, {err}\")\n return result" }, { "identifier": "dt_from_ts", "path": "freqtrade/util/datetime_helpers.py", "snippet": "def dt_from_ts(timestamp: float) -> datetime:\n \"\"\"\n Return a datetime from a timestamp.\n :param timestamp: timestamp in seconds or milliseconds\n \"\"\"\n if timestamp > 1e10:\n # Timezone in ms - convert to seconds\n timestamp /= 1000\n return datetime.fromtimestamp(timestamp, tz=timezone.utc)" }, { "identifier": "dt_now", "path": "freqtrade/util/datetime_helpers.py", "snippet": "def dt_now() -> datetime:\n \"\"\"Return the current datetime in UTC.\"\"\"\n return datetime.now(timezone.utc)" }, { "identifier": "dt_humanize", "path": "freqtrade/util/datetime_helpers.py", "snippet": "def dt_humanize(dt: datetime, **kwargs) -> str:\n \"\"\"\n Return a humanized string for the given datetime.\n :param dt: datetime to humanize\n :param kwargs: kwargs to pass to arrow's humanize()\n \"\"\"\n return arrow.get(dt).humanize(**kwargs)" }, { "identifier": "dt_ts", "path": "freqtrade/util/datetime_helpers.py", "snippet": "def dt_ts(dt: Optional[datetime] = None) -> int:\n \"\"\"\n Return dt in ms as a timestamp in UTC.\n If dt is None, return the current datetime in UTC.\n \"\"\"\n if dt:\n return int(dt.timestamp() * 1000)\n return int(dt_now().timestamp() * 1000)" } ]
import asyncio import inspect import logging import signal import ccxt import ccxt.async_support as ccxt_async from copy import deepcopy from datetime import datetime, timedelta, timezone from math import floor from threading import Lock from typing import Any, Coroutine, Dict, List, Literal, Optional, Tuple, Union from cachetools import TTLCache from ccxt import TICK_SIZE from dateutil import parser from pandas import DataFrame, concat from freqtrade.constants import (DEFAULT_AMOUNT_RESERVE_PERCENT, NON_OPEN_EXCHANGE_STATES, BidAsk, BuySell, Config, EntryExit, ExchangeConfig, ListPairsWithTimeframes, MakerTaker, OBLiteral, PairWithTimeframe) from freqtrade.data.converter import clean_ohlcv_dataframe, ohlcv_to_dataframe, trades_dict_to_list from freqtrade.enums import OPTIMIZE_MODES, CandleType, MarginMode, PriceType, TradingMode from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError, InvalidOrderException, OperationalException, PricingError, RetryableOrderError, TemporaryError) from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, remove_exchange_credentials, retrier, retrier_async) from freqtrade.exchange.exchange_utils import (ROUND, ROUND_DOWN, ROUND_UP, CcxtModuleType, amount_to_contract_precision, amount_to_contracts, amount_to_precision, contracts_to_amount, date_minus_candles, is_exchange_known_ccxt, market_is_active, price_to_precision, timeframe_to_minutes, timeframe_to_msecs, timeframe_to_next_date, timeframe_to_prev_date, timeframe_to_seconds) from freqtrade.exchange.types import OHLCVResponse, OrderBook, Ticker, Tickers from freqtrade.misc import (chunks, deep_merge_dicts, file_dump_json, file_load_json, safe_value_fallback2) from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist from freqtrade.util import dt_from_ts, dt_now from freqtrade.util.datetime_helpers import dt_humanize, dt_ts from freqtrade.persistence import Order
15,268
f'On exchange stoploss is not supported for {self.name}.' ) if self.trading_mode == TradingMode.FUTURES: price_mapping = self._ft_has.get('stop_price_type_value_mapping', {}).keys() if ( order_types.get("stoploss_on_exchange", False) is True and 'stoploss_price_type' in order_types and order_types['stoploss_price_type'] not in price_mapping ): raise OperationalException( f'On exchange stoploss price type is not supported for {self.name}.' ) def validate_pricing(self, pricing: Dict) -> None: if pricing.get('use_order_book', False) and not self.exchange_has('fetchL2OrderBook'): raise OperationalException(f'Orderbook not available for {self.name}.') if (not pricing.get('use_order_book', False) and ( not self.exchange_has('fetchTicker') or not self._ft_has['tickers_have_price'])): raise OperationalException(f'Ticker pricing not available for {self.name}.') def validate_order_time_in_force(self, order_time_in_force: Dict) -> None: """ Checks if order time in force configured in strategy/config are supported """ if any(v.upper() not in self._ft_has["order_time_in_force"] for k, v in order_time_in_force.items()): raise OperationalException( f'Time in force policies are not supported for {self.name} yet.') def validate_required_startup_candles(self, startup_candles: int, timeframe: str) -> int: """ Checks if required startup_candles is more than ohlcv_candle_limit(). Requires a grace-period of 5 candles - so a startup-period up to 494 is allowed by default. """ candle_limit = self.ohlcv_candle_limit( timeframe, self._config['candle_type_def'], int(date_minus_candles(timeframe, startup_candles).timestamp() * 1000) if timeframe else None) # Require one more candle - to account for the still open candle. candle_count = startup_candles + 1 # Allow 5 calls to the exchange per pair required_candle_call_count = int( (candle_count / candle_limit) + (0 if candle_count % candle_limit == 0 else 1)) if self._ft_has['ohlcv_has_history']: if required_candle_call_count > 5: # Only allow 5 calls per pair to somewhat limit the impact raise OperationalException( f"This strategy requires {startup_candles} candles to start, " "which is more than 5x " f"the amount of candles {self.name} provides for {timeframe}.") elif required_candle_call_count > 1: raise OperationalException( f"This strategy requires {startup_candles} candles to start, which is more than " f"the amount of candles {self.name} provides for {timeframe}.") if required_candle_call_count > 1: logger.warning(f"Using {required_candle_call_count} calls to get OHLCV. " f"This can result in slower operations for the bot. Please check " f"if you really need {startup_candles} candles for your strategy") return required_candle_call_count def validate_trading_mode_and_margin_mode( self, trading_mode: TradingMode, margin_mode: Optional[MarginMode] # Only None when trading_mode = TradingMode.SPOT ): """ Checks if freqtrade can perform trades using the configured trading mode(Margin, Futures) and MarginMode(Cross, Isolated) Throws OperationalException: If the trading_mode/margin_mode type are not supported by freqtrade on this exchange """ if trading_mode != TradingMode.SPOT and ( (trading_mode, margin_mode) not in self._supported_trading_mode_margin_pairs ): mm_value = margin_mode and margin_mode.value raise OperationalException( f"Freqtrade does not support {mm_value} {trading_mode.value} on {self.name}" ) def get_option(self, param: str, default: Optional[Any] = None) -> Any: """ Get parameter value from _ft_has """ return self._ft_has.get(param, default) def exchange_has(self, endpoint: str) -> bool: """ Checks if exchange implements a specific API endpoint. Wrapper around ccxt 'has' attribute :param endpoint: Name of endpoint (e.g. 'fetchOHLCV', 'fetchTickers') :return: bool """ return endpoint in self._api.has and self._api.has[endpoint] def get_precision_amount(self, pair: str) -> Optional[float]: """ Returns the amount precision of the exchange. :param pair: Pair to get precision for :return: precision for amount or None. Must be used in combination with precisionMode """ return self.markets.get(pair, {}).get('precision', {}).get('amount', None) def get_precision_price(self, pair: str) -> Optional[float]: """ Returns the price precision of the exchange. :param pair: Pair to get precision for :return: precision for price or None. Must be used in combination with precisionMode """ return self.markets.get(pair, {}).get('precision', {}).get('price', None) def amount_to_precision(self, pair: str, amount: float) -> float: """ Returns the amount to buy or sell to a precision the Exchange accepts """ return amount_to_precision(amount, self.get_precision_amount(pair), self.precisionMode)
# pragma pylint: disable=W0603 """ Cryptocurrency Exchanges support """ logger = logging.getLogger(__name__) class Exchange: # Parameters to add directly to buy/sell calls (like agreeing to trading agreement) _params: Dict = {} # Additional parameters - added to the ccxt object _ccxt_params: Dict = {} # Dict to specify which options each exchange implements # This defines defaults, which can be selectively overridden by subclasses using _ft_has # or by specifying them in the configuration. _ft_has_default: Dict = { "stoploss_on_exchange": False, "stop_price_param": "stopLossPrice", # Used for stoploss_on_exchange request "stop_price_prop": "stopLossPrice", # Used for stoploss_on_exchange response parsing "order_time_in_force": ["GTC"], "ohlcv_params": {}, "ohlcv_candle_limit": 500, "ohlcv_has_history": True, # Some exchanges (Kraken) don't provide history via ohlcv "ohlcv_partial_candle": True, "ohlcv_require_since": False, # Check https://github.com/ccxt/ccxt/issues/10767 for removal of ohlcv_volume_currency "ohlcv_volume_currency": "base", # "base" or "quote" "tickers_have_quoteVolume": True, "tickers_have_bid_ask": True, # bid / ask empty for fetch_tickers "tickers_have_price": True, "trades_pagination": "time", # Possible are "time" or "id" "trades_pagination_arg": "since", "l2_limit_range": None, "l2_limit_range_required": True, # Allow Empty L2 limit (kucoin) "mark_ohlcv_price": "mark", "mark_ohlcv_timeframe": "8h", "ccxt_futures_name": "swap", "needs_trading_fees": False, # use fetch_trading_fees to cache fees "order_props_in_contracts": ['amount', 'filled', 'remaining'], # Override createMarketBuyOrderRequiresPrice where ccxt has it wrong "marketOrderRequiresPrice": False, } _ft_has: Dict = {} _ft_has_futures: Dict = {} _supported_trading_mode_margin_pairs: List[Tuple[TradingMode, MarginMode]] = [ # TradingMode.SPOT always supported and not required in this list ] def __init__(self, config: Config, *, exchange_config: Optional[ExchangeConfig] = None, validate: bool = True, load_leverage_tiers: bool = False) -> None: """ Initializes this module with the given config, it does basic validation whether the specified exchange and pairs are valid. :return: None """ self._api: ccxt.Exchange self._api_async: ccxt_async.Exchange = None self._markets: Dict = {} self._trading_fees: Dict[str, Any] = {} self._leverage_tiers: Dict[str, List[Dict]] = {} # Lock event loop. This is necessary to avoid race-conditions when using force* commands # Due to funding fee fetching. self._loop_lock = Lock() self.loop = self._init_async_loop() self._config: Config = {} self._config.update(config) # Holds last candle refreshed time of each pair self._pairs_last_refresh_time: Dict[PairWithTimeframe, int] = {} # Timestamp of last markets refresh self._last_markets_refresh: int = 0 # Cache for 10 minutes ... self._cache_lock = Lock() self._fetch_tickers_cache: TTLCache = TTLCache(maxsize=2, ttl=60 * 10) # Cache values for 1800 to avoid frequent polling of the exchange for prices # Caching only applies to RPC methods, so prices for open trades are still # refreshed once every iteration. self._exit_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800) self._entry_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800) # Holds candles self._klines: Dict[PairWithTimeframe, DataFrame] = {} # Holds all open sell orders for dry_run self._dry_run_open_orders: Dict[str, Any] = {} if config['dry_run']: logger.info('Instance is running with dry_run enabled') logger.info(f"Using CCXT {ccxt.__version__}") exchange_conf: Dict[str, Any] = exchange_config if exchange_config else config['exchange'] remove_exchange_credentials(exchange_conf, config.get('dry_run', False)) self.log_responses = exchange_conf.get('log_responses', False) # Leverage properties self.trading_mode: TradingMode = config.get('trading_mode', TradingMode.SPOT) self.margin_mode: MarginMode = ( MarginMode(config.get('margin_mode')) if config.get('margin_mode') else MarginMode.NONE ) self.liquidation_buffer = config.get('liquidation_buffer', 0.05) # Deep merge ft_has with default ft_has options self._ft_has = deep_merge_dicts(self._ft_has, deepcopy(self._ft_has_default)) if self.trading_mode == TradingMode.FUTURES: self._ft_has = deep_merge_dicts(self._ft_has_futures, self._ft_has) if exchange_conf.get('_ft_has_params'): self._ft_has = deep_merge_dicts(exchange_conf.get('_ft_has_params'), self._ft_has) logger.info("Overriding exchange._ft_has with config params, result: %s", self._ft_has) # Assign this directly for easy access self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle'] self._trades_pagination = self._ft_has['trades_pagination'] self._trades_pagination_arg = self._ft_has['trades_pagination_arg'] # Initialize ccxt objects ccxt_config = self._ccxt_config ccxt_config = deep_merge_dicts(exchange_conf.get('ccxt_config', {}), ccxt_config) ccxt_config = deep_merge_dicts(exchange_conf.get('ccxt_sync_config', {}), ccxt_config) self._api = self._init_ccxt(exchange_conf, ccxt_kwargs=ccxt_config) ccxt_async_config = self._ccxt_config ccxt_async_config = deep_merge_dicts(exchange_conf.get('ccxt_config', {}), ccxt_async_config) ccxt_async_config = deep_merge_dicts(exchange_conf.get('ccxt_async_config', {}), ccxt_async_config) self._api_async = self._init_ccxt( exchange_conf, ccxt_async, ccxt_kwargs=ccxt_async_config) logger.info(f'Using Exchange "{self.name}"') self.required_candle_call_count = 1 if validate: # Initial markets load self._load_markets() self.validate_config(config) self._startup_candle_count: int = config.get('startup_candle_count', 0) self.required_candle_call_count = self.validate_required_startup_candles( self._startup_candle_count, config.get('timeframe', '')) # Converts the interval provided in minutes in config to seconds self.markets_refresh_interval: int = exchange_conf.get( "markets_refresh_interval", 60) * 60 * 1000 if self.trading_mode != TradingMode.SPOT and load_leverage_tiers: self.fill_leverage_tiers() self.additional_exchange_init() def __del__(self): """ Destructor - clean up async stuff """ self.close() def close(self): logger.debug("Exchange object destroyed, closing async loop") if (self._api_async and inspect.iscoroutinefunction(self._api_async.close) and self._api_async.session): logger.debug("Closing async ccxt session.") self.loop.run_until_complete(self._api_async.close()) if self.loop and not self.loop.is_closed(): self.loop.close() def _init_async_loop(self) -> asyncio.AbstractEventLoop: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop def validate_config(self, config): # Check if timeframe is available self.validate_timeframes(config.get('timeframe')) # Check if all pairs are available self.validate_stakecurrency(config['stake_currency']) if not config['exchange'].get('skip_pair_validation'): self.validate_pairs(config['exchange']['pair_whitelist']) self.validate_ordertypes(config.get('order_types', {})) self.validate_order_time_in_force(config.get('order_time_in_force', {})) self.validate_trading_mode_and_margin_mode(self.trading_mode, self.margin_mode) self.validate_pricing(config['exit_pricing']) self.validate_pricing(config['entry_pricing']) def _init_ccxt(self, exchange_config: Dict[str, Any], ccxt_module: CcxtModuleType = ccxt, ccxt_kwargs: Dict = {}) -> ccxt.Exchange: """ Initialize ccxt with given config and return valid ccxt instance. """ # Find matching class for the given exchange name name = exchange_config['name'] if not is_exchange_known_ccxt(name, ccxt_module): raise OperationalException(f'Exchange {name} is not supported by ccxt') ex_config = { 'apiKey': exchange_config.get('key'), 'secret': exchange_config.get('secret'), 'password': exchange_config.get('password'), 'uid': exchange_config.get('uid', ''), } if ccxt_kwargs: logger.info('Applying additional ccxt config: %s', ccxt_kwargs) if self._ccxt_params: # Inject static options after the above output to not confuse users. ccxt_kwargs = deep_merge_dicts(self._ccxt_params, ccxt_kwargs) if ccxt_kwargs: ex_config.update(ccxt_kwargs) try: api = getattr(ccxt_module, name.lower())(ex_config) except (KeyError, AttributeError) as e: raise OperationalException(f'Exchange {name} is not supported') from e except ccxt.BaseError as e: raise OperationalException(f"Initialization of ccxt failed. Reason: {e}") from e return api @property def _ccxt_config(self) -> Dict: # Parameters to add directly to ccxt sync/async initialization. if self.trading_mode == TradingMode.MARGIN: return { "options": { "defaultType": "margin" } } elif self.trading_mode == TradingMode.FUTURES: return { "options": { "defaultType": self._ft_has["ccxt_futures_name"] } } else: return {} @property def name(self) -> str: """exchange Name (from ccxt)""" return self._api.name @property def id(self) -> str: """exchange ccxt id""" return self._api.id @property def timeframes(self) -> List[str]: return list((self._api.timeframes or {}).keys()) @property def markets(self) -> Dict[str, Any]: """exchange ccxt markets""" if not self._markets: logger.info("Markets were not loaded. Loading them now..") self._load_markets() return self._markets @property def precisionMode(self) -> int: """exchange ccxt precisionMode""" return self._api.precisionMode def additional_exchange_init(self) -> None: """ Additional exchange initialization logic. .api will be available at this point. Must be overridden in child methods if required. """ pass def _log_exchange_response(self, endpoint, response) -> None: """ Log exchange responses """ if self.log_responses: logger.info(f"API {endpoint}: {response}") def ohlcv_candle_limit( self, timeframe: str, candle_type: CandleType, since_ms: Optional[int] = None) -> int: """ Exchange ohlcv candle limit Uses ohlcv_candle_limit_per_timeframe if the exchange has different limits per timeframe (e.g. bittrex), otherwise falls back to ohlcv_candle_limit :param timeframe: Timeframe to check :param candle_type: Candle-type :param since_ms: Starting timestamp :return: Candle limit as integer """ return int(self._ft_has.get('ohlcv_candle_limit_per_timeframe', {}).get( timeframe, self._ft_has.get('ohlcv_candle_limit'))) def get_markets(self, base_currencies: List[str] = [], quote_currencies: List[str] = [], spot_only: bool = False, margin_only: bool = False, futures_only: bool = False, tradable_only: bool = True, active_only: bool = False) -> Dict[str, Any]: """ Return exchange ccxt markets, filtered out by base currency and quote currency if this was requested in parameters. """ markets = self.markets if not markets: raise OperationalException("Markets were not loaded.") if base_currencies: markets = {k: v for k, v in markets.items() if v['base'] in base_currencies} if quote_currencies: markets = {k: v for k, v in markets.items() if v['quote'] in quote_currencies} if tradable_only: markets = {k: v for k, v in markets.items() if self.market_is_tradable(v)} if spot_only: markets = {k: v for k, v in markets.items() if self.market_is_spot(v)} if margin_only: markets = {k: v for k, v in markets.items() if self.market_is_margin(v)} if futures_only: markets = {k: v for k, v in markets.items() if self.market_is_future(v)} if active_only: markets = {k: v for k, v in markets.items() if market_is_active(v)} return markets def get_quote_currencies(self) -> List[str]: """ Return a list of supported quote currencies """ markets = self.markets return sorted(set([x['quote'] for _, x in markets.items()])) def get_pair_quote_currency(self, pair: str) -> str: """ Return a pair's quote currency (base/quote:settlement) """ return self.markets.get(pair, {}).get('quote', '') def get_pair_base_currency(self, pair: str) -> str: """ Return a pair's base currency (base/quote:settlement) """ return self.markets.get(pair, {}).get('base', '') def market_is_future(self, market: Dict[str, Any]) -> bool: return ( market.get(self._ft_has["ccxt_futures_name"], False) is True and market.get('linear', False) is True ) def market_is_spot(self, market: Dict[str, Any]) -> bool: return market.get('spot', False) is True def market_is_margin(self, market: Dict[str, Any]) -> bool: return market.get('margin', False) is True def market_is_tradable(self, market: Dict[str, Any]) -> bool: """ Check if the market symbol is tradable by Freqtrade. Ensures that Configured mode aligns to """ return ( market.get('quote', None) is not None and market.get('base', None) is not None and (self.precisionMode != TICK_SIZE # Too low precision will falsify calculations or market.get('precision', {}).get('price') > 1e-11) and ((self.trading_mode == TradingMode.SPOT and self.market_is_spot(market)) or (self.trading_mode == TradingMode.MARGIN and self.market_is_margin(market)) or (self.trading_mode == TradingMode.FUTURES and self.market_is_future(market))) ) def klines(self, pair_interval: PairWithTimeframe, copy: bool = True) -> DataFrame: if pair_interval in self._klines: return self._klines[pair_interval].copy() if copy else self._klines[pair_interval] else: return DataFrame() def get_contract_size(self, pair: str) -> Optional[float]: if self.trading_mode == TradingMode.FUTURES: market = self.markets.get(pair, {}) contract_size: float = 1.0 if not market: return None if market.get('contractSize') is not None: # ccxt has contractSize in markets as string contract_size = float(market['contractSize']) return contract_size else: return 1 def _trades_contracts_to_amount(self, trades: List) -> List: if len(trades) > 0 and 'symbol' in trades[0]: contract_size = self.get_contract_size(trades[0]['symbol']) if contract_size != 1: for trade in trades: trade['amount'] = trade['amount'] * contract_size return trades def _order_contracts_to_amount(self, order: Dict) -> Dict: if 'symbol' in order and order['symbol'] is not None: contract_size = self.get_contract_size(order['symbol']) if contract_size != 1: for prop in self._ft_has.get('order_props_in_contracts', []): if prop in order and order[prop] is not None: order[prop] = order[prop] * contract_size return order def _amount_to_contracts(self, pair: str, amount: float) -> float: contract_size = self.get_contract_size(pair) return amount_to_contracts(amount, contract_size) def _contracts_to_amount(self, pair: str, num_contracts: float) -> float: contract_size = self.get_contract_size(pair) return contracts_to_amount(num_contracts, contract_size) def amount_to_contract_precision(self, pair: str, amount: float) -> float: """ Helper wrapper around amount_to_contract_precision """ contract_size = self.get_contract_size(pair) return amount_to_contract_precision(amount, self.get_precision_amount(pair), self.precisionMode, contract_size) def _load_async_markets(self, reload: bool = False) -> None: try: if self._api_async: self.loop.run_until_complete( self._api_async.load_markets(reload=reload, params={})) except (asyncio.TimeoutError, ccxt.BaseError) as e: logger.warning('Could not load async markets. Reason: %s', e) return def _load_markets(self) -> None: """ Initialize markets both sync and async """ try: self._markets = self._api.load_markets(params={}) self._load_async_markets() self._last_markets_refresh = dt_ts() if self._ft_has['needs_trading_fees']: self._trading_fees = self.fetch_trading_fees() except ccxt.BaseError: logger.exception('Unable to initialize markets.') def reload_markets(self) -> None: """Reload markets both sync and async if refresh interval has passed """ # Check whether markets have to be reloaded if (self._last_markets_refresh > 0) and ( self._last_markets_refresh + self.markets_refresh_interval > dt_ts()): return None logger.debug("Performing scheduled market reload..") try: self._markets = self._api.load_markets(reload=True, params={}) # Also reload async markets to avoid issues with newly listed pairs self._load_async_markets(reload=True) self._last_markets_refresh = dt_ts() self.fill_leverage_tiers() except ccxt.BaseError: logger.exception("Could not reload markets.") def validate_stakecurrency(self, stake_currency: str) -> None: """ Checks stake-currency against available currencies on the exchange. Only runs on startup. If markets have not been loaded, there's been a problem with the connection to the exchange. :param stake_currency: Stake-currency to validate :raise: OperationalException if stake-currency is not available. """ if not self._markets: raise OperationalException( 'Could not load markets, therefore cannot start. ' 'Please investigate the above error for more details.' ) quote_currencies = self.get_quote_currencies() if stake_currency not in quote_currencies: raise OperationalException( f"{stake_currency} is not available as stake on {self.name}. " f"Available currencies are: {', '.join(quote_currencies)}") def validate_pairs(self, pairs: List[str]) -> None: """ Checks if all given pairs are tradable on the current exchange. :param pairs: list of pairs :raise: OperationalException if one pair is not available :return: None """ if not self.markets: logger.warning('Unable to validate pairs (assuming they are correct).') return extended_pairs = expand_pairlist(pairs, list(self.markets), keep_invalid=True) invalid_pairs = [] for pair in extended_pairs: # Note: ccxt has BaseCurrency/QuoteCurrency format for pairs if self.markets and pair not in self.markets: raise OperationalException( f'Pair {pair} is not available on {self.name} {self.trading_mode.value}. ' f'Please remove {pair} from your whitelist.') # From ccxt Documentation: # markets.info: An associative array of non-common market properties, # including fees, rates, limits and other general market information. # The internal info array is different for each particular market, # its contents depend on the exchange. # It can also be a string or similar ... so we need to verify that first. elif (isinstance(self.markets[pair].get('info'), dict) and self.markets[pair].get('info', {}).get('prohibitedIn', False)): # Warn users about restricted pairs in whitelist. # We cannot determine reliably if Users are affected. logger.warning(f"Pair {pair} is restricted for some users on this exchange." f"Please check if you are impacted by this restriction " f"on the exchange and eventually remove {pair} from your whitelist.") if (self._config['stake_currency'] and self.get_pair_quote_currency(pair) != self._config['stake_currency']): invalid_pairs.append(pair) if invalid_pairs: raise OperationalException( f"Stake-currency '{self._config['stake_currency']}' not compatible with " f"pair-whitelist. Please remove the following pairs: {invalid_pairs}") def get_valid_pair_combination(self, curr_1: str, curr_2: str) -> str: """ Get valid pair combination of curr_1 and curr_2 by trying both combinations. """ for pair in [f"{curr_1}/{curr_2}", f"{curr_2}/{curr_1}"]: if pair in self.markets and self.markets[pair].get('active'): return pair raise ValueError(f"Could not combine {curr_1} and {curr_2} to get a valid pair.") def validate_timeframes(self, timeframe: Optional[str]) -> None: """ Check if timeframe from config is a supported timeframe on the exchange """ if not hasattr(self._api, "timeframes") or self._api.timeframes is None: # If timeframes attribute is missing (or is None), the exchange probably # has no fetchOHLCV method. # Therefore we also show that. raise OperationalException( f"The ccxt library does not provide the list of timeframes " f"for the exchange {self.name} and this exchange " f"is therefore not supported. ccxt fetchOHLCV: {self.exchange_has('fetchOHLCV')}") if timeframe and (timeframe not in self.timeframes): raise OperationalException( f"Invalid timeframe '{timeframe}'. This exchange supports: {self.timeframes}") if timeframe and timeframe_to_minutes(timeframe) < 1: raise OperationalException("Timeframes < 1m are currently not supported by Freqtrade.") def validate_ordertypes(self, order_types: Dict) -> None: """ Checks if order-types configured in strategy/config are supported """ if any(v == 'market' for k, v in order_types.items()): if not self.exchange_has('createMarketOrder'): raise OperationalException( f'Exchange {self.name} does not support market orders.') self.validate_stop_ordertypes(order_types) def validate_stop_ordertypes(self, order_types: Dict) -> None: """ Validate stoploss order types """ if (order_types.get("stoploss_on_exchange") and not self._ft_has.get("stoploss_on_exchange", False)): raise OperationalException( f'On exchange stoploss is not supported for {self.name}.' ) if self.trading_mode == TradingMode.FUTURES: price_mapping = self._ft_has.get('stop_price_type_value_mapping', {}).keys() if ( order_types.get("stoploss_on_exchange", False) is True and 'stoploss_price_type' in order_types and order_types['stoploss_price_type'] not in price_mapping ): raise OperationalException( f'On exchange stoploss price type is not supported for {self.name}.' ) def validate_pricing(self, pricing: Dict) -> None: if pricing.get('use_order_book', False) and not self.exchange_has('fetchL2OrderBook'): raise OperationalException(f'Orderbook not available for {self.name}.') if (not pricing.get('use_order_book', False) and ( not self.exchange_has('fetchTicker') or not self._ft_has['tickers_have_price'])): raise OperationalException(f'Ticker pricing not available for {self.name}.') def validate_order_time_in_force(self, order_time_in_force: Dict) -> None: """ Checks if order time in force configured in strategy/config are supported """ if any(v.upper() not in self._ft_has["order_time_in_force"] for k, v in order_time_in_force.items()): raise OperationalException( f'Time in force policies are not supported for {self.name} yet.') def validate_required_startup_candles(self, startup_candles: int, timeframe: str) -> int: """ Checks if required startup_candles is more than ohlcv_candle_limit(). Requires a grace-period of 5 candles - so a startup-period up to 494 is allowed by default. """ candle_limit = self.ohlcv_candle_limit( timeframe, self._config['candle_type_def'], int(date_minus_candles(timeframe, startup_candles).timestamp() * 1000) if timeframe else None) # Require one more candle - to account for the still open candle. candle_count = startup_candles + 1 # Allow 5 calls to the exchange per pair required_candle_call_count = int( (candle_count / candle_limit) + (0 if candle_count % candle_limit == 0 else 1)) if self._ft_has['ohlcv_has_history']: if required_candle_call_count > 5: # Only allow 5 calls per pair to somewhat limit the impact raise OperationalException( f"This strategy requires {startup_candles} candles to start, " "which is more than 5x " f"the amount of candles {self.name} provides for {timeframe}.") elif required_candle_call_count > 1: raise OperationalException( f"This strategy requires {startup_candles} candles to start, which is more than " f"the amount of candles {self.name} provides for {timeframe}.") if required_candle_call_count > 1: logger.warning(f"Using {required_candle_call_count} calls to get OHLCV. " f"This can result in slower operations for the bot. Please check " f"if you really need {startup_candles} candles for your strategy") return required_candle_call_count def validate_trading_mode_and_margin_mode( self, trading_mode: TradingMode, margin_mode: Optional[MarginMode] # Only None when trading_mode = TradingMode.SPOT ): """ Checks if freqtrade can perform trades using the configured trading mode(Margin, Futures) and MarginMode(Cross, Isolated) Throws OperationalException: If the trading_mode/margin_mode type are not supported by freqtrade on this exchange """ if trading_mode != TradingMode.SPOT and ( (trading_mode, margin_mode) not in self._supported_trading_mode_margin_pairs ): mm_value = margin_mode and margin_mode.value raise OperationalException( f"Freqtrade does not support {mm_value} {trading_mode.value} on {self.name}" ) def get_option(self, param: str, default: Optional[Any] = None) -> Any: """ Get parameter value from _ft_has """ return self._ft_has.get(param, default) def exchange_has(self, endpoint: str) -> bool: """ Checks if exchange implements a specific API endpoint. Wrapper around ccxt 'has' attribute :param endpoint: Name of endpoint (e.g. 'fetchOHLCV', 'fetchTickers') :return: bool """ return endpoint in self._api.has and self._api.has[endpoint] def get_precision_amount(self, pair: str) -> Optional[float]: """ Returns the amount precision of the exchange. :param pair: Pair to get precision for :return: precision for amount or None. Must be used in combination with precisionMode """ return self.markets.get(pair, {}).get('precision', {}).get('amount', None) def get_precision_price(self, pair: str) -> Optional[float]: """ Returns the price precision of the exchange. :param pair: Pair to get precision for :return: precision for price or None. Must be used in combination with precisionMode """ return self.markets.get(pair, {}).get('precision', {}).get('price', None) def amount_to_precision(self, pair: str, amount: float) -> float: """ Returns the amount to buy or sell to a precision the Exchange accepts """ return amount_to_precision(amount, self.get_precision_amount(pair), self.precisionMode)
def price_to_precision(self, pair: str, price: float, *, rounding_mode: int = ROUND) -> float:
21
2023-10-21 10:02:05+00:00
24k
yanzhh/HGERE
transformers/src/transformers/modeling_bert.py
[ { "identifier": "gelu", "path": "transformers/src/transformers/activations.py", "snippet": "def swish(x):\ndef _gelu_python(x):\ndef gelu_new(x):\ndef get_activation(activation_string):\nACT2FN = {\n \"relu\": F.relu,\n \"swish\": swish,\n \"gelu\": gelu,\n \"tanh\": F.tanh,\n \"gelu_new\": gelu_new,\n}" }, { "identifier": "BertConfig", "path": "transformers/src/transformers/configuration_bert.py", "snippet": "class BertConfig(PretrainedConfig):\n r\"\"\"\n This is the configuration class to store the configuration of a :class:`~transformers.BertModel`.\n It is used to instantiate an BERT model according to the specified arguments, defining the model\n architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of\n the BERT `bert-base-uncased <https://huggingface.co/bert-base-uncased>`__ architecture.\n\n Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used\n to control the model outputs. Read the documentation from :class:`~transformers.PretrainedConfig`\n for more information.\n\n\n Args:\n vocab_size (:obj:`int`, optional, defaults to 30522):\n Vocabulary size of the BERT model. Defines the different tokens that\n can be represented by the `inputs_ids` passed to the forward method of :class:`~transformers.BertModel`.\n hidden_size (:obj:`int`, optional, defaults to 768):\n Dimensionality of the encoder layers and the pooler layer.\n num_hidden_layers (:obj:`int`, optional, defaults to 12):\n Number of hidden layers in the Transformer encoder.\n num_attention_heads (:obj:`int`, optional, defaults to 12):\n Number of attention heads for each attention layer in the Transformer encoder.\n intermediate_size (:obj:`int`, optional, defaults to 3072):\n Dimensionality of the \"intermediate\" (i.e., feed-forward) layer in the Transformer encoder.\n hidden_act (:obj:`str` or :obj:`function`, optional, defaults to \"gelu\"):\n The non-linear activation function (function or string) in the encoder and pooler.\n If string, \"gelu\", \"relu\", \"swish\" and \"gelu_new\" are supported.\n hidden_dropout_prob (:obj:`float`, optional, defaults to 0.1):\n The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob (:obj:`float`, optional, defaults to 0.1):\n The dropout ratio for the attention probabilities.\n max_position_embeddings (:obj:`int`, optional, defaults to 512):\n The maximum sequence length that this model might ever be used with.\n Typically set this to something large just in case (e.g., 512 or 1024 or 2048).\n type_vocab_size (:obj:`int`, optional, defaults to 2):\n The vocabulary size of the `token_type_ids` passed into :class:`~transformers.BertModel`.\n initializer_range (:obj:`float`, optional, defaults to 0.02):\n The standard deviation of the truncated_normal_initializer for initializing all weight matrices.\n layer_norm_eps (:obj:`float`, optional, defaults to 1e-12):\n The epsilon used by the layer normalization layers.\n\n Example::\n\n from transformers import BertModel, BertConfig\n\n # Initializing a BERT bert-base-uncased style configuration\n configuration = BertConfig()\n\n # Initializing a model from the bert-base-uncased style configuration\n model = BertModel(configuration)\n\n # Accessing the model configuration\n configuration = model.config\n\n Attributes:\n pretrained_config_archive_map (Dict[str, str]):\n A dictionary containing all the available pre-trained checkpoints.\n \"\"\"\n pretrained_config_archive_map = BERT_PRETRAINED_CONFIG_ARCHIVE_MAP\n model_type = \"bert\"\n\n def __init__(\n self,\n vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps" }, { "identifier": "add_start_docstrings", "path": "transformers/src/transformers/file_utils.py", "snippet": "def add_start_docstrings(*docstr):\n def docstring_decorator(fn):\n fn.__doc__ = \"\".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else \"\")\n return fn\n\n return docstring_decorator" }, { "identifier": "add_start_docstrings_to_callable", "path": "transformers/src/transformers/file_utils.py", "snippet": "def add_start_docstrings_to_callable(*docstr):\n def docstring_decorator(fn):\n class_name = \":class:`~transformers.{}`\".format(fn.__qualname__.split(\".\")[0])\n intro = \" The {} forward method, overrides the :func:`__call__` special method.\".format(class_name)\n note = r\"\"\"\n\n .. note::\n Although the recipe for forward pass needs to be defined within\n this function, one should call the :class:`Module` instance afterwards\n instead of this since the former takes care of running the\n pre and post processing steps while the latter silently ignores them.\n \"\"\"\n fn.__doc__ = intro + note + \"\".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else \"\")\n return fn\n\n return docstring_decorator" }, { "identifier": "PreTrainedModel", "path": "transformers/src/transformers/modeling_utils.py", "snippet": "class PreTrainedModel(nn.Module, ModuleUtilsMixin):\n r\"\"\" Base class for all models.\n\n :class:`~transformers.PreTrainedModel` takes care of storing the configuration of the models and handles methods for loading/downloading/saving models\n as well as a few methods common to all models to (i) resize the input embeddings and (ii) prune heads in the self-attention heads.\n\n Class attributes (overridden by derived classes):\n - ``config_class``: a class derived from :class:`~transformers.PretrainedConfig` to use as configuration class for this model architecture.\n - ``pretrained_model_archive_map``: a python ``dict`` of with `short-cut-names` (string) as keys and `url` (string) of associated pretrained weights as values.\n - ``load_tf_weights``: a python ``method`` for loading a TensorFlow checkpoint in a PyTorch model, taking as arguments:\n\n - ``model``: an instance of the relevant subclass of :class:`~transformers.PreTrainedModel`,\n - ``config``: an instance of the relevant subclass of :class:`~transformers.PretrainedConfig`,\n - ``path``: a path (string) to the TensorFlow checkpoint.\n\n - ``base_model_prefix``: a string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model.\n \"\"\"\n config_class = None\n pretrained_model_archive_map = {}\n base_model_prefix = \"\"\n\n @property\n def dummy_inputs(self):\n \"\"\" Dummy inputs to do a forward pass in the network.\n\n Returns:\n torch.Tensor with dummy inputs\n \"\"\"\n return {\"input_ids\": torch.tensor(DUMMY_INPUTS)}\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__()\n if not isinstance(config, PretrainedConfig):\n raise ValueError(\n \"Parameter config in `{}(config)` should be an instance of class `PretrainedConfig`. \"\n \"To create a model from a pretrained model use \"\n \"`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(\n self.__class__.__name__, self.__class__.__name__\n )\n )\n # Save config in model\n self.config = config\n\n @property\n def base_model(self):\n return getattr(self, self.base_model_prefix, self)\n\n def get_input_embeddings(self):\n \"\"\"\n Returns the model's input embeddings.\n\n Returns:\n :obj:`nn.Module`:\n A torch module mapping vocabulary to hidden states.\n \"\"\"\n base_model = getattr(self, self.base_model_prefix, self)\n if base_model is not self:\n return base_model.get_input_embeddings()\n else:\n raise NotImplementedError\n\n def set_input_embeddings(self, value):\n \"\"\"\n Set model's input embeddings\n\n Args:\n value (:obj:`nn.Module`):\n A module mapping vocabulary to hidden states.\n \"\"\"\n base_model = getattr(self, self.base_model_prefix, self)\n if base_model is not self:\n base_model.set_input_embeddings(value)\n else:\n raise NotImplementedError\n\n def get_output_embeddings(self):\n \"\"\"\n Returns the model's output embeddings.\n\n Returns:\n :obj:`nn.Module`:\n A torch module mapping hidden states to vocabulary.\n \"\"\"\n return None # Overwrite for models with output embeddings\n\n def tie_weights(self):\n \"\"\"\n Tie the weights between the input embeddings and the output embeddings.\n If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning\n the weights instead.\n \"\"\"\n output_embeddings = self.get_output_embeddings()\n if output_embeddings is not None:\n if isinstance(output_embeddings, list):\n for x in output_embeddings:\n self._tie_or_clone_weights(x, self.get_input_embeddings())\n else:\n self._tie_or_clone_weights(output_embeddings, self.get_input_embeddings())\n\n def _tie_or_clone_weights(self, output_embeddings, input_embeddings):\n \"\"\" Tie or clone module weights depending of weither we are using TorchScript or not\n \"\"\"\n if self.config.torchscript:\n output_embeddings.weight = nn.Parameter(input_embeddings.weight.clone())\n else:\n output_embeddings.weight = input_embeddings.weight\n\n if hasattr(output_embeddings, \"bias\") and output_embeddings.bias is not None:\n output_embeddings.bias.data = torch.nn.functional.pad(\n output_embeddings.bias.data,\n (0, output_embeddings.weight.shape[0] - output_embeddings.bias.shape[0]),\n \"constant\",\n 0,\n )\n if hasattr(output_embeddings, \"out_features\") and hasattr(input_embeddings, \"num_embeddings\"):\n output_embeddings.out_features = input_embeddings.num_embeddings\n\n def resize_token_embeddings(self, new_num_tokens=None):\n \"\"\" Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size.\n Take care of tying weights embeddings afterwards if the model class has a `tie_weights()` method.\n\n Arguments:\n\n new_num_tokens: (`optional`) int:\n New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end.\n If not provided or None: does nothing and just returns a pointer to the input tokens ``torch.nn.Embeddings`` Module of the model.\n\n Return: ``torch.nn.Embeddings``\n Pointer to the input tokens Embeddings Module of the model\n \"\"\"\n base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed\n model_embeds = base_model._resize_token_embeddings(new_num_tokens)\n if new_num_tokens is None:\n return model_embeds\n\n # Update base model and current model config\n self.config.vocab_size = new_num_tokens\n base_model.vocab_size = new_num_tokens\n\n # Tie weights again if needed\n self.tie_weights()\n\n return model_embeds\n\n def _resize_token_embeddings(self, new_num_tokens):\n old_embeddings = self.get_input_embeddings()\n new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)\n self.set_input_embeddings(new_embeddings)\n return self.get_input_embeddings()\n\n def _get_resized_embeddings(self, old_embeddings, new_num_tokens=None):\n \"\"\" Build a resized Embedding Module from a provided token Embedding Module.\n Increasing the size will add newly initialized vectors at the end\n Reducing the size will remove vectors from the end\n\n Args:\n new_num_tokens: (`optional`) int\n New number of tokens in the embedding matrix.\n Increasing the size will add newly initialized vectors at the end\n Reducing the size will remove vectors from the end\n If not provided or None: return the provided token Embedding Module.\n Return: ``torch.nn.Embeddings``\n Pointer to the resized Embedding Module or the old Embedding Module if new_num_tokens is None\n \"\"\"\n if new_num_tokens is None:\n return old_embeddings\n\n old_num_tokens, old_embedding_dim = old_embeddings.weight.size()\n if old_num_tokens == new_num_tokens:\n return old_embeddings\n\n # Build new embeddings\n new_embeddings = nn.Embedding(new_num_tokens, old_embedding_dim)\n new_embeddings.to(old_embeddings.weight.device)\n\n # initialize all new embeddings (in particular added tokens)\n self._init_weights(new_embeddings)\n\n # Copy word embeddings from the previous weights\n num_tokens_to_copy = min(old_num_tokens, new_num_tokens)\n new_embeddings.weight.data[:num_tokens_to_copy, :] = old_embeddings.weight.data[:num_tokens_to_copy, :]\n\n return new_embeddings\n\n def init_weights(self):\n \"\"\" Initialize and prunes weights if needed. \"\"\"\n # Initialize weights\n self.apply(self._init_weights)\n\n # Prune heads if needed\n if self.config.pruned_heads:\n self.prune_heads(self.config.pruned_heads)\n\n # Tie weights if needed\n self.tie_weights()\n\n def prune_heads(self, heads_to_prune):\n \"\"\" Prunes heads of the base model.\n\n Arguments:\n\n heads_to_prune: dict with keys being selected layer indices (`int`) and associated values being the list of heads to prune in said layer (list of `int`).\n E.g. {1: [0, 2], 2: [2, 3]} will prune heads 0 and 2 on layer 1 and heads 2 and 3 on layer 2.\n \"\"\"\n # save new sets of pruned heads as union of previously stored pruned heads and newly pruned heads\n for layer, heads in heads_to_prune.items():\n union_heads = set(self.config.pruned_heads.get(layer, [])) | set(heads)\n self.config.pruned_heads[layer] = list(union_heads) # Unfortunately we have to store it as list for JSON\n\n self.base_model._prune_heads(heads_to_prune)\n\n def save_pretrained(self, save_directory):\n \"\"\" Save a model and its configuration file to a directory, so that it\n can be re-loaded using the `:func:`~transformers.PreTrainedModel.from_pretrained`` class method.\n \"\"\"\n assert os.path.isdir(\n save_directory\n ), \"Saving path should be a directory where the model and configuration can be saved\"\n\n # Only save the model itself if we are using distributed training\n model_to_save = self.module if hasattr(self, \"module\") else self\n\n # Attach architecture to the config\n model_to_save.config.architectures = [model_to_save.__class__.__name__]\n\n # Save configuration file\n model_to_save.config.save_pretrained(save_directory)\n\n # If we save using the predefined names, we can load using `from_pretrained`\n output_model_file = os.path.join(save_directory, WEIGHTS_NAME)\n torch.save(model_to_save.state_dict(), output_model_file)\n logger.info(\"Model weights saved in {}\".format(output_model_file))\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n r\"\"\"Instantiate a pretrained pytorch model from a pre-trained model configuration.\n\n The model is set in evaluation mode by default using ``model.eval()`` (Dropout modules are deactivated)\n To train the model, you should first set it back in training mode with ``model.train()``\n\n The warning ``Weights from XXX not initialized from pretrained model`` means that the weights of XXX do not come pre-trained with the rest of the model.\n It is up to you to train those weights with a downstream fine-tuning task.\n\n The warning ``Weights from XXX not used in YYY`` means that the layer XXX is not used by YYY, therefore those weights are discarded.\n\n Parameters:\n pretrained_model_name_or_path: either:\n - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``.\n - a string with the `identifier name` of a pre-trained model that was user-uploaded to our S3, e.g.: ``dbmdz/bert-base-german-cased``.\n - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/``.\n - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.\n - None if you are both providing the configuration and state dictionary (resp. with keyword arguments ``config`` and ``state_dict``)\n\n model_args: (`optional`) Sequence of positional arguments:\n All remaning positional arguments will be passed to the underlying model's ``__init__`` method\n\n config: (`optional`) one of:\n - an instance of a class derived from :class:`~transformers.PretrainedConfig`, or\n - a string valid as input to :func:`~transformers.PretrainedConfig.from_pretrained()`\n Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when:\n - the model is a model provided by the library (loaded with the ``shortcut-name`` string of a pretrained model), or\n - the model was saved using :func:`~transformers.PreTrainedModel.save_pretrained` and is reloaded by suppling the save directory.\n - the model is loaded by suppling a local directory as ``pretrained_model_name_or_path`` and a configuration JSON file named `config.json` is found in the directory.\n\n state_dict: (`optional`) dict:\n an optional state dictionnary for the model to use instead of a state dictionary loaded from saved weights file.\n This option can be used if you want to create a model from a pretrained configuration but load your own weights.\n In this case though, you should check if using :func:`~transformers.PreTrainedModel.save_pretrained` and :func:`~transformers.PreTrainedModel.from_pretrained` is not a simpler option.\n\n cache_dir: (`optional`) string:\n Path to a directory in which a downloaded pre-trained model\n configuration should be cached if the standard cache should not be used.\n\n force_download: (`optional`) boolean, default False:\n Force to (re-)download the model weights and configuration files and override the cached versions if they exists.\n\n resume_download: (`optional`) boolean, default False:\n Do not delete incompletely recieved file. Attempt to resume the download if such a file exists.\n\n proxies: (`optional`) dict, default None:\n A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.\n The proxies are used on each request.\n\n output_loading_info: (`optional`) boolean:\n Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages.\n\n kwargs: (`optional`) Remaining dictionary of keyword arguments:\n Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. ``output_attention=True``). Behave differently depending on whether a `config` is provided or automatically loaded:\n\n - If a configuration is provided with ``config``, ``**kwargs`` will be directly passed to the underlying model's ``__init__`` method (we assume all relevant updates to the configuration have already been done)\n - If a configuration is not provided, ``kwargs`` will be first passed to the configuration class initialization function (:func:`~transformers.PretrainedConfig.from_pretrained`). Each key of ``kwargs`` that corresponds to a configuration attribute will be used to override said attribute with the supplied ``kwargs`` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's ``__init__`` function.\n\n Examples::\n\n # For example purposes. Not runnable.\n model = BertModel.from_pretrained('bert-base-uncased') # Download model and configuration from S3 and cache.\n model = BertModel.from_pretrained('./test/saved_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`\n model = BertModel.from_pretrained('bert-base-uncased', output_attention=True) # Update configuration during loading\n assert model.config.output_attention == True\n # Loading from a TF checkpoint file instead of a PyTorch model (slower)\n config = BertConfig.from_json_file('./tf_model/my_tf_model_config.json')\n model = BertModel.from_pretrained('./tf_model/my_tf_checkpoint.ckpt.index', from_tf=True, config=config)\n\n \"\"\"\n config = kwargs.pop(\"config\", None)\n state_dict = kwargs.pop(\"state_dict\", None)\n cache_dir = kwargs.pop(\"cache_dir\", None)\n from_tf = kwargs.pop(\"from_tf\", False)\n force_download = kwargs.pop(\"force_download\", False)\n resume_download = kwargs.pop(\"resume_download\", False)\n proxies = kwargs.pop(\"proxies\", None)\n output_loading_info = kwargs.pop(\"output_loading_info\", False)\n local_files_only = kwargs.pop(\"local_files_only\", False)\n\n # Load config if we don't provide a configuration\n if not isinstance(config, PretrainedConfig):\n config_path = config if config is not None else pretrained_model_name_or_path\n config, model_kwargs = cls.config_class.from_pretrained(\n config_path,\n *model_args,\n cache_dir=cache_dir,\n return_unused_kwargs=True,\n force_download=force_download,\n resume_download=resume_download,\n proxies=proxies,\n local_files_only=local_files_only,\n **kwargs,\n )\n else:\n model_kwargs = kwargs\n\n # Load model\n if pretrained_model_name_or_path is not None:\n if pretrained_model_name_or_path in cls.pretrained_model_archive_map:\n archive_file = cls.pretrained_model_archive_map[pretrained_model_name_or_path]\n elif os.path.isdir(pretrained_model_name_or_path):\n if from_tf and os.path.isfile(os.path.join(pretrained_model_name_or_path, TF_WEIGHTS_NAME + \".index\")):\n # Load from a TF 1.0 checkpoint\n archive_file = os.path.join(pretrained_model_name_or_path, TF_WEIGHTS_NAME + \".index\")\n elif from_tf and os.path.isfile(os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_NAME)):\n # Load from a TF 2.0 checkpoint\n archive_file = os.path.join(pretrained_model_name_or_path, TF2_WEIGHTS_NAME)\n elif os.path.isfile(os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)):\n # Load from a PyTorch checkpoint\n archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)\n else:\n raise EnvironmentError(\n \"Error no file named {} found in directory {} or `from_tf` set to False\".format(\n [WEIGHTS_NAME, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME + \".index\"], pretrained_model_name_or_path\n )\n )\n elif os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):\n archive_file = pretrained_model_name_or_path\n elif os.path.isfile(pretrained_model_name_or_path + \".index\"):\n assert (\n from_tf\n ), \"We found a TensorFlow checkpoint at {}, please set from_tf to True to load from this checkpoint\".format(\n pretrained_model_name_or_path + \".index\"\n )\n archive_file = pretrained_model_name_or_path + \".index\"\n else:\n archive_file = hf_bucket_url(\n pretrained_model_name_or_path, postfix=(TF2_WEIGHTS_NAME if from_tf else WEIGHTS_NAME)\n )\n\n # redirect to the cache, if necessary\n try:\n resolved_archive_file = cached_path(\n archive_file,\n cache_dir=cache_dir,\n force_download=force_download,\n proxies=proxies,\n resume_download=resume_download,\n local_files_only=local_files_only,\n )\n except EnvironmentError:\n if pretrained_model_name_or_path in cls.pretrained_model_archive_map:\n msg = \"Couldn't reach server at '{}' to download pretrained weights.\".format(archive_file)\n else:\n msg = (\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url to model weight files named one of {} but \"\n \"couldn't find any such file at this path or url.\".format(\n pretrained_model_name_or_path,\n \", \".join(cls.pretrained_model_archive_map.keys()),\n archive_file,\n [WEIGHTS_NAME, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME],\n )\n )\n raise EnvironmentError(msg)\n\n if resolved_archive_file == archive_file:\n logger.info(\"loading weights file {}\".format(archive_file))\n else:\n logger.info(\"loading weights file {} from cache at {}\".format(archive_file, resolved_archive_file))\n else:\n resolved_archive_file = None\n\n # Instantiate model.\n model = cls(config, *model_args, **model_kwargs)\n\n if state_dict is None and not from_tf:\n try:\n state_dict = torch.load(resolved_archive_file, map_location=\"cpu\")\n except Exception:\n raise OSError(\n \"Unable to load weights from pytorch checkpoint file. \"\n \"If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True. \"\n )\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n\n if from_tf:\n if resolved_archive_file.endswith(\".index\"):\n # Load from a TensorFlow 1.X checkpoint - provided by original authors\n model = cls.load_tf_weights(model, config, resolved_archive_file[:-6]) # Remove the '.index'\n else:\n # Load from our TensorFlow 2.0 checkpoints\n try:\n from transformers import load_tf2_checkpoint_in_pytorch_model\n\n model = load_tf2_checkpoint_in_pytorch_model(model, resolved_archive_file, allow_missing_keys=True)\n except ImportError:\n logger.error(\n \"Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see \"\n \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\"\n )\n raise\n else:\n # Convert old format to new format if needed from a PyTorch state_dict\n old_keys = []\n new_keys = []\n for key in state_dict.keys():\n new_key = None\n if \"gamma\" in key:\n new_key = key.replace(\"gamma\", \"weight\")\n if \"beta\" in key:\n new_key = key.replace(\"beta\", \"bias\")\n if new_key:\n old_keys.append(key)\n new_keys.append(new_key)\n for old_key, new_key in zip(old_keys, new_keys):\n state_dict[new_key] = state_dict.pop(old_key)\n\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, \"_metadata\", None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants\n # so we need to apply the function recursively.\n def load(module: nn.Module, prefix=\"\"):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs\n )\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + \".\")\n\n # Make sure we are able to load base models as well as derived models (with heads)\n start_prefix = \"\"\n model_to_load = model\n if not hasattr(model, cls.base_model_prefix) and any(\n s.startswith(cls.base_model_prefix) for s in state_dict.keys()\n ):\n start_prefix = cls.base_model_prefix + \".\"\n if hasattr(model, cls.base_model_prefix) and not any(\n s.startswith(cls.base_model_prefix) for s in state_dict.keys()\n ):\n model_to_load = getattr(model, cls.base_model_prefix)\n\n load(model_to_load, prefix=start_prefix)\n if len(missing_keys) > 0:\n logger.info(\n \"Weights of {} not initialized from pretrained model: {}\".format(\n model.__class__.__name__, missing_keys\n )\n )\n if len(unexpected_keys) > 0:\n logger.info(\n \"Weights from pretrained model not used in {}: {}\".format(\n model.__class__.__name__, unexpected_keys\n )\n )\n if len(error_msgs) > 0:\n raise RuntimeError(\n \"Error(s) in loading state_dict for {}:\\n\\t{}\".format(\n model.__class__.__name__, \"\\n\\t\".join(error_msgs)\n )\n )\n\n model.tie_weights() # make sure word embedding weights are still tied if needed\n\n # Set model in evaluation mode to desactivate DropOut modules by default\n model.eval()\n\n if output_loading_info:\n loading_info = {\"missing_keys\": missing_keys, \"unexpected_keys\": unexpected_keys, \"error_msgs\": error_msgs}\n return model, loading_info\n\n return model\n\n def prepare_inputs_for_generation(self, input_ids, **kwargs):\n return {\"input_ids\": input_ids}\n\n def _do_output_past(self, outputs):\n has_output_past = hasattr(self.config, \"output_past\") and self.config.output_past\n has_mem_len = hasattr(self.config, \"mem_len\") and self.config.mem_len\n\n if has_output_past and not has_mem_len and len(outputs) > 1:\n return True\n elif has_mem_len and self.config.mem_len > 0 and len(outputs) > 1:\n return True\n\n return False\n\n @torch.no_grad()\n def generate(\n self,\n input_ids=None,\n max_length=None,\n do_sample=True,\n num_beams=None,\n temperature=None,\n top_k=None,\n top_p=None,\n repetition_penalty=None,\n bos_token_id=None,\n pad_token_id=None,\n eos_token_ids=None,\n length_penalty=None,\n num_return_sequences=None,\n ):\n r\"\"\" Generates sequences for models with a LM head. The method currently supports greedy or penalized greedy decoding, sampling with top-k or nucleus sampling\n and beam-search.\n\n Adapted in part from `Facebook's XLM beam search code`_.\n\n .. _`Facebook's XLM beam search code`:\n https://github.com/facebookresearch/XLM/blob/9e6f6814d17be4fe5b15f2e6c43eb2b2d76daeb4/src/model/transformer.py#L529\n\n\n Parameters:\n\n input_ids: (`optional`) `torch.LongTensor` of shape `(batch_size, sequence_length)`\n The sequence used as a prompt for the generation. If `None` the method initializes\n it as an empty `torch.LongTensor` of shape `(1,)`.\n\n max_length: (`optional`) int\n The max length of the sequence to be generated. Between 1 and infinity. Default to 20.\n\n do_sample: (`optional`) bool\n If set to `False` greedy decoding is used. Otherwise sampling is used. Defaults to `True`.\n\n num_beams: (`optional`) int\n Number of beams for beam search. Must be between 1 and infinity. 1 means no beam search. Default to 1.\n\n temperature: (`optional`) float\n The value used to module the next token probabilities. Must be strictely positive. Default to 1.0.\n\n top_k: (`optional`) int\n The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.\n\n top_p: (`optional`) float\n The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.\n\n repetition_penalty: (`optional`) float\n The parameter for repetition penalty. Between 1.0 and infinity. 1.0 means no penalty. Default to 1.0.\n\n bos_token_id: (`optional`) int\n Beginning of sentence token if no prompt is provided. Default to 0.\n\n eos_token_ids: (`optional`) int or list of int\n End of sequence token or list of tokens to stop the generation. Default to 0.\n length_penalty: (`optional`) float\n Exponential penalty to the length. Default to 1.\n\n num_return_sequences: (`optional`) int\n The number of independently computed returned sequences for each element in the batch. Default to 1.\n\n Return:\n\n output: `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`\n sequence_length is either equal to max_length or shorter if all batches finished early due to the `eos_token_id`\n\n Examples::\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelWithLMHead.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n outputs = model.generate(max_length=40, bos_token_id=tokenizer.bos_token_id, eos_token_ids=tokenizer.eos_token_id, do_sample=False) # do greedy decoding\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('openai-gpt') # Initialize tokenizer\n model = AutoModelWithLMHead.from_pretrained('openai-gpt') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = torch.tensor(tokenizer.encode(input_context)).unsqueeze(0) # encode input context\n outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3, temperature=1.5) # generate 3 independent sequences using beam search decoding (5 beams) with sampling from initial context 'The dog'\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelWithLMHead.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = torch.tensor(tokenizer.encode(input_context)).unsqueeze(0) # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, bos_token_id=tokenizer.bos_token_id, pad_token_id=tokenizer.pad_token_id, eos_token_ids=tokenizer.eos_token_id, num_return_sequences=3) # 3 generate sequences using by sampling\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('ctrl') # Initialize tokenizer\n model = AutoModelWithLMHead.from_pretrained('ctrl') # Download model and configuration from S3 and cache.\n input_context = 'Legal My neighbor is' # \"Legal\" is one of the control codes for ctrl\n input_ids = torch.tensor(tokenizer.encode(input_context)).unsqueeze(0) # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2) # generate sequences\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n \"\"\"\n\n # We cannot generate if the model does not have a LM head\n if self.get_output_embeddings() is None:\n raise AttributeError(\n \"You tried to generate sequences with a model that does not have a LM Head.\"\n \"Please use another model class (e.g. `OpenAIGPTLMHeadModel`, `XLNetLMHeadModel`, `GPT2LMHeadModel`, `CTRLLMHeadModel`, `T5WithLMHeadModel`, `TransfoXLLMHeadModel`)\"\n )\n\n max_length = max_length if max_length is not None else self.config.max_length\n do_sample = do_sample if do_sample is not None else self.config.do_sample\n num_beams = num_beams if num_beams is not None else self.config.num_beams\n temperature = temperature if temperature is not None else self.config.temperature\n top_k = top_k if top_k is not None else self.config.top_k\n top_p = top_p if top_p is not None else self.config.top_p\n repetition_penalty = repetition_penalty if repetition_penalty is not None else self.config.repetition_penalty\n bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id\n pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n eos_token_ids = eos_token_ids if eos_token_ids is not None else self.config.eos_token_ids\n length_penalty = length_penalty if length_penalty is not None else self.config.length_penalty\n num_return_sequences = (\n num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences\n )\n\n if input_ids is not None:\n batch_size = input_ids.shape[0] # overriden by the input batch_size\n else:\n batch_size = 1\n if isinstance(eos_token_ids, int):\n eos_token_ids = [eos_token_ids]\n\n assert isinstance(max_length, int) and max_length > 0, \"`max_length` should be a strictely positive integer.\"\n assert isinstance(do_sample, bool), \"`do_sample` should be a boolean.\"\n assert isinstance(num_beams, int) and num_beams > 0, \"`num_beams` should be a strictely positive integer.\"\n assert temperature > 0, \"`temperature` should be strictely positive.\"\n assert isinstance(top_k, int) and top_k >= 0, \"`top_k` should be a positive integer.\"\n assert 0 <= top_p <= 1, \"`top_p` should be between 0 and 1.\"\n assert repetition_penalty >= 1.0, \"`repetition_penalty` should be >= 1.\"\n assert input_ids is not None or (\n isinstance(bos_token_id, int) and bos_token_id >= 0\n ), \"If input_ids is not defined, `bos_token_id` should be a positive integer.\"\n assert pad_token_id is None or (\n isinstance(pad_token_id, int) and (pad_token_id >= 0)\n ), \"`pad_token_id` should be a positive integer.\"\n assert (eos_token_ids is None) or (\n isinstance(eos_token_ids, (list, tuple)) and ((isinstance(e, int) and e >= 0) for e in eos_token_ids)\n ), \"`eos_token_ids` should be a positive integer or a list/tuple of positive integers.\"\n assert length_penalty > 0, \"`length_penalty` should be strictely positive.\"\n assert (\n isinstance(num_return_sequences, int) and num_return_sequences > 0\n ), \"`num_return_sequences` should be a strictely positive integer.\"\n\n if input_ids is None:\n assert isinstance(bos_token_id, int) and bos_token_id >= 0, (\n \"you should either supply a context to complete as `input_ids` input \"\n \"or a `bos_token_id` (integer >= 0) as a first token to start the generation.\"\n )\n input_ids = torch.full(\n (batch_size, 1), bos_token_id, dtype=torch.long, device=next(self.parameters()).device\n )\n else:\n assert input_ids.dim() == 2, \"Input prompt should be of shape (batch_size, sequence length).\"\n\n if pad_token_id is None and eos_token_ids is not None:\n logger.warning(\n \"Setting `pad_token_id` to {} (first `eos_token_id`) to generate sequence\".format(eos_token_ids[0])\n )\n pad_token_id = eos_token_ids[0]\n\n # current position and vocab size\n cur_len = input_ids.shape[1]\n vocab_size = self.config.vocab_size\n\n if num_return_sequences != 1:\n # Expand input to num return sequences\n input_ids = input_ids.unsqueeze(1).expand(batch_size, num_return_sequences, cur_len)\n input_ids = input_ids.contiguous().view(\n batch_size * num_return_sequences, cur_len\n ) # (batch_size * num_return_sequences, cur_len)\n effective_batch_size = batch_size * num_return_sequences\n else:\n effective_batch_size = batch_size\n\n if num_beams > 1:\n output = self._generate_beam_search(\n input_ids,\n cur_len,\n max_length,\n do_sample,\n temperature,\n top_k,\n top_p,\n repetition_penalty,\n pad_token_id,\n eos_token_ids,\n effective_batch_size,\n length_penalty,\n num_beams,\n vocab_size,\n )\n else:\n output = self._generate_no_beam_search(\n input_ids,\n cur_len,\n max_length,\n do_sample,\n temperature,\n top_k,\n top_p,\n repetition_penalty,\n pad_token_id,\n eos_token_ids,\n effective_batch_size,\n )\n\n return output\n\n def _generate_no_beam_search(\n self,\n input_ids,\n cur_len,\n max_length,\n do_sample,\n temperature,\n top_k,\n top_p,\n repetition_penalty,\n pad_token_id,\n eos_token_ids,\n batch_size,\n ):\n \"\"\" Generate sequences for each example without beam search (num_beams == 1).\n All returned sequence are generated independantly.\n \"\"\"\n # current position / max lengths / length of generated sentences / unfinished sentences\n unfinished_sents = input_ids.new(batch_size).fill_(1)\n sent_lengths = input_ids.new(batch_size).fill_(max_length)\n\n past = None\n\n while cur_len < max_length:\n model_inputs = self.prepare_inputs_for_generation(input_ids, past=past)\n outputs = self(**model_inputs)\n next_token_logits = outputs[0][:, -1, :]\n\n # if model has past, then set the past variable to speed up decoding\n if self._do_output_past(outputs):\n past = outputs[1]\n\n # repetition penalty from CTRL paper (https://arxiv.org/abs/1909.05858)\n if repetition_penalty != 1.0:\n for i in range(batch_size):\n for previous_token in set(input_ids[i].tolist()):\n # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability\n if next_token_logits[i, previous_token] < 0:\n next_token_logits[i, previous_token] *= repetition_penalty\n else:\n next_token_logits[i, previous_token] /= repetition_penalty\n\n if do_sample:\n # Temperature (higher temperature => more likely to sample low probability tokens)\n if temperature != 1.0:\n next_token_logits = next_token_logits / temperature\n # Top-p/top-k filtering\n next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)\n # Sample\n next_token = torch.multinomial(F.softmax(next_token_logits, dim=-1), num_samples=1).squeeze(1)\n else:\n # Greedy decoding\n next_token = torch.argmax(next_token_logits, dim=-1)\n\n # update generations and finished sentences\n if eos_token_ids is not None:\n # pad finished sentences if eos_token_ids exist\n tokens_to_add = next_token * unfinished_sents + (pad_token_id) * (1 - unfinished_sents)\n else:\n tokens_to_add = next_token\n\n input_ids = torch.cat([input_ids, tokens_to_add.unsqueeze(-1)], dim=-1)\n\n if eos_token_ids is not None:\n for eos_token_id in eos_token_ids:\n eos_in_sents = tokens_to_add == eos_token_id\n # if sentence is unfinished and the token to add is eos, sent_lengths is filled with current length\n is_sents_unfinished_and_token_to_add_is_eos = unfinished_sents.mul(eos_in_sents.long()).bool()\n sent_lengths.masked_fill_(is_sents_unfinished_and_token_to_add_is_eos, cur_len + 1)\n # unfinished_sents is set to zero if eos in sentence\n unfinished_sents.mul_((~eos_in_sents).long())\n\n cur_len = cur_len + 1\n\n # stop when there is a </s> in each sentence, or if we exceed the maximul length\n if unfinished_sents.max() == 0:\n break\n\n # if there are different sentences lengths in the batch, some batches have to be padded\n if sent_lengths.min().item() != sent_lengths.max().item():\n assert pad_token_id is not None, \"`Pad_token_id` has to be defined if batches have different lengths\"\n # finished sents are filled with pad_token\n decoded = input_ids.new(batch_size, sent_lengths.max().item()).fill_(pad_token_id)\n else:\n decoded = input_ids\n\n for hypo_idx, hypo in enumerate(input_ids):\n decoded[hypo_idx, : sent_lengths[hypo_idx]] = hypo[: sent_lengths[hypo_idx]]\n\n return decoded\n\n def _generate_beam_search(\n self,\n input_ids,\n cur_len,\n max_length,\n do_sample,\n temperature,\n top_k,\n top_p,\n repetition_penalty,\n pad_token_id,\n eos_token_ids,\n batch_size,\n length_penalty,\n num_beams,\n vocab_size,\n ):\n \"\"\" Generate sequences for each example with beam search.\n \"\"\"\n # Expand input to num beams\n input_ids = input_ids.unsqueeze(1).expand(batch_size, num_beams, cur_len)\n input_ids = input_ids.contiguous().view(batch_size * num_beams, cur_len) # (batch_size * num_beams, cur_len)\n\n # generated hypotheses\n generated_hyps = [\n BeamHypotheses(num_beams, max_length, length_penalty, early_stopping=False) for _ in range(batch_size)\n ]\n\n # scores for each sentence in the beam\n beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)\n beam_scores[:, 1:] = -1e9\n beam_scores = beam_scores.view(-1) # shape (batch_size * num_beams,)\n\n # cache compute states\n past = None\n\n # done sentences\n done = [False for _ in range(batch_size)]\n\n while cur_len < max_length:\n model_inputs = self.prepare_inputs_for_generation(input_ids, past=past)\n outputs = self(**model_inputs) # (batch_size * num_beams, cur_len, vocab_size)\n scores = outputs[0][:, -1, :] # (batch_size * num_beams, vocab_size)\n\n # if model has past, then set the past variable to speed up decoding\n if self._do_output_past(outputs):\n past = outputs[1]\n\n # repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858)\n if repetition_penalty != 1.0:\n for i in range(batch_size * num_beams):\n for previous_token in set(input_ids[i].tolist()):\n # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability\n if scores[i, previous_token] < 0:\n scores[i, previous_token] *= repetition_penalty\n else:\n scores[i, previous_token] /= repetition_penalty\n\n if do_sample:\n # Temperature (higher temperature => more likely to sample low probability tokens)\n if temperature != 1.0:\n scores = scores / temperature\n # Top-p/top-k filtering\n scores = top_k_top_p_filtering(\n scores, top_k=top_k, top_p=top_p, min_tokens_to_keep=2\n ) # (batch_size * num_beams, vocab_size)\n # Sample 2 next words for each beam (so we have some spare tokens and match output of greedy beam search)\n next_words = torch.multinomial(F.softmax(scores, dim=-1), num_samples=2) # (batch_size * num_beams, 2)\n # Compute next scores\n _scores = F.log_softmax(scores, dim=-1) # (batch_size * num_beams, vocab_size)\n _scores = torch.gather(_scores, -1, next_words) # (batch_size * num_beams, 2)\n next_scores = _scores + beam_scores[:, None].expand_as(_scores) # (batch_size * num_beams, 2)\n # Match shape of greedy beam search\n next_words = next_words.view(batch_size, 2 * num_beams) # (batch_size, 2 * num_beams)\n next_scores = next_scores.view(batch_size, 2 * num_beams) # (batch_size, 2 * num_beams)\n else:\n # do greedy beam search\n scores = F.log_softmax(scores, dim=-1) # (batch_size * num_beams, vocab_size)\n assert scores.size() == (batch_size * num_beams, vocab_size)\n # Add the log prob of the new beams to the log prob of the beginning of the sequence (sum of logs == log of the product)\n _scores = scores + beam_scores[:, None].expand_as(scores) # (batch_size * num_beams, vocab_size)\n # re-organize to group the beam together (we are keeping top hypothesis accross beams)\n _scores = _scores.view(batch_size, num_beams * vocab_size) # (batch_size, num_beams * vocab_size)\n next_scores, next_words = torch.topk(_scores, 2 * num_beams, dim=1, largest=True, sorted=True)\n\n assert next_scores.size() == next_words.size() == (batch_size, 2 * num_beams)\n\n # next batch beam content\n # list of (batch_size * num_beams) tuple(next hypothesis score, next word, current position in the batch)\n next_batch_beam = []\n\n # for each sentence\n for batch_idx in range(batch_size):\n\n # if we are done with this sentence\n done[batch_idx] = done[batch_idx] or generated_hyps[batch_idx].is_done(\n next_scores[batch_idx].max().item()\n )\n if done[batch_idx]:\n assert (\n len(generated_hyps[batch_idx]) >= num_beams\n ), \"Batch can only be done if at least {} beams have been generated\".format(num_beams)\n assert (\n eos_token_ids is not None and pad_token_id is not None\n ), \"generated beams >= num_beams -> eos_token_id and pad_token have to be defined\"\n next_batch_beam.extend([(0, pad_token_id, 0)] * num_beams) # pad the batch\n continue\n\n # next sentence beam content\n next_sent_beam = []\n\n # next words for this sentence\n for idx, score in zip(next_words[batch_idx], next_scores[batch_idx]):\n\n # get beam and word IDs\n beam_id = idx // vocab_size\n word_id = idx % vocab_size\n\n # add to generated hypotheses if end of sentence or last iteration\n if eos_token_ids is not None and word_id.item() in eos_token_ids:\n generated_hyps[batch_idx].add(\n input_ids[batch_idx * num_beams + beam_id, :cur_len].clone(), score.item()\n )\n else:\n # add next predicted word if it is not eos_token\n next_sent_beam.append((score, word_id, batch_idx * num_beams + beam_id))\n\n # the beam for next step is full\n if len(next_sent_beam) == num_beams:\n break\n\n # update next beam content\n assert len(next_sent_beam) == num_beams, \"Beam should always be full\"\n next_batch_beam.extend(next_sent_beam)\n assert len(next_batch_beam) == num_beams * (batch_idx + 1)\n\n # sanity check / prepare next batch\n assert len(next_batch_beam) == batch_size * num_beams\n beam_scores = beam_scores.new([x[0] for x in next_batch_beam])\n beam_words = input_ids.new([x[1] for x in next_batch_beam])\n beam_idx = input_ids.new([x[2] for x in next_batch_beam])\n\n # re-order batch\n input_ids = input_ids[beam_idx, :]\n input_ids = torch.cat([input_ids, beam_words.unsqueeze(1)], dim=-1)\n\n # re-order internal states\n if past:\n reordered_past = []\n for layer_past in past:\n # get the correct batch idx from layer past batch dim\n # batch dim of `past` and `mems` is at 2nd position\n reordered_layer_past = [layer_past[:, i].unsqueeze(1).clone().detach() for i in beam_idx]\n reordered_layer_past = torch.cat(reordered_layer_past, dim=1)\n # check that shape matches\n assert reordered_layer_past.shape == layer_past.shape\n reordered_past.append(reordered_layer_past)\n past = tuple(reordered_past)\n\n # update current length\n cur_len = cur_len + 1\n\n # stop when we are done with each sentence\n if all(done):\n break\n\n for batch_idx in range(batch_size):\n # Add all open beam hypothesis to generated_hyps\n if not done[batch_idx]:\n for idx, score in zip(next_words[batch_idx], next_scores[batch_idx]):\n\n # get beam and word IDs\n beam_id = idx // vocab_size\n word_id = idx % vocab_size\n generated_hyps[batch_idx].add(\n input_ids[batch_idx * num_beams + beam_id, :cur_len].clone(), score.item()\n )\n\n # select the best hypotheses\n sent_lengths = input_ids.new(batch_size)\n best = []\n\n for i, hypotheses in enumerate(generated_hyps):\n best_hyp = max(hypotheses.beams, key=lambda x: x[0])[1]\n sent_lengths[i] = len(best_hyp)\n best.append(best_hyp)\n\n # shorter batches are filled with pad_token\n if sent_lengths.min().item() != sent_lengths.max().item():\n assert pad_token_id is not None, \"`Pad_token_id` has to be defined\"\n sent_max_len = min(sent_lengths.max().item() + 1, max_length)\n decoded = input_ids.new(batch_size, sent_max_len).fill_(pad_token_id)\n\n # fill with hypothesis and eos_token_id if necessary\n for i, hypo in enumerate(best):\n decoded[i, : sent_lengths[i]] = hypo\n if sent_lengths[i] < max_length:\n decoded[i, sent_lengths[i]] = eos_token_ids[0]\n else:\n # none of the hypotheses have an eos_token\n assert (len(hypo) == max_length for hypo in best)\n decoded = torch.stack(best).type(torch.long).to(next(self.parameters()).device)\n\n return decoded" }, { "identifier": "prune_linear_layer", "path": "transformers/src/transformers/modeling_utils.py", "snippet": "def prune_linear_layer(layer, index, dim=0):\n \"\"\" Prune a linear layer (a model parameters) to keep only entries in index.\n Return the pruned layer as a new layer with requires_grad=True.\n Used to remove heads.\n \"\"\"\n index = index.to(layer.weight.device)\n W = layer.weight.index_select(dim, index).clone().detach()\n if layer.bias is not None:\n if dim == 1:\n b = layer.bias.clone().detach()\n else:\n b = layer.bias[index].clone().detach()\n new_size = list(layer.weight.size())\n new_size[dim] = len(index)\n new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None).to(layer.weight.device)\n new_layer.weight.requires_grad = False\n new_layer.weight.copy_(W.contiguous())\n new_layer.weight.requires_grad = True\n if layer.bias is not None:\n new_layer.bias.requires_grad = False\n new_layer.bias.copy_(b.contiguous())\n new_layer.bias.requires_grad = True\n return new_layer" } ]
import logging import math import os import torch import torch.nn.functional as F import pdb import re import numpy as np import tensorflow as tf import pdb from symbol import factor from tkinter import E from torch import nn from torch.nn import CrossEntropyLoss, MSELoss, BCEWithLogitsLoss from torch.nn.utils.rnn import pad_sequence from .modules import * from .activations import gelu, gelu_new, swish from .configuration_bert import BertConfig from .file_utils import add_start_docstrings, add_start_docstrings_to_callable from .modeling_utils import PreTrainedModel, prune_linear_layer
16,299
full_attention_mask=None, ): all_hidden_states = () all_attentions = () for i, layer_module in enumerate(self.layer): if i==self.use_full_layer: attention_mask = full_attention_mask if self.output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_outputs = layer_module( hidden_states, attention_mask, head_mask[i], encoder_hidden_states, encoder_attention_mask ) hidden_states = layer_outputs[0] if self.output_attentions: all_attentions = all_attentions + (layer_outputs[1],) # Add last layer if self.output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) outputs = (hidden_states,) if self.output_hidden_states: outputs = outputs + (all_hidden_states,) if self.output_attentions: outputs = outputs + (all_attentions,) return outputs # last-layer hidden state, (all hidden states), (all attentions) class BertPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class BertPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class BertLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states class BertOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class BertOnlyNSPHead(nn.Module): def __init__(self, config): super().__init__() self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, pooled_output): seq_relationship_score = self.seq_relationship(pooled_output) return seq_relationship_score class BertPreTrainingHeads(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output, pooled_output): prediction_scores = self.predictions(sequence_output) seq_relationship_score = self.seq_relationship(pooled_output) return prediction_scores, seq_relationship_score class BertPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch BERT model. """ # from .modules import BiaffineSpanRepr, BiaffineRelationCls, BiafEncoder, \ # CatEncoder, max_pool, Tetrafine, BiaffineMessagePasser, \ # LinearMessegePasser, CPDTrilinear, CatEncoderCross, \ # bilinear_classifier, BiafCrossEncoder logger = logging.getLogger(__name__) BERT_PRETRAINED_MODEL_ARCHIVE_MAP = { "bert-base-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-pytorch_model.bin", "bert-large-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-pytorch_model.bin", "bert-base-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-pytorch_model.bin", "bert-large-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-pytorch_model.bin", "bert-base-multilingual-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-pytorch_model.bin", "bert-base-multilingual-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-pytorch_model.bin", "bert-base-chinese": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-pytorch_model.bin", "bert-base-german-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-cased-pytorch_model.bin", "bert-large-uncased-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-pytorch_model.bin", "bert-large-cased-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-pytorch_model.bin", "bert-large-uncased-whole-word-masking-finetuned-squad": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.bin", "bert-large-cased-whole-word-masking-finetuned-squad": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-pytorch_model.bin", "bert-base-cased-finetuned-mrpc": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-pytorch_model.bin", "bert-base-german-dbmdz-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-cased-pytorch_model.bin", "bert-base-german-dbmdz-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-uncased-pytorch_model.bin", "bert-base-japanese": "https://s3.amazonaws.com/models.huggingface.co/bert/cl-tohoku/bert-base-japanese-pytorch_model.bin", "bert-base-japanese-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/cl-tohoku/bert-base-japanese-whole-word-masking-pytorch_model.bin", "bert-base-japanese-char": "https://s3.amazonaws.com/models.huggingface.co/bert/cl-tohoku/bert-base-japanese-char-pytorch_model.bin", "bert-base-japanese-char-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/cl-tohoku/bert-base-japanese-char-whole-word-masking-pytorch_model.bin", "bert-base-finnish-cased-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/TurkuNLP/bert-base-finnish-cased-v1/pytorch_model.bin", "bert-base-finnish-uncased-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/TurkuNLP/bert-base-finnish-uncased-v1/pytorch_model.bin", "bert-base-dutch-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/wietsedv/bert-base-dutch-cased/pytorch_model.bin", } def load_tf_weights_in_bert(model, config, tf_checkpoint_path): """ Load tf checkpoints in a pytorch model. """ try: except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise tf_path = os.path.abspath(tf_checkpoint_path) logger.info("Converting TensorFlow checkpoint from {}".format(tf_path)) # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: logger.info("Loading TF weight {} with shape {}".format(name, shape)) array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array) for name, array in zip(names, arrays): name = name.split("/") # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any( n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name ): logger.info("Skipping {}".format("/".join(name))) continue pointer = model for m_name in name: if re.fullmatch(r"[A-Za-z]+_\d+", m_name): scope_names = re.split(r"_(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] == "kernel" or scope_names[0] == "gamma": pointer = getattr(pointer, "weight") elif scope_names[0] == "output_bias" or scope_names[0] == "beta": pointer = getattr(pointer, "bias") elif scope_names[0] == "output_weights": pointer = getattr(pointer, "weight") elif scope_names[0] == "squad": pointer = getattr(pointer, "classifier") else: try: pointer = getattr(pointer, scope_names[0]) except AttributeError: logger.info("Skipping {}".format("/".join(name))) continue if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] if m_name[-11:] == "_embeddings": pointer = getattr(pointer, "weight") elif m_name == "kernel": array = np.transpose(array) try: assert pointer.shape == array.shape except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info("Initialize PyTorch weight {}".format(name)) pointer.data = torch.from_numpy(array) return model def mish(x): return x * torch.tanh(nn.functional.softplus(x)) ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish, "gelu_new": gelu_new, "mish": mish} BertLayerNorm = torch.nn.LayerNorm class BertEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings. """ def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] device = input_ids.device if input_ids is not None else inputs_embeds.device if position_ids is None: position_ids = torch.arange(seq_length, dtype=torch.long, device=device) position_ids = position_ids.unsqueeze(0).expand(input_shape) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) position_embeddings = self.position_embeddings(position_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = inputs_embeds + position_embeddings + token_type_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings class BertSelfAttention(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads) ) self.output_attentions = config.output_attentions self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, ): mixed_query_layer = self.query(hidden_states) # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. if encoder_hidden_states is not None: mixed_key_layer = self.key(encoder_hidden_states) mixed_value_layer = self.value(encoder_hidden_states) attention_mask = encoder_attention_mask else: mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, attention_probs) if self.output_attentions else (context_layer,) return outputs class BertSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttention(nn.Module): def __init__(self, config): super().__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) self.pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return mask = torch.ones(self.self.num_attention_heads, self.self.attention_head_size) heads = set(heads) - self.pruned_heads # Convert to set and remove already pruned heads for head in heads: # Compute how many pruned heads are before the head and move the index accordingly head = head - sum(1 if h < head else 0 for h in self.pruned_heads) mask[head] = 0 mask = mask.view(-1).contiguous().eq(1) index = torch.arange(len(mask))[mask].long() # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, ): self_outputs = self.self( hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask ) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs class BertIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class BertOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertLayer(nn.Module): def __init__(self, config): super().__init__() self.attention = BertAttention(config) self.is_decoder = config.is_decoder if self.is_decoder: self.crossattention = BertAttention(config) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, ): self_attention_outputs = self.attention(hidden_states, attention_mask, head_mask) attention_output = self_attention_outputs[0] outputs = self_attention_outputs[1:] # add self attentions if we output attention weights if self.is_decoder and encoder_hidden_states is not None: cross_attention_outputs = self.crossattention( attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) outputs = (layer_output,) + outputs return outputs class BertEncoder(nn.Module): def __init__(self, config): super().__init__() self.output_attentions = config.output_attentions self.output_hidden_states = config.output_hidden_states self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)]) try: self.use_full_layer = config.use_full_layer except: self.use_full_layer = -1 def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, full_attention_mask=None, ): all_hidden_states = () all_attentions = () for i, layer_module in enumerate(self.layer): if i==self.use_full_layer: attention_mask = full_attention_mask if self.output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_outputs = layer_module( hidden_states, attention_mask, head_mask[i], encoder_hidden_states, encoder_attention_mask ) hidden_states = layer_outputs[0] if self.output_attentions: all_attentions = all_attentions + (layer_outputs[1],) # Add last layer if self.output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) outputs = (hidden_states,) if self.output_hidden_states: outputs = outputs + (all_hidden_states,) if self.output_attentions: outputs = outputs + (all_attentions,) return outputs # last-layer hidden state, (all hidden states), (all attentions) class BertPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class BertPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class BertLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states class BertOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class BertOnlyNSPHead(nn.Module): def __init__(self, config): super().__init__() self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, pooled_output): seq_relationship_score = self.seq_relationship(pooled_output) return seq_relationship_score class BertPreTrainingHeads(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output, pooled_output): prediction_scores = self.predictions(sequence_output) seq_relationship_score = self.seq_relationship(pooled_output) return prediction_scores, seq_relationship_score class BertPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """
config_class = BertConfig
1
2023-10-15 02:31:09+00:00
24k
akashgreninja/GreSec
backend/venv/lib/python3.10/site-packages/urllib3/connectionpool.py
[ { "identifier": "_TYPE_BODY", "path": "backend/venv/lib/python3.10/site-packages/urllib3/_base_connection.py", "snippet": "_TYPE_BODY = typing.Union[bytes, typing.IO[typing.Any], typing.Iterable[bytes], str]" }, { "identifier": "HTTPHeaderDict", "path": "backend/venv/lib/python3.10/site-packages/urllib3/_collections.py", "snippet": "class HTTPHeaderDict(typing.MutableMapping[str, str]):\n \"\"\"\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-insensitively.\n\n :param kwargs:\n Additional field-value pairs to pass in to ``dict.update``.\n\n A ``dict`` like container for storing HTTP Headers.\n\n Field names are stored and compared case-insensitively in compliance with\n RFC 7230. Iteration provides the first case-sensitive key seen for each\n case-insensitive pair.\n\n Using ``__setitem__`` syntax overwrites fields that compare equal\n case-insensitively in order to maintain ``dict``'s api. For fields that\n compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n in a loop.\n\n If multiple fields that are equal case-insensitively are passed to the\n constructor or ``.update``, the behavior is undefined and some will be\n lost.\n\n >>> headers = HTTPHeaderDict()\n >>> headers.add('Set-Cookie', 'foo=bar')\n >>> headers.add('set-cookie', 'baz=quxx')\n >>> headers['content-length'] = '7'\n >>> headers['SET-cookie']\n 'foo=bar, baz=quxx'\n >>> headers['Content-Length']\n '7'\n \"\"\"\n\n _container: typing.MutableMapping[str, list[str]]\n\n def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str):\n super().__init__()\n self._container = {} # 'dict' is insert-ordered in Python 3.7+\n if headers is not None:\n if isinstance(headers, HTTPHeaderDict):\n self._copy_from(headers)\n else:\n self.extend(headers)\n if kwargs:\n self.extend(kwargs)\n\n def __setitem__(self, key: str, val: str) -> None:\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n self._container[key.lower()] = [key, val]\n\n def __getitem__(self, key: str) -> str:\n val = self._container[key.lower()]\n return \", \".join(val[1:])\n\n def __delitem__(self, key: str) -> None:\n del self._container[key.lower()]\n\n def __contains__(self, key: object) -> bool:\n if isinstance(key, str):\n return key.lower() in self._container\n return False\n\n def setdefault(self, key: str, default: str = \"\") -> str:\n return super().setdefault(key, default)\n\n def __eq__(self, other: object) -> bool:\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return False\n else:\n other_as_http_header_dict = type(self)(maybe_constructable)\n\n return {k.lower(): v for k, v in self.itermerged()} == {\n k.lower(): v for k, v in other_as_http_header_dict.itermerged()\n }\n\n def __ne__(self, other: object) -> bool:\n return not self.__eq__(other)\n\n def __len__(self) -> int:\n return len(self._container)\n\n def __iter__(self) -> typing.Iterator[str]:\n # Only provide the originally cased names\n for vals in self._container.values():\n yield vals[0]\n\n def discard(self, key: str) -> None:\n try:\n del self[key]\n except KeyError:\n pass\n\n def add(self, key: str, val: str, *, combine: bool = False) -> None:\n \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n If this is called with combine=True, instead of adding a new header value\n as a distinct item during iteration, this will instead append the value to\n any existing header value with a comma. If no existing header value exists\n for the key, then the value will simply be added, ignoring the combine parameter.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n >>> list(headers.items())\n [('foo', 'bar'), ('foo', 'baz')]\n >>> headers.add('foo', 'quz', combine=True)\n >>> list(headers.items())\n [('foo', 'bar, baz, quz')]\n \"\"\"\n # avoid a bytes/str comparison by decoding before httplib\n if isinstance(key, bytes):\n key = key.decode(\"latin-1\")\n key_lower = key.lower()\n new_vals = [key, val]\n # Keep the common case aka no item present as fast as possible\n vals = self._container.setdefault(key_lower, new_vals)\n if new_vals is not vals:\n # if there are values here, then there is at least the initial\n # key/value pair\n assert len(vals) >= 2\n if combine:\n vals[-1] = vals[-1] + \", \" + val\n else:\n vals.append(val)\n\n def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None:\n \"\"\"Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n \"\"\"\n if len(args) > 1:\n raise TypeError(\n f\"extend() takes at most 1 positional arguments ({len(args)} given)\"\n )\n other = args[0] if len(args) >= 1 else ()\n\n if isinstance(other, HTTPHeaderDict):\n for key, val in other.iteritems():\n self.add(key, val)\n elif isinstance(other, typing.Mapping):\n for key, val in other.items():\n self.add(key, val)\n elif isinstance(other, typing.Iterable):\n other = typing.cast(typing.Iterable[typing.Tuple[str, str]], other)\n for key, value in other:\n self.add(key, value)\n elif hasattr(other, \"keys\") and hasattr(other, \"__getitem__\"):\n # THIS IS NOT A TYPESAFE BRANCH\n # In this branch, the object has a `keys` attr but is not a Mapping or any of\n # the other types indicated in the method signature. We do some stuff with\n # it as though it partially implements the Mapping interface, but we're not\n # doing that stuff safely AT ALL.\n for key in other.keys():\n self.add(key, other[key])\n\n for key, value in kwargs.items():\n self.add(key, value)\n\n @typing.overload\n def getlist(self, key: str) -> list[str]:\n ...\n\n @typing.overload\n def getlist(self, key: str, default: _DT) -> list[str] | _DT:\n ...\n\n def getlist(\n self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed\n ) -> list[str] | _DT:\n \"\"\"Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist.\"\"\"\n try:\n vals = self._container[key.lower()]\n except KeyError:\n if default is _Sentinel.not_passed:\n # _DT is unbound; empty list is instance of List[str]\n return []\n # _DT is bound; default is instance of _DT\n return default\n else:\n # _DT may or may not be bound; vals[1:] is instance of List[str], which\n # meets our external interface requirement of `Union[List[str], _DT]`.\n return vals[1:]\n\n def _prepare_for_method_change(self) -> Self:\n \"\"\"\n Remove content-specific header fields before changing the request\n method to GET or HEAD according to RFC 9110, Section 15.4.\n \"\"\"\n content_specific_headers = [\n \"Content-Encoding\",\n \"Content-Language\",\n \"Content-Location\",\n \"Content-Type\",\n \"Content-Length\",\n \"Digest\",\n \"Last-Modified\",\n ]\n for header in content_specific_headers:\n self.discard(header)\n return self\n\n # Backwards compatibility for httplib\n getheaders = getlist\n getallmatchingheaders = getlist\n iget = getlist\n\n # Backwards compatibility for http.cookiejar\n get_all = getlist\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}({dict(self.itermerged())})\"\n\n def _copy_from(self, other: HTTPHeaderDict) -> None:\n for key in other:\n val = other.getlist(key)\n self._container[key.lower()] = [key, *val]\n\n def copy(self) -> HTTPHeaderDict:\n clone = type(self)()\n clone._copy_from(self)\n return clone\n\n def iteritems(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n for key in self:\n vals = self._container[key.lower()]\n for val in vals[1:]:\n yield vals[0], val\n\n def itermerged(self) -> typing.Iterator[tuple[str, str]]:\n \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n for key in self:\n val = self._container[key.lower()]\n yield val[0], \", \".join(val[1:])\n\n def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]\n return HTTPHeaderDictItemView(self)\n\n def _has_value_for_header(self, header_name: str, potential_value: str) -> bool:\n if header_name in self:\n return potential_value in self._container[header_name.lower()][1:]\n return False\n\n def __ior__(self, other: object) -> HTTPHeaderDict:\n # Supports extending a header dict in-place using operator |=\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n self.extend(maybe_constructable)\n return self\n\n def __or__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator |\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = self.copy()\n result.extend(maybe_constructable)\n return result\n\n def __ror__(self, other: object) -> HTTPHeaderDict:\n # Supports merging header dicts using operator | when other is on left side\n # combining items with add instead of __setitem__\n maybe_constructable = ensure_can_construct_http_header_dict(other)\n if maybe_constructable is None:\n return NotImplemented\n result = type(self)(maybe_constructable)\n result.extend(self)\n return result" }, { "identifier": "RequestMethods", "path": "backend/venv/lib/python3.10/site-packages/urllib3/_request_methods.py", "snippet": "class RequestMethods:\n \"\"\"\n Convenience mixin for classes who implement a :meth:`urlopen` method, such\n as :class:`urllib3.HTTPConnectionPool` and\n :class:`urllib3.PoolManager`.\n\n Provides behavior for making common types of HTTP request methods and\n decides which type of request field encoding to use.\n\n Specifically,\n\n :meth:`.request_encode_url` is for sending requests whose fields are\n encoded in the URL (such as GET, HEAD, DELETE).\n\n :meth:`.request_encode_body` is for sending requests whose fields are\n encoded in the *body* of the request using multipart or www-form-urlencoded\n (such as for POST, PUT, PATCH).\n\n :meth:`.request` is for making any kind of request, it will look up the\n appropriate encoding format and use one of the above two methods to make\n the request.\n\n Initializer parameters:\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n \"\"\"\n\n _encode_url_methods = {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\"}\n\n def __init__(self, headers: typing.Mapping[str, str] | None = None) -> None:\n self.headers = headers or {}\n\n def urlopen(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n encode_multipart: bool = True,\n multipart_boundary: str | None = None,\n **kw: typing.Any,\n ) -> BaseHTTPResponse: # Abstract\n raise NotImplementedError(\n \"Classes extending RequestMethods must implement \"\n \"their own ``urlopen`` method.\"\n )\n\n def request(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n fields: _TYPE_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n json: typing.Any | None = None,\n **urlopen_kw: typing.Any,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the appropriate encoding of\n ``fields`` based on the ``method`` used.\n\n This is a convenience method that requires the least amount of manual\n effort. It can be used in most situations, while still having the\n option to drop down to more specific methods when necessary, such as\n :meth:`request_encode_url`, :meth:`request_encode_body`,\n or even the lowest level :meth:`urlopen`.\n \"\"\"\n method = method.upper()\n\n if json is not None and body is not None:\n raise TypeError(\n \"request got values for both 'body' and 'json' parameters which are mutually exclusive\"\n )\n\n if json is not None:\n if headers is None:\n headers = self.headers.copy() # type: ignore\n if not (\"content-type\" in map(str.lower, headers.keys())):\n headers[\"Content-Type\"] = \"application/json\" # type: ignore\n\n body = _json.dumps(json, separators=(\",\", \":\"), ensure_ascii=False).encode(\n \"utf-8\"\n )\n\n if body is not None:\n urlopen_kw[\"body\"] = body\n\n if method in self._encode_url_methods:\n return self.request_encode_url(\n method,\n url,\n fields=fields, # type: ignore[arg-type]\n headers=headers,\n **urlopen_kw,\n )\n else:\n return self.request_encode_body(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n\n def request_encode_url(\n self,\n method: str,\n url: str,\n fields: _TYPE_ENCODE_URL_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n **urlopen_kw: str,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw: dict[str, typing.Any] = {\"headers\": headers}\n extra_kw.update(urlopen_kw)\n\n if fields:\n url += \"?\" + urlencode(fields)\n\n return self.urlopen(method, url, **extra_kw)\n\n def request_encode_body(\n self,\n method: str,\n url: str,\n fields: _TYPE_FIELDS | None = None,\n headers: typing.Mapping[str, str] | None = None,\n encode_multipart: bool = True,\n multipart_boundary: str | None = None,\n **urlopen_kw: str,\n ) -> BaseHTTPResponse:\n \"\"\"\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :func:`urllib3.encode_multipart_formdata` is used to encode\n the payload with the appropriate content type. Otherwise\n :func:`urllib.parse.urlencode` is used with the\n 'application/x-www-form-urlencoded' content type.\n\n Multipart encoding must be used when posting files, and it's reasonably\n safe to use it in other times too. However, it may break request\n signing, such as with OAuth.\n\n Supports an optional ``fields`` parameter of key/value strings AND\n key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n the MIME type is optional. For example::\n\n fields = {\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(),\n 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n }\n\n When uploading a file, providing a filename (the first parameter of the\n tuple) is optional but recommended to best mimic behavior of browsers.\n\n Note that if ``headers`` are supplied, the 'Content-Type' header will\n be overwritten because it depends on the dynamic random boundary string\n which is used to compose the body of the request. The random boundary\n string can be explicitly set with the ``multipart_boundary`` parameter.\n \"\"\"\n if headers is None:\n headers = self.headers\n\n extra_kw: dict[str, typing.Any] = {\"headers\": HTTPHeaderDict(headers)}\n body: bytes | str\n\n if fields:\n if \"body\" in urlopen_kw:\n raise TypeError(\n \"request got values for both 'fields' and 'body', can only specify one.\"\n )\n\n if encode_multipart:\n body, content_type = encode_multipart_formdata(\n fields, boundary=multipart_boundary\n )\n else:\n body, content_type = (\n urlencode(fields), # type: ignore[arg-type]\n \"application/x-www-form-urlencoded\",\n )\n\n extra_kw[\"body\"] = body\n extra_kw[\"headers\"].setdefault(\"Content-Type\", content_type)\n\n extra_kw.update(urlopen_kw)\n\n return self.urlopen(method, url, **extra_kw)" }, { "identifier": "BaseSSLError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/connection.py", "snippet": " class BaseSSLError(BaseException): # type: ignore[no-redef]\nclass HTTPConnection(_HTTPConnection):\nclass HTTPSConnection(HTTPConnection):\nclass _WrappedAndVerifiedSocket(typing.NamedTuple):\nclass DummyConnection:\nRECENT_DATE = datetime.date(2022, 1, 1)\n_CONTAINS_CONTROL_CHAR_RE = re.compile(r\"[^-!#$%&'*+.^_`|~0-9a-zA-Z]\")\n_HAS_SYS_AUDIT = hasattr(sys, \"audit\")\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n ) -> None:\n def host(self) -> str:\n def host(self, value: str) -> None:\n def _new_conn(self) -> socket.socket:\n def set_tunnel(\n self,\n host: str,\n port: int | None = None,\n headers: typing.Mapping[str, str] | None = None,\n scheme: str = \"http\",\n ) -> None:\n def connect(self) -> None:\n def is_closed(self) -> bool:\n def is_connected(self) -> bool:\n def has_connected_to_proxy(self) -> bool:\n def close(self) -> None:\n def putrequest(\n self,\n method: str,\n url: str,\n skip_host: bool = False,\n skip_accept_encoding: bool = False,\n ) -> None:\n def putheader(self, header: str, *values: str) -> None:\n def request( # type: ignore[override]\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n *,\n chunked: bool = False,\n preload_content: bool = True,\n decode_content: bool = True,\n enforce_content_length: bool = True,\n ) -> None:\n def request_chunked(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n ) -> None:\n def getresponse( # type: ignore[override]\n self,\n ) -> HTTPResponse:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = HTTPConnection.default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n cert_reqs: int | str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n server_hostname: str | None = None,\n ssl_context: ssl.SSLContext | None = None,\n ca_certs: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ssl_minimum_version: int | None = None,\n ssl_maximum_version: int | None = None,\n ssl_version: int | str | None = None, # Deprecated\n cert_file: str | None = None,\n key_file: str | None = None,\n key_password: str | None = None,\n ) -> None:\n def set_cert(\n self,\n key_file: str | None = None,\n cert_file: str | None = None,\n cert_reqs: int | str | None = None,\n key_password: str | None = None,\n ca_certs: str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ) -> None:\n def connect(self) -> None:\n def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket:\ndef _ssl_wrap_socket_and_match_hostname(\n sock: socket.socket,\n *,\n cert_reqs: None | str | int,\n ssl_version: None | str | int,\n ssl_minimum_version: int | None,\n ssl_maximum_version: int | None,\n cert_file: str | None,\n key_file: str | None,\n key_password: str | None,\n ca_certs: str | None,\n ca_cert_dir: str | None,\n ca_cert_data: None | str | bytes,\n assert_hostname: None | str | Literal[False],\n assert_fingerprint: str | None,\n server_hostname: str | None,\n ssl_context: ssl.SSLContext | None,\n tls_in_tls: bool = False,\n) -> _WrappedAndVerifiedSocket:\ndef _match_hostname(\n cert: _TYPE_PEER_CERT_RET_DICT | None,\n asserted_hostname: str,\n hostname_checks_common_name: bool = False,\n) -> None:\ndef _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError:\ndef _get_default_user_agent() -> str:\ndef _url_from_connection(\n conn: HTTPConnection | HTTPSConnection, path: str | None = None\n) -> str:" }, { "identifier": "port_by_scheme", "path": "backend/venv/lib/python3.10/site-packages/urllib3/connection.py", "snippet": " class BaseSSLError(BaseException): # type: ignore[no-redef]\nclass HTTPConnection(_HTTPConnection):\nclass HTTPSConnection(HTTPConnection):\nclass _WrappedAndVerifiedSocket(typing.NamedTuple):\nclass DummyConnection:\nRECENT_DATE = datetime.date(2022, 1, 1)\n_CONTAINS_CONTROL_CHAR_RE = re.compile(r\"[^-!#$%&'*+.^_`|~0-9a-zA-Z]\")\n_HAS_SYS_AUDIT = hasattr(sys, \"audit\")\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n ) -> None:\n def host(self) -> str:\n def host(self, value: str) -> None:\n def _new_conn(self) -> socket.socket:\n def set_tunnel(\n self,\n host: str,\n port: int | None = None,\n headers: typing.Mapping[str, str] | None = None,\n scheme: str = \"http\",\n ) -> None:\n def connect(self) -> None:\n def is_closed(self) -> bool:\n def is_connected(self) -> bool:\n def has_connected_to_proxy(self) -> bool:\n def close(self) -> None:\n def putrequest(\n self,\n method: str,\n url: str,\n skip_host: bool = False,\n skip_accept_encoding: bool = False,\n ) -> None:\n def putheader(self, header: str, *values: str) -> None:\n def request( # type: ignore[override]\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n *,\n chunked: bool = False,\n preload_content: bool = True,\n decode_content: bool = True,\n enforce_content_length: bool = True,\n ) -> None:\n def request_chunked(\n self,\n method: str,\n url: str,\n body: _TYPE_BODY | None = None,\n headers: typing.Mapping[str, str] | None = None,\n ) -> None:\n def getresponse( # type: ignore[override]\n self,\n ) -> HTTPResponse:\n def __init__(\n self,\n host: str,\n port: int | None = None,\n *,\n timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n source_address: tuple[str, int] | None = None,\n blocksize: int = 16384,\n socket_options: None\n | (connection._TYPE_SOCKET_OPTIONS) = HTTPConnection.default_socket_options,\n proxy: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n cert_reqs: int | str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n server_hostname: str | None = None,\n ssl_context: ssl.SSLContext | None = None,\n ca_certs: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ssl_minimum_version: int | None = None,\n ssl_maximum_version: int | None = None,\n ssl_version: int | str | None = None, # Deprecated\n cert_file: str | None = None,\n key_file: str | None = None,\n key_password: str | None = None,\n ) -> None:\n def set_cert(\n self,\n key_file: str | None = None,\n cert_file: str | None = None,\n cert_reqs: int | str | None = None,\n key_password: str | None = None,\n ca_certs: str | None = None,\n assert_hostname: None | str | Literal[False] = None,\n assert_fingerprint: str | None = None,\n ca_cert_dir: str | None = None,\n ca_cert_data: None | str | bytes = None,\n ) -> None:\n def connect(self) -> None:\n def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket:\ndef _ssl_wrap_socket_and_match_hostname(\n sock: socket.socket,\n *,\n cert_reqs: None | str | int,\n ssl_version: None | str | int,\n ssl_minimum_version: int | None,\n ssl_maximum_version: int | None,\n cert_file: str | None,\n key_file: str | None,\n key_password: str | None,\n ca_certs: str | None,\n ca_cert_dir: str | None,\n ca_cert_data: None | str | bytes,\n assert_hostname: None | str | Literal[False],\n assert_fingerprint: str | None,\n server_hostname: str | None,\n ssl_context: ssl.SSLContext | None,\n tls_in_tls: bool = False,\n) -> _WrappedAndVerifiedSocket:\ndef _match_hostname(\n cert: _TYPE_PEER_CERT_RET_DICT | None,\n asserted_hostname: str,\n hostname_checks_common_name: bool = False,\n) -> None:\ndef _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError:\ndef _get_default_user_agent() -> str:\ndef _url_from_connection(\n conn: HTTPConnection | HTTPSConnection, path: str | None = None\n) -> str:" }, { "identifier": "ClosedPoolError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class ClosedPoolError(PoolError):\n \"\"\"Raised when a request enters a pool after the pool has been closed.\"\"\"" }, { "identifier": "EmptyPoolError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class EmptyPoolError(PoolError):\n \"\"\"Raised when a pool runs out of connections and no more are allowed.\"\"\"" }, { "identifier": "FullPoolError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class FullPoolError(PoolError):\n \"\"\"Raised when we try to add a connection to a full pool in blocking mode.\"\"\"" }, { "identifier": "HostChangedError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class HostChangedError(RequestError):\n \"\"\"Raised when an existing pool gets a request for a foreign host.\"\"\"\n\n def __init__(\n self, pool: ConnectionPool, url: str, retries: Retry | int = 3\n ) -> None:\n message = f\"Tried to open a foreign host with url: {url}\"\n super().__init__(pool, url, message)\n self.retries = retries" }, { "identifier": "InsecureRequestWarning", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class InsecureRequestWarning(SecurityWarning):\n \"\"\"Warned when making an unverified HTTPS request.\"\"\"" }, { "identifier": "LocationValueError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class LocationValueError(ValueError, HTTPError):\n \"\"\"Raised when there is something wrong with a given URL input.\"\"\"" }, { "identifier": "MaxRetryError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class MaxRetryError(RequestError):\n \"\"\"Raised when the maximum number of retries is exceeded.\n\n :param pool: The connection pool\n :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n :param str url: The requested Url\n :param reason: The underlying error\n :type reason: :class:`Exception`\n\n \"\"\"\n\n def __init__(\n self, pool: ConnectionPool, url: str, reason: Exception | None = None\n ) -> None:\n self.reason = reason\n\n message = f\"Max retries exceeded with url: {url} (Caused by {reason!r})\"\n\n super().__init__(pool, url, message)" }, { "identifier": "NewConnectionError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class NewConnectionError(ConnectTimeoutError, HTTPError):\n \"\"\"Raised when we fail to establish a new connection. Usually ECONNREFUSED.\"\"\"\n\n def __init__(self, conn: HTTPConnection, message: str) -> None:\n self.conn = conn\n super().__init__(f\"{conn}: {message}\")\n\n @property\n def pool(self) -> HTTPConnection:\n warnings.warn(\n \"The 'pool' property is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Use 'conn' instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n return self.conn" }, { "identifier": "ProtocolError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class ProtocolError(HTTPError):\n \"\"\"Raised when something unexpected happens mid-request/response.\"\"\"" }, { "identifier": "ProxyError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class ProxyError(HTTPError):\n \"\"\"Raised when the connection to a proxy fails.\"\"\"\n\n # The original error is also available as __cause__.\n original_error: Exception\n\n def __init__(self, message: str, error: Exception) -> None:\n super().__init__(message, error)\n self.original_error = error" }, { "identifier": "ReadTimeoutError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class ReadTimeoutError(TimeoutError, RequestError):\n \"\"\"Raised when a socket timeout occurs while receiving data from a server\"\"\"" }, { "identifier": "SSLError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class SSLError(HTTPError):\n \"\"\"Raised when SSL certificate fails in an HTTPS connection.\"\"\"" }, { "identifier": "TimeoutError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/exceptions.py", "snippet": "class TimeoutError(HTTPError):\n \"\"\"Raised when a socket timeout error occurs.\n\n Catching this error will catch both :exc:`ReadTimeoutErrors\n <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.\n \"\"\"" }, { "identifier": "BaseHTTPResponse", "path": "backend/venv/lib/python3.10/site-packages/urllib3/response.py", "snippet": "class BaseHTTPResponse(io.IOBase):\n CONTENT_DECODERS = [\"gzip\", \"deflate\"]\n if brotli is not None:\n CONTENT_DECODERS += [\"br\"]\n if zstd is not None:\n CONTENT_DECODERS += [\"zstd\"]\n REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (IOError, zlib.error)\n if brotli is not None:\n DECODER_ERROR_CLASSES += (brotli.error,)\n\n if zstd is not None:\n DECODER_ERROR_CLASSES += (zstd.ZstdError,)\n\n def __init__(\n self,\n *,\n headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None,\n status: int,\n version: int,\n reason: str | None,\n decode_content: bool,\n request_url: str | None,\n retries: Retry | None = None,\n ) -> None:\n if isinstance(headers, HTTPHeaderDict):\n self.headers = headers\n else:\n self.headers = HTTPHeaderDict(headers) # type: ignore[arg-type]\n self.status = status\n self.version = version\n self.reason = reason\n self.decode_content = decode_content\n self._has_decoded_content = False\n self._request_url: str | None = request_url\n self.retries = retries\n\n self.chunked = False\n tr_enc = self.headers.get(\"transfer-encoding\", \"\").lower()\n # Don't incur the penalty of creating a list and then discarding it\n encodings = (enc.strip() for enc in tr_enc.split(\",\"))\n if \"chunked\" in encodings:\n self.chunked = True\n\n self._decoder: ContentDecoder | None = None\n\n def get_redirect_location(self) -> str | None | Literal[False]:\n \"\"\"\n Should we redirect and where to?\n\n :returns: Truthy redirect location string if we got a redirect status\n code and valid location. ``None`` if redirect status and no\n location. ``False`` if not a redirect status code.\n \"\"\"\n if self.status in self.REDIRECT_STATUSES:\n return self.headers.get(\"location\")\n return False\n\n @property\n def data(self) -> bytes:\n raise NotImplementedError()\n\n def json(self) -> typing.Any:\n \"\"\"\n Parses the body of the HTTP response as JSON.\n\n To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to the decoder.\n\n This method can raise either `UnicodeDecodeError` or `json.JSONDecodeError`.\n\n Read more :ref:`here <json>`.\n \"\"\"\n data = self.data.decode(\"utf-8\")\n return _json.loads(data)\n\n @property\n def url(self) -> str | None:\n raise NotImplementedError()\n\n @url.setter\n def url(self, url: str | None) -> None:\n raise NotImplementedError()\n\n @property\n def connection(self) -> HTTPConnection | None:\n raise NotImplementedError()\n\n @property\n def retries(self) -> Retry | None:\n return self._retries\n\n @retries.setter\n def retries(self, retries: Retry | None) -> None:\n # Override the request_url if retries has a redirect location.\n if retries is not None and retries.history:\n self.url = retries.history[-1].redirect_location\n self._retries = retries\n\n def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()\n\n def read(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n cache_content: bool = False,\n ) -> bytes:\n raise NotImplementedError()\n\n def read_chunked(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()\n\n def release_conn(self) -> None:\n raise NotImplementedError()\n\n def drain_conn(self) -> None:\n raise NotImplementedError()\n\n def close(self) -> None:\n raise NotImplementedError()\n\n def _init_decoder(self) -> None:\n \"\"\"\n Set-up the _decoder attribute if necessary.\n \"\"\"\n # Note: content-encoding value should be case-insensitive, per RFC 7230\n # Section 3.2\n content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n if self._decoder is None:\n if content_encoding in self.CONTENT_DECODERS:\n self._decoder = _get_decoder(content_encoding)\n elif \",\" in content_encoding:\n encodings = [\n e.strip()\n for e in content_encoding.split(\",\")\n if e.strip() in self.CONTENT_DECODERS\n ]\n if encodings:\n self._decoder = _get_decoder(content_encoding)\n\n def _decode(\n self, data: bytes, decode_content: bool | None, flush_decoder: bool\n ) -> bytes:\n \"\"\"\n Decode the data passed in and potentially flush the decoder.\n \"\"\"\n if not decode_content:\n if self._has_decoded_content:\n raise RuntimeError(\n \"Calling read(decode_content=False) is not supported after \"\n \"read(decode_content=True) was called.\"\n )\n return data\n\n try:\n if self._decoder:\n data = self._decoder.decompress(data)\n self._has_decoded_content = True\n except self.DECODER_ERROR_CLASSES as e:\n content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n raise DecodeError(\n \"Received response with content-encoding: %s, but \"\n \"failed to decode it.\" % content_encoding,\n e,\n ) from e\n if flush_decoder:\n data += self._flush_decoder()\n\n return data\n\n def _flush_decoder(self) -> bytes:\n \"\"\"\n Flushes the decoder. Should only be called if the decoder is actually\n being used.\n \"\"\"\n if self._decoder:\n return self._decoder.decompress(b\"\") + self._decoder.flush()\n return b\"\"\n\n # Compatibility methods for `io` module\n def readinto(self, b: bytearray) -> int:\n temp = self.read(len(b))\n if len(temp) == 0:\n return 0\n else:\n b[: len(temp)] = temp\n return len(temp)\n\n # Compatibility methods for http.client.HTTPResponse\n def getheaders(self) -> HTTPHeaderDict:\n warnings.warn(\n \"HTTPResponse.getheaders() is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers\n\n def getheader(self, name: str, default: str | None = None) -> str | None:\n warnings.warn(\n \"HTTPResponse.getheader() is deprecated and will be removed \"\n \"in urllib3 v2.1.0. Instead use HTTPResponse.headers.get(name, default).\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers.get(name, default)\n\n # Compatibility method for http.cookiejar\n def info(self) -> HTTPHeaderDict:\n return self.headers\n\n def geturl(self) -> str | None:\n return self.url" }, { "identifier": "is_connection_dropped", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/connection.py", "snippet": "def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific\n \"\"\"\n Returns True if the connection is dropped and should be closed.\n :param conn: :class:`urllib3.connection.HTTPConnection` object.\n \"\"\"\n return not conn.is_connected" }, { "identifier": "connection_requires_http_tunnel", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/proxy.py", "snippet": "def connection_requires_http_tunnel(\n proxy_url: Url | None = None,\n proxy_config: ProxyConfig | None = None,\n destination_scheme: str | None = None,\n) -> bool:\n \"\"\"\n Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n :param URL proxy_url:\n URL of the proxy.\n :param ProxyConfig proxy_config:\n Proxy configuration from poolmanager.py\n :param str destination_scheme:\n The scheme of the destination. (i.e https, http, etc)\n \"\"\"\n # If we're not using a proxy, no way to use a tunnel.\n if proxy_url is None:\n return False\n\n # HTTP destinations never require tunneling, we always forward.\n if destination_scheme == \"http\":\n return False\n\n # Support for forwarding with HTTPS proxies and HTTPS destinations.\n if (\n proxy_url.scheme == \"https\"\n and proxy_config\n and proxy_config.use_forwarding_for_https\n ):\n return False\n\n # Otherwise always use a tunnel.\n return True" }, { "identifier": "_TYPE_BODY_POSITION", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/request.py", "snippet": "_TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL]" }, { "identifier": "set_file_position", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/request.py", "snippet": "def set_file_position(\n body: typing.Any, pos: _TYPE_BODY_POSITION | None\n) -> _TYPE_BODY_POSITION | None:\n \"\"\"\n If a position is provided, move file to that point.\n Otherwise, we'll attempt to record a position for future use.\n \"\"\"\n if pos is not None:\n rewind_body(body, pos)\n elif getattr(body, \"tell\", None) is not None:\n try:\n pos = body.tell()\n except OSError:\n # This differentiates from None, allowing us to catch\n # a failed `tell()` later when trying to rewind the body.\n pos = _FAILEDTELL\n\n return pos" }, { "identifier": "Retry", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/retry.py", "snippet": "class Retry:\n \"\"\"Retry configuration.\n\n Each retry attempt will create a new Retry object with updated values, so\n they can be safely reused.\n\n Retries can be defined as a default for a pool:\n\n .. code-block:: python\n\n retries = Retry(connect=5, read=2, redirect=5)\n http = PoolManager(retries=retries)\n response = http.request(\"GET\", \"https://example.com/\")\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", retries=Retry(10))\n\n Retries can be disabled by passing ``False``:\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", retries=False)\n\n Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n retries are disabled, in which case the causing exception will be raised.\n\n :param int total:\n Total number of retries to allow. Takes precedence over other counts.\n\n Set to ``None`` to remove this constraint and fall back on other\n counts.\n\n Set to ``0`` to fail on the first retry.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int connect:\n How many connection-related errors to retry on.\n\n These are errors raised before the request is sent to the remote server,\n which we assume has not triggered the server to process the request.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int read:\n How many times to retry on read errors.\n\n These errors are raised after the request was sent to the server, so the\n request may have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int redirect:\n How many redirects to perform. Limit this to avoid infinite redirect\n loops.\n\n A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n 308.\n\n Set to ``0`` to fail on the first retry of this type.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int status:\n How many times to retry on bad status codes.\n\n These are retries made on responses, where status code matches\n ``status_forcelist``.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int other:\n How many times to retry on other errors.\n\n Other errors are errors that are not connect, read, redirect or status errors.\n These errors might be raised after the request was sent to the server, so the\n request might have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n If ``total`` is not set, it's a good idea to set this to 0 to account\n for unexpected edge cases and avoid infinite retry loops.\n\n :param Collection allowed_methods:\n Set of uppercased HTTP method verbs that we should retry on.\n\n By default, we only retry on methods which are considered to be\n idempotent (multiple requests with the same parameters end with the\n same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n Set to a ``None`` value to retry on any verb.\n\n :param Collection status_forcelist:\n A set of integer HTTP status codes that we should force a retry on.\n A retry is initiated if the request method is in ``allowed_methods``\n and the response status code is in ``status_forcelist``.\n\n By default, this is disabled with ``None``.\n\n :param float backoff_factor:\n A backoff factor to apply between attempts after the second try\n (most errors are resolved immediately by a second try without a\n delay). urllib3 will sleep for::\n\n {backoff factor} * (2 ** ({number of previous retries}))\n\n seconds. If `backoff_jitter` is non-zero, this sleep is extended by::\n\n random.uniform(0, {backoff jitter})\n\n seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will\n sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever\n be longer than `backoff_max`.\n\n By default, backoff is disabled (factor set to 0).\n\n :param bool raise_on_redirect: Whether, if the number of redirects is\n exhausted, to raise a MaxRetryError, or to return a response with a\n response code in the 3xx range.\n\n :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n whether we should raise an exception, or return a response,\n if status falls in ``status_forcelist`` range and retries have\n been exhausted.\n\n :param tuple history: The history of the request encountered during\n each call to :meth:`~Retry.increment`. The list is in the order\n the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n :param bool respect_retry_after_header:\n Whether to respect Retry-After header on status codes defined as\n :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n :param Collection remove_headers_on_redirect:\n Sequence of headers to remove from the request when a response\n indicating a redirect is returned before firing off the redirected\n request.\n \"\"\"\n\n #: Default methods to be used for ``allowed_methods``\n DEFAULT_ALLOWED_METHODS = frozenset(\n [\"HEAD\", \"GET\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"]\n )\n\n #: Default status codes to be used for ``status_forcelist``\n RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n #: Default headers to be used for ``remove_headers_on_redirect``\n DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset([\"Cookie\", \"Authorization\"])\n\n #: Default maximum backoff time.\n DEFAULT_BACKOFF_MAX = 120\n\n # Backward compatibility; assigned outside of the class.\n DEFAULT: typing.ClassVar[Retry]\n\n def __init__(\n self,\n total: bool | int | None = 10,\n connect: int | None = None,\n read: int | None = None,\n redirect: bool | int | None = None,\n status: int | None = None,\n other: int | None = None,\n allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS,\n status_forcelist: typing.Collection[int] | None = None,\n backoff_factor: float = 0,\n backoff_max: float = DEFAULT_BACKOFF_MAX,\n raise_on_redirect: bool = True,\n raise_on_status: bool = True,\n history: tuple[RequestHistory, ...] | None = None,\n respect_retry_after_header: bool = True,\n remove_headers_on_redirect: typing.Collection[\n str\n ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT,\n backoff_jitter: float = 0.0,\n ) -> None:\n self.total = total\n self.connect = connect\n self.read = read\n self.status = status\n self.other = other\n\n if redirect is False or total is False:\n redirect = 0\n raise_on_redirect = False\n\n self.redirect = redirect\n self.status_forcelist = status_forcelist or set()\n self.allowed_methods = allowed_methods\n self.backoff_factor = backoff_factor\n self.backoff_max = backoff_max\n self.raise_on_redirect = raise_on_redirect\n self.raise_on_status = raise_on_status\n self.history = history or ()\n self.respect_retry_after_header = respect_retry_after_header\n self.remove_headers_on_redirect = frozenset(\n h.lower() for h in remove_headers_on_redirect\n )\n self.backoff_jitter = backoff_jitter\n\n def new(self, **kw: typing.Any) -> Retry:\n params = dict(\n total=self.total,\n connect=self.connect,\n read=self.read,\n redirect=self.redirect,\n status=self.status,\n other=self.other,\n allowed_methods=self.allowed_methods,\n status_forcelist=self.status_forcelist,\n backoff_factor=self.backoff_factor,\n backoff_max=self.backoff_max,\n raise_on_redirect=self.raise_on_redirect,\n raise_on_status=self.raise_on_status,\n history=self.history,\n remove_headers_on_redirect=self.remove_headers_on_redirect,\n respect_retry_after_header=self.respect_retry_after_header,\n backoff_jitter=self.backoff_jitter,\n )\n\n params.update(kw)\n return type(self)(**params) # type: ignore[arg-type]\n\n @classmethod\n def from_int(\n cls,\n retries: Retry | bool | int | None,\n redirect: bool | int | None = True,\n default: Retry | bool | int | None = None,\n ) -> Retry:\n \"\"\"Backwards-compatibility for the old retries format.\"\"\"\n if retries is None:\n retries = default if default is not None else cls.DEFAULT\n\n if isinstance(retries, Retry):\n return retries\n\n redirect = bool(redirect) and None\n new_retries = cls(retries, redirect=redirect)\n log.debug(\"Converted retries value: %r -> %r\", retries, new_retries)\n return new_retries\n\n def get_backoff_time(self) -> float:\n \"\"\"Formula for computing the current backoff\n\n :rtype: float\n \"\"\"\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n if self.backoff_jitter != 0.0:\n backoff_value += random.random() * self.backoff_jitter\n return float(max(0, min(self.backoff_max, backoff_value)))\n\n def parse_retry_after(self, retry_after: str) -> float:\n seconds: float\n # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n if re.match(r\"^\\s*[0-9]+\\s*$\", retry_after):\n seconds = int(retry_after)\n else:\n retry_date_tuple = email.utils.parsedate_tz(retry_after)\n if retry_date_tuple is None:\n raise InvalidHeader(f\"Invalid Retry-After header: {retry_after}\")\n\n retry_date = email.utils.mktime_tz(retry_date_tuple)\n seconds = retry_date - time.time()\n\n seconds = max(seconds, 0)\n\n return seconds\n\n def get_retry_after(self, response: BaseHTTPResponse) -> float | None:\n \"\"\"Get the value of Retry-After in seconds.\"\"\"\n\n retry_after = response.headers.get(\"Retry-After\")\n\n if retry_after is None:\n return None\n\n return self.parse_retry_after(retry_after)\n\n def sleep_for_retry(self, response: BaseHTTPResponse) -> bool:\n retry_after = self.get_retry_after(response)\n if retry_after:\n time.sleep(retry_after)\n return True\n\n return False\n\n def _sleep_backoff(self) -> None:\n backoff = self.get_backoff_time()\n if backoff <= 0:\n return\n time.sleep(backoff)\n\n def sleep(self, response: BaseHTTPResponse | None = None) -> None:\n \"\"\"Sleep between retry attempts.\n\n This method will respect a server's ``Retry-After`` response header\n and sleep the duration of the time requested. If that is not present, it\n will use an exponential backoff. By default, the backoff factor is 0 and\n this method will return immediately.\n \"\"\"\n\n if self.respect_retry_after_header and response:\n slept = self.sleep_for_retry(response)\n if slept:\n return\n\n self._sleep_backoff()\n\n def _is_connection_error(self, err: Exception) -> bool:\n \"\"\"Errors when we're fairly sure that the server did not receive the\n request, so it should be safe to retry.\n \"\"\"\n if isinstance(err, ProxyError):\n err = err.original_error\n return isinstance(err, ConnectTimeoutError)\n\n def _is_read_error(self, err: Exception) -> bool:\n \"\"\"Errors that occur after the request has been started, so we should\n assume that the server began processing it.\n \"\"\"\n return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n def _is_method_retryable(self, method: str) -> bool:\n \"\"\"Checks if a given HTTP method should be retried upon, depending if\n it is included in the allowed_methods\n \"\"\"\n if self.allowed_methods and method.upper() not in self.allowed_methods:\n return False\n return True\n\n def is_retry(\n self, method: str, status_code: int, has_retry_after: bool = False\n ) -> bool:\n \"\"\"Is this method/status code retryable? (Based on allowlists and control\n variables such as the number of total retries to allow, whether to\n respect the Retry-After header, whether this header is present, and\n whether the returned status code is on the list of status codes to\n be retried upon on the presence of the aforementioned header)\n \"\"\"\n if not self._is_method_retryable(method):\n return False\n\n if self.status_forcelist and status_code in self.status_forcelist:\n return True\n\n return bool(\n self.total\n and self.respect_retry_after_header\n and has_retry_after\n and (status_code in self.RETRY_AFTER_STATUS_CODES)\n )\n\n def is_exhausted(self) -> bool:\n \"\"\"Are we out of retries?\"\"\"\n retry_counts = [\n x\n for x in (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n if x\n ]\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0\n\n def increment(\n self,\n method: str | None = None,\n url: str | None = None,\n response: BaseHTTPResponse | None = None,\n error: Exception | None = None,\n _pool: ConnectionPool | None = None,\n _stacktrace: TracebackType | None = None,\n ) -> Retry:\n \"\"\"Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.BaseHTTPResponse`\n :param Exception error: An error encountered during the request, or\n None if the response was received successfully.\n\n :return: A new ``Retry`` object.\n \"\"\"\n if self.total is False and error:\n # Disabled, indicate to re-raise the error.\n raise reraise(type(error), error, _stacktrace)\n\n total = self.total\n if total is not None:\n total -= 1\n\n connect = self.connect\n read = self.read\n redirect = self.redirect\n status_count = self.status\n other = self.other\n cause = \"unknown\"\n status = None\n redirect_location = None\n\n if error and self._is_connection_error(error):\n # Connect retry?\n if connect is False:\n raise reraise(type(error), error, _stacktrace)\n elif connect is not None:\n connect -= 1\n\n elif error and self._is_read_error(error):\n # Read retry?\n if read is False or method is None or not self._is_method_retryable(method):\n raise reraise(type(error), error, _stacktrace)\n elif read is not None:\n read -= 1\n\n elif error:\n # Other retry?\n if other is not None:\n other -= 1\n\n elif response and response.get_redirect_location():\n # Redirect retry?\n if redirect is not None:\n redirect -= 1\n cause = \"too many redirects\"\n response_redirect_location = response.get_redirect_location()\n if response_redirect_location:\n redirect_location = response_redirect_location\n status = response.status\n\n else:\n # Incrementing because of a server error like a 500 in\n # status_forcelist and the given method is in the allowed_methods\n cause = ResponseError.GENERIC_ERROR\n if response and response.status:\n if status_count is not None:\n status_count -= 1\n cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n status = response.status\n\n history = self.history + (\n RequestHistory(method, url, error, status, redirect_location),\n )\n\n new_retry = self.new(\n total=total,\n connect=connect,\n read=read,\n redirect=redirect,\n status=status_count,\n other=other,\n history=history,\n )\n\n if new_retry.is_exhausted():\n reason = error or ResponseError(cause)\n raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]\n\n log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n return new_retry\n\n def __repr__(self) -> str:\n return (\n f\"{type(self).__name__}(total={self.total}, connect={self.connect}, \"\n f\"read={self.read}, redirect={self.redirect}, status={self.status})\"\n )" }, { "identifier": "CertificateError", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/ssl_match_hostname.py", "snippet": "class CertificateError(ValueError):\n pass" }, { "identifier": "_DEFAULT_TIMEOUT", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/timeout.py", "snippet": "_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token" }, { "identifier": "_TYPE_DEFAULT", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/timeout.py", "snippet": "class _TYPE_DEFAULT(Enum):\n # This value should never be passed to socket.settimeout() so for safety we use a -1.\n # socket.settimout() raises a ValueError for negative values.\n token = -1" }, { "identifier": "Timeout", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/timeout.py", "snippet": "class Timeout:\n \"\"\"Timeout configuration.\n\n Timeouts can be defined as a default for a pool:\n\n .. code-block:: python\n\n import urllib3\n\n timeout = urllib3.util.Timeout(connect=2.0, read=7.0)\n\n http = urllib3.PoolManager(timeout=timeout)\n\n resp = http.request(\"GET\", \"https://example.com/\")\n\n print(resp.status)\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request(\"GET\", \"https://example.com/\", timeout=Timeout(10))\n\n Timeouts can be disabled by setting all the parameters to ``None``:\n\n .. code-block:: python\n\n no_timeout = Timeout(connect=None, read=None)\n response = http.request(\"GET\", \"https://example.com/\", timeout=no_timeout)\n\n\n :param total:\n This combines the connect and read timeouts into one; the read timeout\n will be set to the time leftover from the connect attempt. In the\n event that both a connect timeout and a total are specified, or a read\n timeout and a total are specified, the shorter timeout will be applied.\n\n Defaults to None.\n\n :type total: int, float, or None\n\n :param connect:\n The maximum amount of time (in seconds) to wait for a connection\n attempt to a server to succeed. Omitting the parameter will default the\n connect timeout to the system default, probably `the global default\n timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout for connection attempts.\n\n :type connect: int, float, or None\n\n :param read:\n The maximum amount of time (in seconds) to wait between consecutive\n read operations for a response from the server. Omitting the parameter\n will default the read timeout to the system default, probably `the\n global default timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout.\n\n :type read: int, float, or None\n\n .. note::\n\n Many factors can affect the total amount of time for urllib3 to return\n an HTTP response.\n\n For example, Python's DNS resolver does not obey the timeout specified\n on the socket. Other factors that can affect total request time include\n high CPU load, high swap, the program running at a low priority level,\n or other behaviors.\n\n In addition, the read and total timeouts only measure the time between\n read operations on the socket connecting the client and the server,\n not the total amount of time for the request to return a complete\n response. For most requests, the timeout is raised because the server\n has not sent the first byte in the specified time. This is not always\n the case; if a server streams one byte every fifteen seconds, a timeout\n of 20 seconds will not trigger, even though the request will take\n several minutes to complete.\n\n If your goal is to cut off any request after a set amount of wall clock\n time, consider having a second \"watcher\" thread to cut off a slow\n request.\n \"\"\"\n\n #: A sentinel object representing the default timeout value\n DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT\n\n def __init__(\n self,\n total: _TYPE_TIMEOUT = None,\n connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,\n ) -> None:\n self._connect = self._validate_timeout(connect, \"connect\")\n self._read = self._validate_timeout(read, \"read\")\n self.total = self._validate_timeout(total, \"total\")\n self._start_connect: float | None = None\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})\"\n\n # __str__ provided for backwards compatibility\n __str__ = __repr__\n\n @staticmethod\n def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None:\n return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout\n\n @classmethod\n def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT:\n \"\"\"Check that a timeout attribute is valid.\n\n :param value: The timeout value to validate\n :param name: The name of the timeout attribute to validate. This is\n used to specify in error messages.\n :return: The validated and casted version of the given value.\n :raises ValueError: If it is a numeric value less than or equal to\n zero, or the type is not an integer, float, or None.\n \"\"\"\n if value is None or value is _DEFAULT_TIMEOUT:\n return value\n\n if isinstance(value, bool):\n raise ValueError(\n \"Timeout cannot be a boolean value. It must \"\n \"be an int, float or None.\"\n )\n try:\n float(value)\n except (TypeError, ValueError):\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n try:\n if value <= 0:\n raise ValueError(\n \"Attempted to set %s timeout to %s, but the \"\n \"timeout cannot be set to a value less \"\n \"than or equal to 0.\" % (name, value)\n )\n except TypeError:\n raise ValueError(\n \"Timeout value %s was %s, but it must be an \"\n \"int, float or None.\" % (name, value)\n ) from None\n\n return value\n\n @classmethod\n def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout:\n \"\"\"Create a new Timeout from a legacy timeout value.\n\n The timeout value used by httplib.py sets the same timeout on the\n connect(), and recv() socket requests. This creates a :class:`Timeout`\n object that sets the individual timeouts to the ``timeout`` value\n passed to this function.\n\n :param timeout: The legacy timeout value.\n :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None\n :return: Timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n return Timeout(read=timeout, connect=timeout)\n\n def clone(self) -> Timeout:\n \"\"\"Create a copy of the timeout object\n\n Timeout properties are stored per-pool but each request needs a fresh\n Timeout object to ensure each one has its own start/stop configured.\n\n :return: a copy of the timeout object\n :rtype: :class:`Timeout`\n \"\"\"\n # We can't use copy.deepcopy because that will also create a new object\n # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to\n # detect the user default.\n return Timeout(connect=self._connect, read=self._read, total=self.total)\n\n def start_connect(self) -> float:\n \"\"\"Start the timeout clock, used during a connect() attempt\n\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to start a timer that has been started already.\n \"\"\"\n if self._start_connect is not None:\n raise TimeoutStateError(\"Timeout timer has already been started.\")\n self._start_connect = time.monotonic()\n return self._start_connect\n\n def get_connect_duration(self) -> float:\n \"\"\"Gets the time elapsed since the call to :meth:`start_connect`.\n\n :return: Elapsed time in seconds.\n :rtype: float\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to get duration for a timer that hasn't been started.\n \"\"\"\n if self._start_connect is None:\n raise TimeoutStateError(\n \"Can't get connect duration for timer that has not started.\"\n )\n return time.monotonic() - self._start_connect\n\n @property\n def connect_timeout(self) -> _TYPE_TIMEOUT:\n \"\"\"Get the value to use when setting a connection timeout.\n\n This will be a positive float or integer, the value None\n (never timeout), or the default system timeout.\n\n :return: Connect timeout.\n :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n \"\"\"\n if self.total is None:\n return self._connect\n\n if self._connect is None or self._connect is _DEFAULT_TIMEOUT:\n return self.total\n\n return min(self._connect, self.total) # type: ignore[type-var]\n\n @property\n def read_timeout(self) -> float | None:\n \"\"\"Get the value for the read timeout.\n\n This assumes some time has elapsed in the connection timeout and\n computes the read timeout appropriately.\n\n If self.total is set, the read timeout is dependent on the amount of\n time taken by the connect timeout. If the connection time has not been\n established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be\n raised.\n\n :return: Value to use for the read timeout.\n :rtype: int, float or None\n :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`\n has not yet been called on this object.\n \"\"\"\n if (\n self.total is not None\n and self.total is not _DEFAULT_TIMEOUT\n and self._read is not None\n and self._read is not _DEFAULT_TIMEOUT\n ):\n # In case the connect timeout has not yet been established.\n if self._start_connect is None:\n return self._read\n return max(0, min(self.total - self.get_connect_duration(), self._read))\n elif self.total is not None and self.total is not _DEFAULT_TIMEOUT:\n return max(0, self.total - self.get_connect_duration())\n else:\n return self.resolve_default_timeout(self._read)" }, { "identifier": "Url", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/url.py", "snippet": "class Url(\n typing.NamedTuple(\n \"Url\",\n [\n (\"scheme\", typing.Optional[str]),\n (\"auth\", typing.Optional[str]),\n (\"host\", typing.Optional[str]),\n (\"port\", typing.Optional[int]),\n (\"path\", typing.Optional[str]),\n (\"query\", typing.Optional[str]),\n (\"fragment\", typing.Optional[str]),\n ],\n )\n):\n \"\"\"\n Data structure for representing an HTTP URL. Used as a return value for\n :func:`parse_url`. Both the scheme and host are normalized as they are\n both case-insensitive according to RFC 3986.\n \"\"\"\n\n def __new__( # type: ignore[no-untyped-def]\n cls,\n scheme: str | None = None,\n auth: str | None = None,\n host: str | None = None,\n port: int | None = None,\n path: str | None = None,\n query: str | None = None,\n fragment: str | None = None,\n ):\n if path and not path.startswith(\"/\"):\n path = \"/\" + path\n if scheme is not None:\n scheme = scheme.lower()\n return super().__new__(cls, scheme, auth, host, port, path, query, fragment)\n\n @property\n def hostname(self) -> str | None:\n \"\"\"For backwards-compatibility with urlparse. We're nice like that.\"\"\"\n return self.host\n\n @property\n def request_uri(self) -> str:\n \"\"\"Absolute path including the query string.\"\"\"\n uri = self.path or \"/\"\n\n if self.query is not None:\n uri += \"?\" + self.query\n\n return uri\n\n @property\n def authority(self) -> str | None:\n \"\"\"\n Authority component as defined in RFC 3986 3.2.\n This includes userinfo (auth), host and port.\n\n i.e.\n userinfo@host:port\n \"\"\"\n userinfo = self.auth\n netloc = self.netloc\n if netloc is None or userinfo is None:\n return netloc\n else:\n return f\"{userinfo}@{netloc}\"\n\n @property\n def netloc(self) -> str | None:\n \"\"\"\n Network location including host and port.\n\n If you need the equivalent of urllib.parse's ``netloc``,\n use the ``authority`` property instead.\n \"\"\"\n if self.host is None:\n return None\n if self.port:\n return f\"{self.host}:{self.port}\"\n return self.host\n\n @property\n def url(self) -> str:\n \"\"\"\n Convert self into a url\n\n This function should more or less round-trip with :func:`.parse_url`. The\n returned url may not be exactly the same as the url inputted to\n :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n with a blank port will have : removed).\n\n Example:\n\n .. code-block:: python\n\n import urllib3\n\n U = urllib3.util.parse_url(\"https://google.com/mail/\")\n\n print(U.url)\n # \"https://google.com/mail/\"\n\n print( urllib3.util.Url(\"https\", \"username:password\",\n \"host.com\", 80, \"/path\", \"query\", \"fragment\"\n ).url\n )\n # \"https://username:[email protected]:80/path?query#fragment\"\n \"\"\"\n scheme, auth, host, port, path, query, fragment = self\n url = \"\"\n\n # We use \"is not None\" we want things to happen with empty strings (or 0 port)\n if scheme is not None:\n url += scheme + \"://\"\n if auth is not None:\n url += auth + \"@\"\n if host is not None:\n url += host\n if port is not None:\n url += \":\" + str(port)\n if path is not None:\n url += path\n if query is not None:\n url += \"?\" + query\n if fragment is not None:\n url += \"#\" + fragment\n\n return url\n\n def __str__(self) -> str:\n return self.url" }, { "identifier": "_encode_target", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/url.py", "snippet": "def _encode_target(target: str) -> str:\n \"\"\"Percent-encodes a request target so that there are no invalid characters\n\n Pre-condition for this function is that 'target' must start with '/'.\n If that is the case then _TARGET_RE will always produce a match.\n \"\"\"\n match = _TARGET_RE.match(target)\n if not match: # Defensive:\n raise LocationParseError(f\"{target!r} is not a valid request URI\")\n\n path, query = match.groups()\n encoded_target = _encode_invalid_chars(path, _PATH_CHARS)\n if query is not None:\n query = _encode_invalid_chars(query, _QUERY_CHARS)\n encoded_target += \"?\" + query\n return encoded_target" }, { "identifier": "_normalize_host", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/url.py", "snippet": "@typing.overload\ndef _normalize_host(host: None, scheme: str | None) -> None:\n ..." }, { "identifier": "parse_url", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/url.py", "snippet": "def parse_url(url: str) -> Url:\n \"\"\"\n Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n performed to parse incomplete urls. Fields not provided will be None.\n This parser is RFC 3986 and RFC 6874 compliant.\n\n The parser logic and helper functions are based heavily on\n work done in the ``rfc3986`` module.\n\n :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n Partly backwards-compatible with :mod:`urllib.parse`.\n\n Example:\n\n .. code-block:: python\n\n import urllib3\n\n print( urllib3.util.parse_url('http://google.com/mail/'))\n # Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n\n print( urllib3.util.parse_url('google.com:80'))\n # Url(scheme=None, host='google.com', port=80, path=None, ...)\n\n print( urllib3.util.parse_url('/foo?bar'))\n # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n \"\"\"\n if not url:\n # Empty\n return Url()\n\n source_url = url\n if not _SCHEME_RE.search(url):\n url = \"//\" + url\n\n scheme: str | None\n authority: str | None\n auth: str | None\n host: str | None\n port: str | None\n port_int: int | None\n path: str | None\n query: str | None\n fragment: str | None\n\n try:\n scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr]\n normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES\n\n if scheme:\n scheme = scheme.lower()\n\n if authority:\n auth, _, host_port = authority.rpartition(\"@\")\n auth = auth or None\n host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr]\n if auth and normalize_uri:\n auth = _encode_invalid_chars(auth, _USERINFO_CHARS)\n if port == \"\":\n port = None\n else:\n auth, host, port = None, None, None\n\n if port is not None:\n port_int = int(port)\n if not (0 <= port_int <= 65535):\n raise LocationParseError(url)\n else:\n port_int = None\n\n host = _normalize_host(host, scheme)\n\n if normalize_uri and path:\n path = _remove_path_dot_segments(path)\n path = _encode_invalid_chars(path, _PATH_CHARS)\n if normalize_uri and query:\n query = _encode_invalid_chars(query, _QUERY_CHARS)\n if normalize_uri and fragment:\n fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS)\n\n except (ValueError, AttributeError) as e:\n raise LocationParseError(source_url) from e\n\n # For the sake of backwards compatibility we put empty\n # string values for path if there are any defined values\n # beyond the path in the URL.\n # TODO: Remove this when we break backwards compatibility.\n if not path:\n if query is not None or fragment is not None:\n path = \"\"\n else:\n path = None\n\n return Url(\n scheme=scheme,\n auth=auth,\n host=host,\n port=port_int,\n path=path,\n query=query,\n fragment=fragment,\n )" }, { "identifier": "to_str", "path": "backend/venv/lib/python3.10/site-packages/urllib3/util/util.py", "snippet": "def to_str(\n x: str | bytes, encoding: str | None = None, errors: str | None = None\n) -> str:\n if isinstance(x, str):\n return x\n elif not isinstance(x, bytes):\n raise TypeError(f\"not expecting type {type(x).__name__}\")\n if encoding or errors:\n return x.decode(encoding or \"utf-8\", errors=errors or \"strict\")\n return x.decode()" } ]
import errno import logging import queue import sys import typing import warnings import weakref import ssl from socket import timeout as SocketTimeout from types import TracebackType from ._base_connection import _TYPE_BODY from ._collections import HTTPHeaderDict from ._request_methods import RequestMethods from .connection import ( BaseSSLError, BrokenPipeError, DummyConnection, HTTPConnection, HTTPException, HTTPSConnection, ProxyConfig, _wrap_proxy_error, ) from .connection import port_by_scheme as port_by_scheme from .exceptions import ( ClosedPoolError, EmptyPoolError, FullPoolError, HostChangedError, InsecureRequestWarning, LocationValueError, MaxRetryError, NewConnectionError, ProtocolError, ProxyError, ReadTimeoutError, SSLError, TimeoutError, ) from .response import BaseHTTPResponse from .util.connection import is_connection_dropped from .util.proxy import connection_requires_http_tunnel from .util.request import _TYPE_BODY_POSITION, set_file_position from .util.retry import Retry from .util.ssl_match_hostname import CertificateError from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_DEFAULT, Timeout from .util.url import Url, _encode_target from .util.url import _normalize_host as normalize_host from .util.url import parse_url from .util.util import to_str from typing_extensions import Literal from ._base_connection import BaseHTTPConnection, BaseHTTPSConnection
21,004
from __future__ import annotations if typing.TYPE_CHECKING: log = logging.getLogger(__name__) _TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None] _SelfT = typing.TypeVar("_SelfT") # Pool objects class ConnectionPool: """ Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. .. note:: ConnectionPool.urlopen() does not normalize or percent-encode target URIs which is useful if your target server doesn't support percent-encoded target URIs. """ scheme: str | None = None QueueCls = queue.LifoQueue def __init__(self, host: str, port: int | None = None) -> None: if not host: raise LocationValueError("No host specified.") self.host = _normalize_host(host, scheme=self.scheme) self.port = port # This property uses 'normalize_host()' (not '_normalize_host()') # to avoid removing square braces around IPv6 addresses. # This value is sent to `HTTPConnection.set_tunnel()` if called # because square braces are required for HTTP CONNECT tunneling. self._tunnel_host = normalize_host(host, scheme=self.scheme).lower() def __str__(self) -> str: return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})" def __enter__(self: _SelfT) -> _SelfT: return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> Literal[False]: self.close() # Return False to re-raise any potential exceptions return False def close(self) -> None: """ Close all pooled connections and disable the pool. """ # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252 _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
from __future__ import annotations if typing.TYPE_CHECKING: log = logging.getLogger(__name__) _TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None] _SelfT = typing.TypeVar("_SelfT") # Pool objects class ConnectionPool: """ Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. .. note:: ConnectionPool.urlopen() does not normalize or percent-encode target URIs which is useful if your target server doesn't support percent-encoded target URIs. """ scheme: str | None = None QueueCls = queue.LifoQueue def __init__(self, host: str, port: int | None = None) -> None: if not host: raise LocationValueError("No host specified.") self.host = _normalize_host(host, scheme=self.scheme) self.port = port # This property uses 'normalize_host()' (not '_normalize_host()') # to avoid removing square braces around IPv6 addresses. # This value is sent to `HTTPConnection.set_tunnel()` if called # because square braces are required for HTTP CONNECT tunneling. self._tunnel_host = normalize_host(host, scheme=self.scheme).lower() def __str__(self) -> str: return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})" def __enter__(self: _SelfT) -> _SelfT: return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> Literal[False]: self.close() # Return False to re-raise any potential exceptions return False def close(self) -> None: """ Close all pooled connections and disable the pool. """ # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252 _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
class HTTPConnectionPool(ConnectionPool, RequestMethods):
2
2023-10-23 18:09:28+00:00
24k
zju3dv/nr_in_a_room
test/test_light_adaptation.py
[ { "identifier": "RoomOptimizer", "path": "optim/room_optimizer.py", "snippet": "class RoomOptimizer:\n def __init__(\n self,\n scale_factor: float,\n bg_scale_factor: float,\n bg_scene_center: list,\n img_wh: list,\n near: float,\n far: float,\n chunk: int,\n model_ckpt_path_dict: Dict[str, Any],\n config=None,\n scale_factor_dict: Dict[str, Any] = {},\n scene_info_path: str = None,\n scene_info_json_path: str = None,\n model_type=\"NeuS\",\n N_samples: int = 64,\n N_importance: int = 128,\n relation_info: Dict[str, Any] = {},\n output_path: str = None,\n prefix: str = \"\",\n active_instance_id: list = [46, 4, 9, 102],\n virtual_instance_id: list = [], # specific for edit (insert virtual to real) mode\n filter_door_and_window: bool = True,\n lr: float = 1e-2,\n N_optim_step: int = 500,\n adjust_lr_per_step: int = 150,\n optim_batch_size: int = 1024,\n use_amp: bool = False,\n extract_obj_bbox_from_neural_model: bool = False,\n ig_data_base_dir: str = \"data/ig_dataset_v1.0.1/\",\n mask_per_object: bool = False,\n bbox_ray_intersect: bool = True,\n bbox_enlarge: float = 0.1,\n optimize_light_env: bool = True,\n optimize_appearance_code: bool = False,\n use_light_from_image_attr: bool = False,\n use_appearance_from_image_attr: bool = False,\n optimize_option: list = [\n \"photometric_loss\",\n \"perceptual_loss\",\n \"z_axis_align_loss\",\n \"object_room_wall_attach\",\n \"object_room_floor_attach\",\n \"physical_violation\",\n \"object_object_attach\",\n ],\n ):\n # load config\n self.scene_info_path = scene_info_path\n self.scale_factor = scale_factor\n self.scale_factor_dict = scale_factor_dict\n self.bg_scale_factor = bg_scale_factor\n self.bg_scene_center = np.array(bg_scene_center)\n self.ig_data_base_dir = ig_data_base_dir\n self.mask_per_object = mask_per_object\n self.bbox_ray_intersect = bbox_ray_intersect\n self.bbox_enlarge = bbox_enlarge\n self.virtual_instance_id = virtual_instance_id\n\n self.img_wh = img_wh\n self.w = img_wh[0]\n self.h = img_wh[1]\n self.near = near\n self.far = far\n self.N_importance = N_importance\n self.N_samples = N_samples\n self.chunk = chunk\n self.lr = lr\n self.N_optim_step = N_optim_step\n self.adjust_lr_per_step = adjust_lr_per_step\n self.optim_batch_size = optim_batch_size\n self.use_amp = use_amp\n self.optimize_light_env = optimize_light_env\n self.optimize_appearance_code = optimize_appearance_code\n self.optimize_option = optimize_option\n self.config = config\n\n self.use_light_from_image_attr = use_light_from_image_attr\n if self.use_light_from_image_attr:\n print(\n \"WARNING: self.use_light_from_image_attr = True, using hard coded light env.\"\n )\n self.hard_coded_light_id = 0 # just for compatibility\n # self.hard_coded_light_id = 9 # probe_03 in 10 HDR multi_light training\n\n self.use_appearance_from_image_attr = use_appearance_from_image_attr\n if self.use_appearance_from_image_attr:\n print(\n \"WARNING: self.use_appearance_from_image_attr = True, using first frame appearance code.\"\n )\n self.hard_coded_appearance_frame_id = 0\n\n self.optimize_exposure = \"optimize_exposure\" in self.optimize_option\n\n # laod scene info\n if scene_info_json_path is None:\n scene_info_json_path = os.path.join(scene_info_path, \"data.json\")\n self.scene_meta = read_json(scene_info_json_path)\n\n self.active_instance_id = active_instance_id\n if filter_door_and_window:\n self.filter_door_and_window()\n\n self.relation_info = relation_info\n\n self.model_type = model_type\n # self.load_model(\n # model_type, model_ckpt_path_dict[\"obj\"], model_ckpt_path_dict[\"bg\"]\n # )\n self.load_model_from_dict_path(model_type, model_ckpt_path_dict)\n\n self.reset_optimizable_parameters()\n\n if extract_obj_bbox_from_neural_model:\n self.extract_bounding_boxes_from_neural_model()\n\n if self.bbox_ray_intersect:\n self.prepare_bbox_ray_helper()\n\n self.set_output_path(output_path, prefix)\n\n print(\"RoomOptimizer initialize finished.\")\n\n def load_model_from_dict_path(self, model_type, model_ckpt_path_dict):\n assert model_type == \"NeuS\"\n self.models = {}\n self.image_attrs = {}\n\n # avoid duplicate loading\n self.models_cache = {}\n self.image_attrs_cache = {}\n\n print(\"loading model with instance_id\", self.active_instance_id)\n\n # print(model_ckpt_path_dict)\n for obj_id in self.active_instance_id:\n # identify ckpt_path\n if str(obj_id) in model_ckpt_path_dict:\n ckpt_info = model_ckpt_path_dict[str(obj_id)]\n elif obj_id == 0:\n assert (\n \"bg\" in model_ckpt_path_dict or \"0\" in model_ckpt_path_dict\n ), \"model_ckpt_path_dict missing background 'bg' or '0' ckpt\"\n ckpt_info = model_ckpt_path_dict.get(\"bg\", model_ckpt_path_dict[\"0\"])\n else:\n print(\n f\"Cannot find specific model for obj_id = {obj_id}, \\\n maybe config file is not compatible with given active_instance_id.\"\n )\n ckpt_info = model_ckpt_path_dict[\"obj\"]\n # load with cache\n ckpt_path, neus_conf = ckpt_info[\"path\"], ckpt_info[\"neus_conf\"]\n if ckpt_info not in self.models_cache:\n (\n self.models_cache[ckpt_path],\n self.image_attrs_cache[ckpt_path],\n ) = self.load_model_neus(ckpt_path, obj_id, neus_conf)\n self.models[f\"neus_{obj_id}\"] = self.models_cache[ckpt_path]\n self.image_attrs[str(obj_id)] = self.image_attrs_cache[ckpt_path]\n\n def load_model_nerf(self, ckpt_path):\n # TODO(ybbbbt): fix hard coding\n conf = {\n \"N_max_objs\": 128,\n \"N_obj_embedding\": 64,\n }\n nerf_coarse = NeRF_Object(conf)\n nerf_fine = NeRF_Object(conf)\n image_attributes = ImageAttributes(conf)\n load_ckpt(nerf_coarse, ckpt_path, model_name=\"nerf_coarse\")\n load_ckpt(nerf_fine, ckpt_path, model_name=\"nerf_fine\")\n load_ckpt(image_attributes, ckpt_path, model_name=\"image_attributes\")\n\n nerf_coarse = nerf_coarse.cuda().eval()\n nerf_fine = nerf_fine.cuda().eval()\n image_attributes = image_attributes.cuda().eval()\n\n models = {\n \"coarse\": nerf_coarse,\n \"fine\": nerf_fine,\n }\n\n embedding_xyz = Embedding(3, 10)\n embedding_dir = Embedding(3, 4)\n embeddings = {\n \"xyz\": embedding_xyz,\n \"dir\": embedding_dir,\n }\n return models, embeddings, image_attributes\n\n def load_model_neus(self, ckpt_path, obj_id, config_path=\"config/neus.yaml\"):\n conf = {\n \"model\": {\n \"N_max_objs\": 128,\n \"N_obj_embedding\": 64,\n },\n }\n if self.optimize_light_env:\n # conf[\"model\"].update({\"N_max_lights\": 128, \"N_light_embedding\": 16})\n conf[\"model\"].update({\"N_max_lights\": 1024, \"N_light_embedding\": 16})\n\n if self.optimize_appearance_code and obj_id not in self.virtual_instance_id:\n conf[\"model\"].update(\n {\"N_max_appearance_frames\": 10000, \"N_appearance_embedding\": 16}\n )\n\n neus, render_kwargs_train, render_kwargs_test = get_model_neus(\n config_path=config_path, need_trainer=False, extra_conf=conf\n )\n self.render_kwargs_neus = render_kwargs_test\n image_attributes = ImageAttributes(conf[\"model\"])\n\n print(ckpt_path)\n load_ckpt(neus, ckpt_path, model_name=\"neus\")\n load_ckpt(image_attributes, ckpt_path, model_name=\"image_attributes\")\n\n if self.config is not None and (\n str(obj_id) in self.config.get(\"map_virtual_to_local\", {})\n ):\n # image_attributes.embedding_instance\n real_id_in_ckpt = self.config.map_virtual_to_local[str(obj_id)]\n image_attributes.embedding_instance.weight.requires_grad = False\n image_attributes.embedding_instance.weight[\n obj_id\n ] = image_attributes.embedding_instance.weight[real_id_in_ckpt]\n # ipdb.set_trace()\n\n neus.cuda().eval()\n image_attributes.cuda().eval()\n return neus, image_attributes\n\n def reset_optimizable_parameters(self):\n self.params = []\n self.relation_info = {}\n if self.optimize_light_env:\n self.initialize_light_code()\n\n if self.optimize_appearance_code:\n self.initialize_appearance_code()\n\n if self.optimize_exposure:\n self.initialize_autoexposure()\n\n def save_optimizable_parameters(self, path):\n all_param_dict = {}\n # all_param_dict[\"params\"] = self.params\n all_param_dict[\"relation_info\"] = self.relation_info\n all_param_dict[\"object_pose_dict\"] = copy.deepcopy(self.object_pose_dict)\n all_param_dict[\"active_instance_id\"] = copy.deepcopy(self.active_instance_id)\n if self.optimize_light_env:\n all_param_dict[\"light_code\"] = copy.deepcopy(self.light_code_dict)\n if self.optimize_appearance_code:\n all_param_dict[\"appearance_code\"] = copy.deepcopy(self.appearance_code_dict)\n if self.optimize_exposure:\n all_param_dict[\"exposure\"] = copy.deepcopy(self.autoexposure_param)\n torch.save(all_param_dict, path)\n\n def load_optimizable_parameters(self, path):\n all_param_dict = torch.load(path)\n # self.params = all_param_dict[\"params\"]\n self.relation_info = all_param_dict[\"relation_info\"]\n if len(self.virtual_instance_id) == 0: # not overwrite in edit mode\n self.active_instance_id = all_param_dict[\"active_instance_id\"]\n\n def to_gpu(code_dict):\n for k, v in code_dict.items():\n if isinstance(v, torch.Tensor):\n code_dict[k] = v.cuda()\n elif isinstance(v, dict):\n for k2, v2 in v.items():\n if isinstance(v2, torch.Tensor):\n code_dict[k][k2] = v2.cuda()\n\n if len(self.virtual_instance_id) == 0: # not modify edit mode pose\n if hasattr(self, \"object_pose_dict\"):\n self.object_pose_dict.update(all_param_dict[\"object_pose_dict\"])\n else:\n self.object_pose_dict = all_param_dict[\"object_pose_dict\"]\n if self.optimize_light_env:\n self.light_code_dict = all_param_dict[\"light_code\"]\n to_gpu(self.light_code_dict)\n if self.optimize_appearance_code:\n self.appearance_code_dict = all_param_dict[\"appearance_code\"]\n to_gpu(self.appearance_code_dict)\n if self.optimize_exposure and \"exposure\" in all_param_dict:\n self.autoexposure_param = all_param_dict[\"exposure\"]\n to_gpu(self.autoexposure_param)\n # ipdb.set_trace()\n\n def interpolate_light_env_from_states(self, path1, path2, interp):\n all_param_dict_1 = torch.load(path1)\n all_param_dict_2 = torch.load(path2)\n\n # self.params = all_param_dict[\"params\"]\n def to_gpu(code_dict):\n for k, v in code_dict.items():\n if isinstance(v, torch.Tensor):\n code_dict[k] = v.cuda()\n elif isinstance(v, dict):\n for k2, v2 in v.items():\n if isinstance(v2, torch.Tensor):\n code_dict[k][k2] = v2.cuda()\n\n if self.optimize_light_env:\n light_code_dict_1 = all_param_dict_1[\"light_code\"]\n light_code_dict_2 = all_param_dict_2[\"light_code\"]\n for k, v in self.light_code_dict.items():\n self.light_code_dict[k] = light_code_dict_1[\n k\n ] * interp + light_code_dict_2[k] * (1 - interp)\n to_gpu(self.light_code_dict)\n if self.optimize_appearance_code:\n appearance_code_dict_1 = all_param_dict_1[\"appearance_code\"]\n appearance_code_dict_2 = all_param_dict_2[\"appearance_code\"]\n for k, v in self.appearance_code_dict.items():\n self.appearance_code_dict[k] = appearance_code_dict_1[\n k\n ] * interp + appearance_code_dict_2[k] * (1 - interp)\n to_gpu(self.appearance_code_dict)\n if self.optimize_exposure:\n autoexposure_param_1 = all_param_dict_1[\"exposure\"]\n autoexposure_param_2 = all_param_dict_2[\"exposure\"]\n for k, v in self.autoexposure_param.items():\n self.autoexposure_param[k] = autoexposure_param_1[\n k\n ] * interp + autoexposure_param_2[k] * (1 - interp)\n to_gpu(self.autoexposure_param)\n\n def reset_active_instance_id(self, active_instance_id, filter_door_and_window=True):\n self.active_instance_id = active_instance_id\n if filter_door_and_window:\n self.filter_door_and_window()\n\n def set_output_path(self, output_path: str, prefix: str, with_timestamp=True):\n if output_path is not None:\n if with_timestamp:\n self.output_path = os.path.join(\n output_path, f\"rendered_{get_timestamp()}_{prefix}\"\n )\n else:\n self.output_path = os.path.join(output_path, f\"{prefix}\")\n os.makedirs(self.output_path, exist_ok=True)\n\n def filter_door_and_window(self):\n print(\"Filtering door and window objects.\")\n filtered_active_instance_id = []\n for obj_id in self.active_instance_id:\n if self.get_type_of_instance(obj_id) not in [\"door\", \"window\"]:\n filtered_active_instance_id += [obj_id]\n self.active_instance_id = filtered_active_instance_id\n\n def initialize_light_code(self):\n self.light_code_dict = {}\n for obj_id in self.active_instance_id:\n # light_code = torch.randn((16)).cuda()\n light_code = torch.zeros((16)).cuda()\n light_code.requires_grad = True\n self.params += [\n {\"params\": light_code, \"lr\": self.lr}\n ] # light code can be optimized with larger lr\n self.light_code_dict[str(obj_id)] = light_code\n\n def initialize_appearance_code(self):\n self.appearance_code_dict = {}\n for obj_id in self.active_instance_id:\n # appearance_code = torch.randn((16)).cuda()\n appearance_code = torch.zeros((16)).cuda()\n appearance_code.requires_grad = True\n self.params += [\n {\"params\": appearance_code, \"lr\": self.lr}\n ] # light code can be optimized with larger lr\n self.appearance_code_dict[str(obj_id)] = appearance_code\n\n def initialize_autoexposure(self):\n self.autoexposure_param = {}\n for obj_id in self.active_instance_id:\n # scale and shift\n autoexposure_param = torch.Tensor([1, 1, 1, 0, 0, 0]).cuda()\n autoexposure_param.requires_grad = True\n self.params += [\n {\"params\": autoexposure_param, \"lr\": self.lr * 0.1}\n ] # light code can be optimized with larger lr\n self.autoexposure_param[str(obj_id)] = autoexposure_param\n\n def get_scale_factor(self, obj_id):\n if obj_id == 0:\n return self.bg_scale_factor\n elif str(obj_id) in self.scale_factor_dict:\n return self.scale_factor_dict[str(obj_id)]\n else:\n return self.scale_factor\n\n def extract_bounding_boxes_from_neural_model(self):\n print(\"Extracting object bounding boxes from neural model...\")\n assert self.model_type == \"NeuS\"\n for obj_id in tqdm(self.active_instance_id):\n mesh = extract_mesh_from_neus(\n self.models[f\"neus_{obj_id}\"],\n self.image_attrs[str(obj_id)],\n obj_id,\n )\n bbox = mesh.get_axis_aligned_bounding_box()\n bound = np.array([bbox.min_bound, bbox.max_bound])\n size = (bound[1] - bound[0]) * self.get_scale_factor(obj_id)\n # update scene_meta\n for idx, obj_info in enumerate(self.scene_meta[\"objs\"]):\n if obj_info[\"id\"] == obj_id:\n self.scene_meta[\"objs\"][idx][\"bdb3d\"][\"size\"] = size.tolist()\n\n def prepare_bbox_ray_helper(self):\n # bbox ray helper dict\n self.bbox_ray_helper_dict = {}\n for obj_id in self.active_instance_id:\n if obj_id == 0:\n continue\n obj_meta_info = get_object_meta_info(\n self.ig_data_base_dir, self.scene_meta, obj_id\n )\n length = np.array(obj_meta_info[\"bbox3d\"][\"size\"])\n self.bbox_ray_helper_dict[str(obj_id)] = BBoxRayHelper(np.zeros(3), length)\n\n def generate_object_rays(\n self, rays_o_obj, rays_d_obj, obj_id, near=None, far=None, select_ind=None\n ):\n \"\"\"\n Generate object rays given rays_o, rays_d and obj_id\n Input:\n select_ind: only for masked rendering\n \"\"\"\n if obj_id == 0: # background\n return self.generate_bg_rays(rays_o_obj, rays_d_obj, near=near, far=far)\n if self.bbox_ray_intersect:\n # for object, rays_o and rays_d should lie in world scale (unscaled)\n bbox_mask, bbox_batch_near, bbox_batch_far = self.bbox_ray_helper_dict[\n str(obj_id)\n ].get_ray_bbox_intersections(\n rays_o_obj,\n rays_d_obj,\n self.get_scale_factor(obj_id),\n # bbox_enlarge=self.bbox_enlarge / self.get_scale_factor(obj_id),\n bbox_enlarge=self.bbox_enlarge, # in physical world\n )\n # for area which hits bbox, we use bbox hit near far\n # bbox_ray_helper has scale for us, do no need to rescale\n batch_near_obj, batch_far_obj = bbox_batch_near, bbox_batch_far\n rays_o_obj = rays_o_obj / self.get_scale_factor(obj_id)\n # for the invalid part, we use 0 as near far, which assume that (0, 0, 0) is empty\n batch_near_obj[~bbox_mask] = torch.zeros_like(batch_near_obj[~bbox_mask])\n batch_far_obj[~bbox_mask] = torch.zeros_like(batch_far_obj[~bbox_mask])\n else:\n near = self.near if near is None else near\n far = self.far if far is None else far\n batch_near_obj = (\n near\n / self.get_scale_factor(obj_id)\n * torch.ones_like(rays_o_obj[:, :1])\n )\n batch_far_obj = (\n far / self.get_scale_factor(obj_id) * torch.ones_like(rays_d_obj[:, :1])\n )\n rays_o_obj = rays_o_obj / self.get_scale_factor(obj_id)\n\n if self.mask_per_object:\n # mask out of bound rendering\n obj_mask = torch.from_numpy(self.instance_mask == obj_id).view(-1)\n obj_mask = obj_mask[select_ind]\n batch_near_obj[~obj_mask] = 0\n batch_far_obj[~obj_mask] = 0\n\n rays_obj = torch.cat(\n [rays_o_obj, rays_d_obj, batch_near_obj, batch_far_obj], 1\n ) # (H*W, 8)\n rays_obj = rays_obj.cuda()\n return rays_obj\n\n def generate_bg_rays(self, rays_o_bg, rays_d_bg, near=None, far=None):\n near = self.near if near is None else near\n far = self.far if far is None else far\n batch_near_bg = near / self.bg_scale_factor * torch.ones_like(rays_o_bg[:, :1])\n batch_far_bg = far / self.bg_scale_factor * torch.ones_like(rays_d_bg[:, :1])\n rays_o_bg = rays_o_bg / self.bg_scale_factor\n rays_bg = torch.cat(\n [rays_o_bg, rays_d_bg, batch_near_bg, batch_far_bg], 1\n ) # (H*W, 8)\n rays_bg = rays_bg.cuda()\n return rays_bg\n\n def batched_inference_multi(\n self,\n rays_list,\n obj_id_list,\n to_cpu=True,\n hit_test_only=False,\n need_normal=False,\n use_sphere_tracing=True,\n safe_region_volume_rendering=True,\n refine_edge=False,\n refine_edge_obj_ids=[],\n render_mask=False,\n # use_sphere_tracing=False,\n show_progress=False,\n **kwargs,\n ):\n \"\"\"Do batched inference on rays using chunk.\"\"\"\n B = rays_list[0].shape[0]\n results = defaultdict(list)\n for i in tqdm(range(0, B, self.chunk), disable=not show_progress):\n extra_chunk = dict()\n for k, v in kwargs.items():\n if isinstance(v, torch.Tensor) and \"autoexposure_\" not in k:\n extra_chunk[k] = v[i : i + self.chunk]\n else:\n extra_chunk[k] = v\n if self.model_type == \"NeRF\":\n rendered_ray_chunks = render_rays_multi(\n self.models,\n self.embeddings,\n [r[i : i + self.chunk] for r in rays_list],\n obj_id_list,\n self.N_samples,\n use_disp=False,\n perturb=0.001,\n # perturb=0.00,\n noise_std=0,\n N_importance=self.N_importance,\n chunk=self.chunk,\n white_back=True,\n individual_weight_for_coarse=True,\n obj_bg_relative_scale=self.bg_scale_factor / self.scale_factor,\n **extra_chunk,\n )\n elif self.model_type == \"NeuS\":\n rendered_ray_chunks = render_rays_multi_neus(\n self,\n self.models,\n [r[i : i + self.chunk] for r in rays_list],\n obj_id_list,\n noise_std=0,\n white_back=True,\n # white_back=False,\n # obj_bg_relative_scale=self.bg_scale_factor / self.scale_factor,\n hit_test_only=hit_test_only,\n need_normal=need_normal,\n use_sphere_tracing=use_sphere_tracing,\n safe_region_volume_rendering=safe_region_volume_rendering,\n refine_edge=refine_edge,\n refine_edge_obj_ids=refine_edge_obj_ids,\n render_mask=render_mask,\n extra_dict=extra_chunk,\n render_kwargs=self.render_kwargs_neus,\n )\n\n for k, v in rendered_ray_chunks.items():\n if to_cpu:\n results[k] += [v.cpu()]\n else:\n results[k] += [v]\n\n for k, v in results.items():\n results[k] = torch.cat(v, 0)\n return results\n\n def render_full_scene(\n self,\n pose: np.ndarray,\n idx: int,\n h: int,\n w: int,\n write_idx_on_image=True,\n return_raw_image=False,\n render_mask=False,\n refine_edge=False,\n use_sphere_tracing=True,\n safe_region_volume_rendering=False,\n show_progress=False,\n refine_edge_obj_ids=[],\n fovx_deg=0,\n ):\n extra_dict = dict()\n extra_dict[\"compute_3d_mask\"] = False\n extra_dict[\"is_eval\"] = True\n\n rays_list = []\n object_id_list = []\n\n if fovx_deg > 0:\n focal = (w / 2) / np.tan((fovx_deg / 2) / (180 / np.pi))\n print(\"focal =\", focal)\n directions = get_ray_directions(h, w, focal).cuda() # (h, w, 3)\n else:\n directions = get_ray_directions_equirectangular(h, w).cuda() # (h, w, 3)\n\n for obj_id in self.active_instance_id:\n # get object location\n # Two: object to world pose\n if obj_id == 0: # 0 denotes background\n Two = np.eye(4)\n Two[:3, 3] = self.bg_scene_center\n else: # other objects\n Two = torch.eye(4).cuda()\n Two[:3, :3] = rotation_6d_to_matrix(\n self.object_pose_dict[str(obj_id)][\"rot6d\"]\n )\n Two[:3, 3] = self.object_pose_dict[str(obj_id)][\"trans\"]\n Two = Two.detach().cpu().numpy()\n # pose: Twc\n # we need: Toc\n Twc = np.eye(4)\n Twc[:3, :4] = pose[:3, :4]\n\n Toc = np.linalg.inv(Two) @ Twc\n\n Toc = torch.from_numpy(Toc).float().cuda()[:3, :4]\n rays_o, rays_d = get_rays(directions, Toc)\n\n rays = self.generate_object_rays(rays_o, rays_d, obj_id)\n\n rays_list += [rays]\n object_id_list += [obj_id]\n\n # set image_attr for object code\n extra_dict[\"embedding_inst_{}\".format(obj_id)] = self.image_attrs[\n str(obj_id)\n ].embedding_instance(torch.ones_like(rays_o[..., 0]).long().cuda() * obj_id)\n # light code\n if self.optimize_light_env:\n if self.use_light_from_image_attr or obj_id in self.virtual_instance_id:\n if not hasattr(self, \"hard_code_light_id\"):\n self.hard_coded_light_id = 0\n extra_dict[\"embedding_light_{}\".format(obj_id)] = self.image_attrs[\n str(obj_id)\n ].embedding_light(\n torch.ones_like(rays_o[..., 0]).long().cuda()\n * self.hard_coded_light_id\n )\n else:\n extra_dict[\"embedding_light_{}\".format(obj_id)] = (\n self.light_code_dict[str(obj_id)]\n .view(1, -1)\n .expand(rays_o.shape[0], -1)\n )\n # appearance code\n if self.optimize_appearance_code and obj_id not in self.virtual_instance_id:\n if self.use_appearance_from_image_attr:\n extra_dict[\n \"embedding_appearance_{}\".format(obj_id)\n ] = self.image_attrs[str(obj_id)].embedding_appearance(\n torch.ones_like(rays_o[..., 0]).long().cuda() * 0\n )\n else:\n extra_dict[\"embedding_appearance_{}\".format(obj_id)] = (\n self.appearance_code_dict[str(obj_id)]\n .view(1, -1)\n .expand(rays_o.shape[0], -1)\n )\n\n # optimize exposure\n if self.optimize_exposure and obj_id not in self.virtual_instance_id:\n extra_dict[f\"autoexposure_{obj_id}\"] = self.autoexposure_param[\n str(obj_id)\n ]\n\n with torch.cuda.amp.autocast(enabled=True):\n with torch.no_grad():\n results = self.batched_inference_multi(\n rays_list,\n object_id_list,\n to_cpu=False,\n use_sphere_tracing=use_sphere_tracing,\n # use_sphere_tracing=True,\n safe_region_volume_rendering=safe_region_volume_rendering,\n refine_edge=refine_edge,\n render_mask=render_mask,\n show_progress=show_progress,\n **extra_dict,\n )\n img = results[f\"rgb_fine\"]\n img_pred = np.clip(img.view(h, w, 3).cpu().numpy(), 0, 1)\n img_pred_ = (img_pred * 255).astype(np.uint8)\n\n if return_raw_image:\n if render_mask:\n img_mask = results[f\"rendered_instance_mask\"]\n img_mask = (\n img_mask.view(h, w, 3)[:, :, 0]\n .cpu()\n .numpy()\n .round()\n .astype(np.uint16)\n )\n return img_pred_, img_mask\n return img_pred_ # raw image in [h, w, 3] np.uint8\n\n if write_idx_on_image:\n img_pred_ = cv2.putText(\n img_pred_,\n \"Iter: {:03d}\".format(idx),\n (20, 20),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.7,\n (255, 0, 0),\n 2,\n )\n\n imageio.imwrite(\n os.path.join(self.output_path, f\"{idx:06d}.multi_obj.png\"), img_pred_\n )\n if render_mask:\n img_mask = results[f\"rendered_instance_mask\"]\n img_mask = (\n img_mask.view(h, w, 3)[:, :, 0].cpu().numpy().round().astype(np.uint16)\n )\n cv2.imwrite(os.path.join(self.output_path, f\"{idx:06d}.seg.png\"), img_mask)\n\n def set_initial_object_poses_from_scene_meta(self, add_noise=True):\n self.object_pose_dict = {}\n\n for obj_id in self.active_instance_id:\n if obj_id == 0:\n continue\n obj_meta_info = get_object_meta_info(\n self.ig_data_base_dir, self.scene_meta, obj_id\n )\n if \"gt_T_wo\" in obj_meta_info:\n Two = obj_meta_info[\"gt_T_wo\"]\n else:\n print(\n f\"Cannot find object pose for obj_id = {obj_id}, use custom pose with minor offset.\"\n )\n Two = np.eye(4)\n from scipy.spatial.transform import Rotation as R\n\n rot_fix = np.array([1, 0, 0, 0, 0, 1, 0, -1, 0]).reshape(3, 3)\n # TODO: update initial pose for real-world scenes\n # if obj_id == 31:\n # blender_xyz = np.array([-1.44, 1.18, 0.1])\n # blender_rot = R.from_quat([0.5, -0.5, 0.5, 0.5]).as_matrix()\n # elif obj_id == 32:\n # blender_xyz = np.array([0.76, 0.54, 0.98])\n # blender_rot = R.from_quat([0.707107, 0, 0, 0.707107]).as_matrix()\n # elif obj_id == 33:\n # blender_xyz = np.array([-0.06, 1.01, -0.9])\n # blender_rot = R.from_quat([0, 0.707107, -0.707107, 0]).as_matrix()\n # elif obj_id == 34:\n # blender_xyz = np.array([-0.05, 1.14, -0.15])\n # blender_rot = R.from_quat([0, 0.707107, -0.707107, 0]).as_matrix()\n # elif obj_id == 35:\n # blender_xyz = np.array([-0.35, 1.1, 0.98])\n # blender_rot = R.from_quat([0.707107, 0, 0, 0.707107]).as_matrix()\n\n # Two[:3, :3] = blender_rot @ rot_fix\n # Two[:3, :3] = rot_fix @ blender_rot\n # Two[:3, 3] = rot_fix @ blender_xyz\n\n # Two[1, 3] += 0.75\n # Two[2, 3] -= 0.7\n\n # add noise\n if add_noise:\n Two[:3, 3] += 0.1\n from scipy.spatial.transform import Rotation as R\n\n rot_noise = R.from_euler(\"z\", 20, degrees=True).as_matrix()\n Two[:3, :3] = Two[:3, :3] @ rot_noise\n Two = torch.from_numpy(Two).float().cuda()\n\n # split parameters\n rot6d = matrix_to_rotation_6d(Two[:3, :3])\n trans = Two[:3, 3]\n rot6d.requires_grad = True\n trans.requires_grad = True\n\n self.object_pose_dict[str(obj_id)] = {\n \"trans\": trans,\n \"rot6d\": rot6d,\n }\n if \"fix_object_pose\" not in self.optimize_option:\n self.params += [{\"params\": trans, \"lr\": self.lr}]\n self.params += [{\"params\": rot6d, \"lr\": self.lr}]\n\n def set_initial_pose_from_prediction(self, pred_json_path):\n print(\"Initial pose from\", pred_json_path)\n self.object_pose_dict = {}\n self.initial_pose_prediction = {}\n pred_info = read_json(pred_json_path)\n for obj_id in self.active_instance_id:\n if obj_id == 0:\n continue\n Two = np.array(pred_info[str(obj_id)][\"Two\"])\n Two = torch.from_numpy(Two).float().cuda()\n self.initial_pose_prediction[str(obj_id)] = {\"Two\": Two.clone()}\n\n # split parameters\n rot6d = matrix_to_rotation_6d(Two[:3, :3])\n trans = Two[:3, 3]\n\n if not \"fix_object_pose\" in self.optimize_option:\n rot6d.requires_grad = True\n trans.requires_grad = True\n\n self.object_pose_dict[str(obj_id)] = {\n \"trans\": trans,\n \"rot6d\": rot6d,\n }\n self.params += [{\"params\": trans, \"lr\": self.lr}]\n self.params += [{\"params\": rot6d, \"lr\": self.lr}]\n\n def set_initial_pose_as_identity(self):\n print(\"Initial pose as identity.\")\n self.object_pose_dict = {}\n self.initial_pose_prediction = {}\n for obj_id in self.active_instance_id:\n if obj_id == 0:\n continue\n Two = np.eye(4)\n Two = torch.from_numpy(Two).float().cuda()\n self.initial_pose_prediction[str(obj_id)] = {\"Two\": Two.clone()}\n\n # split parameters\n rot6d = matrix_to_rotation_6d(Two[:3, :3])\n trans = Two[:3, 3]\n rot6d.requires_grad = True\n trans.requires_grad = True\n\n self.object_pose_dict[str(obj_id)] = {\n \"trans\": trans,\n \"rot6d\": rot6d,\n }\n self.params += [{\"params\": trans, \"lr\": self.lr}]\n self.params += [{\"params\": rot6d, \"lr\": self.lr}]\n\n def set_sampling_mask_from_seg(\n self,\n seg_mask=None,\n seg_mask_path=None,\n add_noise_to_seg=0,\n convert_seg_mask_to_box_mask=False,\n ):\n if seg_mask_path is not None:\n print(\"Read segmentation from gt mask\")\n # read mask\n self.instance_mask = get_instance_mask(seg_mask_path, img_wh=self.img_wh)\n elif seg_mask is not None:\n self.instance_mask = seg_mask\n else:\n print(\"Warning: empty mask\")\n self.merged_mask = (\n np.ones((self.img_wh[1], self.img_wh[0])).reshape(-1).astype(bool)\n )\n return\n\n # merge active object masks\n merged_mask = np.zeros_like(self.instance_mask)\n for i_obj, obj_id in enumerate(self.active_instance_id):\n if obj_id == 0:\n continue # do not accumulate background obj_id\n instance_mask_obj = self.instance_mask == obj_id\n # use tightly fit bbox instead of segmentation mask\n if convert_seg_mask_to_box_mask:\n instance_mask_obj = seg_mask_to_box_mask(instance_mask_obj)\n merged_mask = np.logical_or(merged_mask, instance_mask_obj)\n\n # if add noise to gt segmentation\n if add_noise_to_seg != 0:\n is_dilate = add_noise_to_seg > 0\n add_noise_to_seg = abs(add_noise_to_seg)\n kernel = np.ones((add_noise_to_seg, add_noise_to_seg), np.uint8)\n if is_dilate:\n merged_mask = cv2.dilate(\n merged_mask.astype(np.uint8), kernel, iterations=1\n ).astype(bool)\n else:\n merged_mask = cv2.erode(\n merged_mask.astype(np.uint8), kernel, iterations=1\n ).astype(bool)\n cv2.imwrite(\n f\"{self.output_path}/merged_mask.png\", merged_mask.astype(np.uint8) * 255\n )\n self.merged_mask = merged_mask.reshape(-1)\n\n def get_type_of_instance(self, instance_id):\n for obj_info in self.scene_meta[\"objs\"]:\n if obj_info[\"id\"] == instance_id:\n return obj_info[\"classname\"]\n return \"unknown\"\n\n def generate_relation(\n self,\n obj_to_room_distance_th: float = 0.5,\n top_down_dist_th: float = 0.3,\n top_down_xy_close_factor: float = 0.8,\n ):\n \"\"\"\n Generate relationship : object-wall, object-floor, object-object\n \"\"\"\n print(\"Start to generate relation from initial poses and neural models...\")\n all_obj_info = {}\n for i, obj_id in enumerate(self.active_instance_id):\n if obj_id == 0:\n continue\n Rwo = rotation_6d_to_matrix(self.object_pose_dict[str(obj_id)][\"rot6d\"])\n two = self.object_pose_dict[str(obj_id)][\"trans\"]\n optimized_meta = get_object_meta_info(\n self.ig_data_base_dir, self.scene_meta, obj_id\n )\n optimized_meta.pop(\"gt_T_wo\", None) # pop gt\n # pass optimized object pose\n optimized_meta[\"Rwo\"] = Rwo\n optimized_meta[\"two\"] = two\n optimized_meta[\"obj_id\"] = obj_id\n all_obj_info[str(obj_id)] = optimized_meta\n with torch.no_grad():\n generate_relation_for_all(\n room_optimizer=self,\n all_obj_info=all_obj_info,\n obj_to_room_distance_th=obj_to_room_distance_th,\n top_down_dist_th=top_down_dist_th,\n top_down_xy_close_factor=top_down_xy_close_factor,\n )\n # print(\"Relation:\\n\", self.relation_info)\n for k, v in self.relation_info.items():\n print(k, v)\n\n def optimize(self, input_rgb: torch.Tensor, pose=None):\n \"\"\"\n Inputs:\n input_rgb: torch.Tensor [h, w, 3] normalized in 0...1\n \"\"\"\n if pose is None:\n pose = np.array(self.scene_meta[\"camera\"][\"cam3d2world\"]).reshape(4, 4)\n # Original poses has rotation in form \"right down forward\", change to NDC \"right up back\"\n fix_rot = np.array([1, 0, 0, 0, -1, 0, 0, 0, -1]).reshape(3, 3)\n pose[:3, :3] = pose[:3, :3] @ fix_rot\n\n # camera to world pose\n Twc = np.eye(4)\n Twc[:3, :4] = pose[:3, :4]\n Twc = torch.from_numpy(Twc).float().cuda()\n\n if \"keypoint_mask\" in self.optimize_option:\n # detect keypoint for interest region\n keypoint_mask = detect_keypoints(input_rgb.numpy(), circle_radius=5)\n self.merged_mask = np.logical_and(\n keypoint_mask, self.merged_mask.reshape(keypoint_mask.shape)\n )\n cv2.imwrite(\n f\"{self.output_path}/merged_mask_keypoint.png\",\n self.merged_mask.astype(np.uint8) * 255,\n )\n self.merged_mask = self.merged_mask.reshape(-1)\n\n input_rgb = input_rgb.view(-1, 3) # (H*W, 3) RGB\n\n directions = get_ray_directions_equirectangular(\n self.h, self.w\n ).cuda() # (h, w, 3)\n\n mse_loss = nn.MSELoss(reduction=\"none\")\n\n assert hasattr(\n self, \"params\"\n ), \"Please set initial pose params before optimization.\"\n optimizer = torch.optim.Adam(self.params)\n\n scaler = torch.cuda.amp.GradScaler(enabled=self.use_amp)\n perceptual_net = perceptual_model.VGG16_for_Perceptual().cuda()\n\n sample_prob = pano_sample_probability(self.h, self.w).reshape(-1)\n\n t = trange(self.N_optim_step, desc=\"Opt.\", leave=True)\n for i_step in t:\n if \"regenerate_relation_during_test\" in self.optimize_option:\n if i_step != 0 and i_step % 50 == 0:\n self.generate_relation()\n if self.adjust_lr_per_step > 0:\n adjust_learning_rate(\n self.lr,\n optimizer,\n i_step,\n base=0.5,\n adjust_lr_every=self.adjust_lr_per_step,\n )\n extra_dict = dict()\n rays_list = []\n object_id_list = []\n # sample according to batch size limitation\n select_ind = np.arange(self.merged_mask.shape[0])[self.merged_mask]\n if (\n \"perceptual_loss\" not in self.optimize_option\n ): # we only sample some points in this case\n # sample according to pano distribution\n select_sample_prob = sample_prob[self.merged_mask]\n select_sample_prob /= select_sample_prob.sum()\n # assert select_ind.shape[0] > self.optim_batch_size\n sample_size = min(select_ind.shape[0], self.optim_batch_size)\n select_ind = np.random.choice(\n select_ind,\n size=sample_size,\n replace=False,\n p=select_sample_prob,\n )\n\n # add some sampling on the background for bg light code\n if self.optimize_light_env:\n bg_sample_ratio = 0.2\n bg_sample_prob = sample_prob[~self.merged_mask]\n bg_sample_prob /= bg_sample_prob.sum()\n bg_sample_ind = np.arange(self.merged_mask.shape[0])[~self.merged_mask]\n # assert bg_sample_ind.shape[0] > self.optim_batch_size\n bg_sample_size = min(\n bg_sample_ind.shape[0], int(bg_sample_ratio * self.optim_batch_size)\n )\n if bg_sample_size > 0:\n bg_sample_ind = np.random.choice(\n bg_sample_ind,\n size=bg_sample_size,\n replace=False,\n p=bg_sample_prob,\n )\n select_ind = np.concatenate([select_ind, bg_sample_ind], axis=-1)\n\n select_ind = np.unique(select_ind)\n if i_step == 0:\n print(\"Actual optimization rays\", select_ind.shape[0])\n select_input_rgb = input_rgb[select_ind].float().cuda()\n\n loss_dict = {}\n all_obj_info = {} # prepare for violation loss\n\n for i, obj_id in enumerate(self.active_instance_id):\n # object to world pose\n if obj_id == 0:\n Rwo = torch.eye(3).cuda()\n two = torch.from_numpy(self.bg_scene_center).float().cuda()\n else:\n Rwo = rotation_6d_to_matrix(\n self.object_pose_dict[str(obj_id)][\"rot6d\"]\n )\n two = self.object_pose_dict[str(obj_id)][\"trans\"]\n\n # camera to object pose\n Toc = torch.eye(4).cuda()\n Toc[:3, :3] = Rwo.T @ Twc[:3, :3]\n Toc[:3, 3] = Rwo.T @ (Twc[:3, 3] - two)\n\n # generate object rays\n rays_o, rays_d = get_rays(directions, Toc[:3, :4])\n\n rays_o = rays_o[select_ind]\n rays_d = rays_d[select_ind]\n\n rays = self.generate_object_rays(rays_o, rays_d, obj_id)\n rays_list += [rays]\n object_id_list += [obj_id]\n\n # set image_attr for object code\n extra_dict[\"embedding_inst_{}\".format(obj_id)] = self.image_attrs[\n str(obj_id)\n ].embedding_instance(\n torch.ones_like(rays_o[..., 0]).long().cuda() * obj_id\n )\n # light code\n if self.optimize_light_env:\n if self.use_light_from_image_attr:\n extra_dict[\n \"embedding_light_{}\".format(obj_id)\n ] = self.image_attrs[str(obj_id)].embedding_light(\n torch.ones_like(rays_o[..., 0]).long().cuda()\n * self.hard_coded_light_id\n )\n else:\n extra_dict[\"embedding_light_{}\".format(obj_id)] = (\n self.light_code_dict[str(obj_id)]\n .view(1, -1)\n .expand(rays_o.shape[0], -1)\n )\n # appearance code\n if self.optimize_appearance_code:\n if self.use_appearance_from_image_attr:\n extra_dict[\n \"embedding_appearance_{}\".format(obj_id)\n ] = self.image_attrs[str(obj_id)].embedding_appearance(\n torch.ones_like(rays_o[..., 0]).long().cuda() * 0\n )\n else:\n extra_dict[\"embedding_appearance_{}\".format(obj_id)] = (\n self.appearance_code_dict[str(obj_id)]\n .view(1, -1)\n .expand(rays_o.shape[0], -1)\n )\n # autoexposure\n if self.optimize_exposure:\n extra_dict[f\"autoexposure_{obj_id}\"] = self.autoexposure_param[\n str(obj_id)\n ]\n\n # we do not need to add relation constraints to bg\n if obj_id == 0:\n continue\n\n # enforce optimising on yaw\n if \"z_axis_align_loss\" in self.optimize_option:\n loss_dict[\"z_axis_loss_{}\".format(obj_id)] = (\n z_axis_loss(Rwo, 1.0) * 1e2\n )\n\n optimized_meta = get_object_meta_info(\n self.ig_data_base_dir, self.scene_meta, obj_id\n )\n optimized_meta.pop(\"gt_T_wo\", None) # pop gt\n # pass optimized object pose\n optimized_meta[\"Rwo\"] = Rwo\n optimized_meta[\"two\"] = two\n optimized_meta[\"obj_id\"] = obj_id\n obj_id_key = str(obj_id)\n\n if obj_id_key not in self.relation_info:\n continue\n\n # get obj_relation from input\n obj_relation = self.relation_info[obj_id_key]\n # supplement obj_type\n obj_type = self.get_type_of_instance(obj_id)\n optimized_meta[\"obj_type\"] = obj_type\n\n all_obj_info[str(obj_id)] = optimized_meta\n\n with torch.cuda.amp.autocast(enabled=self.use_amp):\n \"\"\"attach wall loss\"\"\"\n if (\n \"object_room_wall_attach\" in self.optimize_option\n and obj_relation.get(\"attach_wall\", False)\n ):\n kwargs = {\n \"room_optimizer\": self,\n \"obj_info\": optimized_meta,\n # \"face_direction\": torch.Tensor([0, 1, 0]),\n # \"face_direction\": obj_relation.get(\n # \"attach_wall_face_dir\", torch.Tensor([0, 1, 0])\n # ),\n \"face_direction\": obj_relation[\"attach_wall_face_dir\"],\n \"ray_grid_size\": 10,\n }\n # for door object, we slightly stretch the size to ensure successive hit-test\n if obj_type == \"door\" or obj_type == \"window\":\n kwargs.update(\n {\n \"ray_grid_stretch\": torch.Tensor([1.2, 1.2, 1]),\n \"use_bbox_surface_as_in_detect\": True,\n }\n )\n loss_dict.update(object_room_magnetic_loss(**kwargs))\n\n \"\"\"attach floor loss\"\"\"\n if (\n \"object_room_floor_attach\" in self.optimize_option\n and obj_relation.get(\"attach_floor\", False)\n ):\n # # TODO(ybbbbt): hard code floor\n # loss_dict.update(\n # obj_attach_floor_loss(optimized_meta, floor=0.0)\n # )\n kwargs = {\n \"room_optimizer\": self,\n \"obj_info\": optimized_meta,\n \"face_direction\": torch.Tensor([0, 0, -1]),\n \"ray_grid_stretch\": torch.Tensor(\n [0.8, 0.8, 1.0]\n ), # avoid too close to wall\n \"use_bbox_surface_as_in_detect\": True,\n \"ray_grid_size\": 3,\n }\n if obj_type == \"door\":\n # kwargs[\"ray_grid_offset\"] = torch.Tensor(\n # [0, -0.3, 0]\n # ) # to avoid to close to wall\n assert (\n \"attach_wall_face_dir\" in obj_relation\n ), f\"door {obj_id} relation prediction failed.\"\n kwargs[\"ray_grid_offset\"] = (\n obj_relation[\"attach_wall_face_dir\"] * -0.3\n ) # to avoid to close to wall\n loss_dict.update(object_room_magnetic_loss(**kwargs))\n\n with torch.cuda.amp.autocast(enabled=self.use_amp):\n results = self.batched_inference_multi(\n rays_list,\n object_id_list,\n to_cpu=False,\n # use_sphere_tracing=True,\n use_sphere_tracing=False,\n **extra_dict,\n )\n pred_rgb = results[\"rgb_fine\"]\n\n if \"photometric_loss\" in self.optimize_option:\n loss_dict[\"mse_loss\"] = mse_loss(pred_rgb, select_input_rgb).mean()\n\n if \"visualize_pred\" in self.optimize_option: # dump image for debug\n # pred_rgb_full = input_rgb.cuda()\n pred_rgb_full = torch.zeros_like(input_rgb.cuda())\n pred_rgb_full[select_ind] = pred_rgb\n\n imageio.imwrite(\n f\"debug/pred_rgb_full.png\",\n (pred_rgb_full * 255)\n .view(self.img_wh[1], self.img_wh[0], 3)\n .detach()\n .cpu()\n .numpy()\n .astype(np.uint8),\n )\n\n if \"perceptual_loss\" in self.optimize_option:\n pred_rgb_full = input_rgb.cuda()\n pred_rgb_full[select_ind] = pred_rgb\n loss_dict.update(\n patch_perceptual_loss(\n perceptual_net,\n pred_rgb_full,\n input_rgb,\n all_obj_info,\n self.instance_mask,\n self.img_wh,\n )\n )\n\n \"\"\"attach bottom to other object loss\"\"\"\n if \"object_object_attach\" in self.optimize_option:\n for obj_id_str, obj_relation in self.relation_info.items():\n if obj_relation.get(\"attach_bottom_to_object\", False):\n kwargs = {\n \"room_optimizer\": self,\n \"obj_info_src\": all_obj_info[obj_id_str],\n \"obj_info_tgt\": all_obj_info[\n str(obj_relation[\"attach_tgt_obj_id\"])\n ],\n \"face_direction\": torch.Tensor([0, 0, -1]),\n }\n loss_dict.update(object_object_attach_loss(**kwargs))\n\n # physical violation loss\n if \"physical_violation\" in self.optimize_option:\n if (\n not \"physical_violation_delayed_start\" in self.optimize_option\n or i_step >= 100\n ):\n loss_dict.update(\n physical_violation_loss(\n self,\n all_obj_info,\n N_nearest_obj=3,\n check_background_violation=True,\n # N_sample_points=1000,\n N_sample_points=2000,\n # N_sample_points=300,\n )\n )\n\n if \"viewing_constraint\" in self.optimize_option:\n loss_dict.update(viewing_constraint_loss(self, Twc, all_obj_info))\n\n if \"print_loss_dict\" in self.optimize_option:\n for k, v in loss_dict.items():\n # if \"_62\" not in k:\n # continue\n print(k, \"=\", float(v))\n loss = sum(list(loss_dict.values()))\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n optimizer.zero_grad()\n\n t.set_description(\"Loss: %f\" % float(loss))\n t.refresh()\n # dump image\n if i_step % 20 == 0:\n self.save_optimizable_parameters(\n f\"{self.output_path}/{i_step:06d}.state.ckpt\"\n )\n # self.load_optimizable_parameters(\n # f\"{self.output_path}/{i_step:06d}.state.ckpt\"\n # )\n if i_step >= self.N_optim_step - 20:\n self.render_full_scene(\n pose=pose,\n idx=i_step,\n write_idx_on_image=False,\n render_mask=True,\n h=512,\n w=1280,\n )\n else:\n self.render_full_scene(\n pose=pose,\n idx=i_step,\n render_mask=False,\n h=self.h,\n w=self.w,\n )\n dump_optimization_meta_to_file(\n filepath=f\"{self.output_path}/{i_step:06d}.optim.json\",\n obj_pose_dict=self.object_pose_dict,\n )" }, { "identifier": "read_real_scene_localization", "path": "optim/misc_utils.py", "snippet": "def read_real_scene_localization(pose_path: str, transform_info_json_path: str):\n pose_dict = {}\n transform_info = read_json(transform_info_json_path)\n trans_colmap_to_arkit = np.array(transform_info[\"transform_colmap_to_arkit_sRT\"])\n trans_align = np.array(transform_info[\"transform_alignment\"])\n with open(pose_path) as file:\n lines = file.readlines()\n lines = lines[1:]\n for line in lines:\n fname, tx, ty, tz, qx, qy, qz, qw, _, _ = line.strip().split(\" \")\n fname += \".png\"\n pose = np.eye(4)\n pose[0, 3] = tx\n pose[1, 3] = ty\n pose[2, 3] = tz\n # Twc\n pose[:3, :3] = Rotation.from_quat([qx, qy, qz, qw]).as_matrix()\n # pose = np.linalg.inv(pose)\n # pose_ndc = np.linalg.inv(pose_ndc)\n\n # convert to ndc\n # pose_ndc = pose\n # fix_rot = np.array([1, 0, 0, 0, -1, 0, 0, 0, -1]).reshape(3, 3)\n # pose_ndc[:3, :3] = pose_ndc[:3, :3] @ fix_rot\n\n # transform to arkit pose\n s, R, t = decompose_to_sRT(trans_colmap_to_arkit)\n # pose_ndc = transform_colmap_to_arkit @ pose_ndc\n # print(s, R, t)\n pose[:3, 3] = R @ (pose[:3, 3] * s) + t\n pose[:3, :3] = R @ pose[:3, :3]\n\n # apply alignment to poses\n pose = trans_align @ pose\n\n pose_dict[fname] = {\"pose_slam_Twc\": pose}\n # print(fname, pose)\n return pose_dict" }, { "identifier": "read_real_scene_localization_with_name", "path": "optim/misc_utils.py", "snippet": "def read_real_scene_localization_with_name(arrangement_name):\n localization_info = read_real_scene_localization(\n f\"data/real_room_0/arrangement_panorama_select/{arrangement_name}/traj.txt\",\n \"data/real_room_0/objects/000/background_hloc_neus_normal_converge/transform_info.json\",\n )\n return localization_info" }, { "identifier": "read_testing_config", "path": "optim/misc_utils.py", "snippet": "def read_testing_config():\n conf_cli = OmegaConf.from_cli()\n conf_test_file = OmegaConf.load(conf_cli.config)\n # read dataset config\n conf_test_file[\"dataset_config\"] = read_dataset_config_file(\n conf_test_file[\"dataset_config_path\"]\n )\n conf_test_file[\"bg_dataset_config\"] = read_dataset_config_file(\n conf_test_file[\"bg_dataset_config_path\"]\n )\n\n # processing ckpt\n ckpt_path_dict = {}\n for item in conf_test_file[\"ckpt_lists\"]:\n path = item[\"path\"]\n obj_ids = item[\"obj_ids\"]\n neus_conf = item.get(\"neus_conf\", \"config/neus.yaml\")\n for obj_id in obj_ids:\n ckpt_path_dict[str(obj_id)] = {\"path\": path, \"neus_conf\": neus_conf}\n conf_test_file[\"ckpt_path_dict\"] = ckpt_path_dict\n\n conf_merged = OmegaConf.merge(conf_test_file, conf_cli)\n return conf_merged" }, { "identifier": "read_json", "path": "utils/util.py", "snippet": "def read_json(fname):\n fname = Path(fname)\n with fname.open(\"rt\") as handle:\n return json.load(handle, object_hook=OrderedDict)" } ]
import sys import os import torch import numpy as np from PIL import Image from omegaconf import OmegaConf from optim.room_optimizer import RoomOptimizer from optim.misc_utils import ( read_real_scene_localization, read_real_scene_localization_with_name, read_testing_config, ) from utils.util import read_json
14,414
os.environ["OMP_NUM_THREADS"] = "1" # noqa os.environ["MKL_NUM_THREADS"] = "1" # noqa sys.path.append(".") # noqa def main(config): # active_instance_id = config.active_instance_id scene_info_json_path = config.scene_info_json active_instance_id = [] for obj_info in read_json(scene_info_json_path)["objs"]: active_instance_id += [obj_info["id"]] if 0 not in active_instance_id: active_instance_id += [0] active_instance_id = [0, 33, 35, 37] image_path = config.test_image_path dataset_config = config.dataset_config["dataset"] bg_scale_factor = 1 bg_scene_center = [0, 0, 0] if config.bg_dataset_config != "": bg_dataset_config = config.bg_dataset_config["dataset"] bg_scale_factor = bg_dataset_config["scale_factor"] bg_scene_center = bg_dataset_config["scene_center"] img_wh = config.img_wh # read image input_rgb = Image.open(image_path) input_rgb = input_rgb.resize(img_wh, Image.LANCZOS) input_rgb = np.array(input_rgb) input_rgb = torch.from_numpy(input_rgb).float() / 255 # (H, W, 3) refine_pose = config.get("refine_pose", False) print("refine_pose = ", refine_pose) # intialize room optimizer
os.environ["OMP_NUM_THREADS"] = "1" # noqa os.environ["MKL_NUM_THREADS"] = "1" # noqa sys.path.append(".") # noqa def main(config): # active_instance_id = config.active_instance_id scene_info_json_path = config.scene_info_json active_instance_id = [] for obj_info in read_json(scene_info_json_path)["objs"]: active_instance_id += [obj_info["id"]] if 0 not in active_instance_id: active_instance_id += [0] active_instance_id = [0, 33, 35, 37] image_path = config.test_image_path dataset_config = config.dataset_config["dataset"] bg_scale_factor = 1 bg_scene_center = [0, 0, 0] if config.bg_dataset_config != "": bg_dataset_config = config.bg_dataset_config["dataset"] bg_scale_factor = bg_dataset_config["scale_factor"] bg_scene_center = bg_dataset_config["scene_center"] img_wh = config.img_wh # read image input_rgb = Image.open(image_path) input_rgb = input_rgb.resize(img_wh, Image.LANCZOS) input_rgb = np.array(input_rgb) input_rgb = torch.from_numpy(input_rgb).float() / 255 # (H, W, 3) refine_pose = config.get("refine_pose", False) print("refine_pose = ", refine_pose) # intialize room optimizer
room_optimizer = RoomOptimizer(
0
2023-10-15 08:41:29+00:00
24k
WenzhengZhang/Seq2seqCoref
main_trainer.py
[ { "identifier": "DataArguments", "path": "arguments.py", "snippet": "class DataArguments:\n data_dir: Optional[str] = field(\n default=None, metadata={\"help\": \"Path to data directory\"}\n )\n\n max_train_len: Optional[int] = field(\n default=1536,\n metadata={\n \"help\": \"maximum train source input length\"\n },\n )\n max_train_len_out: Optional[int] = field(\n default=2048,\n metadata={\n \"help\": \"maximum train target decoder length\"\n },\n )\n max_eval_len: Optional[int] = field(\n default=1536,\n metadata={\n \"help\": \"maximum dev/test source input length\"\n },\n )\n max_eval_len_out: Optional[int] = field(\n default=2048,\n metadata={\n \"help\": \"maximum dev/test target decode length\"\n },\n )\n\n data_cache_dir: Optional[str] = field(\n default=None, metadata={\n \"help\": \"Where do you want to store the data downloaded from huggingface\"}\n )\n\n beam_sz: Optional[int] = field(\n default=4, metadata={\n \"help\": \"num beams\"\n }\n )\n\n oracle_mentions_dir: Optional[str] = field(\n default=None, metadata={\n \"help\": \"oracle mentions directory\"\n }\n )\n language: Optional[str] = field(\n default='english', metadata={\n \"help\": \"coreference language\"\n }\n )\n joint_data_dirs: Optional[str] = field(\n default=None, metadata={\"help\": \"datasets dirs for joint training\"}\n )\n joint_max_train_lens: Optional[str] = field(\n default=None, metadata={\"help\": \"max train len for each dataset for \"\n \"joint training\"}\n )\n joint_max_eval_lens: Optional[str] = field(\n default=None, metadata={\"help\": \"max eval len for each dataset for \"\n \"joint training\"}\n )\n joint_num_samples: Optional[int] = field(\n default=2000, metadata={\"help\": \"num samples to subsample for joint \"\n \"training\"}\n )" }, { "identifier": "ModelArguments", "path": "arguments.py", "snippet": "class ModelArguments:\n model_name_or_path: str = field(\n default=\"t5-base\",\n metadata={\n \"help\": \"Path to pretrained model or model identifier from huggingface.co/models\"}\n )\n\n config_name: Optional[str] = field(\n default=None, metadata={\n \"help\": \"Pretrained config name or path if not the same as model_name\"}\n )\n tokenizer_name: Optional[str] = field(\n default=None, metadata={\n \"help\": \"Pretrained tokenizer name or path if not the same as model_name\"}\n )\n cache_dir: Optional[str] = field(\n default=None, metadata={\n \"help\": \"Where do you want to store the pretrained models downloaded from s3\"}\n )\n\n decay_rate: Optional[float] = field(\n default=0.6, metadata={\"help\": \"Decay learning rate\"}\n )\n low_cpu_mem_usage: Optional[bool] = field(\n default=False, metadata={\"help\": \"low cpu mem usage when load model\"}\n )" }, { "identifier": "CorefTrainingArguments", "path": "arguments.py", "snippet": "class CorefTrainingArguments(Seq2SeqTrainingArguments):\n do_train: bool = field(default=True,\n metadata={\"help\": \"Whether to run training.\"})\n save_dir: Optional[str] = field(\n default=None, metadata={\"help\": \"Path to save predicts directory\"}\n )\n save_predicts: Optional[bool] = field(\n default=True, metadata={\"help\": \"whether to save predictions\"}\n )\n mark_sentence: Optional[bool] = field(\n default=False, metadata={\"help\": \"mark sentence end for short target?\"}\n )\n align_mode: Optional[str] = field(\n default='l', metadata={\"help\": \"alignment mode: highroad (h) or \"\n \"lowroad (l) \"}\n )\n optim: Union[OptimizerNames, str] = field(\n default=\"adamw_apex_fused\",\n metadata={\"help\": \"The optimizer to use.\"},\n )\n parallelize_model: Optional[bool] = field(\n default=False, metadata={\"help\": \"whether to enable naive model \"\n \"parallel\"}\n )\n manual_empty_cache: Optional[bool] = field(\n default=False, metadata={\"help\": \"whether to empty cuda cache manually\"}\n )\n is_stage3: Optional[bool] = field(\n default=False, metadata={\"help\": \"use deepspeed stage3 for inference \"\n \"if is stage3\"}\n )\n val_after_train: Optional[bool] = field(\n default=False, metadata={\"help\": \"save the checkpoints then do \"\n \"validation after training\"}\n )\n allow_singletons: Optional[bool] = field(\n default=False, metadata={\n \"help\": \"whether to allow singletons\"\n }\n )\n seq2seq_type: Optional[str] = field(\n default='action', metadata={\n \"help\": \"seq2seq type: action, short_seq, full_seq, tagging, \"\n \"input_feed, action_non_int\"\n }\n )\n action_type: Optional[str] = field(\n default='integer', metadata={\n \"help\": \"target action type: integer, non_integer\"\n }\n )\n do_oracle: Optional[bool] = field(\n default=False, metadata={\n \"help\": \"do oracle experiments or not. Provide (gold) mentions \"\n \"and ask the model to predict coreference predictions\"\n }\n )\n add_mention_end: Optional[bool] = field(\n default=False, metadata={\n \"help\": \"add mention end token when using non-integer action format\"\n }\n )\n joint_data_names: Optional[str] = field(\n default=None, metadata={\"help\": \"datasets names for joint training\"}\n )\n joint_min_num_mentions: Optional[str] = field(\n default=None, metadata={\"help\": \"threshold for num mentions per epoch \"\n \"in joint training for each dataset\"}\n )\n min_num_mentions: Optional[int] = field(\n default=2, metadata={\"help\": \"minimum number of mentions per cluster,\"\n \"ontonotes is 2 other datasets is 1 \"\n \"(allow singletons)\"}\n )\n joint_train: Optional[bool] = field(\n default=False, metadata={\"help\": \"whether to use joint training\"}\n )" }, { "identifier": "CorefDataset", "path": "data.py", "snippet": "class CorefDataset(Dataset):\n\n def __init__(self, tokenizer,\n data_args, train_args, split):\n self.tokenizer = tokenizer\n self.data_args = data_args\n self.train_args = train_args\n self.split = split\n # self.task_prefix = self.data_args.task_prefix\n # convert tokens to ids for each sample\n self.samples, self.doc_labels = self.load_dataset()\n\n def __len__(self):\n return len(self.samples)\n\n def load_dataset(self):\n max_len = self.data_args.max_train_len if self.split == 'train' else \\\n self.data_args.max_eval_len\n data_path = os.path.join(\n self.data_args.data_dir,\n f'{self.split}.t5-small.english.{max_len}.jsonlines')\n samples = []\n doc_labels = {}\n thred = self.train_args.min_num_mentions\n with open(data_path, 'r') as f:\n for line in f:\n item = json.loads(line)\n doc_key = item['doc_key']\n doc_id = re.sub(r'_\\d+$', '', doc_key)\n if self.train_args.action_type == \"integer\":\n target_sent = self.tokenizer.convert_tokens_to_ids(\n item['target_sentence'])\n elif self.train_args.action_type == \"non_integer\":\n if self.train_args.add_mention_end:\n target_sent = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_mention_end_sentence\"])\n else:\n target_sent = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_sentence\"])\n else:\n raise ValueError(f\"wrong action type \"\n f\"{self.train_args.action_type}\")\n\n if self.train_args.seq2seq_type == 'action' or \\\n self.train_args.seq2seq_type == 'input_feed':\n if self.train_args.action_type == 'integer':\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item['target_action'])\n elif self.train_args.action_type == 'non_integer':\n if self.train_args.add_mention_end:\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_mention_end_action\"])\n else:\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_action\"])\n else:\n raise ValueError(\"wrong action type (\"\n \"integer/non_integer)\")\n elif self.train_args.seq2seq_type == 'short_seq':\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item['target_short_sentence'])\n elif self.train_args.seq2seq_type == 'full_seq':\n target_seq = deepcopy(target_sent)\n elif self.train_args.seq2seq_type == 'tagging':\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item['target_action'])\n # set the last token as eos token\n target_seq[-1] = self.tokenizer.eos_token_id\n else:\n raise ValueError('wrong seq2seq type')\n sample = {'doc_key': doc_key,\n 'sentence': self.tokenizer.convert_tokens_to_ids(\n item['sentence']),\n 'target_sentence': target_sent,\n 'target_seq': target_seq,\n 'subtoken_map': item['subtoken_map'],\n 'seg_clusters': [[tuple(m) for m in c] for c in item[\n 'seg_clusters'] if len(c) >= thred],\n 'offset': item['offset']\n }\n doc_labels[doc_id] = [[tuple(m) for m in c] for c in item[\n 'gold_clusters']]\n samples.append(sample)\n return samples, doc_labels\n\n def __getitem__(self, index):\n sample = self.samples[index]\n input_ids = torch.tensor(sample['sentence'], dtype=torch.long)\n if self.train_args.seq2seq_type == 'action' or \\\n self.train_args.seq2seq_type == 'input_feed':\n label_ids = torch.tensor(sample['target_sentence'],\n dtype=torch.long)\n target_ids = torch.tensor(sample['target_seq'], dtype=torch.long)\n input_len, tgt_len = input_ids.size(0), label_ids.size(0)\n attention_mask = torch.tensor([1] * input_len, dtype=torch.long)\n src_encoding = {'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'decoder_labels': label_ids,\n 'labels': target_ids\n }\n else:\n label_ids = torch.tensor(sample['target_seq'],\n dtype=torch.long)\n input_len, tgt_len = input_ids.size(0), label_ids.size(0)\n attention_mask = torch.tensor([1] * input_len, dtype=torch.long)\n src_encoding = {'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'labels': label_ids,\n }\n return src_encoding" }, { "identifier": "JointDataset", "path": "data.py", "snippet": "class JointDataset(Dataset):\n\n def __init__(self, tokenizer,\n data_args, train_args, split):\n self.tokenizer = tokenizer\n self.data_args = data_args\n self.train_args = train_args\n self.split = split\n self.all_samples, self.doc_labels, self.id_to_name = self.load_dataset()\n self.samples = None if self.split == 'train' else [\n s for data_samples in self.all_samples.values() for s in\n data_samples\n ]\n\n def __len__(self):\n if self.split == 'train':\n num_samples = 0\n for s in self.all_samples.values():\n num_samples += min(self.data_args.joint_num_samples, len(s))\n else:\n num_samples = len(self.samples)\n return num_samples\n\n def set_samples(self, epoch):\n # subsample larger datasets and then concat them\n sample_seed = self.train_args.seed + epoch\n min_num_samples = min(len(s) for s in self.all_samples.values())\n samples = []\n for data_name, data_samples in self.all_samples.items():\n if len(data_samples) > min_num_samples:\n subsamples = random.Random(sample_seed).sample(\n data_samples, self.data_args.joint_num_samples)\n else:\n subsamples = data_samples\n samples += subsamples\n self.samples = samples\n\n def _load_single_data(self, data_dir,\n data_name,\n max_len,\n thred):\n\n samples = []\n doc_labels = {}\n id_to_name = {}\n data_path = os.path.join(\n data_dir,\n f'{self.split}.t5-small.english.{max_len}.jsonlines')\n with open(data_path, 'r') as f:\n for line in f:\n item = json.loads(line)\n doc_key = item['doc_key']\n doc_id = re.sub(r'_\\d+$', '', doc_key)\n id_to_name[doc_id] = data_name\n if self.train_args.action_type == \"integer\":\n target_sent = self.tokenizer.convert_tokens_to_ids(\n item['target_sentence'])\n elif self.train_args.action_type == \"non_integer\":\n if self.train_args.add_mention_end:\n target_sent = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_mention_end_sentence\"])\n else:\n target_sent = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_sentence\"])\n else:\n raise ValueError(f\"wrong action type \"\n f\"{self.train_args.action_type}\")\n\n if self.train_args.seq2seq_type == 'action' or \\\n self.train_args.seq2seq_type == 'input_feed':\n if self.train_args.action_type == 'integer':\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item['target_action'])\n elif self.train_args.action_type == 'non_integer':\n if self.train_args.add_mention_end:\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_mention_end_action\"])\n else:\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item[\"target_non_int_action\"])\n else:\n raise ValueError(\"wrong action type (\"\n \"integer/non_integer)\")\n elif self.train_args.seq2seq_type == 'short_seq':\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item['target_short_sentence'])\n elif self.train_args.seq2seq_type == 'full_seq':\n target_seq = deepcopy(target_sent)\n elif self.train_args.seq2seq_type == 'tagging':\n target_seq = self.tokenizer.convert_tokens_to_ids(\n item['target_action'])\n # set the last token as eos token\n target_seq[-1] = self.tokenizer.eos_token_id\n else:\n raise ValueError('wrong seq2seq type')\n sample = {'doc_key': doc_key,\n 'sentence': self.tokenizer.convert_tokens_to_ids(\n item['sentence']),\n 'target_sentence': target_sent,\n 'target_seq': target_seq,\n 'subtoken_map': item['subtoken_map'],\n 'seg_clusters': [[tuple(m) for m in c] for c in item[\n 'seg_clusters'] if len(c) >= thred],\n 'offset': item['offset']\n }\n doc_labels[doc_id] = [[tuple(m) for m in c] for c in item[\n 'gold_clusters']]\n samples.append(sample)\n return samples, doc_labels, id_to_name\n\n def load_dataset(self):\n doc_labels = {}\n id_to_name = {}\n samples = {}\n max_lens = self.data_args.joint_max_train_lens.split(\n ',') if self.split == 'train' else \\\n self.data_args.joint_max_eval_lens.split(',')\n max_lens = [int(l) for l in max_lens]\n threds = self.train_args.joint_min_num_mentions.split(',')\n threds = [int(t) for t in threds]\n data_dirs = self.data_args.joint_data_dirs.split(',')\n data_names = self.train_args.joint_data_names.split(',')\n for data_dir, data_name, max_len, thred in zip(\n data_dirs, data_names, max_lens, threds):\n single_samples, single_doc_labels, single_id_to_name = \\\n self._load_single_data(data_dir, data_name, max_len, thred)\n samples[data_name] = single_samples\n doc_labels.update(single_doc_labels)\n id_to_name.update(single_id_to_name)\n return samples, doc_labels, id_to_name\n\n def __getitem__(self, index):\n sample = self.samples[index]\n input_ids = torch.tensor(sample['sentence'], dtype=torch.long)\n if self.train_args.seq2seq_type == 'action' or \\\n self.train_args.seq2seq_type == 'input_feed':\n label_ids = torch.tensor(sample['target_sentence'],\n dtype=torch.long)\n target_ids = torch.tensor(sample['target_seq'], dtype=torch.long)\n input_len, tgt_len = input_ids.size(0), label_ids.size(0)\n attention_mask = torch.tensor([1] * input_len, dtype=torch.long)\n src_encoding = {'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'decoder_labels': label_ids,\n 'labels': target_ids\n }\n else:\n label_ids = torch.tensor(sample['target_seq'],\n dtype=torch.long)\n input_len, tgt_len = input_ids.size(0), label_ids.size(0)\n attention_mask = torch.tensor([1] * input_len, dtype=torch.long)\n src_encoding = {'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'labels': label_ids,\n }\n return src_encoding" }, { "identifier": "SPEAKER_START", "path": "constants.py", "snippet": "SPEAKER_START = '<speaker>'" }, { "identifier": "SPEAKER_END", "path": "constants.py", "snippet": "SPEAKER_END = '</speaker>'" }, { "identifier": "MENTION_START", "path": "constants.py", "snippet": "MENTION_START = '<m>'" }, { "identifier": "MENTION_END", "path": "constants.py", "snippet": "MENTION_END = '</m>'" }, { "identifier": "COPY", "path": "constants.py", "snippet": "COPY = '<copy>'" }, { "identifier": "CLUSTER_NEW", "path": "constants.py", "snippet": "CLUSTER_NEW = '</new>'" }, { "identifier": "CLUSTERS", "path": "constants.py", "snippet": "CLUSTERS = []" }, { "identifier": "SENTENCE_START", "path": "constants.py", "snippet": "SENTENCE_START = '<sentence>'" }, { "identifier": "SENTENCE_END", "path": "constants.py", "snippet": "SENTENCE_END = '</sentence>'" }, { "identifier": "SPECIAL_IDS", "path": "constants.py", "snippet": "SPECIAL_IDS = {\n 'speaker_start': int_tokenizer.encode(SPEAKER_START,\n add_special_tokens=False)[0],\n 'speaker_end': int_tokenizer.encode(SPEAKER_END, add_special_tokens=False)[\n 0],\n 'mention_start': int_tokenizer.encode(MENTION_START,\n add_special_tokens=False)[0],\n 'mention_end': int_tokenizer.encode(MENTION_END, add_special_tokens=False)[\n 0],\n 'sep': int_tokenizer.encode(SEP_TOKEN, add_special_tokens=False)[0],\n 'copy': int_tokenizer.encode(COPY, add_special_tokens=False)[0],\n 'eos': int_tokenizer.eos_token_id\n}" }, { "identifier": "NON_INT_SPECIAL_IDS", "path": "constants.py", "snippet": "NON_INT_SPECIAL_IDS = {\n 'speaker_start': non_int_tokenizer.encode(\n SPEAKER_START,\n add_special_tokens=False)[0],\n 'speaker_end':\n non_int_tokenizer.encode(\n SPEAKER_END, add_special_tokens=False)[0],\n 'mention_start': non_int_tokenizer.encode(\n MENTION_START,\n add_special_tokens=False)[0],\n 'cluster_ids': MENTION_ENDS_IDS,\n 'cluster_ids_to_num': END_IDS_TO_NUM,\n 'cluster_new': non_int_tokenizer.encode(\n CLUSTER_NEW,\n add_special_tokens=False)[0],\n 'copy': non_int_tokenizer.encode(\n COPY, add_special_tokens=False)[0],\n 'eos': non_int_tokenizer.eos_token_id\n}" }, { "identifier": "MARK_SPECIAL_IDS", "path": "constants.py", "snippet": "MARK_SPECIAL_IDS = deepcopy(SPECIAL_IDS)" }, { "identifier": "MENTION_END_NON_INT_SPECIAL_IDS", "path": "constants.py", "snippet": "MENTION_END_NON_INT_SPECIAL_IDS = {\n 'speaker_start': mention_end_non_int_tokenizer.encode(\n SPEAKER_START,\n add_special_tokens=False)[0],\n 'speaker_end':\n mention_end_non_int_tokenizer.encode(\n SPEAKER_END, add_special_tokens=False)[0],\n 'mention_start': mention_end_non_int_tokenizer.encode(\n MENTION_START,\n add_special_tokens=False)[0],\n 'mention_end': mention_end_non_int_tokenizer.encode(\n MENTION_END,\n add_special_tokens=False)[0],\n 'cluster_ids': CLUSTER_IDS,\n 'cluster_ids_to_num': CLUSTER_IDS_TO_NUM,\n 'cluster_new': mention_end_non_int_tokenizer.encode(\n CLUSTER_NEW,\n add_special_tokens=False)[0],\n 'copy': mention_end_non_int_tokenizer.encode(\n COPY, add_special_tokens=False)[0],\n 'eos': mention_end_non_int_tokenizer.eos_token_id\n}" }, { "identifier": "MENTION_ENDS", "path": "constants.py", "snippet": "MENTION_ENDS = []" }, { "identifier": "CorefTrainer", "path": "trainer.py", "snippet": "class CorefTrainer(Seq2SeqTrainer):\n\n def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None:\n if self.args.save_total_limit is None or self.args.save_total_limit <= 0:\n return\n\n # Check if we should delete older checkpoint(s)\n checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime,\n output_dir=output_dir)\n if self.args.val_after_train and self.args.eval_delay < \\\n self.state.global_step:\n for checkpoint in checkpoints_sorted[:-1]:\n states_dir = [str(x) for x in Path(\n checkpoint).glob(f'global_step*') if os.path.isdir(x)]\n for state_dir in states_dir:\n logger.info(f\"Deleting optimizer states of saved \"\n f\"checkpoint {checkpoint}\")\n if os.path.exists(state_dir) and os.path.isdir(\n state_dir):\n shutil.rmtree(state_dir)\n else:\n if len(checkpoints_sorted) <= self.args.save_total_limit:\n return\n\n # If save_total_limit=1 with load_best_model_at_end=True, we could end up deleting the last checkpoint, which\n # we don't do to allow resuming.\n save_total_limit = self.args.save_total_limit\n if (\n self.state.best_model_checkpoint is not None\n and self.args.save_total_limit == 1\n and checkpoints_sorted[\n -1] != self.state.best_model_checkpoint\n ):\n save_total_limit = 2\n\n number_of_checkpoints_to_delete = max(0, len(\n checkpoints_sorted) - save_total_limit)\n checkpoints_to_be_deleted = checkpoints_sorted[\n :number_of_checkpoints_to_delete]\n for checkpoint in checkpoints_to_be_deleted:\n logger.info(\n f\"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit\")\n shutil.rmtree(checkpoint)\n\n def _save(self, output_dir: Optional[str] = None, state_dict=None):\n # If we are executing this function, we are the process zero, so we don't check for that.\n output_dir = output_dir if output_dir is not None else self.args.output_dir\n os.makedirs(output_dir, exist_ok=True)\n logger.info(f\"Saving model checkpoint to {output_dir}\")\n # Save a trained model and configuration using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n if not isinstance(self.model, PreTrainedModel) and not hasattr(\n self.model, 'save_pretrained'):\n if state_dict is None:\n state_dict = self.model.state_dict()\n\n if isinstance(unwrap_model(self.model), PreTrainedModel):\n unwrap_model(self.model).save_pretrained(\n output_dir, state_dict=state_dict,\n # safe_serialization=self.args.save_safetensors\n )\n else:\n logger.info(\n \"Trainer.model is not a `PreTrainedModel`, only saving its state dict.\")\n # if self.args.save_safetensors:\n # safetensors.torch.save_file(state_dict,\n # os.path.join(output_dir,\n # SAFE_WEIGHTS_NAME))\n # else:\n torch.save(state_dict, os.path.join(output_dir,\n WEIGHTS_NAME))\n else:\n self.model.save_pretrained(\n output_dir, state_dict=state_dict,\n # safe_serialization=self.args.save_safetensors\n )\n\n if self.tokenizer is not None:\n self.tokenizer.save_pretrained(output_dir)\n\n # Good practice: save your training arguments together with the trained model\n torch.save(self.args, os.path.join(output_dir, TRAINING_ARGS_NAME))\n\n def _inner_training_loop(\n self, batch_size=None, args=None, resume_from_checkpoint=None,\n trial=None, ignore_keys_for_eval=None\n ):\n self._train_batch_size = batch_size\n # Data loader and number of training steps\n train_dataloader = self.get_train_dataloader()\n\n # Setting up training control variables:\n # number of training epochs: num_train_epochs\n # number of training steps per epoch: num_update_steps_per_epoch\n # total number of training steps to execute: max_steps\n total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size\n\n len_dataloader = None\n if has_length(train_dataloader):\n len_dataloader = len(train_dataloader)\n num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps\n num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)\n num_examples = self.num_examples(train_dataloader)\n if args.max_steps > 0:\n max_steps = args.max_steps\n num_train_epochs = args.max_steps // num_update_steps_per_epoch + int(\n args.max_steps % num_update_steps_per_epoch > 0\n )\n # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's\n # the best we can do.\n num_train_samples = args.max_steps * total_train_batch_size\n else:\n max_steps = math.ceil(\n args.num_train_epochs * num_update_steps_per_epoch)\n num_train_epochs = math.ceil(args.num_train_epochs)\n num_train_samples = self.num_examples(\n train_dataloader) * args.num_train_epochs\n elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size\n max_steps = args.max_steps\n # Setting a very large number of epochs so we go as many times as necessary over the iterator.\n num_train_epochs = sys.maxsize\n num_update_steps_per_epoch = max_steps\n num_examples = total_train_batch_size * args.max_steps\n num_train_samples = args.max_steps * total_train_batch_size\n else:\n raise ValueError(\n \"args.max_steps must be set to a positive value if dataloader does not have a length, was\"\n f\" {args.max_steps}\"\n )\n\n if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug:\n if self.args.n_gpu > 1:\n # nn.DataParallel(model) replicates the model, creating new variables and module\n # references registered here no longer work on other gpus, breaking the module\n raise ValueError(\n \"Currently --debug underflow_overflow is not supported under DP. Please use DDP\"\n \" (torch.distributed.launch).\"\n )\n else:\n debug_overflow = DebugUnderflowOverflow(self.model) # noqa\n\n delay_optimizer_creation = (\n self.sharded_ddp is not None\n and self.sharded_ddp != ShardedDDPOption.SIMPLE\n or is_sagemaker_mp_enabled()\n or self.fsdp is not None\n )\n if args.deepspeed:\n deepspeed_engine, optimizer, lr_scheduler = deepspeed_init(\n self, num_training_steps=max_steps,\n resume_from_checkpoint=resume_from_checkpoint\n )\n self.model = deepspeed_engine.module\n self.model_wrapped = deepspeed_engine\n self.deepspeed = deepspeed_engine\n self.optimizer = optimizer\n self.lr_scheduler = lr_scheduler\n elif not delay_optimizer_creation:\n self.create_optimizer_and_scheduler(num_training_steps=max_steps)\n\n self.state = TrainerState()\n self.state.is_hyper_param_search = trial is not None\n\n # Activate gradient checkpointing if needed\n if args.gradient_checkpointing:\n self.model.gradient_checkpointing_enable()\n\n model = self._wrap_model(self.model_wrapped)\n\n if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None:\n self._load_from_checkpoint(resume_from_checkpoint, model)\n\n # for the rest of this function `model` is the outside model, whether it was wrapped or not\n if model is not self.model:\n self.model_wrapped = model\n\n if delay_optimizer_creation:\n self.create_optimizer_and_scheduler(num_training_steps=max_steps)\n\n # Check if saved optimizer or scheduler states exist\n self._load_optimizer_and_scheduler(resume_from_checkpoint)\n\n # important: at this point:\n # self.model is the Transformers Model\n # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.\n\n # Train!\n logger.info(\"***** Running training *****\")\n logger.info(f\" Num examples = {num_examples}\")\n logger.info(f\" Num Epochs = {num_train_epochs}\")\n logger.info(\n f\" Instantaneous batch size per device = {args.per_device_train_batch_size}\")\n logger.info(\n f\" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}\")\n logger.info(\n f\" Gradient Accumulation steps = {args.gradient_accumulation_steps}\")\n logger.info(f\" Total optimization steps = {max_steps}\")\n logger.info(\n f\" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}\"\n )\n\n self.state.epoch = 0\n start_time = time.time()\n epochs_trained = 0\n steps_trained_in_current_epoch = 0\n steps_trained_progress_bar = None\n\n # Check if continuing training from a checkpoint\n if resume_from_checkpoint is not None and os.path.isfile(\n os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)\n ):\n self.state = TrainerState.load_from_json(\n os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME))\n epochs_trained = self.state.global_step // num_update_steps_per_epoch\n if not args.ignore_data_skip:\n steps_trained_in_current_epoch = self.state.global_step % (\n num_update_steps_per_epoch)\n steps_trained_in_current_epoch *= args.gradient_accumulation_steps\n else:\n steps_trained_in_current_epoch = 0\n\n logger.info(\n \" Continuing training from checkpoint, will skip to saved global_step\")\n logger.info(f\" Continuing training from epoch {epochs_trained}\")\n logger.info(\n f\" Continuing training from global step {self.state.global_step}\")\n if not args.ignore_data_skip:\n logger.info(\n f\" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} \"\n \"batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` \"\n \"flag to your launch command, but you will resume the training on data already seen by your model.\"\n )\n if self.is_local_process_zero() and not args.disable_tqdm:\n steps_trained_progress_bar = tqdm(\n total=steps_trained_in_current_epoch)\n steps_trained_progress_bar.set_description(\n \"Skipping the first batches\")\n\n # Update the references\n self.callback_handler.model = self.model\n self.callback_handler.optimizer = self.optimizer\n self.callback_handler.lr_scheduler = self.lr_scheduler\n self.callback_handler.train_dataloader = train_dataloader\n if self.hp_name is not None and self._trial is not None:\n # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial\n # parameter to Train when using DDP.\n self.state.trial_name = self.hp_name(self._trial)\n if trial is not None:\n assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial\n self.state.trial_params = hp_params(assignments)\n else:\n self.state.trial_params = None\n # This should be the same if the state has been saved but in case the training arguments changed, it's safer\n # to set this after the load.\n self.state.max_steps = max_steps\n self.state.num_train_epochs = num_train_epochs\n self.state.is_local_process_zero = self.is_local_process_zero()\n self.state.is_world_process_zero = self.is_world_process_zero()\n\n # tr_loss is a tensor to avoid synchronization of TPUs through .item()\n tr_loss = torch.tensor(0.0).to(args.device)\n # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses\n self._total_loss_scalar = 0.0\n self._globalstep_last_logged = self.state.global_step\n model.zero_grad()\n\n self.control = self.callback_handler.on_train_begin(args, self.state,\n self.control)\n\n # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.\n if not args.ignore_data_skip:\n for epoch in range(epochs_trained):\n is_random_sampler = hasattr(train_dataloader,\n \"sampler\") and isinstance(\n train_dataloader.sampler, RandomSampler\n )\n if is_torch_less_than_1_11 or not is_random_sampler:\n # We just need to begin an iteration to create the randomization of the sampler.\n # That was before PyTorch 1.11 however...\n if self.args.joint_train:\n train_dataloader.dataset.set_samples(epoch)\n for _ in train_dataloader:\n break\n else:\n # Otherwise we need to call the whooooole sampler cause there is some random operation added\n # AT THE VERY END!\n _ = list(train_dataloader.sampler)\n if args.manual_empty_cache:\n torch.cuda.empty_cache()\n for epoch in range(epochs_trained, num_train_epochs):\n if self.args.joint_train:\n train_dataloader.dataset.set_samples(epoch)\n if isinstance(train_dataloader, DataLoader) and isinstance(\n train_dataloader.sampler, DistributedSampler):\n train_dataloader.sampler.set_epoch(epoch)\n elif hasattr(train_dataloader, \"dataset\") and isinstance(\n train_dataloader.dataset, IterableDatasetShard):\n train_dataloader.dataset.set_epoch(epoch)\n\n if is_torch_tpu_available():\n parallel_loader = pl.ParallelLoader(train_dataloader, [\n args.device]).per_device_loader(args.device)\n epoch_iterator = parallel_loader\n else:\n epoch_iterator = train_dataloader\n\n # Reset the past mems state at the beginning of each epoch if necessary.\n if args.past_index >= 0:\n self._past = None\n\n steps_in_epoch = (\n len(epoch_iterator)\n if len_dataloader is not None\n else args.max_steps * args.gradient_accumulation_steps\n )\n self.control = self.callback_handler.on_epoch_begin(args,\n self.state,\n self.control)\n\n if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0:\n self._load_rng_state(resume_from_checkpoint)\n\n step = -1\n if args.manual_empty_cache:\n torch.cuda.empty_cache()\n for step, inputs in enumerate(epoch_iterator):\n\n # Skip past any already trained steps if resuming training\n if args.manual_empty_cache:\n torch.cuda.empty_cache()\n if steps_trained_in_current_epoch > 0:\n steps_trained_in_current_epoch -= 1\n if steps_trained_progress_bar is not None:\n steps_trained_progress_bar.update(1)\n if steps_trained_in_current_epoch == 0:\n self._load_rng_state(resume_from_checkpoint)\n continue\n elif steps_trained_progress_bar is not None:\n steps_trained_progress_bar.close()\n steps_trained_progress_bar = None\n\n if step % args.gradient_accumulation_steps == 0:\n self.control = self.callback_handler.on_step_begin(args,\n self.state,\n self.control)\n # if args.manual_empty_cache:\n # torch.cuda.empty_cache()\n if (\n ((step + 1) % args.gradient_accumulation_steps != 0)\n and args.local_rank != -1\n and args._no_sync_in_gradient_accumulation\n ):\n # Avoid unnecessary DDP synchronization since there will be no backward pass on this example.\n with model.no_sync():\n tr_loss_step = self.training_step(model, inputs)\n else:\n tr_loss_step = self.training_step(model, inputs)\n\n if (\n args.logging_nan_inf_filter\n and not is_torch_tpu_available()\n and (\n torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step))\n ):\n # if loss is nan or inf simply add the average of previous logged losses\n tr_loss += tr_loss / (\n 1 + self.state.global_step - self._globalstep_last_logged)\n else:\n tr_loss += tr_loss_step\n\n self.current_flos += float(self.floating_point_ops(inputs))\n\n # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps\n if self.deepspeed:\n if args.manual_empty_cache:\n torch.cuda.empty_cache()\n self.deepspeed.step()\n\n if (step + 1) % args.gradient_accumulation_steps == 0 or (\n # last step in epoch but step is always smaller than gradient_accumulation_steps\n steps_in_epoch <= args.gradient_accumulation_steps\n and (step + 1) == steps_in_epoch\n ):\n # Gradient clipping\n if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed:\n # deepspeed does its own clipping\n\n if self.do_grad_scaling:\n # Reduce gradients first for XLA\n if is_torch_tpu_available():\n gradients = xm._fetch_gradients(self.optimizer)\n xm.all_reduce(\"sum\", gradients,\n scale=1.0 / xm.xrt_world_size())\n # AMP: gradients need unscaling\n self.scaler.unscale_(self.optimizer)\n\n if is_sagemaker_mp_enabled() and args.fp16:\n self.optimizer.clip_master_grads(args.max_grad_norm)\n elif hasattr(self.optimizer, \"clip_grad_norm\"):\n # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping\n self.optimizer.clip_grad_norm(args.max_grad_norm)\n elif hasattr(model, \"clip_grad_norm_\"):\n # Some models (like FullyShardedDDP) have a specific way to do gradient clipping\n model.clip_grad_norm_(args.max_grad_norm)\n else:\n # Revert to normal clipping otherwise, handling Apex or full precision\n nn.utils.clip_grad_norm_(\n amp.master_params(\n self.optimizer) if self.use_apex else model.parameters(),\n args.max_grad_norm,\n )\n\n # Optimizer step\n optimizer_was_run = True\n if self.deepspeed:\n pass # called outside the loop\n elif is_torch_tpu_available():\n if self.do_grad_scaling:\n self.scaler.step(self.optimizer)\n self.scaler.update()\n else:\n xm.optimizer_step(self.optimizer)\n elif self.do_grad_scaling:\n scale_before = self.scaler.get_scale()\n self.scaler.step(self.optimizer)\n self.scaler.update()\n scale_after = self.scaler.get_scale()\n optimizer_was_run = scale_before <= scale_after\n else:\n self.optimizer.step()\n\n if optimizer_was_run and not self.deepspeed:\n self.lr_scheduler.step()\n\n model.zero_grad()\n self.state.global_step += 1\n self.state.epoch = epoch + (step + 1) / steps_in_epoch\n if args.manual_empty_cache:\n torch.cuda.empty_cache()\n self.control = self.callback_handler.on_step_end(args,\n self.state,\n self.control)\n\n self._maybe_log_save_evaluate(tr_loss, model, trial, epoch,\n ignore_keys_for_eval)\n else:\n self.control = self.callback_handler.on_substep_end(args,\n self.state,\n self.control)\n\n if self.control.should_epoch_stop or self.control.should_training_stop:\n break\n if step < 0:\n logger.warning(\n \"There seems to be not a single sample in your epoch_iterator, stopping training at step\"\n f\" {self.state.global_step}! This is expected if you're using an IterableDataset and set\"\n f\" num_steps ({max_steps}) higher than the number of available samples.\"\n )\n self.control.should_training_stop = True\n\n self.control = self.callback_handler.on_epoch_end(args, self.state,\n self.control)\n self._maybe_log_save_evaluate(tr_loss, model, trial, epoch,\n ignore_keys_for_eval)\n\n if DebugOption.TPU_METRICS_DEBUG in self.args.debug:\n if is_torch_tpu_available():\n # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)\n xm.master_print(met.metrics_report())\n else:\n logger.warning(\n \"You enabled PyTorch/XLA debug metrics but you don't have a TPU \"\n \"configured. Check your training configuration if this is unexpected.\"\n )\n if self.control.should_training_stop:\n break\n\n if args.past_index and hasattr(self, \"_past\"):\n # Clean the state at the end of training\n delattr(self, \"_past\")\n\n logger.info(\n \"\\n\\nTraining completed. Do not forget to share your model on huggingface.co/models =)\\n\\n\")\n if args.load_best_model_at_end and self.state.best_model_checkpoint is not None:\n # Wait for everyone to get here so we are sur the model has been saved by process 0.\n if is_torch_tpu_available():\n xm.rendezvous(\"load_best_model_at_end\")\n elif args.local_rank != -1:\n dist.barrier()\n elif is_sagemaker_mp_enabled():\n smp.barrier()\n\n self._load_best_model()\n\n # add remaining tr_loss\n self._total_loss_scalar += tr_loss.item()\n train_loss = self._total_loss_scalar / self.state.global_step\n\n metrics = speed_metrics(\"train\", start_time,\n num_samples=num_train_samples,\n num_steps=self.state.max_steps)\n self.store_flos()\n metrics[\"total_flos\"] = self.state.total_flos\n metrics[\"train_loss\"] = train_loss\n\n self.is_in_train = False\n\n self._memory_tracker.stop_and_update_metrics(metrics)\n\n self.log(metrics)\n\n run_dir = self._get_output_dir(trial)\n checkpoints_sorted = self._sorted_checkpoints(use_mtime=False,\n output_dir=run_dir)\n\n # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint.\n if self.state.best_model_checkpoint is not None and \\\n self.args.save_total_limit == 1 and self.is_world_process_zero():\n for checkpoint in checkpoints_sorted:\n if checkpoint != self.state.best_model_checkpoint:\n logger.info(\n f\"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit\")\n shutil.rmtree(checkpoint)\n\n self.control = self.callback_handler.on_train_end(args, self.state,\n self.control)\n\n return TrainOutput(self.state.global_step, train_loss, metrics)\n\n def my_compute_metrics(self,\n doc_labels: Dict[str, List[List]],\n predicts: Any,\n samples: List,\n split: str,\n id_to_name: Dict = None\n ) -> Dict:\n if self.args.joint_train:\n data_names = self.args.joint_data_names.split(',')\n joint_threds = [\n int(t) for t in self.args.joint_min_num_mentions.split(',')]\n name_to_threds = {n: t for n, t in zip(data_names, joint_threds)}\n documents_to_chunk_data = defaultdict(list)\n documents_to_chunk_gold = defaultdict(list)\n predictions = {}\n golds = {}\n assert len(samples) == len(predicts)\n out_sents = []\n last_doc_id = re.sub(r'_\\d+$', '', samples[0]['doc_key'])\n for sample, predict in zip(samples, predicts):\n doc_key = sample['doc_key']\n doc_id = re.sub(r'_\\d+$', '', doc_key)\n # require convert to ids first\n input_ids = sample['sentence']\n subtoken_map = sample['subtoken_map']\n offset = sample['offset']\n # remove bos\n predict_ids = predict[1:].tolist()\n gold_data = sample['seg_clusters']\n if self.args.joint_train:\n thred = name_to_threds[id_to_name[doc_id]]\n else:\n thred = self.args.min_num_mentions\n if self.args.seq2seq_type == \"short_seq\":\n special_ids = MARK_SPECIAL_IDS if self.args.mark_sentence \\\n else SPECIAL_IDS\n pred_data, aligned_input_ids, aligned_pred_ids = \\\n parse_short_target_tokens(input_ids, predict_ids,\n special_ids, subtoken_map,\n self.tokenizer,\n self.args.align_mode,\n thred,\n self.args.mark_sentence\n )\n pred_tokens = self.tokenizer.convert_ids_to_tokens(\n predict_ids)\n out_predict = {\n 'doc_key': doc_key,\n 'pred_tokens': pred_tokens,\n 'pred_text': self.tokenizer.convert_tokens_to_string(\n pred_tokens),\n 'pred_aligned_text': self.tokenizer.convert_ids_to_tokens(\n aligned_pred_ids\n ),\n 'input_aligned_text': self.tokenizer.convert_ids_to_tokens(\n aligned_input_ids\n )\n }\n else:\n is_tagging = (self.args.seq2seq_type == 'tagging')\n if self.args.action_type == 'integer':\n pred_data, pred_token_mentions, predict_ids = \\\n parse_int_output_tokens(\n input_ids,\n predict_ids,\n SPECIAL_IDS,\n subtoken_map,\n self.tokenizer,\n thred, is_tagging)\n else:\n special_ids = MENTION_END_NON_INT_SPECIAL_IDS if \\\n self.args.add_mention_end else NON_INT_SPECIAL_IDS\n pred_data, pred_token_mentions, predict_ids = \\\n parse_nonint_output_tokens(\n input_ids,\n predict_ids,\n special_ids,\n subtoken_map,\n self.tokenizer, self.args.add_mention_end,\n thred)\n pred_token_mentions = [(m[0] + offset, m[1] + offset) for m in\n pred_token_mentions]\n pred_tokens = self.tokenizer.convert_ids_to_tokens(\n predict_ids)\n out_predict = {'doc_key': doc_key,\n 'pred_tokens': pred_tokens,\n 'pred_text':\n self.tokenizer.convert_tokens_to_string(\n pred_tokens),\n 'predict_clusters': pred_data,\n 'gold_clusters': gold_data,\n 'predict_token_mentions': pred_token_mentions\n }\n # list of (m1,m2)\n\n documents_to_chunk_data[doc_id].extend(pred_data)\n documents_to_chunk_gold[doc_id].extend(gold_data)\n\n out_sents.append(out_predict)\n if doc_id != last_doc_id:\n predictions[last_doc_id] = get_document_predicts(\n documents_to_chunk_data[\n last_doc_id])\n golds[last_doc_id] = get_document_predicts(\n documents_to_chunk_gold[\n last_doc_id])\n last_doc_id = doc_id\n # final one\n predictions[last_doc_id] = get_document_predicts(\n documents_to_chunk_data[last_doc_id]\n )\n golds[last_doc_id] = get_document_predicts(\n documents_to_chunk_gold[last_doc_id]\n )\n # print(predictions)\n if self.args.joint_train:\n predictions_list = defaultdict(list)\n labels_list = defaultdict(list)\n golds_list = defaultdict(list)\n else:\n predictions_list = []\n labels_list = []\n golds_list = []\n for document_id, doc_label in doc_labels.items():\n if self.args.joint_train:\n predictions_list[id_to_name[document_id]].append(\n predictions[document_id])\n labels_list[id_to_name[document_id]].append(doc_label)\n golds_list[id_to_name[document_id]].append(golds[document_id])\n else:\n predictions_list.append(predictions[document_id])\n labels_list.append(doc_label)\n golds_list.append(golds[document_id])\n if self.args.joint_train:\n label_results = {}\n gold_results = {}\n for dn in predictions_list.keys():\n metrics = CorefAllMetrics().get_all_metrics(\n labels_list[dn],\n predictions_list[dn])\n metrics_golds = CorefAllMetrics().get_all_metrics(\n golds_list[dn],\n predictions_list[dn])\n single_label_results = {\n f'{dn}_{metric_name}_{x}': v\n for metric_name, metric_values in metrics['micro'].items()\n for x, v in metric_values.items()\n }\n single_gold_results = {\n f'{dn}_gold_{metric_name}_{x}': v\n for metric_name, metric_values in\n metrics_golds['micro'].items()\n for x, v in metric_values.items()\n }\n label_results.update(single_label_results)\n gold_results.update(single_gold_results)\n\n else:\n metrics = CorefAllMetrics().get_all_metrics(labels_list,\n predictions_list)\n metrics_golds = CorefAllMetrics().get_all_metrics(golds_list,\n predictions_list)\n label_results = {\n f'{metric_name}_{x}': v\n for metric_name, metric_values in metrics['micro'].items()\n for x, v in metric_values.items()\n }\n gold_results = {\n f'gold_{metric_name}_{x}': v\n for metric_name, metric_values in metrics_golds['micro'].items()\n for x, v in metric_values.items()\n }\n results = {**label_results, **gold_results}\n if self.args.joint_train:\n avg_f1s = [results[f\"{dname}_average_f1\"] for dname in\n data_names]\n results[\"average_f1\"] = sum(avg_f1s) / len(avg_f1s)\n if self.is_world_process_zero() and self.args.save_predicts:\n os.makedirs(self.args.save_dir, exist_ok=True)\n save_path = os.path.join(self.args.save_dir,\n f'{split}-predicts.txt')\n results_path = os.path.join(self.args.save_dir,\n f'{split}-results.json')\n with open(save_path, 'w') as f:\n for p in out_sents:\n f.write('%s\\n' % json.dumps(p))\n with open(results_path, 'w') as f:\n json.dump(results, f)\n\n return results\n\n def evaluation_loop(\n self,\n dataloader: DataLoader,\n description: str,\n prediction_loss_only: Optional[bool] = False,\n ignore_keys: Optional[List[str]] = None,\n metric_key_prefix: str = \"eval\",\n ) -> EvalLoopOutput:\n \"\"\"\n Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.\n Works both with or without labels.\n \"\"\"\n args = self.args\n\n prediction_loss_only = False\n\n # if eval is called w/o train init deepspeed here\n if args.deepspeed and not self.deepspeed:\n # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval\n # from the checkpoint eventually\n deepspeed_engine, _, _ = deepspeed_init(\n self, num_training_steps=0, resume_from_checkpoint=None,\n inference=is_deepspeed_zero3_enabled()\n )\n self.model = deepspeed_engine.module\n self.model_wrapped = deepspeed_engine\n self.deepspeed = deepspeed_engine\n if self.args.gradient_checkpointing:\n self.model.config.use_cache = True\n model = self._wrap_model(self.model, training=False,\n dataloader=dataloader)\n\n # if full fp16 or bf16 eval is wanted and this ``evaluation`` or ``predict`` isn't called\n # while ``train`` is running, cast it to the right dtype first and then put on device\n if not self.is_in_train:\n if args.fp16_full_eval:\n model = model.to(dtype=torch.float16, device=args.device)\n elif args.bf16_full_eval:\n model = model.to(dtype=torch.bfloat16, device=args.device)\n\n batch_size = self.args.eval_batch_size\n\n logger.info(f\"***** Running {description} *****\")\n if has_length(dataloader):\n logger.info(f\" Num examples = {self.num_examples(dataloader)}\")\n else:\n logger.info(\" Num examples: Unknown\")\n logger.info(f\" Batch size = {batch_size}\")\n\n model.eval()\n\n self.callback_handler.eval_dataloader = dataloader\n # Do this before wrapping.\n eval_dataset = getattr(dataloader, \"dataset\", None)\n\n if is_torch_tpu_available():\n dataloader = pl.ParallelLoader(dataloader,\n [args.device]).per_device_loader(\n args.device)\n\n if args.past_index >= 0:\n self._past = None\n\n # Initialize containers\n # losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps)\n losses_host = None\n preds_host = None\n labels_host = None\n inputs_host = None\n\n # losses/preds/labels on CPU (final containers)\n all_losses = None\n all_preds = None\n all_labels = None\n all_inputs = None\n # Will be useful when we have an iterable dataset so don't know its length.\n\n observed_num_examples = 0\n # Main evaluation loop\n for step, inputs in enumerate(dataloader):\n # Update the observed num examples\n observed_batch_size = find_batch_size(inputs)\n if observed_batch_size is not None:\n observed_num_examples += observed_batch_size\n # For batch samplers, batch_size is not known by the dataloader in advance.\n if batch_size is None:\n batch_size = observed_batch_size\n\n # Prediction step\n loss, logits, labels = self.prediction_step(model, inputs,\n prediction_loss_only,\n ignore_keys=ignore_keys)\n inputs_decode = self._prepare_input(inputs[\n \"input_ids\"]) if args.include_inputs_for_metrics else None\n\n if is_torch_tpu_available():\n xm.mark_step()\n\n # Update containers on host\n if loss is not None:\n losses = self._nested_gather(loss.repeat(batch_size))\n losses_host = losses if losses_host is None else torch.cat(\n (losses_host, losses), dim=0)\n if labels is not None:\n labels = self._pad_across_processes(labels)\n labels = self._nested_gather(labels)\n labels_host = labels if labels_host is None else nested_concat(\n labels_host, labels, padding_index=-100)\n if inputs_decode is not None:\n inputs_decode = self._pad_across_processes(inputs_decode)\n inputs_decode = self._nested_gather(inputs_decode)\n inputs_host = (\n inputs_decode\n if inputs_host is None\n else nested_concat(inputs_host, inputs_decode,\n padding_index=-100)\n )\n if logits is not None:\n logits = self._pad_across_processes(logits)\n logits = self._nested_gather(logits)\n if self.preprocess_logits_for_metrics is not None:\n logits = self.preprocess_logits_for_metrics(logits, labels)\n preds_host = logits if preds_host is None else nested_concat(\n preds_host, logits, padding_index=-100)\n self.control = self.callback_handler.on_prediction_step(args,\n self.state,\n self.control)\n\n # Gather all tensors and put them back on the CPU if we have done enough accumulation steps.\n if args.eval_accumulation_steps is not None and (\n step + 1) % args.eval_accumulation_steps == 0:\n if losses_host is not None:\n losses = nested_numpify(losses_host)\n all_losses = losses if all_losses is None else np.concatenate(\n (all_losses, losses), axis=0)\n if preds_host is not None:\n logits = nested_numpify(preds_host)\n all_preds = logits if all_preds is None else nested_concat(\n all_preds, logits, padding_index=-100)\n if inputs_host is not None:\n inputs_decode = nested_numpify(inputs_host)\n all_inputs = (\n inputs_decode\n if all_inputs is None\n else nested_concat(all_inputs, inputs_decode,\n padding_index=-100)\n )\n if labels_host is not None:\n labels = nested_numpify(labels_host)\n all_labels = (\n labels if all_labels is None else nested_concat(\n all_labels, labels, padding_index=-100)\n )\n\n # Set back to None to begin a new accumulation\n losses_host, preds_host, inputs_host, labels_host = None, None, None, None\n\n if args.past_index and hasattr(self, \"_past\"):\n # Clean the state at the end of the evaluation loop\n delattr(self, \"_past\")\n\n # Gather all remaining tensors and put them back on the CPU\n if losses_host is not None:\n losses = nested_numpify(losses_host)\n all_losses = losses if all_losses is None else np.concatenate(\n (all_losses, losses), axis=0)\n if preds_host is not None:\n logits = nested_numpify(preds_host)\n all_preds = logits if all_preds is None else nested_concat(\n all_preds, logits, padding_index=-100)\n if inputs_host is not None:\n inputs_decode = nested_numpify(inputs_host)\n all_inputs = (\n inputs_decode if all_inputs is None else nested_concat(\n all_inputs, inputs_decode, padding_index=-100)\n )\n if labels_host is not None:\n labels = nested_numpify(labels_host)\n all_labels = labels if all_labels is None else nested_concat(\n all_labels, labels, padding_index=-100)\n\n # Number of samples\n if has_length(eval_dataset):\n num_samples = len(eval_dataset)\n # The instance check is weird and does not actually check for the type, but whether the dataset has the right\n # methods. Therefore we need to make sure it also has the attribute.\n elif isinstance(eval_dataset, IterableDatasetShard) and getattr(\n eval_dataset, \"num_examples\", 0) > 0:\n num_samples = eval_dataset.num_examples\n else:\n if has_length(dataloader):\n num_samples = self.num_examples(dataloader)\n else: # both len(dataloader.dataset) and len(dataloader) fail\n num_samples = observed_num_examples\n if num_samples == 0 and observed_num_examples > 0:\n num_samples = observed_num_examples\n\n # Number of losses has been rounded to a multiple of batch_size and in a distributed training, the number of\n # samplers has been rounded to a multiple of batch_size, so we truncate.\n if all_losses is not None:\n all_losses = all_losses[:num_samples]\n if all_preds is not None:\n all_preds = nested_truncate(all_preds, num_samples)\n if all_labels is not None:\n all_labels = nested_truncate(all_labels, num_samples)\n if all_inputs is not None:\n all_inputs = nested_truncate(all_inputs, num_samples)\n\n # Metrics!\n doc_labels = eval_dataset.doc_labels\n eval_samples = eval_dataset.samples\n split = eval_dataset.split\n if self.args.joint_train:\n doc_id_to_name = eval_dataset.id_to_name\n else:\n doc_id_to_name = None\n # allow_singletons = eval_dataset.data_args.allow_singletons\n assert all_preds is not None\n metrics = self.my_compute_metrics(doc_labels, all_preds,\n eval_samples, split,\n doc_id_to_name)\n # if all_preds is not None and doc_labels is not None:\n # metrics = self.get_eval_metrics(doc_labels, all_preds,\n # eval_samples, split)\n # else:\n # metrics = {}\n\n # To be JSON-serializable, we need to remove numpy types or zero-d tensors\n metrics = denumpify_detensorize(metrics)\n\n if all_losses is not None:\n metrics[f\"{metric_key_prefix}_loss\"] = all_losses.mean().item()\n\n # Prefix all keys with metric_key_prefix + '_'\n for key in list(metrics.keys()):\n if not key.startswith(f\"{metric_key_prefix}_\"):\n metrics[f\"{metric_key_prefix}_{key}\"] = metrics.pop(key)\n if self.args.gradient_checkpointing:\n self.model.config.use_cache = False\n return EvalLoopOutput(predictions=all_preds, label_ids=all_labels,\n metrics=metrics, num_samples=num_samples)\n\n def prediction_step(\n self,\n model: nn.Module,\n inputs: Dict[str, Union[torch.Tensor, Any]],\n prediction_loss_only: bool,\n ignore_keys: Optional[List[str]] = None,\n ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:\n \"\"\"\n Perform an evaluation step on `model` using `inputs`.\n\n Subclass and override to inject custom behavior.\n\n Args:\n model (`nn.Module`):\n The model to evaluate.\n inputs (`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n The dictionary will be unpacked before being fed to the model. Most models expect the targets under the\n argument `labels`. Check your model's documentation for all accepted arguments.\n prediction_loss_only (`bool`):\n Whether or not to return the loss only.\n ignore_keys:\n list of ignore keys\n\n Return:\n Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and\n labels (each being optional).\n \"\"\"\n\n if not self.args.predict_with_generate or prediction_loss_only:\n return super().prediction_step(\n model, inputs, prediction_loss_only=prediction_loss_only,\n ignore_keys=ignore_keys\n )\n\n has_labels = \"labels\" in inputs\n inputs = self._prepare_inputs(inputs)\n\n # XXX: adapt synced_gpus for fairscale as well\n gen_kwargs = self._gen_kwargs.copy()\n gen_kwargs[\"max_length\"] = (\n gen_kwargs[\"max_length\"] if gen_kwargs.get(\n \"max_length\") is not None else self.model.config.max_length\n )\n gen_kwargs[\"num_beams\"] = (\n gen_kwargs[\"num_beams\"] if gen_kwargs.get(\n \"num_beams\") is not None else self.model.config.num_beams\n )\n default_synced_gpus = True if is_deepspeed_zero3_enabled() else False\n gen_kwargs[\"synced_gpus\"] = (\n gen_kwargs[\"synced_gpus\"] if gen_kwargs.get(\n \"synced_gpus\") is not None else default_synced_gpus\n )\n\n if \"attention_mask\" in inputs:\n gen_kwargs[\"attention_mask\"] = inputs.get(\"attention_mask\", None)\n if \"global_attention_mask\" in inputs:\n gen_kwargs[\"global_attention_mask\"] = inputs.get(\n \"global_attention_mask\", None)\n\n # prepare generation inputs\n # some encoder-decoder models can have varying encoder's and thus\n # varying model input names\n if hasattr(self.model,\n \"encoder\") and self.model.encoder.main_input_name != self.model.main_input_name:\n generation_inputs = inputs[self.model.encoder.main_input_name]\n else:\n generation_inputs = inputs[self.model.main_input_name]\n # add our logits_processor here\n if self.args.seq2seq_type != 'short_seq':\n if self.args.action_type == 'non_integer':\n special_ids = MENTION_END_NON_INT_SPECIAL_IDS if \\\n self.args.add_mention_end else NON_INT_SPECIAL_IDS\n gen_kwargs['logits_processor'] = LogitsProcessorList(\n [NonIntProcessor(generation_inputs, special_ids,\n self.args.seq2seq_type,\n self.args.add_mention_end)])\n else:\n gen_kwargs['logits_processor'] = LogitsProcessorList(\n [IntProcessor(generation_inputs, SPECIAL_IDS,\n self.args.seq2seq_type)])\n elif self.args.mark_sentence:\n gen_kwargs['logits_processor'] = LogitsProcessorList(\n [ShortSeqProcessor(generation_inputs, MARK_SPECIAL_IDS)])\n # if self.args.use_peft:\n # gen_kwargs[\"input_ids\"] = generation_inputs\n # gen_kwargs[\"use_cache\"] = True\n # generated_tokens = self.model.generate(\n # **gen_kwargs,\n # )\n # else:\n generated_tokens = self.model.generate(\n generation_inputs,\n **gen_kwargs,\n )\n # in case the batch is shorter than max length, the output should be padded\n if generated_tokens.shape[-1] < gen_kwargs[\"max_length\"]:\n generated_tokens = self._pad_tensors_to_max_len(generated_tokens,\n gen_kwargs[\n \"max_length\"])\n\n with torch.no_grad():\n with self.compute_loss_context_manager():\n outputs = model(**inputs)\n if has_labels:\n if self.label_smoother is not None:\n loss = self.label_smoother(outputs,\n inputs[\"labels\"]).mean().detach()\n else:\n loss = (outputs[\"loss\"] if isinstance(outputs, dict) else\n outputs[0]).mean().detach()\n else:\n loss = None\n\n if self.args.prediction_loss_only:\n return (loss, None, None)\n\n if has_labels:\n labels = inputs[\"labels\"]\n if labels.shape[-1] < gen_kwargs[\"max_length\"]:\n labels = self._pad_tensors_to_max_len(labels,\n gen_kwargs[\"max_length\"])\n else:\n labels = None\n\n return (loss, generated_tokens, labels)" }, { "identifier": "ConstrainedDataCollator", "path": "data.py", "snippet": "class ConstrainedDataCollator:\n \"\"\"\n Data collator that will dynamically pad the inputs received, as well as the labels.\n\n Args:\n tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):\n The tokenizer used for encoding the data.\n model ([`PreTrainedModel`]):\n The model that is being trained. If set and has the *prepare_decoder_input_ids_from_labels*, use it to\n prepare the *decoder_input_ids*\n\n This is useful when using *label_smoothing* to avoid calculating loss twice.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):\n Select a strategy to pad the returned sequences (according to the model's padding side and padding index)\n among:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n is provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n max_length (`int`, *optional*):\n Maximum length of the returned list and optionally padding length (see above).\n pad_to_multiple_of (`int`, *optional*):\n If set will pad the sequence to a multiple of the provided value.\n\n This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=\n 7.5 (Volta).\n label_pad_token_id (`int`, *optional*, defaults to -100):\n The id to use when padding the labels (-100 will be automatically ignored by PyTorch loss functions).\n return_tensors (`str`):\n The type of Tensor to return. Allowable values are \"np\", \"pt\" and \"tf\".\n \"\"\"\n\n tokenizer: PreTrainedTokenizerBase\n model: Optional[Any] = None\n padding: Union[bool, str, PaddingStrategy] = True\n max_length: Optional[int] = None\n pad_to_multiple_of: Optional[int] = None\n label_pad_token_id: int = -100\n return_tensors: str = \"pt\"\n\n def __call__(self, features, return_tensors=None):\n import numpy as np\n\n if return_tensors is None:\n return_tensors = self.return_tensors\n labels = [feature[\"labels\"] for\n feature in features] if \"labels\" in features[\n 0].keys() else None\n decoder_labels = [feature[\"decoder_labels\"] for\n feature in features] if \"decoder_labels\" in features[\n 0].keys() else None\n # We have to pad the labels before calling `tokenizer.pad` as this method won't pad them and needs them of the\n # same length to return tensors.\n if labels is not None:\n assert decoder_labels is not None\n max_label_length = max(len(l) for l in labels)\n if self.pad_to_multiple_of is not None:\n max_label_length = (\n (max_label_length + self.pad_to_multiple_of - 1)\n // self.pad_to_multiple_of\n * self.pad_to_multiple_of\n )\n\n padding_side = self.tokenizer.padding_side\n for feature in features:\n remainder = [self.label_pad_token_id] * (\n max_label_length - len(feature[\"labels\"]))\n if isinstance(feature[\"labels\"], list):\n feature[\"labels\"] = (\n feature[\n \"labels\"] + remainder if padding_side == \"right\"\n else remainder + feature[\"labels\"]\n )\n feature[\"decoder_labels\"] = (\n feature[\n \"decoder_labels\"] + remainder if padding_side ==\n \"right\"\n else remainder + feature[\"decoder_labels\"]\n )\n elif padding_side == \"right\":\n feature[\"labels\"] = np.concatenate(\n [feature[\"labels\"], remainder]).astype(np.int64)\n feature[\"decoder_labels\"] = np.concatenate(\n [feature[\"decoder_labels\"], remainder]).astype(np.int64)\n else:\n feature[\"labels\"] = np.concatenate(\n [remainder, feature[\"labels\"]]).astype(np.int64)\n feature[\"decoder_labels\"] = np.concatenate(\n [remainder, feature[\"decoder_labels\"]]).astype(np.int64)\n\n features = self.tokenizer.pad(\n features,\n padding=self.padding,\n max_length=self.max_length,\n pad_to_multiple_of=self.pad_to_multiple_of,\n return_tensors=return_tensors,\n )\n\n # prepare decoder_input_ids\n if (\n labels is not None\n and self.model is not None\n and hasattr(self.model, \"prepare_decoder_input_ids_from_labels\")\n ):\n decoder_input_ids = self.model.prepare_decoder_input_ids_from_labels(\n labels=features[\"decoder_labels\"])\n features[\"decoder_input_ids\"] = decoder_input_ids\n if self.model.is_input_feed:\n decoder_input_actions = \\\n self.model.prepare_decoder_input_ids_from_labels(\n labels=features[\"labels\"])\n features[\"decoder_input_actions\"] = decoder_input_actions\n del features[\"decoder_labels\"]\n return features" }, { "identifier": "ConstrainedT5", "path": "model.py", "snippet": "class ConstrainedT5(T5ForConditionalGeneration):\n\n def __init__(self, config: T5Config, special_ids: Dict,\n seq2seq_type: str, action_type: str,\n add_mention_end: bool):\n super().__init__(config)\n self.mention_start = special_ids['mention_start']\n self.mention_end = special_ids.get('mention_end',None)\n self.eos_id = special_ids['eos']\n self.action_type = action_type\n self.add_mention_end = add_mention_end\n self.cluster_ids = None\n self.copy_id = special_ids['copy']\n self.seq2seq_type = seq2seq_type\n if action_type == 'integer':\n self.sep = special_ids['sep']\n self.ent_ids = special_ids['integers'] + [\n special_ids['mention_end']]\n self.specials = [self.mention_start, self.sep,\n self.copy_id] + self.ent_ids\n # self.seq2seq_type = seq2seq_type\n else:\n self.cluster_new = special_ids['cluster_new']\n self.cluster_ids = special_ids['cluster_ids']\n self.eos_id = special_ids['eos']\n if self.add_mention_end:\n self.specials = [self.mention_start,\n self.mention_end,\n self.cluster_new,\n self.copy_id] + self.cluster_ids\n else:\n self.specials = [self.mention_start,\n self.cluster_new,\n self.copy_id] + self.cluster_ids\n if self.seq2seq_type == 'tagging':\n self.specials.append(self.eos_id)\n self.is_input_feed = (self.seq2seq_type == \"input_feed\")\n\n @add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Seq2SeqLMOutput,\n config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n decoder_input_ids: Optional[torch.LongTensor] = None,\n decoder_attention_mask: Optional[torch.BoolTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n decoder_head_mask: Optional[torch.FloatTensor] = None,\n cross_attn_head_mask: Optional[torch.Tensor] = None,\n encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n decoder_inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n decoder_input_actions: Optional[torch.LongTensor] = None,\n full_decoder_input_ids: Optional[torch.LongTensor] = None\n ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,\n config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for\n labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n \"\"\"\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask\n if head_mask is not None and decoder_head_mask is None:\n if self.config.num_layers == self.config.num_decoder_layers:\n warnings.warn(HEAD_MASK_WARNING_MSG, FutureWarning)\n decoder_head_mask = head_mask\n\n # Encode if needed (training, first prediction pass)\n if encoder_outputs is None:\n # Convert encoder inputs in embeddings if needed\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n inputs_embeds=inputs_embeds,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):\n encoder_outputs = BaseModelOutput(\n last_hidden_state=encoder_outputs[0],\n hidden_states=encoder_outputs[1] if len(\n encoder_outputs) > 1 else None,\n attentions=encoder_outputs[2] if len(\n encoder_outputs) > 2 else None,\n )\n\n hidden_states = encoder_outputs[0]\n\n if self.model_parallel:\n torch.cuda.set_device(self.decoder.first_device)\n\n if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:\n # get decoder inputs from shifting lm labels to the right\n decoder_input_ids = self._shift_right(labels)\n # Set device for model parallelism\n if self.is_input_feed and not self.training and decoder_input_actions is None:\n decoder_input_actions = self.input_to_actions(\n full_decoder_input_ids)\n if self.model_parallel:\n torch.cuda.set_device(self.decoder.first_device)\n hidden_states = hidden_states.to(self.decoder.first_device)\n if decoder_input_ids is not None:\n decoder_input_ids = decoder_input_ids.to(\n self.decoder.first_device)\n if attention_mask is not None:\n attention_mask = attention_mask.to(self.decoder.first_device)\n if decoder_attention_mask is not None:\n decoder_attention_mask = decoder_attention_mask.to(\n self.decoder.first_device)\n if self.is_input_feed and decoder_input_actions is \\\n not None:\n decoder_input_actions = decoder_input_actions.to(\n self.decoder.first_device\n )\n if self.is_input_feed:\n decoder_token_embeds = self.decoder.embed_tokens(decoder_input_ids)\n if not self.training and past_key_values is not None:\n decoder_action_embeds = self.decoder.embed_tokens(\n decoder_input_actions[:, -1:])\n else:\n decoder_action_embeds = self.decoder.embed_tokens(\n decoder_input_actions)\n decoder_inputs_embeds = decoder_token_embeds / 2 + decoder_action_embeds / 2\n # Decode\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids if not self.is_input_feed else None,\n attention_mask=decoder_attention_mask,\n inputs_embeds=decoder_inputs_embeds,\n past_key_values=past_key_values,\n encoder_hidden_states=hidden_states,\n encoder_attention_mask=attention_mask,\n head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = decoder_outputs[0]\n\n # Set device for model parallelism\n if self.model_parallel:\n torch.cuda.set_device(self.encoder.first_device)\n self.lm_head = self.lm_head.to(self.encoder.first_device)\n sequence_output = sequence_output.to(self.lm_head.weight.device)\n\n if self.config.tie_word_embeddings:\n # Rescale output before projecting on vocab\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586\n sequence_output = sequence_output * (self.model_dim ** -0.5)\n\n lm_logits = self.lm_head(sequence_output)\n masks = torch.ones_like(lm_logits,\n dtype=torch.bool)\n masks[:, :, self.specials] = False\n lm_logits.masked_fill_(masks, -float('inf'))\n\n loss = None\n if labels is not None:\n # construct constrained mask here\n\n loss_fct = CrossEntropyLoss(ignore_index=-100)\n loss = loss_fct(lm_logits.view(-1, lm_logits.size(\n -1)), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs\n return ((loss,) + output) if loss is not None else output\n\n return Seq2SeqLMOutput(\n loss=loss,\n logits=lm_logits,\n past_key_values=decoder_outputs.past_key_values,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )\n\n def prepare_inputs_for_generation(\n self,\n input_ids,\n past=None,\n attention_mask=None,\n head_mask=None,\n decoder_head_mask=None,\n cross_attn_head_mask=None,\n use_cache=None,\n encoder_outputs=None,\n **kwargs\n ):\n\n # cut decoder_input_ids if past is used\n if past is not None:\n cut_input_ids = input_ids[:, -1:]\n else:\n cut_input_ids = input_ids\n\n return {\n \"decoder_input_ids\": cut_input_ids,\n \"past_key_values\": past,\n \"encoder_outputs\": encoder_outputs,\n \"attention_mask\": attention_mask,\n \"head_mask\": head_mask,\n \"decoder_head_mask\": decoder_head_mask,\n \"cross_attn_head_mask\": cross_attn_head_mask,\n \"use_cache\": use_cache,\n \"full_decoder_input_ids\": input_ids\n }\n\n def input_to_actions(self, input_ids: torch.LongTensor):\n # input_ids : B x L\n input_actions = deepcopy(input_ids)\n if self.action_type == 'integer':\n is_sep = (input_ids == self.sep)\n is_end = (input_ids == self.mention_end)\n is_start = (input_ids == self.mention_start)\n is_ent = (is_sep.cumsum(-1) - is_end.cumsum(-1)).bool()\n is_copy = ((~is_start) & (~is_ent) & (~is_end))\n else:\n cluster_ids = self.cluster_ids.to(input_ids.device)\n is_not_cid = torch.isin(input_ids, cluster_ids, invert=True)\n is_not_start = (input_ids != self.mention_start)\n if self.add_mention_end:\n is_not_end = (input_ids != self.mention_end)\n is_copy = (is_not_start & is_not_end & is_not_cid)\n else:\n is_copy = (is_not_start & is_not_cid)\n input_actions[:, 1:][is_copy[:, 1:]] = self.copy_id\n return input_actions" } ]
import logging import os import sys from transformers import HfArgumentParser, set_seed from transformers import AutoModelForSeq2SeqLM, \ DataCollatorForSeq2Seq, AutoConfig, AutoTokenizer from transformers.integrations import TensorBoardCallback from arguments import DataArguments, ModelArguments, CorefTrainingArguments \ as TrainingArguments from data import CorefDataset, JointDataset from constants import SPEAKER_START, SPEAKER_END, MENTION_START, MENTION_END, \ COPY, CLUSTER_NEW, CLUSTERS, SENTENCE_START, SENTENCE_END, SPECIAL_IDS, \ NON_INT_SPECIAL_IDS, MARK_SPECIAL_IDS, MENTION_END_NON_INT_SPECIAL_IDS, \ MENTION_ENDS from trainer import CorefTrainer from data import ConstrainedDataCollator from model import ConstrainedT5
20,367
logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stdout)) def main(): parser = HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, training_args = parser.parse_json_file( json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments training_args: TrainingArguments if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, fp16 training: %s, bf16 training: %s", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, training_args.bf16, ) logger.info("Training/evaluation parameters %s", training_args) logger.info("MODEL parameters %s", model_args) logger.info("Data arguments %s", data_args) set_seed(training_args.seed) tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path) if training_args.action_type == "integer": num_new_tokens = tokenizer.add_tokens([SPEAKER_START, SPEAKER_END, MENTION_START, MENTION_END, COPY]) elif training_args.action_type == "non_integer": if training_args.add_mention_end: num_new_tokens = tokenizer.add_tokens([SPEAKER_START, SPEAKER_END, MENTION_START, MENTION_END, COPY, CLUSTER_NEW] + CLUSTERS) else: num_new_tokens = tokenizer.add_tokens([SPEAKER_START, SPEAKER_END, MENTION_START, COPY, CLUSTER_NEW] +
logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stdout)) def main(): parser = HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, training_args = parser.parse_json_file( json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments training_args: TrainingArguments if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, fp16 training: %s, bf16 training: %s", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, training_args.bf16, ) logger.info("Training/evaluation parameters %s", training_args) logger.info("MODEL parameters %s", model_args) logger.info("Data arguments %s", data_args) set_seed(training_args.seed) tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path) if training_args.action_type == "integer": num_new_tokens = tokenizer.add_tokens([SPEAKER_START, SPEAKER_END, MENTION_START, MENTION_END, COPY]) elif training_args.action_type == "non_integer": if training_args.add_mention_end: num_new_tokens = tokenizer.add_tokens([SPEAKER_START, SPEAKER_END, MENTION_START, MENTION_END, COPY, CLUSTER_NEW] + CLUSTERS) else: num_new_tokens = tokenizer.add_tokens([SPEAKER_START, SPEAKER_END, MENTION_START, COPY, CLUSTER_NEW] +
MENTION_ENDS)
18
2023-10-17 17:39:16+00:00
24k
giulio98/functional-diffusion-processes
src/functional_diffusion_processes/trainers/trainer.py
[ { "identifier": "AudioDataset", "path": "src/functional_diffusion_processes/datasets/audio_dataset.py", "snippet": "class AudioDataset(BaseDataset, abc.ABC):\n \"\"\"Base class for defining audio datasets.\n\n This class serves as the foundation for defining datasets containing audio data.\n It includes methods for preprocessing, resizing, and normalizing audio data.\n Subclasses may override these methods to implement dataset-specific processing and resizing logic.\n \"\"\"\n\n def __init__(self, data_config: DictConfig, split: str, evaluation: bool = False) -> None:\n \"\"\"Initialize an AudioDataset instance.\n\n Args:\n data_config (DictConfig): Configuration for loading the dataset, including paths, audio properties, etc.\n split (str): Specifies which split of the dataset to load (e.g., 'train', 'validation', 'test').\n evaluation (bool, optional): Indicates whether the dataset is for evaluation purposes. Defaults to False.\n \"\"\"\n super().__init__(data_config, split, evaluation)\n\n @staticmethod\n def normalize_audio(audio_np: np.ndarray, sample_rate: int) -> np.ndarray:\n \"\"\"Normalize the amplitude of the audio data to a standard range.\n\n This method utilizes PyDub's effects module to perform audio normalization.\n\n Args:\n audio_np (np.ndarray): Audio data represented as a NumPy array.\n sample_rate (int): The sample rate of the audio data.\n\n Returns:\n np.ndarray: The normalized audio data as a NumPy array.\n \"\"\"\n # Convert numpy array to AudioSegment\n audio_segment = AudioSegment(audio_np.tobytes(), frame_rate=int(sample_rate), sample_width=2, channels=1)\n\n # Normalize with PyDub\n normalized_audio_segment = effects.normalize(audio_segment)\n\n # Convert back to numpy\n normalized_audio_np = np.array(normalized_audio_segment.get_array_of_samples())\n\n return normalized_audio_np\n\n def _resize_op(self, audio: tf.Tensor, size: int) -> tf.Tensor:\n \"\"\"Resize the input audio to a specified size and normalize its amplitude to the range [0, 1].\n\n If the audio length is less than the specified size, zero padding is applied to reach the desired size.\n If the audio length is greater, it is truncated to the specified size.\n\n Args:\n audio (tf.Tensor): Input audio data as a TensorFlow tensor.\n size (int): The target size for the audio data.\n\n Returns:\n tf.Tensor: The resized and normalized audio data as a TensorFlow tensor.\n \"\"\"\n # Normalize dataset\n pylogger.info(\"Normalizing audio...\")\n audio = tf.cast(audio, dtype=tf.int16)\n # Calculate current length of the audio\n pylogger.info(\"Resizing audio to size {}...\".format(size))\n audio_length = tf.shape(audio)[0]\n audio = tf.cond(\n audio_length < size,\n lambda: tf.concat([audio, tf.zeros(size - audio_length, dtype=audio.dtype)], axis=0),\n lambda: audio[:size],\n )\n audio_np = tf.numpy_function(self.normalize_audio, [audio, self.data_config.audio_sample_rate], tf.int16)\n audio = tf.convert_to_tensor(audio_np, dtype=tf.int16)\n audio = tf.cast(audio, dtype=tf.float32)\n pylogger.info(\"Converting audio to range [-1, 1]...\")\n max_intensity = self.data_config.audio_max_intensity\n audio = audio / max_intensity\n return audio\n\n def preprocess_fn(self, d: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Preprocess the input audio data.\n\n This method resizes the audio data to a specified size based on the dataset configuration and normalizes the amplitude to the range [-1, +1].\n\n Args:\n d (Dict[str, Any]): A dictionary containing the input audio data and any associated metadata.\n\n Returns:\n Dict[str, Any]: A dictionary containing the preprocessed audio data and any associated metadata.\n \"\"\"\n pylogger.info(\"Preprocessing audios for split {}...\".format(self.split))\n audio = self._resize_op(\n audio=d[\"audio\"], size=int(self.data_config.audio_sample_rate * self.data_config.audio_max_duration)\n )\n audio = tf.reshape(\n tensor=audio,\n shape=(-1, self.data_config.output_size),\n )\n pylogger.info(\"Audio reshaped to shape {}...\".format(audio.shape))\n return dict(data=audio, label=d.get(\"label\", None))\n\n def postprocess_fn(self, batch_data: Any, inverse_scaler: Callable) -> Any:\n \"\"\"Postprocess the output audio data.\n\n This method applies the inverse of the preprocessing steps to revert the audio data to its original form.\n\n Args:\n batch_data (Any): A batch of audio data to postprocess.\n inverse_scaler (Callable): A function that applies the inverse of the preprocessing steps.\n\n Returns:\n Any: A batch of postprocessed audio data.\n \"\"\"\n max_intensity = self.data_config.audio_max_intensity\n batch_audio = inverse_scaler(batch_data)\n batch_audio = batch_audio * max_intensity\n batch_post_processed = tf.cast(batch_audio, tf.int16)\n audio_np = tf.numpy_function(\n self.normalize_audio, [batch_post_processed, self.data_config.audio_sample_rate], tf.int16\n )\n batch_post_processed = tf.convert_to_tensor(audio_np, dtype=tf.int16)\n return batch_post_processed" }, { "identifier": "ImageDataset", "path": "src/functional_diffusion_processes/datasets/image_dataset.py", "snippet": "class ImageDataset(BaseDataset, abc.ABC):\n \"\"\"Base class for handling image datasets.\n\n Provides a structured way to load, preprocess, and post-process image data.\n This class can be extended to handle specific image datasets as required.\n\n Attributes:\n data_config (DictConfig): Configuration settings for loading the dataset.\n split (str): Specifies the dataset split to load ('train', 'val', 'test', etc.).\n evaluation (bool): Indicates if the dataset is used for evaluation.\n \"\"\"\n\n def __init__(self, data_config: DictConfig, split: str, evaluation: bool = False) -> None:\n \"\"\"Initializes the ImageDataset object with dataset configurations.\n\n Args:\n data_config (DictConfig): Configuration settings for loading the dataset.\n split (str): Specifies the dataset split to load ('train', 'val', 'test', etc.).\n evaluation (bool): Indicates if the dataset is used for evaluation.\n \"\"\"\n super().__init__(data_config, split, evaluation)\n\n @staticmethod\n def _resize_op(image: Any, size: int) -> Any:\n \"\"\"Resizes the input image to the specified size and normalizes its values to the range [0,1].\n\n Args:\n image (Any): A tensor representing the input image.\n size (int): The target size for each dimension of the output image.\n\n Returns:\n Any: A tensor representing the resized and normalized image.\n \"\"\"\n # convert to range [0,1]\n pylogger.info(\"Converting image to range [0,1]...\")\n image = tf.image.convert_image_dtype(image=image, dtype=tf.float32)\n\n # resize to size\n pylogger.info(\"Resizing image to size {}...\".format(size))\n\n image = tf.image.resize(images=image, size=[size, size])\n\n return image\n\n def preprocess_fn(self, d: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Preprocesses the input data by resizing, possibly flipping, and applying uniform dequantization.\n\n Args:\n d (Dict[str, Any]): A dictionary containing the input data with keys 'image' and optionally 'label'.\n\n Returns:\n Dict[str, Any]: A dictionary containing the preprocessed data, with keys 'data' and optionally 'label'.\n \"\"\"\n image = self._resize_op(image=d[\"image\"], size=self.data_config.image_width_size)\n\n pylogger.info(\"Preprocessing images for split {}...\".format(self.split))\n\n if self.data_config.random_flip and not self.evaluation:\n pylogger.info(\"Applying random flips...\")\n image = tf.image.random_flip_left_right(image=image, seed=self.data_config.seed)\n\n if self.data_config.uniform_dequantization:\n pylogger.info(\"Applying uniform dequantization...\")\n image = (\n tf.random.uniform(shape=image.shape, dtype=tf.float32, seed=self.data_config.seed) + image * 255.0\n ) / 256.0\n\n image = tf.reshape(\n tensor=image,\n shape=(-1, self.data_config.output_size),\n )\n pylogger.info(\"Image reshaped to shape {}...\".format(image.shape))\n\n return dict(data=image, label=d.get(\"label\", None))\n\n def postprocess_fn(self, batch_data: Any, inverse_scaler: Callable) -> Any:\n \"\"\"Post-processes the output data by reverting the preprocessing steps.\n\n Args:\n batch_data (Any): A batch of data to postprocess.\n inverse_scaler (Callable): A function to invert the scaling applied to the data.\n\n Returns:\n Any: A batch of postprocessed data, arranged in a grid for visualization.\n \"\"\"\n batch_post_processed = make_grid_image(\n ndarray=process_images(images=batch_data),\n inverse_scaler=inverse_scaler,\n )\n return batch_post_processed" }, { "identifier": "BaseDataset", "path": "src/functional_diffusion_processes/datasets/base_dataset.py", "snippet": "class BaseDataset(abc.ABC):\n \"\"\"Abstract base class for defining datasets.\n\n Provides a template for loading, preprocessing, and iterating over datasets.\n It encapsulates common dataset configurations and operations while allowing for dataset-specific\n preprocessing and post-processing through abstract methods.\n\n Attributes:\n dataset_builder: A builder object for loading the dataset.\n data_config (DictConfig): Configuration parameters for the dataset.\n split (str): Specifies which split of the dataset to load, e.g., 'train', 'validation', or 'test'.\n evaluation (bool): Indicates whether the dataset is for evaluation purposes.\n dataset_options: Options for configuring the dataset pipeline.\n \"\"\"\n\n def __init__(self, data_config: DictConfig, split: str, evaluation: bool = False) -> None:\n \"\"\"Abstract base class for defining datasets.\n\n This class provides a skeleton for defining datasets, with abstract methods for\n preprocessing data, generating batches of data, and resizing images. Subclasses\n must implement these methods to define their specific datasets.\n\n Args:\n data_config (DictConfig): A dictionary-like object containing the configuration for\n loading the dataset.\n\n split (str): A string specifying which split of the dataset to load.\n\n evaluation (bool): A boolean specifying whether the dataset is for evaluation purposes.\n \"\"\"\n self.dataset_builder = None\n self.data_config = data_config\n self.split = split\n self.evaluation = evaluation\n self.dataset_options = tf.data.Options()\n self.dataset_options.experimental_optimization.map_parallelization = True\n self.dataset_options.experimental_threading.private_threadpool_size = 48\n self.dataset_options.experimental_threading.max_intra_op_parallelism = 1\n\n @abc.abstractmethod\n def preprocess_fn(self, d: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Abstract method for preprocessing input data.\n\n Subclasses should override this method to implement dataset-specific preprocessing.\n\n Args:\n d (Dict[str, Any]): A dictionary containing the input data.\n\n Returns:\n Dict[str, Any]: A dictionary containing the preprocessed data.\n \"\"\"\n raise NotImplementedError(\"Subclasses must implement preprocess_fn method.\")\n\n @abc.abstractmethod\n def postprocess_fn(self, batch_data: Any, inverse_scaler: Callable) -> Any:\n \"\"\"Abstract method for postprocessing output data.\n\n Subclasses should override this method to implement dataset-specific post-processing.\n\n Args:\n batch_data (Any): A batch of data to postprocess.\n inverse_scaler (Callable): A function to inverse the scaling of the data.\n\n Returns:\n Any: A dictionary containing the postprocessed data.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the postprocess_fn method.\")\n\n def _generator(self) -> Iterator[Any]:\n \"\"\"Generate batches of preprocessed data.\n\n Loads the dataset, shuffles the data, applies preprocessing, and batches the data.\n Subclasses might override this method to implement dataset-specific batching logic.\n\n Returns:\n Iterator[Any]: An iterator that generates batches of preprocessed data.\n \"\"\"\n # load the dataset\n if isinstance(self.dataset_builder, tfds.core.DatasetBuilder):\n read_config = tfds.ReadConfig(options=self.dataset_options)\n if self.data_config.download:\n self.dataset_builder.download_and_prepare()\n ds = self.dataset_builder.as_dataset(\n split=self.split,\n shuffle_files=False,\n read_config=read_config,\n as_supervised=False,\n )\n else:\n ds = self.dataset_builder.with_options(options=self.dataset_options)\n\n ds = ds.shuffle(buffer_size=10000, seed=self.data_config.seed)\n\n # apply the preprocessing function to each element in the dataset\n ds = ds.map(map_func=self.preprocess_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n # determine the batch size per device\n ds = ds.batch(batch_size=self.data_config.batch_size, drop_remainder=True)\n ds = ds.batch(batch_size=jax.device_count(), drop_remainder=True)\n\n ds = ds.repeat(count=100000 if not self.evaluation else 1)\n\n return iter(ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE))\n\n def __iter__(self) -> Iterator[Any]:\n \"\"\"Return an iterator that generates batches of preprocessed data.\n\n Calls the `_generator` method to obtain an iterator for generating preprocessed data batches.\n\n Returns:\n Iterator[Any]: An iterator that generates batches of preprocessed data.\n \"\"\"\n return self._generator()\n\n def __len__(self) -> int:\n \"\"\"Return the number of examples in the dataset.\n\n Obtains the total number of examples in the specified dataset split from the dataset builder's info attribute.\n\n Returns:\n int: The number of examples in the dataset.\n \"\"\"\n return self.dataset_builder.info.splits[self.split].num_examples" }, { "identifier": "Loss", "path": "src/functional_diffusion_processes/losses/base_loss.py", "snippet": "class Loss(abc.ABC):\n \"\"\"Abstract class representing a loss function.\n\n Provides a framework for defining custom loss functions by enforcing the implementation\n of `construct_loss_fn` method in any derived classes. This class holds a reference to\n a stochastic differential equation (SDE) object which is used to calculate the weight factor for the loss.\n\n Attributes:\n sde (SDE): The stochastic differential equation instance associated with this loss.\n \"\"\"\n\n def __init__(self, sde: SDE) -> None:\n \"\"\"Initializes the Loss instance with a given SDE.\n\n Args:\n sde (SDE): An SDE instance which might be used in the loss computation.\n \"\"\"\n self.sde = sde\n\n def construct_loss_fn(self, model: Any) -> Callable:\n \"\"\"Abstract method to construct a loss function for a given model.\n\n This method should be implemented by any derived class to define the loss\n computation specific to the type of loss being implemented.\n\n Args:\n model (Any): The model for which to construct the loss function.\n\n Returns:\n Callable: A callable representing the constructed loss function.\n\n Raises:\n NotImplementedError: If the method is not implemented by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the construct_loss_fn method.\")" }, { "identifier": "FIDMetric", "path": "src/functional_diffusion_processes/metrics/fid_metric.py", "snippet": "class FIDMetric:\n \"\"\"Class for computing the Frechet Inception Distance (FID) metric.\n\n This class facilitates the computation of the FID metric, which measures the similarity between two distributions of images.\n It precomputes features for the real dataset using a specified Inception feature extractor and provides methods to compute\n and store features for generated images, and to compute the FID and Inception Score (IS).\n\n Attributes:\n metric_config (DictConfig): Configuration parameters for the FID metric.\n feature_extractor (InceptionFeatureExtractor): Inception feature extractor for computing the FID metric.\n dataset (BaseDataset): Dataset object providing real samples for FID computation.\n generated_pools (list): List to store features of generated images.\n generated_logits (list): List to store logits of generated images.\n real_features (dict): Dictionary to store precomputed features of real dataset.\n \"\"\"\n\n def __init__(\n self,\n metric_config: DictConfig,\n feature_extractor: InceptionFeatureExtractor,\n dataset: BaseDataset,\n ) -> None:\n \"\"\"Initializes the FIDMetric class with specified configurations, feature extractor, and dataset.\n\n Args:\n metric_config (DictConfig): Configuration parameters for the FID metric.\n feature_extractor (InceptionFeatureExtractor): Inception feature extractor for computing the FID metric.\n dataset (BaseDataset): Dataset object providing real samples for FID computation.\n \"\"\"\n self.metric_config = metric_config\n self.feature_extractor = feature_extractor\n self.dataset = dataset\n self.generated_pools = []\n self.generated_logits = []\n try:\n self.real_features = load_dataset_stats(\n save_path=metric_config.real_features_path,\n dataset_name=metric_config.dataset_name,\n )\n except FileNotFoundError:\n self._precompute_features(\n dataset_name=metric_config.dataset_name,\n save_path=metric_config.real_features_path,\n )\n self.real_features = load_dataset_stats(\n save_path=metric_config.real_features_path,\n dataset_name=metric_config.dataset_name,\n )\n\n def _precompute_features(self, dataset_name: str, save_path: str) -> None:\n \"\"\"Precomputes and saves features for the real dataset.\n\n Args:\n dataset_name (str): Name of the dataset.\n save_path (str): Path where the computed features will be saved.\n \"\"\"\n tf.io.gfile.makedirs(path=save_path)\n\n tf.io.gfile.makedirs(os.path.join(save_path, f\"{dataset_name.lower()}_clean\"))\n\n # Use the feature extractor to compute features for the real dataset\n all_pools = self.feature_extractor.extract_features(\n dataset=self.dataset, save_path=save_path, dataset_name=dataset_name\n )\n\n # Save latent represents of the Inception network to disk or Google Cloud Storage\n filename = f\"{dataset_name.lower()}_stats.npz\"\n\n if jax.host_id() == 0:\n pylogger.info(\"Saving real dataset stats to: %s\" % os.path.join(save_path, filename))\n\n with tf.io.gfile.GFile(os.path.join(save_path, filename), \"wb\") as f_out:\n io_buffer = io.BytesIO()\n np.savez_compressed(io_buffer, pool_3=all_pools)\n f_out.write(io_buffer.getvalue())\n\n def compute_fid(self, eval_dir, num_sampling_round) -> Tuple[float, float]:\n \"\"\"Computes the FID and Inception Score (IS) for the generated and real images.\n\n Args:\n eval_dir (str): Directory path for evaluation.\n num_sampling_round (int): Number of sampling rounds.\n\n Returns:\n Tuple[float, float]: A tuple containing the FID and Inception Score.\n \"\"\"\n real_pools = self.real_features[\"pool_3\"]\n if not self.feature_extractor.inception_v3 and not self.feature_extractor.inception_v3 == \"lenet\":\n if len(self.generated_logits) == 0 or len(self.generated_pools) == 0:\n if jax.host_id() == 0:\n # Load all statistics that have been previously computed and saved for each host\n for host in range(jax.host_count()):\n stats = tf.io.gfile.glob(os.path.join(eval_dir, \"statistics_*.npz\"))\n wait_message = False\n while len(stats) < num_sampling_round:\n if not wait_message:\n print(\"Waiting for statistics on host %d\" % (host,))\n wait_message = True\n stats = tf.io.gfile.glob(os.path.join(eval_dir, \"statistics_*.npz\"))\n time.sleep(10)\n\n for stat_file in stats:\n with tf.io.gfile.GFile(stat_file, \"rb\") as fin:\n stat = np.load(fin)\n\n self.generated_pools.append(stat[\"pool_3\"])\n self.generated_logits.append(stat[\"logits\"])\n\n all_logits = np.concatenate(self.generated_logits, axis=0)[: self.metric_config.num_samples]\n inception_score = tfgan.eval.classifier_score_from_logits(logits=all_logits)\n else:\n inception_score = -1\n\n all_pools = np.concatenate(self.generated_pools, axis=0)[: self.metric_config.num_samples]\n\n fid = tfgan.eval.frechet_classifier_distance_from_activations(activations1=real_pools, activations2=all_pools)\n\n return fid, inception_score\n\n def compute_and_store_generated_features(self, images: Any, sample_dir: str, round_num: int) -> None:\n \"\"\"Computes features for the generated images and stores them in a specified directory.\n\n Args:\n images (Any): Tensor representing the generated images.\n sample_dir (str): Directory where the features will be stored.\n round_num (int): Round number in the training process.\n \"\"\"\n latents = self.feature_extractor.extract_features(images)\n\n self.generated_pools.append(latents[\"pool_3\"])\n\n gc.collect()\n\n if self.feature_extractor.model_name == \"inception\" or self.feature_extractor.inception_v3:\n self.generated_logits.append(latents[\"logits\"])\n with tf.io.gfile.GFile(os.path.join(sample_dir, f\"statistics_{round_num}.npz\"), \"wb\") as f_out:\n io_buffer = io.BytesIO()\n np.savez_compressed(\n io_buffer,\n pool_3=latents[\"pool_3\"],\n logits=latents[\"logits\"],\n )\n\n f_out.write(io_buffer.getvalue())\n\n elif self.feature_extractor.model_name == \"lenet\":\n with tf.io.gfile.GFile(os.path.join(sample_dir, f\"statistics_{round_num}.npz\"), \"wb\") as f_out:\n io_buffer = io.BytesIO()\n np.savez_compressed(io_buffer, pool_3=latents[\"pool_3\"])\n f_out.write(io_buffer.getvalue())" }, { "identifier": "Sampler", "path": "src/functional_diffusion_processes/samplers/base_sampler.py", "snippet": "class Sampler(abc.ABC):\n \"\"\"Abstract base class for creating sampler objects.\n\n This class serves as a template for creating sampler objects which are\n designed to generate samples of a stochastic process governed by a\n specified stochastic differential equation (SDE). The process of sampling\n is carried out by employing specified predictor and corrector methods.\n\n Attributes:\n predictor (Predictor): The predictor method to be used in the sampling process.\n corrector (Corrector): The corrector method to be used in the sampling process.\n sde (SDE): The stochastic differential equation governing the process to be sampled.\n sampler_config (DictConfig): Configuration settings for the sampler.\n\n Methods:\n make_sampler(predict_fn: Callable) -> Callable:\n Abstract method to create a sampling function based on the specified predictor,\n corrector, and SDE.\n \"\"\"\n\n def __init__(self, predictor: Predictor, corrector: Corrector, sde: SDE, sampler_config: DictConfig) -> None:\n \"\"\"Initializes the Sampler object with specified predictor, corrector, SDE, and configuration.\n\n Args:\n predictor (Predictor): The predictor method for the sampler.\n corrector (Corrector): The corrector method for the sampler.\n sde (SDE): The stochastic differential equation governing the process.\n sampler_config (DictConfig): Configuration settings for the sampler.\n \"\"\"\n super().__init__()\n self.predictor = predictor\n self.corrector = corrector\n self.sampler_config = sampler_config\n self.sde = sde\n\n def make_sampler(self, predict_fn: Callable, auxiliary_fn: Union[Any, Callable]) -> Callable:\n \"\"\"Abstract method to create a sampler function.\n\n This method is intended to be overridden by derived classes to provide\n specific implementations for creating a sampler function. The sampler\n function will utilize the specified predictor and corrector methods\n along with the provided SDE to generate samples of the stochastic process.\n\n Args:\n predict_fn (Callable): The model prediction function.\n auxiliary_fn (Callable): The auxiliary prediction function for the model.\n\n Returns:\n Callable: The constructed sampling function.\n\n Raises:\n NotImplementedError: If this method is not overridden by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the make_sampler method.\")" }, { "identifier": "SDE", "path": "src/functional_diffusion_processes/sdetools/base_sde.py", "snippet": "class SDE(abc.ABC):\n \"\"\"Abstract base class for representing Stochastic Differential Equations (SDEs).\n\n This class provides a structured way to define and work with SDEs, including computing\n Fourier transforms, discretizing the equations, and defining the drift and diffusion terms.\n\n Attributes:\n sde_config (DictConfig): Configuration object containing SDE settings.\n T (float): Total time duration.\n N (int): Number of time steps.\n eps (float): Small constant for numerical stability.\n is_unidimensional (bool): Flag indicating if the SDE is unidimensional.\n \"\"\"\n\n def __init__(self, sde_config: DictConfig) -> None:\n \"\"\"Initializes the SDE with the given configuration.\n\n Args:\n sde_config (DictConfig): Configuration object containing SDE settings.\n \"\"\"\n super().__init__()\n self.sde_config = sde_config\n self.T = self.sde_config.T\n self.N = self.sde_config.N\n self.eps = self.sde_config.eps\n self.is_unidimensional = True if len(self.sde_config.shape) == 1 else False\n\n def fourier_transform(self, state: jnp.ndarray) -> jnp.ndarray:\n \"\"\"Computes the Fourier transform of the given state.\n\n This method can handle both vectorized and non-vectorized input states.\n\n Args:\n state (jnp.ndarray): State whose Fourier transform is to be computed.\n\n Returns:\n jnp.ndarray: Fourier transform of the given state.\n \"\"\"\n return (\n jnp.fft.fft(state, norm=\"ortho\", axis=1)\n if self.is_unidimensional\n else jnp.fft.fft2(state, norm=\"ortho\", axes=(1, 2))\n )\n\n def inverse_fourier_transform(self, state: jnp.ndarray) -> jnp.ndarray:\n \"\"\"Computes the inverse Fourier transform of the given state.\n\n This method can handle both vectorized and non-vectorized input states.\n\n Args:\n state (jnp.ndarray): State whose inverse Fourier transform is to be computed.\n\n Returns:\n jnp.ndarray: Inverse Fourier transform of the given state.\n \"\"\"\n return (\n jnp.fft.ifft(state, norm=\"ortho\", axis=1)\n if self.is_unidimensional\n else jnp.fft.ifft2(state, norm=\"ortho\", axes=(1, 2))\n )\n\n @abc.abstractmethod\n def sde(\n self,\n y_corrupted: jnp.ndarray,\n t: jnp.ndarray,\n rng: Optional[PRNGKeyArray] = None,\n y_reconstructed: Optional[jnp.ndarray] = None,\n ) -> Tuple[jnp.ndarray, jnp.ndarray]:\n \"\"\"Abstract method to compute the drift and diffusion terms of the SDE.\n\n Args:\n y_corrupted (jnp.ndarray): Corrupted state of the system.\n t (jnp.ndarray): Current time.\n rng (Optional[PRNGKeyArray], optional): Random number generator. Defaults to None.\n y_reconstructed (Optional[jnp.ndarray], optional): Reconstructed state of the system. Defaults to None.\n\n Returns:\n Tuple[jnp.ndarray, jnp.ndarray]: Tuple containing the drift and diffusion terms of the SDE.\n\n Raises:\n NotImplementedError: If this method is not overridden by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the sde method.\")\n\n @abc.abstractmethod\n def marginal_prob(\n self,\n rng: PRNGKeyArray,\n x: jnp.ndarray,\n t: jnp.ndarray,\n t0: Optional[jnp.ndarray] = None,\n ) -> Tuple[Any, jnp.ndarray | Any]:\n \"\"\"Computes the marginal probability density at a given time.\n\n This is an abstract method that should be overridden by subclasses to\n compute the marginal probability density based on the state and time.\n\n Args:\n rng (PRNGKeyArray): Random number generator.\n x (jnp.ndarray): State of the system.\n t (jnp.ndarray): Current time.\n t0 (Optional[jnp.ndarray], optional): Initial time. Defaults to None.\n\n Returns:\n Tuple[Any, jnp.ndarray | Any]: Marginal probability density at the given time.\n\n Raises:\n NotImplementedError: If this method is not overridden by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the marginal_prob method.\")\n\n @abc.abstractmethod\n def diffuse(\n self, rng: PRNGKeyArray, x: jnp.ndarray, t: jnp.ndarray, t0: Optional[jnp.ndarray] = None\n ) -> Tuple[jnp.ndarray, jnp.ndarray]:\n \"\"\"Performs diffusion of the input from time t0 to time t.\n\n This is an abstract method that should be overridden by subclasses to\n implement the diffusion process based on the state and time.\n\n Args:\n rng (PRNGKeyArray): Random number generator.\n x (jnp.ndarray): Input state.\n t (jnp.ndarray): Current time.\n t0 (Optional[jnp.ndarray], optional): Initial time. Defaults to None.\n\n Returns:\n Tuple[jnp.ndarray, jnp.ndarray]: Mean of the corrupted input and the corrupted input.\n\n Raises:\n NotImplementedError: If this method is not overridden by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the diffuse method.\")\n\n @abc.abstractmethod\n def prior_sampling(\n self, rng: PRNGKeyArray, shape: Tuple[int, ...], t0: Optional[jnp.ndarray] = None\n ) -> jnp.ndarray:\n \"\"\"Generates a sample from the prior distribution of the SDE.\n\n This is an abstract method that should be overridden by subclasses to\n implement the prior sampling process based on the shape and initial time.\n\n Args:\n rng (PRNGKeyArray): Random number generator.\n shape (Tuple[int, ...]): Shape of the sample to be generated.\n t0 (Optional[jnp.ndarray], optional): Initial time. Defaults to None.\n\n Returns:\n jnp.ndarray: A sample from the prior distribution of the SDE.\n\n Raises:\n NotImplementedError: If this method is not overridden by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the prior_sampling method.\")\n\n @abc.abstractmethod\n def score_fn(\n self, y_corrupted: jnp.ndarray, y_reconstructed: jnp.ndarray, t: jnp.ndarray, rng: Optional[PRNGKeyArray] = None\n ) -> jnp.ndarray:\n \"\"\"Computes the score function based on the corrupted and reconstructed states.\n\n This is an abstract method that should be overridden by subclasses to\n compute the score function based on the state and time.\n\n Args:\n y_corrupted (jnp.ndarray): Corrupted state of the system.\n y_reconstructed (jnp.ndarray): Reconstructed state of the system.\n t (jnp.ndarray): Current time.\n rng (Optional[PRNGKeyArray], optional): Random number generator. Defaults to None.\n\n Returns:\n jnp.ndarray: The score function.\n\n Raises:\n NotImplementedError: If this method is not overridden by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the score_fn method.\")\n\n @abc.abstractmethod\n def get_psm(self, t: jnp.ndarray) -> jnp.ndarray:\n \"\"\"Computes the Power-Special-Matrix(PSM) used as a weighting factor for the loss.\n\n This is an abstract method that should be overridden by subclasses to\n compute the state-dependent diffusion matrix based on the time.\n\n Args:\n t (jnp.ndarray): Current time.\n\n Returns:\n jnp.ndarray: The state-dependent diffusion matrix.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the get_psm method.\")\n\n @abc.abstractmethod\n def get_reverse_noise(self, rng: PRNGKeyArray, shape: Tuple[int, ...]) -> jnp.ndarray:\n \"\"\"Generates noise for the reverse SDE.\n\n This is an abstract method that should be overridden by subclasses to\n generate reverse noise based on the shape.\n\n Args:\n rng (PRNGKeyArray): Random number generator.\n shape (Tuple[int, ...]): Shape of the noise to be generated.\n\n Returns:\n jnp.ndarray: The reverse noise.\n\n Raises:\n NotImplementedError: If this method is not overridden by a derived class.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} must implement the get_reverse_noise method.\")\n\n def discretize(\n self,\n y_corrupted: jnp.ndarray,\n t: jnp.ndarray,\n y_reconstructed: Optional[jnp.ndarray] = None,\n ) -> Tuple[jnp.ndarray, jnp.ndarray]:\n \"\"\"Discretizes the SDE into an iterative update rule.\n\n This method computes the discrete drift and diffusion terms based on the continuous SDE.\n\n Args:\n y_corrupted (jnp.ndarray): Corrupted state of the system.\n t (jnp.ndarray): Current time.\n y_reconstructed (Optional[jnp.ndarray], optional): Reconstructed state of the system. Defaults to None.\n\n Returns:\n Tuple[jnp.ndarray, jnp.ndarray]: Tuple containing the discrete drift and diffusion terms.\n \"\"\"\n dt = (self.T - self.eps) / self.N\n drift, diffusion = self.sde(y_corrupted, t, y_reconstructed)\n f = drift * dt\n g = diffusion * jnp.sqrt(dt)\n return f, g\n\n def reverse(self):\n \"\"\"Creates a reverse-time version of the current SDE.\n\n This method defines a nested class for the reverse-time SDE and returns an instance of it.\n\n Returns:\n ReverseSDE: An instance of the reverse-time SDE subclass.\n \"\"\"\n num_time_steps = self.N\n end_t = self.T\n sde_fn = self.sde\n discretize_fn = self.discretize\n score_fn = self.score_fn\n sde_config = self.sde_config\n\n class ReverseSDE(self.__class__, abc.ABC):\n \"\"\"Reverse Stochastic Differential Equation abstract base class.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialize the ReverseSDE class.\n\n Inherits the properties from the original SDE class and overrides the relevant methods for the\n reverse-time SDE.\n \"\"\"\n super().__init__(sde_config)\n self.N = num_time_steps\n self.T = end_t\n self.score_fn = score_fn\n\n def sde(\n self,\n y_corrupted: jnp.ndarray,\n t: jnp.ndarray,\n rng: Optional[PRNGKeyArray] = None,\n y_reconstructed: Optional[jnp.ndarray] = None,\n ) -> Tuple[jnp.ndarray, jnp.ndarray]:\n \"\"\"Return the drift and diffusion terms for the reverse-time SDE.\n\n Args:\n y_corrupted (jnp.ndarray): Corrupted state of the system.\n t (jnp.ndarray): Current time.\n rng (Optional[PRNGKeyArray], optional): Random number generator. Defaults to None.\n y_reconstructed (Optional[jnp.ndarray], optional): Reconstructed state of the system. Defaults to None.\n\n Returns:\n Tuple[jnp.ndarray, jnp.ndarray]: Drift and diffusion terms for the reverse-time SDE.\n \"\"\"\n drift, diffusion = sde_fn(y_corrupted, t, y_reconstructed)\n score = self.score_fn(y_corrupted, y_reconstructed, t, rng=rng)\n drift = -drift + batch_mul(diffusion**2, score * (0.5 if self.sde_config.probability_flow else 1.0))\n # Set the diffusion function to zero for ODEs.\n diffusion = jnp.zeros_like(diffusion) if self.sde_config.probability_flow else diffusion\n return drift, diffusion\n\n def discretize(\n self,\n y_corrupted: jnp.ndarray,\n t: jnp.ndarray,\n rng: Optional[PRNGKeyArray] = None,\n y_reconstructed: Optional[jnp.ndarray] = None,\n ) -> Tuple[jnp.ndarray, jnp.ndarray]:\n \"\"\"Discretizes the reverse-time SDE in the form of an iterative update rule.\n\n Args:\n y_corrupted (jnp.ndarray): Corrupted state of the system.\n t (jnp.ndarray): Current time.\n rng (Optional[PRNGKeyArray], optional): Random number generator. Defaults to None.\n y_reconstructed (Optional[jnp.ndarray], optional): Reconstructed state of the system. Defaults to None.\n\n Returns:\n Tuple[jnp.ndarray, jnp.ndarray]: Drift and diffusion terms for the discretized reverse-time SDE.\n \"\"\"\n f, g = discretize_fn(y_corrupted, t, y_corrupted)\n rev_f = -f + batch_mul(\n g**2,\n self.score_fn(y_corrupted, y_reconstructed, t, rng=rng)\n * (0.5 if self.sde_config.probability_flow else 1.0),\n )\n rev_g = jnp.zeros_like(g) if self.sde_config.probability_flow else g\n return rev_f, rev_g\n\n def semi_analytic(\n self,\n y_corrupted: jnp.ndarray,\n t: jnp.ndarray,\n rng: Optional[PRNGKeyArray] = None,\n y_reconstructed: Optional[jnp.ndarray] = None,\n ) -> Tuple[jnp.ndarray, jnp.ndarray]:\n \"\"\"Computes the semi-analytic drift and diffusion terms for the reverse-time SDE.\n\n Args:\n y_corrupted (jnp.ndarray): Corrupted state of the system.\n t (jnp.ndarray): Current time.\n rng (Optional[PRNGKeyArray], optional): Random number generator. Defaults to None.\n y_reconstructed (Optional[jnp.ndarray], optional): Reconstructed state of the system. Defaults to None.\n\n Returns:\n Tuple[jnp.ndarray, jnp.ndarray]: Drift and diffusion terms for the semi-analytic reverse-time SDE.\n \"\"\"\n _, diffusion = sde_fn(y_corrupted, t, y_reconstructed)\n score = self.score_fn(y_corrupted, y_reconstructed, t, rng=rng)\n drift = batch_mul(diffusion**2, score * (0.5 if self.sde_config.probability_flow else 1.0))\n diffusion = jnp.zeros_like(diffusion) if self.sde_config.probability_flow else diffusion\n return drift, diffusion\n\n return ReverseSDE()" }, { "identifier": "filter_mask", "path": "src/functional_diffusion_processes/utils/common.py", "snippet": "def filter_mask(shape, radius):\n device_num, batch_size, rows, cols, n_channels = shape\n crow, ccol = int(rows / 2), int(cols / 2)\n center = [crow, ccol]\n x, y = jnp.ogrid[:rows, :cols]\n mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 >= radius * radius\n mask = jnp.ones_like(mask_area)\n mask = jnp.where(mask_area, 0, mask)\n mask = mask.reshape(1, 1, rows, cols, 1)\n mask = jnp.repeat(mask, device_num, axis=0)\n mask = jnp.repeat(mask, batch_size, axis=1)\n mask = jnp.repeat(mask, n_channels, axis=4)\n return mask" }, { "identifier": "make_grid_image", "path": "src/functional_diffusion_processes/utils/common.py", "snippet": "def make_grid_image(ndarray: Any, inverse_scaler: Callable, padding: int = 2, pad_value: float = 0.0) -> Any:\n \"\"\"Make a grid image from a Numpy Array.\n\n Args:\n ndarray: The Numpy Array.\n inverse_scaler: The inverse scaler.\n padding: The padding.\n pad_value: The padding value.\n\n Returns:\n The grid image.\n \"\"\"\n ndarray = jnp.asarray(ndarray)\n\n if ndarray.ndim == 4 and ndarray.shape[-1] == 1: # single-channel images\n ndarray = jnp.concatenate((ndarray, ndarray, ndarray), -1)\n\n n_row = int(np.sqrt(ndarray.shape[0]))\n # make the mini-batch of images into a grid\n n_maps = ndarray.shape[0]\n x_maps = min(n_row, n_maps)\n ymaps = int(math.ceil(float(n_maps) / x_maps))\n height, width = int(ndarray.shape[1] + padding), int(ndarray.shape[2] + padding)\n num_channels = ndarray.shape[3]\n grid = np.full((height * ymaps + padding, width * x_maps + padding, num_channels), pad_value).astype(np.float32)\n k = 0\n for y in range(ymaps):\n for x in range(x_maps):\n if k >= n_maps:\n break\n grid[\n y * height + padding : (y + 1) * height,\n x * width + padding : (x + 1) * width,\n ] = ndarray[k]\n k = k + 1\n\n ndarr = inverse_scaler(grid)\n ndarr = jnp.clip(ndarr * 255, 0, 255).astype(jnp.uint8)\n return ndarr" }, { "identifier": "process_images", "path": "src/functional_diffusion_processes/utils/common.py", "snippet": "def process_images(images: Any) -> Any:\n \"\"\"Reshape images to the correct shape.\n\n Args:\n images: Tensor of images to reshape.\n\n Returns:\n A tensor of images with the correct shape.\n \"\"\"\n w = np.sqrt(images.shape[2]).astype(int)\n h = np.sqrt(images.shape[2]).astype(int)\n o = images.shape[3]\n return images.reshape(-1, w, h, o)" }, { "identifier": "save_samples", "path": "src/functional_diffusion_processes/utils/common.py", "snippet": "def save_samples(round_num: int, samples: Any, file_path: str) -> None:\n \"\"\"Save samples to a file.\n\n Args:\n round_num: The round number of the evaluation.\n samples: Tensor of samples to save.\n file_path: string of the Path to the file where the samples will be saved.\n \"\"\"\n for i in range(samples.shape[0]):\n clean_path = os.path.join(file_path, f\"clean/samples_{round_num}_{i}.npy\")\n np.save(clean_path, samples[i])\n samples_path = os.path.join(file_path, f\"samples_{round_num}.npz\")\n with tf.io.gfile.GFile(samples_path, \"wb\") as f_out:\n io_buffer = io.BytesIO()\n np.savez_compressed(io_buffer, samples=samples)\n f_out.write(io_buffer.getvalue())" }, { "identifier": "to_grayscale", "path": "src/functional_diffusion_processes/utils/common.py", "snippet": "@jax.pmap\ndef to_grayscale(images):\n weights = np.array([0.2989, 0.5870, 0.1140])[None, None, None, :] # Extend dimensions\n grayscale_images = np.sum(images * weights, axis=-1)\n return grayscale_images" }, { "identifier": "get_data_inverse_scaler", "path": "src/functional_diffusion_processes/utils/scaler.py", "snippet": "def get_data_inverse_scaler(is_centered: bool) -> Callable:\n \"\"\"Inverse data normalizer.\n\n Rescale data to original range at the end of the diffusion.\n\n Args:\n is_centered: boolean if True data will rescaled from [-1, 1] to [0, 1].\n \"\"\"\n if is_centered:\n # Rescale [-1, 1] to [0, 1]\n return lambda x: (x + 1.0) / 2.0\n else:\n return lambda x: x" }, { "identifier": "get_data_scaler", "path": "src/functional_diffusion_processes/utils/scaler.py", "snippet": "def get_data_scaler(is_centered: bool) -> Callable:\n \"\"\"Normalize data. Assume data are always in [0, 1].\n\n Args:\n is_centered: boolean if True data will be centered in [-1, 1].\n \"\"\"\n if is_centered:\n # Rescale to [-1, 1]\n return lambda x: x * 2.0 - 1.0\n else:\n return lambda x: x" }, { "identifier": "TrainState", "path": "src/functional_diffusion_processes/utils/training_state.py", "snippet": "class TrainState(train_state.TrainState):\n \"\"\"The training state for the model.\"\"\"\n\n opt_state_params: Any\n ema_params: Any\n rng: jax.random.PRNGKey" }, { "identifier": "colorizing_fn", "path": "src/functional_diffusion_processes/trainers/helpers.py", "snippet": "def colorizing_fn(\n sample_fn: Callable, carry_state: Tuple, batch_input: jnp.ndarray, gray_scale_img: jnp.ndarray\n) -> Tuple:\n \"\"\"Perform colorizing task on a given grayscale image.\n\n Args:\n sample_fn (Callable): The sampling function used for colorization.\n carry_state (Tuple): The current state of the model.\n batch_input (jnp.ndarray): The input data for colorization.\n gray_scale_img (jnp.ndarray): The grayscale image to be colorized.\n\n Returns:\n Tuple: The updated state and the colorized image.\n \"\"\"\n (rng, state) = carry_state\n return sample_fn(rng, batch_input, state.ema_params, gray_scale_img)" }, { "identifier": "construct_sampling_fn", "path": "src/functional_diffusion_processes/trainers/helpers.py", "snippet": "def construct_sampling_fn(model: flax.linen.Module, sampler: Sampler) -> Callable:\n \"\"\"Construct a sampling function for generating samples from the model.\n\n Args:\n model (flax.linen.Module): The model instance from which to generate samples.\n sampler (Sampler): The sampler instance used for sampling.\n\n Returns:\n Callable: The constructed sampling function.\n \"\"\"\n predict_fn = model.make_predict_fn()\n if isinstance(model, BaseMAML):\n super_resolution_fn = model.make_super_resolution_fn()\n sample_fn = sampler.make_sampler(predict_fn, super_resolution_fn)\n else:\n sample_fn = sampler.make_sampler(predict_fn, None)\n return sample_fn" }, { "identifier": "construct_train_step", "path": "src/functional_diffusion_processes/trainers/helpers.py", "snippet": "def construct_train_step(optimizer, loss_fn) -> Callable:\n \"\"\"Construct a train step function to be used in the training loop.\n\n This function creates a training step function which, when called, performs\n a single step of training including forward pass, loss computation, and\n backward pass for gradient computation and updates.\n\n Args:\n optimizer: The optimizer instance used for updating model parameters.\n loss_fn: The loss function used for computing the loss.\n\n Returns:\n Callable: The constructed train step function.\n \"\"\"\n\n @partial(jax.pmap, axis_name=\"device\")\n def train_fn(\n rng,\n params,\n optim_params,\n step,\n batch_input,\n batch,\n ):\n grad_params, (new_rng, loss, loss_inner, batch_reconstructed, batch_corrupted, target) = loss_fn(\n rng, params, step, batch_input, batch\n )\n\n loss = jax.lax.pmean(loss, axis_name=\"device\")\n grad_params = jax.lax.pmean(grad_params, axis_name=\"device\")\n\n updates, optim_params = optimizer.update(grad_params, optim_params, params)\n\n params = optax.apply_updates(params, updates)\n params = clip_learning_rates(params)\n return new_rng, loss, loss_inner, params, optim_params, batch_reconstructed, batch_corrupted, target\n\n return train_fn" }, { "identifier": "inpainting_fn", "path": "src/functional_diffusion_processes/trainers/helpers.py", "snippet": "def inpainting_fn(\n sample_fn: Callable, carry_state: Tuple, batch_input: jnp.ndarray, image: jnp.ndarray, mask: jnp.ndarray\n) -> Tuple:\n \"\"\"Perform inpainting task on a given image using a mask.\n\n Args:\n sample_fn (Callable): The sampling function used for inpainting.\n carry_state (Tuple): The current state of the model.\n batch_input (jnp.ndarray): The input data for inpainting.\n image (jnp.ndarray): The image to be inpainted.\n mask (jnp.ndarray): The mask used for inpainting.\n\n Returns:\n Tuple: The updated state and the inpainted image.\n \"\"\"\n (rng, state) = carry_state\n return sample_fn(rng, batch_input, state.ema_params, image, mask)" }, { "identifier": "sampling_fn", "path": "src/functional_diffusion_processes/trainers/helpers.py", "snippet": "def sampling_fn(sample_fn: Callable, carry_state: Tuple, batch_input: jnp.ndarray) -> Tuple:\n \"\"\"Perform sampling task using a given sampling function.\n\n Args:\n sample_fn (Callable): The sampling function.\n carry_state (Tuple): The current state of the model.\n batch_input (jnp.ndarray): The input data for sampling.\n\n Returns:\n Tuple: The updated state after performing the sampling.\n \"\"\"\n (rng, state) = carry_state\n return sample_fn(rng, batch_input, state.ema_params)" } ]
import abc import gc import io import logging import os import flax import flax.jax_utils as flax_utils import hydra.utils import jax import numpy as np import tensorflow as tf import wandb from typing import Any, Callable, Tuple, Union from cleanfid import fid from flax import linen, traverse_util from flax.training import checkpoints from flax.training.checkpoints import restore_checkpoint from jax import numpy as jnp from omegaconf import DictConfig, OmegaConf from tqdm.auto import tqdm from wandb.sdk.lib import RunDisabled from wandb.sdk.wandb_run import Run from ..datasets import AudioDataset, ImageDataset from ..datasets.base_dataset import BaseDataset from ..losses.base_loss import Loss from ..metrics import FIDMetric from ..samplers import Sampler from ..sdetools.base_sde import SDE from ..utils.common import filter_mask, make_grid_image, process_images, save_samples, to_grayscale from ..utils.scaler import get_data_inverse_scaler, get_data_scaler from ..utils.training_state import TrainState from .helpers import colorizing_fn, construct_sampling_fn, construct_train_step, inpainting_fn, sampling_fn
15,242
batch_data=batch.reshape(-1, b, g, c), inverse_scaler=inverse_scaler ) if isinstance(ds_train, ImageDataset): data_reconstructed = wandb.Image(np.asarray(batch_reconstructed), caption="Reconstructed") data_corrupted = wandb.Image(np.asarray(batch_corrupted), caption="Corrupted") data_real = wandb.Image(np.asarray(batch_real), caption="Real") elif isinstance(ds_train, AudioDataset): sample_rate = ds_train.data_config.audio_sample_rate long_audio_batch_reconstructed = np.concatenate( np.asarray(batch_reconstructed).reshape(-1, sample_rate), axis=0 ) data_reconstructed = wandb.Audio( long_audio_batch_reconstructed, sample_rate=sample_rate, caption="Reconstructed" ) long_audio_batch_corrupted = np.concatenate( np.asarray(batch_corrupted).reshape(-1, sample_rate), axis=0 ) data_corrupted = wandb.Audio( long_audio_batch_corrupted, sample_rate=sample_rate, caption="Corrupted" ) long_audio_batch_real = np.concatenate( np.asarray(batch_real).reshape(-1, sample_rate), axis=0 ) data_real = wandb.Audio(long_audio_batch_real, sample_rate=sample_rate, caption="Real") else: raise ValueError("Unsupported dataset type: {}".format(type(ds_train))) wandb.log({"Reconstructed": data_reconstructed}, step=step) wandb.log({"Corrupted": data_corrupted}, step=step) wandb.log({"Real": data_real}, step=step) # Update the progress bar pbar.update() wandb.finish() def evaluate( self, model: flax.linen.Module, ds_test: BaseDataset, fid_metric: FIDMetric, sde: SDE, ) -> None: """Evaluate the model on the test dataset. Args: model: The model to be evaluated. ds_test: The test dataset. fid_metric: The FID metric. sde: The SDE. """ run, _, inverse_scaler, rng, state, _, sample_fn, batch_input = self.initialize_run(model, ds_test, sde) # Replicate the train state on all devices (p_ema_params, p_params, p_opt_state_params, p_step, p_batch_input) = flax_utils.replicate( (state.ema_params, state.params, state.opt_state_params, state.step, batch_input) ) # update the TrainState with replicated parameters and optimizer state state = state.replace( params=p_params, opt_state_params=p_opt_state_params, step=p_step, ema_params=p_ema_params, ) # Create different random states for different hosts in a multi-host environment (e.g., TPU pods) rng = jax.random.fold_in(rng, jax.host_id()) # A data class for storing intermediate results to resume evaluation after pre-emption @flax.struct.dataclass class EvalMeta: sampling_round_id: int rng: Any num_sampling_rounds = ( self.evaluation_config.num_samples // (ds_test.data_config.batch_size * jax.device_count()) + 1 ) # Restore evaluation after pre-emption eval_meta = EvalMeta(sampling_round_id=-1, rng=rng) eval_meta = checkpoints.restore_checkpoint(self.eval_dir, eval_meta, step=None, prefix=f"meta_{jax.host_id()}_") if eval_meta.sampling_round_id < num_sampling_rounds - 1: begin_sampling_round = eval_meta.sampling_round_id + 1 else: begin_sampling_round = 0 rng = eval_meta.rng if jax.host_id() == 0: pylogger.info("Starting sampling loop at step %d." % (begin_sampling_round,)) # Create a progress bar for tracking the training progress pbar = tqdm( total=num_sampling_rounds, initial=begin_sampling_round, position=0, leave=True, ) for i in range(begin_sampling_round, num_sampling_rounds): if jax.host_id() == 0: pylogger.info("sampling -- round: %d" % i) this_sample_dir = os.path.join(self.eval_dir, f"ckpt_host_{jax.host_id()}") tf.io.gfile.makedirs(this_sample_dir) rng, *rng_s = jax.random.split(rng, jax.device_count() + 1) rng_s = jnp.asarray(rng_s) if not tf.io.gfile.exists(os.path.join(self.eval_dir, f"samples_{i}.npz")): batch_sampled, batch_sampled_last, _ = sampling_fn(sample_fn, (rng_s, state), p_batch_input) samples = inverse_scaler(batch_sampled_last) if isinstance(ds_test, ImageDataset): samples = np.clip(samples * 255.0, 0, 255).astype(np.uint8) samples = process_images(images=samples) elif isinstance(ds_test, AudioDataset): min_intensity = ds_test.data_config.min_intensity max_intensity = ds_test.data_config.max_intensity samples = np.clip( samples * (max_intensity - min_intensity) + min_intensity, min_intensity, max_intensity )
# import imageio # import imageio pylogger = logging.getLogger(__name__) class Trainer(abc.ABC): """Class for training a model.""" def __init__( self, mode: str, model_name: str, training_config: DictConfig, optimizer, evaluation_config: DictConfig, trainer_logging: DictConfig, sampler: Sampler, loss_obj: Loss, ) -> None: """Initialize a Trainer instance with configurations and core components. Args: mode (str): Specifies the mode of the trainer which can be either "train" or "eval". model_name (str): The name identifier for the model. training_config (DictConfig): A configuration dictionary for training settings. optimizer: The optimizer instance used for training. evaluation_config (DictConfig): A configuration dictionary for evaluation settings. trainer_logging (DictConfig): A configuration dictionary for logging settings. sampler (Sampler): A sampler instance for sampling from the model. loss_obj (Loss): A loss object used for computing the loss during training. """ self.mode = mode self.model_name = model_name self.training_config = training_config self.optimizer = hydra.utils.instantiate(optimizer) self.evaluation_config = evaluation_config self.logging = trainer_logging self.sampler = sampler self.loss_obj = loss_obj self.checkpoint_dir = os.path.join(self.training_config.save_dir, self.training_config.checkpoint_dir) self.sample_dir = os.path.join(self.training_config.save_dir, self.training_config.sample_dir) self.eval_dir = os.path.join(self.training_config.save_dir, self.evaluation_config.eval_dir) # Create the directories for saving samples and checkpoints tf.io.gfile.makedirs(self.checkpoint_dir) tf.io.gfile.makedirs(self.sample_dir) tf.io.gfile.makedirs(self.eval_dir) tf.io.gfile.makedirs(os.path.join(self.eval_dir, "clean")) def initialize_wandb( self, dataset_config: DictConfig, sde_config: DictConfig, model_config: DictConfig ) -> Union[Run, RunDisabled, None]: """Initialize wandb if logging is enabled.""" if self.logging.use_wandb: run = wandb.init( name=os.path.basename(self.logging.wandb_init.name), project=self.logging.wandb_init.project, entity=self.logging.wandb_init.entity, save_code=self.logging.wandb_init.save_code, config={ **self.training_config, **dataset_config, **sde_config, **model_config, }, ) else: run = None return run def initialize_run(self, model, ds_train, sde): """Perform all initialization steps required for training.""" run = self.initialize_wandb(ds_train.data_config, sde.sde_config, model.model_config) scaler = get_data_scaler(is_centered=ds_train.data_config.data_centered) inverse_scaler = get_data_inverse_scaler(is_centered=ds_train.data_config.data_centered) rng = jax.random.PRNGKey(seed=self.training_config.seed) rng, step_rng = jax.random.split(rng) batch_input = model.initialize_input( (ds_train.data_config.batch_size, *sde.sde_config.shape, ds_train.data_config.output_size) ) params = jax.jit(model.initialize_model, backend="cpu")(step_rng, batch_input) flat_params = traverse_util.flatten_dict(params).values() tot_params = sum([jnp.size(p) for p in flat_params]) pylogger.info("Total number of parameters: {:.2f}M".format(tot_params / 1e6)) state = TrainState.create( apply_fn=model.apply, params=params, tx=self.optimizer, opt_state_params=self.optimizer.init(params), rng=rng, ema_params=params, ) train_step_fn = construct_train_step(self.optimizer, self.loss_obj.construct_loss_fn(model)) sample_fn = construct_sampling_fn(model, self.sampler) # Resume training when intermediate checkpoints are detected if self.training_config.resume_training: pylogger.warning("Resuming training from the latest checkpoint.") if self.logging.use_wandb and self.model_name != "local": model_file = wandb.use_artifact(self.model_name).download() state = restore_checkpoint(ckpt_dir=model_file, prefix="checkpoint_", target=state) else: state = checkpoints.restore_checkpoint(ckpt_dir=self.checkpoint_dir, target=state) return run, scaler, inverse_scaler, rng, state, train_step_fn, sample_fn, batch_input def train_step( self, train_step_fn: Callable, carry_state: Tuple, batch: jnp.ndarray, batch_input: jnp.ndarray, ) -> Tuple: """Perform a single training step, updating the model parameters. Args: train_step_fn (Callable): The train step function. carry_state (Tuple): The current state of the model and optimizer. batch (jnp.ndarray): The batch of data used for training. batch_input (jnp.ndarray): The input data to the model. Returns: Tuple: The updated state after performing the training step. """ (rng, state) = carry_state ( new_rng, loss, loss_inner, new_params, new_optim_state, batch_reconstructed, batch_corrupted, target, ) = train_step_fn( rng, state.params, state.opt_state_params, state.step, batch_input, batch, ) ema_rate = self.training_config.ema_rate new_params_ema = jax.tree_map( lambda p_ema, p: p_ema * ema_rate + p * (1.0 - ema_rate), state.ema_params, new_params, ) # update the state new_state = state.replace( rng=flax.jax_utils.unreplicate(new_rng), step=state.step + 1, opt_state_params=new_optim_state, params=new_params, ema_params=new_params_ema, ) new_carry_state = (new_rng, new_state) loss = flax.jax_utils.unreplicate(loss) step = int(flax_utils.unreplicate(state.step)) # Log the training progress if jax.host_id() == 0 and step % self.training_config.log_freq == 0: pylogger.info("step: %d, training_loss: %.5e" % (step, loss)) if self.logging.use_wandb: wandb.log({"step": step, "loss": loss}, step=step) if loss_inner is not None: loss_inner = flax.jax_utils.unreplicate(loss_inner) for inner_step, loss in enumerate(loss_inner): pylogger.info("step: %d, training_loss_inner: %.5e" % (step, loss)) if self.logging.use_wandb: wandb.log({"step": step, f"loss inner step {inner_step}": loss}, step=step) return new_carry_state, batch_reconstructed, batch_corrupted, target def save_checkpoint(self, step, run, state): pylogger.info("Saving the model at step %d." % (step,)) # Log the evaluation progress # Save the model parameters ( params, opt_state_params, step_, ema_params, ) = flax_utils.unreplicate( ( state.params, state.opt_state_params, state.step, state.ema_params, ) ) saved_state = state.replace( step=step_, opt_state_params=opt_state_params, params=params, ema_params=ema_params, ) checkpoint_file = checkpoints.save_checkpoint( self.checkpoint_dir, saved_state, step=step_ // self.training_config.eval_freq, keep=np.inf, ) if self.logging.use_wandb: wandb_model_artifact_name = str(step_) + "_" + run.id wandb_model = wandb.Artifact(wandb_model_artifact_name, type="model") wandb_model.add_file(checkpoint_file) run.log_artifact(wandb_model) # noinspection PyProtectedMember def train(self, model: linen.Module, ds_train: BaseDataset, sde: SDE) -> None: """Train the model with optional evaluation and logging. This method encapsulates the entire training process including initialization, training loop, checkpointing, evaluation, and logging. It supports different sampling types like colorization, inpainting, super resolution, and deblurring. Args: model (linen.Module): The model to be trained. ds_train (BaseDataset): The training dataset. sde (SDE): Stochastic differential equation object, governing the dynamics for sampling. Raises: ValueError: If an unsupported dataset type is provided. Note: The method leverages the Weights & Biases (wandb) platform for logging and checkpointing, make sure it's configured properly if logging is enabled. """ run, scaler, inverse_scaler, rng, state, train_step_fn, sample_fn, batch_input = self.initialize_run( model, ds_train, sde ) # `state.step` is JAX integer on the GPU/TPU devices start_step = int(state.step) rng = state.rng # Replicate the train state on all devices ( p_params, p_opt_state_params, p_step, p_ema_params, p_batch_input, ) = flax_utils.replicate( ( state.params, state.opt_state_params, state.step, state.ema_params, batch_input, ) ) # update the TrainState with replicated parameters and optimizer state state = state.replace( params=p_params, opt_state_params=p_opt_state_params, step=p_step, ema_params=p_ema_params, ) if jax.host_id() == 0: pylogger.info("Starting training loop at step %d." % (start_step,)) rng = jax.random.fold_in(rng, jax.host_id()) assert ( self.training_config.log_freq % self.training_config.n_jitted_steps == 0 and self.training_config.eval_freq % self.training_config.n_jitted_steps == 0 ), "Missing logs or checkpoints!" ds_train_iter = iter(ds_train) with tqdm( total=self.training_config.total_steps + 1, initial=start_step, position=0, leave=True, ) as pbar: for step in range( start_step, self.training_config.total_steps + 1, self.training_config.n_jitted_steps, ): # Get the next batch of data and scale it batch = jax.tree_map(f=lambda x: scaler(x._numpy()), tree=next(ds_train_iter)["data"]) if not self.training_config.sampling_only: # Split the random number generator for the current step rng, *next_rng = jax.random.split(key=rng, num=jax.local_device_count() + 1) next_rng = jnp.asarray(next_rng) ((_, state), batch_reconstructed, batch_corrupted, target) = self.train_step( train_step_fn=train_step_fn, carry_state=(next_rng, state), batch=batch, batch_input=p_batch_input, ) if not self.training_config.sampling_only and ( (jax.host_id() == 0 and step % self.training_config.checkpoint_freq == 0 and step != 0) ): self.save_checkpoint(step, run, state) # Evaluate the model if self.training_config.sampling and (step % self.training_config.eval_freq == 0): # if step != 0: if jax.host_id() == 0: pylogger.info("Generating samples at step %d." % (step,)) _, *sample_rng = jax.random.split(rng, jax.local_device_count() + 1) _, b, g, c = batch.shape sample_rng = jnp.asarray(sample_rng) if self.training_config.sampling_type == "full": batch_sampled, batch_sampled_last, batch_sampled_all = sampling_fn( sample_fn, (sample_rng, state), p_batch_input ) elif self.training_config.sampling_type == "colorization": batch_grayscale = to_grayscale(batch) batch_grayscale = batch_grayscale.reshape(-1, b, g, 1) batch_sampled, batch_sampled_last, batch_sampled_all = colorizing_fn( sample_fn, (sample_rng, state), p_batch_input, batch_grayscale ) elif self.training_config.sampling_type == "inpainting": config_object = OmegaConf.create( { "_target_": "functional_diffusion_processes.datasets.mnist_dataset.MNISTDataset", "data_config": { "seed": 42, "batch_size": ds_train.data_config.batch_size, "image_height_size": ds_train.data_config.image_height_size, "image_width_size": ds_train.data_config.image_width_size, "output_size": 1, "random_flip": False, "uniform_dequantization": False, "data_centered": False, "data_dir": "${oc.env:DATA_ROOT}/tensorflow_datasets", "download": True, "is_mask": True, }, "split": "train", "evaluation": False, } ) ds_mask = hydra.utils.instantiate(config_object, _recursive_=False) ds_mask_iter = iter(ds_mask) batch_masked = jax.tree_map(f=lambda x: x._numpy(), tree=next(ds_mask_iter)["data"]) batch_sampled, batch_sampled_last, batch_sampled_all = inpainting_fn( sample_fn, (sample_rng, state), p_batch_input, (batch * batch_masked), batch_masked ) elif self.training_config.sampling_type == "deblurring": n_rows, n_cols = ds_train.data_config.image_height_size, ds_train.data_config.image_width_size batch_masked = filter_mask(batch.reshape(-1, b, n_rows, n_cols, c).shape, radius=10) batch_freq = jnp.fft.fftshift( jnp.fft.fft2(batch.reshape(-1, b, n_rows, n_cols, c), axes=(2, 3)), axes=(2, 3), ) batch_freq = batch_freq * batch_masked batch_blurred = jnp.real(jnp.fft.ifft2(jnp.fft.ifftshift(batch_freq, axes=(2, 3)), axes=(2, 3))) batch_blurred = batch_blurred.reshape(-1, b, g, c) batch_masked = batch_masked.reshape(-1, b, g, c) batch_sampled, batch_sampled_last, batch_sampled_all = inpainting_fn( sample_fn, (sample_rng, state), p_batch_input, batch_blurred, batch_masked ) if jax.host_id() == 0 and self.logging.use_wandb: if isinstance(ds_train, ImageDataset): this_sample_dir = os.path.join( self.sample_dir, "iter_{}_host_{}".format(step, jax.host_id()), ) tf.io.gfile.makedirs(this_sample_dir) # code below to show the gif of the sampled images # processed_images = [] # for n in range(batch_sampled_all.shape[1]): # batch_sampled_i = batch_sampled_all[:, n, :, :, :] # batch_sampled_i = ds_train.postprocess_fn( # batch_data=batch_sampled_i, inverse_scaler=inverse_scaler # ) # processed_images.append(np.asarray(batch_sampled_i)) # # # Log the sampled images as a GIF # imageio.mimwrite( # os.path.join(this_sample_dir, "image_sequence.gif"), # processed_images, # fps=10, # ) # gif_wandb = wandb.Image( # os.path.join(this_sample_dir, "image_sequence.gif"), # caption="Sampled_all_gif", # ) # wandb.log({"Sampled_all_gif": gif_wandb}, step=step) batch_sampled = ds_train.postprocess_fn(batch_data=batch_sampled, inverse_scaler=inverse_scaler) batch_sampled_last = ds_train.postprocess_fn( batch_data=batch_sampled_last, inverse_scaler=inverse_scaler ) batch_real = ds_train.postprocess_fn( batch_data=batch.reshape(-1, b, g, c), inverse_scaler=inverse_scaler ) if not self.training_config.sampling_only: batch_target = ds_train.postprocess_fn( batch_data=target.reshape(-1, b, g, c), inverse_scaler=inverse_scaler ) if isinstance(ds_train, ImageDataset): data_sampled = wandb.Image(np.asarray(batch_sampled), caption="Sampled") data_sampled_rec = wandb.Image(np.asarray(batch_sampled_last), caption="Sampled Rec") data_real = wandb.Image(np.asarray(batch_real), caption="Real") if not self.training_config.sampling_only: data_target = wandb.Image(np.asarray(batch_target), caption="Target") elif isinstance(ds_train, AudioDataset): sample_rate = ds_train.data_config.audio_sample_rate long_audio_sampled = np.concatenate( np.asarray(batch_sampled).reshape(-1, sample_rate), axis=0 ) data_sampled = wandb.Audio(long_audio_sampled, sample_rate=sample_rate, caption="Sampled") if not self.training_config.sampling_only: long_audio_target = np.concatenate( np.asarray(batch_target).reshape(-1, sample_rate), axis=0 ) data_target = wandb.Audio(long_audio_target, sample_rate=sample_rate, caption="Target") long_audio_batch_sampled_rec = np.concatenate( np.asarray(batch_sampled_last).reshape(-1, sample_rate), axis=0 ) data_sampled_rec = wandb.Audio( long_audio_batch_sampled_rec, sample_rate=sample_rate, caption="Sampled Rec" ) long_audio_batch_real = np.concatenate( np.asarray(batch_real).reshape(-1, sample_rate), axis=0 ) data_real = wandb.Audio(long_audio_batch_real, sample_rate=sample_rate, caption="Real") else: raise ValueError("Unsupported dataset type: {}".format(type(ds_train))) wandb.log({"Sampled": data_sampled}, step=step) if not self.training_config.sampling_only: wandb.log({"Target": data_target}, step=step) wandb.log({"Sampled_rec": data_sampled_rec}, step=step) wandb.log({"Real": data_real}, step=step) if self.training_config.sampling_type == "colorization": batch_gray = make_grid_image( batch_grayscale.reshape( -1, ds_train.data_config.image_width_size, ds_train.data_config.image_height_size, 1, ), inverse_scaler=inverse_scaler, ) image_gray = wandb.Image(np.asarray(batch_gray), caption="Gray") wandb.log({"Gray": image_gray}, step=step) elif self.training_config.sampling_type == "inpainting": batch_masked = make_grid_image( ndarray=process_images(images=batch_masked * batch - (1 - batch_masked)), inverse_scaler=inverse_scaler, ) image_masked = wandb.Image(np.asarray(batch_masked), caption="Masked") wandb.log({"Masked": image_masked}, step=step) elif self.training_config.sampling_type == "deblurring": batch_blurred = make_grid_image( ndarray=process_images(images=batch_blurred), inverse_scaler=inverse_scaler, ) image_blurred = wandb.Image(np.asarray(batch_blurred), caption="Blurred") wandb.log({"Blurred": image_blurred}, step=step) if not self.training_config.sampling_only: batch_reconstructed = ds_train.postprocess_fn( batch_data=batch_reconstructed.reshape(-1, b, g, c), inverse_scaler=inverse_scaler ) batch_corrupted = ds_train.postprocess_fn( batch_data=batch_corrupted.reshape(-1, b, g, c), inverse_scaler=inverse_scaler ) batch_real = ds_train.postprocess_fn( batch_data=batch.reshape(-1, b, g, c), inverse_scaler=inverse_scaler ) if isinstance(ds_train, ImageDataset): data_reconstructed = wandb.Image(np.asarray(batch_reconstructed), caption="Reconstructed") data_corrupted = wandb.Image(np.asarray(batch_corrupted), caption="Corrupted") data_real = wandb.Image(np.asarray(batch_real), caption="Real") elif isinstance(ds_train, AudioDataset): sample_rate = ds_train.data_config.audio_sample_rate long_audio_batch_reconstructed = np.concatenate( np.asarray(batch_reconstructed).reshape(-1, sample_rate), axis=0 ) data_reconstructed = wandb.Audio( long_audio_batch_reconstructed, sample_rate=sample_rate, caption="Reconstructed" ) long_audio_batch_corrupted = np.concatenate( np.asarray(batch_corrupted).reshape(-1, sample_rate), axis=0 ) data_corrupted = wandb.Audio( long_audio_batch_corrupted, sample_rate=sample_rate, caption="Corrupted" ) long_audio_batch_real = np.concatenate( np.asarray(batch_real).reshape(-1, sample_rate), axis=0 ) data_real = wandb.Audio(long_audio_batch_real, sample_rate=sample_rate, caption="Real") else: raise ValueError("Unsupported dataset type: {}".format(type(ds_train))) wandb.log({"Reconstructed": data_reconstructed}, step=step) wandb.log({"Corrupted": data_corrupted}, step=step) wandb.log({"Real": data_real}, step=step) # Update the progress bar pbar.update() wandb.finish() def evaluate( self, model: flax.linen.Module, ds_test: BaseDataset, fid_metric: FIDMetric, sde: SDE, ) -> None: """Evaluate the model on the test dataset. Args: model: The model to be evaluated. ds_test: The test dataset. fid_metric: The FID metric. sde: The SDE. """ run, _, inverse_scaler, rng, state, _, sample_fn, batch_input = self.initialize_run(model, ds_test, sde) # Replicate the train state on all devices (p_ema_params, p_params, p_opt_state_params, p_step, p_batch_input) = flax_utils.replicate( (state.ema_params, state.params, state.opt_state_params, state.step, batch_input) ) # update the TrainState with replicated parameters and optimizer state state = state.replace( params=p_params, opt_state_params=p_opt_state_params, step=p_step, ema_params=p_ema_params, ) # Create different random states for different hosts in a multi-host environment (e.g., TPU pods) rng = jax.random.fold_in(rng, jax.host_id()) # A data class for storing intermediate results to resume evaluation after pre-emption @flax.struct.dataclass class EvalMeta: sampling_round_id: int rng: Any num_sampling_rounds = ( self.evaluation_config.num_samples // (ds_test.data_config.batch_size * jax.device_count()) + 1 ) # Restore evaluation after pre-emption eval_meta = EvalMeta(sampling_round_id=-1, rng=rng) eval_meta = checkpoints.restore_checkpoint(self.eval_dir, eval_meta, step=None, prefix=f"meta_{jax.host_id()}_") if eval_meta.sampling_round_id < num_sampling_rounds - 1: begin_sampling_round = eval_meta.sampling_round_id + 1 else: begin_sampling_round = 0 rng = eval_meta.rng if jax.host_id() == 0: pylogger.info("Starting sampling loop at step %d." % (begin_sampling_round,)) # Create a progress bar for tracking the training progress pbar = tqdm( total=num_sampling_rounds, initial=begin_sampling_round, position=0, leave=True, ) for i in range(begin_sampling_round, num_sampling_rounds): if jax.host_id() == 0: pylogger.info("sampling -- round: %d" % i) this_sample_dir = os.path.join(self.eval_dir, f"ckpt_host_{jax.host_id()}") tf.io.gfile.makedirs(this_sample_dir) rng, *rng_s = jax.random.split(rng, jax.device_count() + 1) rng_s = jnp.asarray(rng_s) if not tf.io.gfile.exists(os.path.join(self.eval_dir, f"samples_{i}.npz")): batch_sampled, batch_sampled_last, _ = sampling_fn(sample_fn, (rng_s, state), p_batch_input) samples = inverse_scaler(batch_sampled_last) if isinstance(ds_test, ImageDataset): samples = np.clip(samples * 255.0, 0, 255).astype(np.uint8) samples = process_images(images=samples) elif isinstance(ds_test, AudioDataset): min_intensity = ds_test.data_config.min_intensity max_intensity = ds_test.data_config.max_intensity samples = np.clip( samples * (max_intensity - min_intensity) + min_intensity, min_intensity, max_intensity )
save_samples(
10
2023-10-24 22:01:35+00:00
24k
violet-sto/HN-GFN
main_mobo.py
[ { "identifier": "Dataset", "path": "dataset.py", "snippet": "class Dataset:\n\n def __init__(self, args, bpath, oracle, device):\n self.test_split_rng = np.random.RandomState(142857)\n self.train_rng = np.random.RandomState(int(time.time()))\n self.train_mols = []\n self.test_mols = []\n self.all_mols = []\n self.train_mols_map = {}\n\n self.mdp = MolMDPExtended(bpath)\n self.mdp.post_init(device, args.proxy_repr_type, include_nblocks=args.include_nblocks)\n self.mdp.build_translation_table()\n if args.floatX == 'float64':\n self.mdp.floatX = torch.double\n else:\n self.mdp.floatX = torch.float\n self.mdp._cue_max_blocks = args.max_blocks\n self.max_blocks = args.max_blocks\n self.oracle = oracle\n self._device = device\n self.seen_molecules = set()\n self.stop_event = threading.Event()\n\n self.target_norm = [-8.6, 1.10] # for dockerscore\n\n self.hypervolume = Hypervolume(ref_point=torch.zeros(len(args.objectives)))\n\n def load_h5(self, path, test_ratio=0.1, num_init_examples=None):\n import json\n columns = [\"smiles\", \"dockscore\",\"blockidxs\", \"slices\", \"jbonds\", \"stems\"]\n store = pd.HDFStore(path, 'r')\n df = store.select('df')\n # Pandas has problem with calculating some stuff on float16\n df.dockscore = df.dockscore.astype(\"float64\")\n for cl_mame in columns[2:]:\n df.loc[:, cl_mame] = df[cl_mame].apply(json.loads)\n\n test_idxs = self.test_split_rng.choice(\n len(df), int(test_ratio * len(df)), replace=False)\n\n split_bool = np.zeros(len(df), dtype=np.bool)\n split_bool[test_idxs] = True\n self.scores = []\n self.smis = []\n for i in tqdm(range(len(df))):\n m = BlockMoleculeDataExtended()\n for c in range(1, len(columns)):\n setattr(m, columns[c], df.iloc[i, c - 1])\n m.blocks = [self.mdp.block_mols[i] for i in m.blockidxs]\n if len(m.blocks) > self.max_blocks:\n continue\n m.numblocks = len(m.blocks)\n m.score = self.oracle.get_score([m])\n self.scores.append(m.score)\n self.smis.append(m.smiles)\n self.all_mols.append(m)\n if split_bool[i]: \n self.test_mols.append(m)\n else:\n self.train_mols.append(m)\n if len(self.train_mols)+len(self.test_mols) >= num_init_examples:\n break\n store.close()\n\n print(\"Sampling initial {} molecules from all {} molecules...\".format(\n num_init_examples, len(split_bool)))\n print(len(self.train_mols), 'train mols')\n print(len(self.test_mols), 'test mols')\n\n def r2r(self, dockscore=None, normscore=None):\n if dockscore is not None:\n normscore = 4-(min(0, dockscore) -\n self.target_norm[0])/self.target_norm[1]\n normscore = max(0.1, normscore)\n return (normscore/1) ** 1\n\n def _get(self, i, dset):\n return [(dset[i], dset[i].score)]\n\n def sample(self, n):\n eidx = np.random.randint(0, len(self.train_mols), n)\n samples = sum((self._get(i, self.train_mols) for i in eidx), [])\n\n return zip(*samples)\n\n def sample2batch(self, mb):\n s, r = mb\n s = self.mdp.mols2batch([self.mdp.mol2repr(i) for i in s])\n r = torch.tensor(pd.DataFrame.from_dict(\n r).values, device=self._device).float()\n return (s, r)\n\n def iterset(self, n, mode):\n if mode == 'test':\n dset = self.test_mols\n elif mode == 'train':\n dset = self.train_mols\n\n N = len(dset)\n for i in range(int(np.ceil(N/n))):\n samples = sum((self._get(j, dset)\n for j in range(i*n, min(N, (i+1)*n))), [])\n yield self.sample2batch(zip(*samples))\n\n def add_samples(self, batch):\n picked_mols, scores, picked_smis = batch\n\n for m in picked_mols:\n if np.random.uniform() < (1/10):\n self.test_mols.append(m)\n else:\n self.train_mols.append(m)\n self.all_mols.append(m)\n \n self.scores += scores\n self.smis += [smis[-1] for smis in picked_smis]\n \n self.stop_event.clear()\n\n def compute_hypervolume(self):\n scores = torch.tensor(pd.DataFrame.from_dict(self.scores).values)\n volume = self.hypervolume.compute(scores)\n\n return volume\n \n def start_samplers(self, n, mbsize):\n self.ready_events = [threading.Event() for i in range(n)]\n self.resume_events = [threading.Event() for i in range(n)]\n self.results = [None] * n\n def f(idx):\n while not self.stop_event.is_set():\n try:\n self.results[idx] = self.sample2batch(self.sample(mbsize))\n except Exception as e:\n print(\"Exception while sampling:\")\n print(e)\n self.sampler_threads[idx].failed = True\n self.sampler_threads[idx].exception = e\n self.ready_events[idx].set()\n break\n self.ready_events[idx].set()\n self.resume_events[idx].clear()\n self.resume_events[idx].wait()\n self.sampler_threads = [threading.Thread(target=f, args=(i,)) for i in range(n)]\n [setattr(i, 'failed', False) for i in self.sampler_threads]\n [i.start() for i in self.sampler_threads]\n round_robin_idx = [0]\n def get():\n while True:\n idx = round_robin_idx[0]\n round_robin_idx[0] = (round_robin_idx[0] + 1) % n\n if self.ready_events[idx].is_set():\n r = self.results[idx]\n self.ready_events[idx].clear()\n self.resume_events[idx].set()\n return r\n elif round_robin_idx[0] == 0:\n time.sleep(0.001)\n return get\n\n def stop_samplers_and_join(self):\n self.stop_event.set()\n if hasattr(self, 'sampler_threads'):\n while any([i.is_alive() for i in self.sampler_threads]):\n [i.set() for i in self.resume_events]\n [i.join(0.05) for i in self.sampler_threads]" }, { "identifier": "MolMDPExtended", "path": "mol_mdp_ext.py", "snippet": "class MolMDPExtended(MolMDP):\n\n def build_translation_table(self):\n \"\"\"build a symmetry mapping for blocks. Necessary to compute parent transitions\"\"\"\n self.translation_table = {}\n for blockidx in range(len(self.block_mols)):\n # Blocks have multiple ways of being attached. By default,\n # a new block is attached to the target stem by attaching\n # it's kth atom, where k = block_rs[new_block_idx][0].\n # When computing a reverse action (from a parent), we may\n # wish to attach the new block to a different atom. In\n # the blocks library, there are duplicates of the same\n # block but with block_rs[block][0] set to a different\n # atom. Thus, for the reverse action we have to find out\n # which duplicate this corresponds to.\n\n # Here, we compute, for block blockidx, what is the index\n # of the duplicate block, if someone wants to attach to\n # atom x of the block.\n # So atom_map[x] == bidx, such that block_rs[bidx][0] == x\n atom_map = {}\n for j in range(len(self.block_mols)):\n if self.block_smi[blockidx] == self.block_smi[j]:\n atom_map[self.block_rs[j][0]] = j\n self.translation_table[blockidx] = atom_map\n\n # We're still missing some \"duplicates\", as some might be\n # symmetric versions of each other. For example, block CC with\n # block_rs == [0,1] has no duplicate, because the duplicate\n # with block_rs [1,0] would be a symmetric version (both C\n # atoms are the \"same\").\n\n # To test this, let's create nonsense molecules by attaching\n # duplicate blocks to a Gold atom, and testing whether they\n # are the same.\n gold = Chem.MolFromSmiles('[Au]')\n # If we find that two molecules are the same when attaching\n # them with two different atoms, then that means the atom\n # numbers are symmetries. We can add those to the table.\n for blockidx in range(len(self.block_mols)):\n for j in self.block_rs[blockidx]:\n if j not in self.translation_table[blockidx]:\n symmetric_duplicate = None\n for atom, block_duplicate in self.translation_table[blockidx].items():\n molA, _ = chem.mol_from_frag(\n jun_bonds=[[0,1,0,j]],\n frags=[gold, self.block_mols[blockidx]])\n molB, _ = chem.mol_from_frag(\n jun_bonds=[[0,1,0,atom]],\n frags=[gold, self.block_mols[blockidx]])\n if (Chem.MolToSmiles(molA) == Chem.MolToSmiles(molB) or\n molA.HasSubstructMatch(molB)):\n symmetric_duplicate = block_duplicate\n break\n if symmetric_duplicate is None:\n raise ValueError('block', blockidx, self.block_smi[blockidx],\n 'has no duplicate for atom', j,\n 'in position 0, and no symmetrical correspondance')\n self.translation_table[blockidx][j] = symmetric_duplicate\n #print('block', blockidx, '+ atom', j,\n # 'in position 0 is a symmetric duplicate of',\n # symmetric_duplicate)\n\n def parents(self, mol=None):\n \"\"\"returns all the possible parents of molecule mol (or the current\n molecule if mol is None.\n\n Returns a list of (BlockMoleculeDataExtended, (block_idx, stem_idx)) pairs such that\n for a pair (m, (b, s)), MolMDPExtended.add_block_to(m, b, s) == mol.\n \"\"\"\n if len(mol.blockidxs) == 1:\n # If there's just a single block, then the only parent is\n # the empty block with the action that recreates that block\n return [(BlockMoleculeDataExtended(), (mol.blockidxs[0], 0))]\n\n # Compute the how many blocks each block is connected to\n blocks_degree = defaultdict(int)\n for a,b,_,_ in mol.jbonds:\n blocks_degree[a] += 1\n blocks_degree[b] += 1\n # Keep only blocks of degree 1 (those are the ones that could\n # have just been added)\n blocks_degree_1 = [i for i, d in blocks_degree.items() if d == 1]\n # Form new molecules without these blocks\n parent_mols = []\n\n for rblockidx in blocks_degree_1:\n new_mol = mol.copy()\n # find which bond we're removing\n removed_bonds = [(jbidx, bond) for jbidx, bond in enumerate(new_mol.jbonds)\n if rblockidx in bond[:2]]\n assert len(removed_bonds) == 1\n rjbidx, rbond = removed_bonds[0]\n # Pop the bond\n new_mol.jbonds.pop(rjbidx)\n # Remove the block\n mask = np.ones(len(new_mol.blockidxs), dtype=np.bool)\n mask[rblockidx] = 0\n reindex = new_mol.delete_blocks(mask)\n # reindex maps old blockidx to new blockidx, since the\n # block the removed block was attached to might have its\n # index shifted by 1.\n\n # Compute which stem the bond was using\n stem = ([reindex[rbond[0]], rbond[2]] if rblockidx == rbond[1] else\n [reindex[rbond[1]], rbond[3]])\n # and add it back\n new_mol.stems = [list(i) for i in new_mol.stems] + [stem]\n #new_mol.stems.append(stem)\n # and we have a parent. The stem idx to recreate mol is\n # the last stem, since we appended `stem` in the back of\n # the stem list.\n # We also have to translate the block id to match the bond\n # we broke, see build_translation_table().\n removed_stem_atom = (\n rbond[3] if rblockidx == rbond[1] else rbond[2])\n blockid = mol.blockidxs[rblockidx]\n if removed_stem_atom not in self.translation_table[blockid]:\n raise ValueError('Could not translate removed stem to duplicate or symmetric block.')\n parent_mols.append([new_mol,\n # action = (block_idx, stem_idx)\n (self.translation_table[blockid][removed_stem_atom],\n len(new_mol.stems) - 1)])\n if not len(parent_mols):\n raise ValueError('Could not find any parents')\n return parent_mols\n\n\n def add_block_to(self, mol, block_idx, stem_idx=None, atmidx=None):\n '''out-of-place version of add_block'''\n #assert (block_idx >= 0) and (block_idx <= len(self.block_mols)), \"unknown block\"\n if mol.numblocks == 0:\n stem_idx = None\n new_mol = mol.copy()\n new_mol.add_block(block_idx,\n block=self.block_mols[block_idx],\n block_r=self.block_rs[block_idx],\n stem_idx=stem_idx, atmidx=atmidx)\n return new_mol\n\n def remove_jbond_from(self, mol, jbond_idx=None, atmidx=None):\n new_mol = mol.copy()\n new_mol.remove_jbond(jbond_idx, atmidx)\n return new_mol\n\n def a2mol(self, acts):\n mol = BlockMoleculeDataExtended()\n for i in acts:\n if i[0] >= 0:\n mol = self.add_block_to(mol, *i)\n return mol\n\n def reset(self):\n self.molecule = BlockMoleculeDataExtended()\n return None\n\n\n def post_init(self, device, repr_type, include_bonds=False, include_nblocks=False):\n self.device = device\n self.repr_type = repr_type\n #self.max_bond_atmidx = max([max(i) for i in self.block_rs])\n self.max_num_atm = max(self.block_natm)\n # see model_block.mol2graph\n self.true_block_set = sorted(set(self.block_smi))\n self.stem_type_offset = np.int32([0] + list(np.cumsum([\n max(self.block_rs[self.block_smi.index(i)])+1 for i in self.true_block_set])))\n self.num_stem_types = self.stem_type_offset[-1]\n self.true_blockidx = [self.true_block_set.index(i) for i in self.block_smi]\n self.num_true_blocks = len(self.true_block_set)\n self.include_nblocks = include_nblocks\n self.include_bonds = include_bonds\n #print(self.max_num_atm, self.num_stem_types)\n self.molcache = {}\n\n def mols2batch(self, mols):\n if self.repr_type == 'block_graph':\n return model_block.mols2batch(mols, self)\n elif self.repr_type == 'atom_graph':\n return model_atom.mols2batch(mols, self)\n elif self.repr_type == 'morgan_fingerprint':\n return model_fingerprint.mols2batch(mols, self)\n\n def mol2repr(self, mol=None):\n if mol is None:\n mol = self.molecule\n #molhash = str(mol.blockidxs)+':'+str(mol.stems)+':'+str(mol.jbonds)\n #if molhash in self.molcache:\n # return self.molcache[molhash]\n if self.repr_type == 'block_graph':\n r = model_block.mol2graph(mol, self, self.floatX)\n elif self.repr_type == 'atom_graph':\n r = model_atom.mol2graph(mol, self, self.floatX,\n bonds=self.include_bonds,\n nblocks=self.include_nblocks)\n elif self.repr_type == 'morgan_fingerprint':\n r = model_fingerprint.mol2fp(mol, self, self.floatX)\n #self.molcache[molhash] = r\n return r\n\n def get_nx_graph(self, mol: BlockMoleculeData, true_block=False):\n true_blockidx = self.true_blockidx\n\n G = nx.DiGraph()\n blockidxs = [true_blockidx[xx] for xx in mol.blockidxs] if true_block else mol.blockidxs\n\n G.add_nodes_from([(ix, {\"block\": blockidxs[ix]}) for ix in range(len(blockidxs))])\n\n if len(mol.jbonds) > 0:\n edges = []\n for jbond in mol.jbonds:\n edges.append((jbond[0], jbond[1],\n {\"bond\": [jbond[2], jbond[3]]}))\n edges.append((jbond[1], jbond[0],\n {\"bond\": [jbond[3], jbond[2]]}))\n G.add_edges_from(edges)\n return G\n\n def graphs_are_isomorphic(self, g1, g2):\n return nx.algorithms.is_isomorphic(g1, g2, node_match=node_match, edge_match=edge_match)" }, { "identifier": "BlockMoleculeDataExtended", "path": "mol_mdp_ext.py", "snippet": "class BlockMoleculeDataExtended(BlockMoleculeData):\n\n @property\n def mol(self):\n return chem.mol_from_frag(jun_bonds=self.jbonds, frags=self.blocks)[0]\n\n @property\n def smiles(self):\n return Chem.MolToSmiles(self.mol)\n\n def copy(self): # shallow copy\n o = BlockMoleculeDataExtended()\n o.blockidxs = list(self.blockidxs)\n o.blocks = list(self.blocks)\n o.slices = list(self.slices)\n o.numblocks = self.numblocks\n o.jbonds = list(self.jbonds)\n o.stems = list(self.stems)\n return o\n\n def as_dict(self):\n return {'blockidxs': self.blockidxs,\n 'slices': self.slices,\n 'numblocks': self.numblocks,\n 'jbonds': self.jbonds,\n 'stems': self.stems}" }, { "identifier": "Oracle", "path": "oracle/oracle.py", "snippet": "class Oracle():\n def __init__(self, args, mols_ref=None):\n '''\n @params:\n args (dict): argsurations\n '''\n self.objectives = args.objectives\n self.fps_ref = [AllChem.GetMorganFingerprintAsBitVect(x, 3, 2048) \n for x in mols_ref] if mols_ref else None\n self.device = torch.device(args.device)\n\n def batch_get_scores(self, mols):\n '''\n @params:\n mols: molecules to estimate score\n @return:\n dicts (list): list of score dictionaries\n '''\n dicts = [{} for _ in mols]\n for obj in self.objectives:\n scores = get_scores(obj, mols, device=self.device)\n for i, mol in enumerate(mols):\n dicts[i][obj] = scores[i]\n return dicts\n \n def get_score(self, mol):\n scores = {}\n for obj in self.objectives:\n score = get_scores(obj, mol, device=self.device)\n scores[obj] = score[0]\n \n return scores" }, { "identifier": "get_proxy", "path": "proxy/proxy.py", "snippet": "def get_proxy(args, bpath, oracle):\n if args.acq_fn.lower() == 'none':\n return NoAF(args, bpath, oracle)\n\n elif args.acq_fn.lower() == 'ucb':\n return UCB(args, bpath, oracle)\n \n elif args.acq_fn.lower() == 'ucb_chebyshev':\n return UCB_chebyshev(args, bpath, oracle)\n\n elif args.acq_fn.lower() == 'ei':\n return EI(args, bpath, oracle)" }, { "identifier": "FMGFlowNet", "path": "generator/gfn.py", "snippet": "class FMGFlowNet(nn.Module):\n def __init__(self, args, bpath):\n super().__init__()\n self.args = args\n mdp = MolMDPExtended(bpath)\n mdp.post_init(args.device, args.repr_type,\n include_nblocks=args.include_nblocks)\n mdp.build_translation_table()\n self.model = make_model(args, mdp, is_proxy=False)\n self.opt = torch.optim.Adam(self.model.parameters(\n ), args.learning_rate, weight_decay=args.weight_decay)\n\n self.loginf = 1000 # to prevent nans\n self.log_reg_c = args.log_reg_c\n self.balanced_loss = args.balanced_loss\n self.do_nblocks_reg = False\n self.max_blocks = args.max_blocks\n self.leaf_coef = args.leaf_coef\n self.clip_grad = args.clip_grad\n # self.score_criterion = nn.MSELoss(reduction='none')\n self.score_criterion = nn.MSELoss()\n\n def forward(self, graph_data, vec_data=None, do_stems=True):\n return self.model(graph_data, vec_data, do_stems)\n\n def train_step(self, p, pb, a, pw, w, r, s, d, mols, i):\n loss, term_loss, flow_loss = self.FMLoss(p, pb, a, pw, w, r, s, d)\n\n self.opt.zero_grad()\n loss.backward()\n if self.clip_grad > 0:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.clip_grad)\n self.opt.step()\n self.model.training_steps = i+1\n \n return (loss.item(), term_loss.item(), flow_loss.item())\n\n def FMLoss(self, p, pb, a, pw, w, r, s, d):\n # Since we sampled 'mbsize' trajectories, we're going to get\n # roughly mbsize * H (H is variable) transitions\n ntransitions = r.shape[0]\n # state outputs\n stem_out_s, mol_out_s = self.model(s, w) # log(F)\n # parents of the state outputs\n stem_out_p, mol_out_p = self.model(p, pw)\n # index parents by their corresponding actions\n qsa_p = self.model.index_output_by_action(\n p, stem_out_p, mol_out_p[:, 0], a)\n # then sum the parents' contribution, this is the inflow\n exp_inflow = (torch.zeros((ntransitions,), device=qsa_p.device, dtype=qsa_p.dtype)\n .index_add_(0, pb, torch.exp(qsa_p))) # pb is the parents' batch index\n inflow = torch.log(exp_inflow + self.log_reg_c)\n # sum the state's Q(s,a), this is the outflow\n exp_outflow = self.model.sum_output(s, torch.exp(\n stem_out_s), torch.exp(mol_out_s[:, 0]))\n # include reward and done multiplier, then take the log\n # we're guarenteed that r > 0 iff d = 1, so the log always works\n outflow_plus_r = torch.log(self.log_reg_c + r + exp_outflow * (1-d))\n if self.do_nblocks_reg:\n losses = _losses = ((inflow - outflow_plus_r) /\n (s.nblocks * self.max_blocks)).pow(2)\n else:\n losses = _losses = (inflow - outflow_plus_r).pow(2)\n\n term_loss = (losses * d).sum() / (d.sum() + 1e-20) # terminal nodes\n flow_loss = (losses * (1-d)).sum() / \\\n ((1-d).sum() + 1e-20) # non-terminal nodes\n \n if self.balanced_loss:\n loss = term_loss * self.leaf_coef + flow_loss\n else:\n loss = losses.mean()\n\n return loss, term_loss, flow_loss" }, { "identifier": "TBGFlowNet", "path": "generator/gfn.py", "snippet": "class TBGFlowNet(nn.Module):\n def __init__(self, args, bpath):\n super().__init__()\n self.args = args\n self.mdp = MolMDPExtended(bpath)\n self.mdp.post_init(args.device, args.repr_type,\n include_nblocks=args.include_nblocks)\n self.mdp.build_translation_table()\n self.model = make_model(args, self.mdp, is_proxy=False)\n self.Z = nn.Sequential(nn.Linear(len(args.objectives), args.nemb//2), nn.LeakyReLU(),\n nn.Linear(args.nemb//2, 1))\n self.Z.to(args.device)\n self.opt = torch.optim.Adam(self.model.parameters(), args.learning_rate, weight_decay=args.weight_decay)\n self.opt_Z = torch.optim.Adam(self.Z.parameters(), args.Z_learning_rate, weight_decay=args.weight_decay)\n\n def forward(self, graph_data, vec_data=None, do_stems=True):\n return self.model(graph_data, vec_data, do_stems)\n\n def train_step(self, p, pb, a, pw, w, r, s, d, mols, i):\n loss = self.TBLoss(p, a, w, r, d, mols)\n self.opt.zero_grad()\n self.opt_Z.zero_grad()\n loss.backward()\n if self.args.clip_grad > 0:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.args.clip_grad)\n self.opt.step()\n self.opt_Z.step()\n\n return (loss.item(),)\n\n @property\n def Z(self):\n return self.model.Z\n\n def TBLoss(self, p, a, w, r, d, mols):\n # logit\n stem_out_p, mol_out_p = self.model(p, w)\n # index parents by their corresponding actions\n logits = -self.model.action_negloglikelihood(\n p, a, stem_out_p, mol_out_p)\n\n b = torch.cat([torch.tensor([0], device=logits.device),\n torch.cumsum(d.long(), 0)[:-1]], dim=0)\n n = torch.tensor([len(self.mdp.parents(mol)) if a[idx, 0].item() != -1 else 1.\n for idx, mol in enumerate(mols[1])], device=logits.device)\n # n = torch.tensor([len(self.mdp.parents(mol)) for mol in mols[1]], device=logits.device)\n forward_ll = scatter(logits, b, reduce='sum')\n backward_ll = scatter(torch.log(1/n), b, reduce='sum')\n\n losses = ((self.Z(w[d==1.]) + forward_ll) - (torch.log(r[d == 1.]) + backward_ll)).pow(2) \n loss = losses.mean()\n\n return loss" }, { "identifier": "MOReinforce", "path": "generator/gfn.py", "snippet": "class MOReinforce(TBGFlowNet):\n def TBLoss(self, p, a, w, r, d, mols):\n # logit\n stem_out_p, mol_out_p = self.model(p, w)\n # index parents by their corresponding actions\n logits = -self.model.action_negloglikelihood(\n p, a, stem_out_p, mol_out_p)\n\n b = torch.cat([torch.tensor([0], device=logits.device),\n torch.cumsum(d.long(), 0)[:-1]], dim=0)\n n = torch.tensor([len(self.mdp.parents(mol)) if a[idx, 0].item() != -1 else 1.\n for idx, mol in enumerate(mols[1])], device=logits.device)\n # n = torch.tensor([len(self.mdp.parents(mol)) for mol in mols[1]], device=logits.device)\n forward_ll = scatter(logits, b, reduce='sum')\n\n rewards = r[d == 1.]\n losses = forward_ll * (-rewards - (-1) * rewards.mean())\n loss = losses.mean()\n\n return loss" }, { "identifier": "set_random_seed", "path": "utils/utils.py", "snippet": "def set_random_seed(seed, deterministic=True):\n \"\"\"Set random seed.\"\"\"\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n if deterministic:\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False" }, { "identifier": "compute_success", "path": "utils/metrics.py", "snippet": "def compute_success(mols, scores, objectives, score_succ):\n print(\"Computing successful rate...\")\n positive_mols = []\n success_dict = {k: 0. for k in objectives}\n\n for mol, score in zip(mols, scores):\n all_success = True\n for k, v in score.items():\n if v >= score_succ[k]:\n success_dict[k] += 1\n else:\n all_success = False\n if all_success:\n positive_mols.append(mol)\n\n success = 1.*len(positive_mols)/len(mols)\n\n return success, positive_mols" }, { "identifier": "compute_diversity", "path": "utils/metrics.py", "snippet": "def compute_diversity(mols):\n print(\"Computing diversity...\")\n\n if len(mols) == 0:\n return 0\n\n sims = []\n fps = [AllChem.GetMorganFingerprintAsBitVect(x.mol, 3, 2048) for x in mols]\n for i in range(len(fps)):\n sims += DataStructs.BulkTanimotoSimilarity(fps[i], fps[:i])\n\n return 1 - np.mean(sims)" }, { "identifier": "compute_novelty", "path": "utils/metrics.py", "snippet": "def compute_novelty(mols, ref_mols):\n print(\"Computing novelty...\")\n positive_fps = [AllChem.GetMorganFingerprintAsBitVect(\n x.mol, 3, 2048) for x in mols]\n ref_fps = [AllChem.GetMorganFingerprintAsBitVect(\n x, 3, 2048) for x in ref_mols]\n\n n_sim = 0.\n for i in range(len(positive_fps)):\n sims = DataStructs.BulkTanimotoSimilarity(positive_fps[i], ref_fps)\n if max(sims) >= 0.4:\n n_sim += 1\n novelty = 1. - 1. * n_sim / (len(positive_fps)+1e-6)\n\n return novelty" }, { "identifier": "compute_correlation", "path": "utils/metrics.py", "snippet": "def compute_correlation(args, model, rollout_worker, test_mols):\n\n mdp = rollout_worker.mdp\n device = args.device\n def tf(x): return torch.tensor(x, device=device).to(torch.float)\n def tint(x): return torch.tensor(x, device=device).long()\n\n # test_mols = pickle.load(gzip.open('data/some_mols_U_1k.pkl.gz'))\n logsoftmax = nn.LogSoftmax(0)\n corrs = []\n numblocks = []\n\n start_time = time.time()\n if args.n_objectives == 3:\n test_weights = rollout_worker.test_weights[::2]\n elif args.n_objectives == 4:\n test_weights = rollout_worker.test_weights[1:-2:4]\n else:\n test_weights = rollout_worker.test_weights\n \n for weights in test_weights:\n print(\"Computing correlation w.r.t test weights {}\".format(weights))\n weights = torch.tensor(weights).to(args.device)\n logp = []\n rewards = []\n for m in tqdm(test_mols):\n try:\n agraph = get_mol_path_graph(m, mdp)\n except:\n continue\n # rewards.append(np.log(moli[0][0]))\n reward = rollout_worker._get_reward(m, weights)[0].item()\n rewards.append(np.log(reward))\n s = mdp.mols2batch([mdp.mol2repr(agraph.nodes[i]['mol'])\n for i in agraph.nodes])\n numblocks.append(len(m.blocks))\n with torch.no_grad():\n # get the mols_out_s for ALL molecules not just the end one.\n if args.condition_type == 'Hyper_scorepred':\n stem_out_s, mol_out_s, _ = model(\n s, weights.repeat(s.num_graphs, 1))\n else:\n stem_out_s, mol_out_s = model(\n s, weights.repeat(s.num_graphs, 1))\n per_mol_out = []\n # Compute pi(a|s)\n for j in range(len(agraph.nodes)):\n a, b = s._slice_dict['stems'][j:j+2]\n\n stop_allowed = len(\n agraph.nodes[j]['mol'].blocks) >= args.min_blocks\n mp = logsoftmax(torch.cat([\n stem_out_s[a:b].reshape(-1),\n # If num_blocks < min_blocks, the model is not allowed to stop\n mol_out_s[j, :1] if stop_allowed else tf([-1000])]))\n per_mol_out.append(\n (mp[:-1].reshape((-1, stem_out_s.shape[1])), mp[-1]))\n\n # When the model reaches 8 blocks, it is stopped automatically. If instead it stops before\n # that, we need to take into account the STOP action's logprob\n if len(m.blocks) < 8:\n if args.condition_type == 'Hyper_scorepred':\n stem_out_last, mol_out_last, _ = model(\n mdp.mols2batch([mdp.mol2repr(m)]), weights.unsqueeze(0))\n else:\n stem_out_last, mol_out_last = model(\n mdp.mols2batch([mdp.mol2repr(m)]), weights.unsqueeze(0)) \n mplast = logsoftmax(\n torch.cat([stem_out_last.reshape(-1), mol_out_last[0, :1]]))\n MSTOP = mplast[-1]\n\n # assign logprob to edges\n for u, v in agraph.edges:\n a = agraph.edges[u, v]['action']\n if a[0] == -1:\n agraph.edges[u, v]['logprob'] = per_mol_out[v][1]\n else:\n agraph.edges[u,\n v]['logprob'] = per_mol_out[v][0][a[1], a[0]]\n\n # propagate logprobs through the graph\n for n in list(nx.topological_sort(agraph))[::-1]:\n for c in agraph.predecessors(n):\n if len(m.blocks) < 8 and c == 0:\n agraph.nodes[c]['logprob'] = torch.logaddexp(\n agraph.nodes[c].get('logprob', tf(-1000)),\n agraph.edges[c, n]['logprob'] + agraph.nodes[n].get('logprob', 0) + MSTOP)\n else:\n agraph.nodes[c]['logprob'] = torch.logaddexp(\n agraph.nodes[c].get('logprob', tf(-1000)),\n agraph.edges[c, n]['logprob'] + agraph.nodes[n].get('logprob', 0))\n\n # add the first item\n # logp.append((moli, agraph.nodes[n]['logprob'].item()))\n logp.append(agraph.nodes[n]['logprob'].item())\n corrs.append(stats.spearmanr(rewards, logp).correlation)\n\n print('Spearmanr: {}, mean: {}, Time: {}'.format(corrs, np.mean(corrs), time.time()-start_time))\n return corrs" }, { "identifier": "circle_points", "path": "utils/metrics.py", "snippet": "def circle_points(K, min_angle=None, max_angle=None):\n # generate evenly distributed preference vector\n ang0 = 1e-6 if min_angle is None else min_angle\n ang1 = np.pi / 2 - ang0 if max_angle is None else max_angle\n angles = np.linspace(ang0, ang1, K, endpoint=True)\n x = np.cos(angles)\n y = np.sin(angles)\n weights = np.c_[x, y]\n normalized_weights = weights/weights.sum(1, keepdims=True)\n\n return normalized_weights.astype(np.float32)" }, { "identifier": "get_logger", "path": "utils/logging.py", "snippet": "def get_logger(args):\n if args.enable_tensorboard:\n return TensorboardLogger(args)\n else:\n return Logger(args)" }, { "identifier": "RolloutWorker", "path": "main.py", "snippet": "class RolloutWorker:\n def __init__(self, args, bpath, proxy, device):\n self.args = args\n self.test_split_rng = np.random.RandomState(142857)\n self.train_rng = np.random.RandomState(int(time.time()))\n self.mdp = MolMDPExtended(bpath)\n self.mdp.post_init(device, args.repr_type,\n include_nblocks=args.include_nblocks)\n self.mdp.build_translation_table()\n if args.floatX == 'float64':\n self.mdp.floatX = self.floatX = torch.double\n else:\n self.mdp.floatX = self.floatX = torch.float\n self.proxy = proxy\n self._device = device\n self.seen_molecules = set()\n self.stop_event = threading.Event()\n #######\n # This is the \"result\", here a list of (reward, BlockMolDataExt, info...) tuples\n self.sampled_mols = []\n self.online_mols = []\n self.hindsight_mols = []\n self.max_online_mols = 1000\n self.max_hindsight_mols = 1000\n\n self.min_blocks = args.min_blocks\n self.max_blocks = args.max_blocks\n self.mdp._cue_max_blocks = self.max_blocks\n self.reward_exp = args.reward_exp\n self.reward_min = args.reward_min\n self.reward_norm = args.reward_norm\n self.reward_exp_ramping = args.reward_exp_ramping\n self.random_action_prob = args.random_action_prob\n\n # If True this basically implements Buesing et al's TreeSample Q,\n # samples uniformly from it though, no MTCS involved\n if args.criterion == 'TB' or args.criterion == \"Reinforce\":\n self.ignore_parents = True\n elif args.criterion == 'FM':\n self.ignore_parents = False\n\n def rollout(self, generator, use_rand_policy=True, weights=None, replay=False):\n weights = Dirichlet(torch.ones(len(self.args.objectives))*self.args.alpha).sample_n(1).to(\n self.args.device) if weights is None else weights\n\n m = BlockMoleculeDataExtended()\n samples = []\n max_blocks = self.max_blocks\n trajectory_stats = []\n for t in range(max_blocks):\n s = self.mdp.mols2batch([self.mdp.mol2repr(m)])\n s_o, m_o = generator(s, vec_data=weights, do_stems=True)\n # fix from run 330 onwards\n if t < self.min_blocks:\n m_o = m_o*0 - 1000 # prevent assigning prob to stop\n # when we can't stop\n ##\n logits = torch.cat([m_o.reshape(-1), s_o.reshape(-1)])\n cat = torch.distributions.Categorical(\n logits=logits) \n action = cat.sample().item()\n\n if use_rand_policy and self.random_action_prob > 0: # just for training\n if self.train_rng.uniform() < self.random_action_prob:\n action = self.train_rng.randint(\n int(t < self.min_blocks), logits.shape[0])\n\n q = torch.cat([m_o.reshape(-1), s_o.reshape(-1)])\n trajectory_stats.append(\n (q[action].item(), action, torch.logsumexp(q, 0).item()))\n\n if t >= self.min_blocks and action == 0:\n r, raw_r = self._get_reward(m, weights) # r: reward, raw_r: scores for the objectives\n samples.append(((m,), ((-1, 0),), weights, weights, r, m, 1))\n break\n else:\n action = max(0, action-1)\n action = (action % self.mdp.num_blocks,\n action // self.mdp.num_blocks)\n m_old = m\n m = self.mdp.add_block_to(m, *action)\n if len(m.blocks) and not len(m.stems) or t == max_blocks - 1:\n # can't add anything more to this mol so let's make it\n # terminal. Note that this node's parent isn't just m,\n # because this is a sink for all parent transitions\n r, raw_r = self._get_reward(m, weights)\n if self.ignore_parents:\n samples.append(\n ((m_old,), (action,), weights, weights, r, m, 1))\n else:\n parents, actions = zip(*self.mdp.parents(m))\n samples.append((parents, actions, weights.repeat(\n len(parents), 1), weights, r, m, 1))\n break\n else:\n if self.ignore_parents:\n samples.append(\n ((m_old,), (action,), weights, weights, 0, m, 0))\n else:\n parents, actions = zip(*self.mdp.parents(m))\n samples.append(\n (parents, actions, weights.repeat(len(parents), 1), weights, 0, m, 0))\n\n p = self.mdp.mols2batch([self.mdp.mol2repr(i) for i in samples[-1][0]])\n qp = generator(p, weights.repeat(p.num_graphs, 1))\n qsa_p = generator.model.index_output_by_action(\n p, qp[0], qp[1][:, 0],\n torch.tensor(samples[-1][1], device=self._device).long())\n inflow = torch.logsumexp(qsa_p.flatten(), 0).item()\n self.sampled_mols.append(\n ([i.cpu().numpy() for i in raw_r], weights.cpu().numpy(), m, trajectory_stats, inflow))\n\n if replay and self.args.hindsight_prob > 0.0:\n self._add_mol_to_replay(m)\n\n return samples\n\n def _get_reward(self, m, weights=None):\n rdmol = m.mol\n if rdmol is None:\n return self.reward_min\n \n # get scores from oracle\n score = self.proxy.get_score([m])\n score = torch.tensor(list(score.values())).to(self.args.device)\n \n if self.args.scalar == 'WeightedSum':\n raw_reward = (weights*score).sum()\n \n elif self.args.scalar == 'Tchebycheff':\n raw_reward = (weights*score).min() + 0.1 * (weights*score).sum()\n \n reward = self.l2r(raw_reward.clip(self.reward_min))\n return reward, (raw_reward, score)\n\n def execute_train_episode_batch(self, generator, dataset=None, use_rand_policy=True):\n if self.args.condition_type is None:\n weights = self.test_weights # train specific model\n else:\n weights = Dirichlet(torch.tensor(self.args.alpha_vector)*self.args.alpha).sample_n(1).to(self.args.device) #* sample weights per batch, seem better\n samples = sum((self.rollout(generator, use_rand_policy, weights)\n for i in range(self.args.trajectories_mbsize)), [])\n\n return zip(*samples)\n\n def sample2batch(self, mb):\n p, a, p_weights, weights, r, s, d, *o = mb\n mols = (p, s)\n # The batch index of each parent\n p_batch = torch.tensor(sum([[i]*len(p) for i, p in enumerate(p)], []),\n device=self._device).long()\n # Convert all parents and states to repr. Note that this\n # concatenates all the parent lists, which is why we need\n # p_batch\n p = self.mdp.mols2batch(list(map(self.mdp.mol2repr, sum(p, ()))))\n s = self.mdp.mols2batch([self.mdp.mol2repr(i) for i in s])\n # Concatenate all the actions (one per parent per sample)\n a = torch.tensor(sum(a, ()), device=self._device).long()\n # rewards and dones\n r = torch.tensor(r, device=self._device).to(self.floatX)\n d = torch.tensor(d, device=self._device).to(self.floatX)\n # weights\n p_w = torch.cat(p_weights, 0)\n w = torch.cat(weights, 0)\n return (p, p_batch, a, p_w, w, r, s, d, mols, *o)\n\n def l2r(self, raw_reward, t=0):\n if self.reward_exp_ramping > 0:\n reward_exp = 1 + (self.reward_exp - 1) * \\\n (1 - 1/(1 + t / self.reward_exp_ramping))\n # when t=0, exp = 1; t->∞, exp = self.reward_exp\n else:\n reward_exp = self.reward_exp\n\n reward = (raw_reward/self.reward_norm)**reward_exp\n\n return reward\n\n def start_samplers(self, generator, n, dataset):\n self.ready_events = [threading.Event() for i in range(n)]\n self.resume_events = [threading.Event() for i in range(n)]\n self.results = [None] * n\n\n def f(idx):\n while not self.stop_event.is_set():\n try:\n self.results[idx] = self.sample2batch(\n self.execute_train_episode_batch(generator, dataset, use_rand_policy=True))\n except Exception as e:\n print(\"Exception while sampling:\")\n print(e)\n self.sampler_threads[idx].failed = True\n self.sampler_threads[idx].exception = e\n self.ready_events[idx].set()\n break\n self.ready_events[idx].set()\n self.resume_events[idx].clear()\n self.resume_events[idx].wait()\n\n self.sampler_threads = [threading.Thread(\n target=f, args=(i,)) for i in range(n)]\n [setattr(i, 'failed', False) for i in self.sampler_threads]\n [i.start() for i in self.sampler_threads]\n round_robin_idx = [0]\n\n def get():\n while True:\n idx = round_robin_idx[0]\n round_robin_idx[0] = (round_robin_idx[0] + 1) % n\n if self.ready_events[idx].is_set():\n r = self.results[idx]\n self.ready_events[idx].clear()\n self.resume_events[idx].set()\n return r\n elif round_robin_idx[0] == 0:\n time.sleep(0.001)\n return get\n\n def stop_samplers_and_join(self):\n self.stop_event.set()\n if hasattr(self, 'sampler_threads'):\n while any([i.is_alive() for i in self.sampler_threads]):\n [i.set() for i in self.resume_events]\n [i.join(0.05) for i in self.sampler_threads]" }, { "identifier": "get_test_mols", "path": "main.py", "snippet": "def get_test_mols(args, mdp, num):\n samples = []\n fps = []\n early_stops = []\n while len(samples) < num:\n if len(samples) % 5000 == 0:\n print(f'{len(samples)}/{num} mols have been sampled')\n m = BlockMoleculeDataExtended()\n min_blocks = args.min_blocks\n max_blocks = args.max_blocks\n early_stop_at = np.random.randint(min_blocks, max_blocks + 1)\n early_stops.append(early_stop_at)\n for t in range(max_blocks):\n if t == 0:\n length = mdp.num_blocks+1\n else:\n length = len(m.stems)*mdp.num_blocks+1\n\n action = np.random.randint(1, length)\n\n if t == early_stop_at:\n action = 0\n\n if t >= min_blocks and action == 0:\n fp = AllChem.GetMorganFingerprintAsBitVect(m.mol, 3, 2048)\n if len(samples)==0:\n samples.append(m)\n fps.append(fp)\n else:\n sims = DataStructs.BulkTanimotoSimilarity(fp, fps)\n if max(sims) < 0.7:\n samples.append(m)\n fps.append(fp)\n break\n else:\n action = max(0, action-1)\n action = (action % mdp.num_blocks, action // mdp.num_blocks)\n #print('..', action)\n m = mdp.add_block_to(m, *action)\n if len(m.blocks) and not len(m.stems) or t == max_blocks - 1:\n # can't add anything more to this mol so let's make it\n # terminal. Note that this node's parent isn't just m,\n # because this is a sink for all parent transitions\n fp = AllChem.GetMorganFingerprintAsBitVect(m.mol, 3, 2048)\n if len(samples)==0:\n samples.append(m)\n fps.append(fp)\n else:\n sims = DataStructs.BulkTanimotoSimilarity(fp, fps)\n if max(sims) < 0.7:\n samples.append(m)\n fps.append(fp)\n break\n \n return samples" } ]
from collections import defaultdict from dataset import Dataset from mol_mdp_ext import MolMDPExtended, BlockMoleculeDataExtended from oracle.oracle import Oracle from proxy import get_proxy from generator import TBGFlowNet, FMGFlowNet, MOReinforce from utils.utils import set_random_seed from utils.metrics import compute_success, compute_diversity, compute_novelty, compute_correlation, circle_points from utils.logging import get_logger from datetime import datetime from botorch.utils.multi_objective.hypervolume import Hypervolume from botorch.utils.sampling import sample_simplex from botorch.utils.transforms import normalize, unnormalize from torch.distributions.dirichlet import Dirichlet from main import RolloutWorker, get_test_mols from pymoo.util.ref_dirs import get_reference_directions from copy import deepcopy import random import os import re import argparse import json import time import threading import pdb import pickle import gzip import torch.multiprocessing as mp import torch.nn.functional as F import torch import pandas as pd import numpy as np import warnings
15,608
'train_infos': train_infos} def sample_batch(args, generator, rollout_worker, oracle=None, proxy=None, ref_mols=None, Y_bounds=None, compute_multi_objective_metric=False): score_succ = {'gsk3b': 0.5, 'jnk3': 0.5, 'drd2': 0.5, 'chemprop_sars': 0.5, 'chemprop_hiv': 0.5, "seh": 0.5, 'qed': 0.6, 'sa': 0.67} if Y_bounds is None: Y_bounds = torch.stack([proxy.partitioning.Y.min( dim=-2).values, proxy.partitioning.Y.max(dim=-2).values]) time_start = time.time() print(f"Sampling molecules...") raw_rewards = [] raw_rewards_weight = {} means = [] picked_mols = [] smis = [] for i, weights in enumerate(rollout_worker.test_weights): sampled_mols = [] sampled_raw_rewards = [] sampled_means = [] sampled_smis = [] while len(sampled_mols) < args.num_samples: rollout_worker.rollout(generator, use_rand_policy=False, weights=torch.tensor(weights).unsqueeze(0).to(args.device)) (raw_r, _, m, trajectory_stats, inflow) = rollout_worker.sampled_mols[-1] sampled_mols.append(m) sampled_raw_rewards.append(raw_r[0].item()) sampled_means.append(raw_r[1]) sampled_smis.append(m.smiles) idx_pick = np.argsort(sampled_raw_rewards)[::-1][:int(args.num_samples/len(rollout_worker.test_weights))] picked_mols.extend(np.array(sampled_mols)[idx_pick].tolist()) means.extend(np.array(sampled_means)[idx_pick].tolist()) smis.extend(np.array(sampled_smis)[idx_pick].tolist()) raw_rewards.extend(np.array(sampled_raw_rewards)[idx_pick].tolist()) raw_rewards_weight[str(weights.cpu())] = np.array(sampled_raw_rewards)[idx_pick].mean() raw_rewards_mean = np.mean(list(raw_rewards_weight.values())) assert len(picked_mols) == args.num_samples top_means = torch.tensor(means) scores_dict = oracle.batch_get_scores(picked_mols) scores = torch.tensor(pd.DataFrame.from_dict(scores_dict).values) test_loss = F.mse_loss(top_means, scores) hypervolume = Hypervolume(ref_point=torch.zeros(len(args.objectives))) volume = hypervolume.compute(top_means) volume_oracle = hypervolume.compute(scores) diversity = compute_diversity(picked_mols) batch_metrics = {'Hypervolume_reward': volume, 'Hypervolume_oracle': volume_oracle, 'Reward_mean': raw_rewards_mean, 'scores_max': pd.DataFrame.from_dict(scores_dict).max().to_dict(), 'scores_mean': pd.DataFrame.from_dict(scores_dict).mean().to_dict(), 'Test_loss': test_loss, 'Diversity': diversity} print(batch_metrics) print('Time: {}'.format(time.time()-time_start)) if not compute_multi_objective_metric: return volume, volume_oracle, raw_rewards_weight, raw_rewards_mean, test_loss, diversity else: for i in range(len(picked_mols)): picked_mols[i].score = scores_dict[i] # success/diversity/novelty is computed among the top mols. success, positive_mols = compute_success( picked_mols, scores_dict, args.objectives, score_succ) succ_diversity = compute_diversity(positive_mols) if ref_mols: novelty = compute_novelty(positive_mols, ref_mols) else: novelty = 1. mo_metrics = {'success': success, 'novelty': novelty, 'succ_diversity': succ_diversity, } picked_smis = [(raw_rewards[i], picked_mols[i].score, smis[i]) for i in range(len(raw_rewards))] print(mo_metrics) return (picked_mols, scores_dict, picked_smis), batch_metrics, mo_metrics def log_overall_metrics(args, dataset, batch_infos=None, MultiObjective_metrics=None): volume = dataset.compute_hypervolume() print("Hypervolume for {}: {}".format(args.logger.context, volume)) args.logger.add_scalar('Metric/hypervolume', volume, use_context=False) args.logger.add_object('scores', dataset.scores) args.logger.add_object('smis', dataset.smis) if batch_infos: args.logger.add_scalar( 'Metric/test_loss', batch_infos['Test_loss'], use_context=False) args.logger.add_object('collected_info', batch_infos) if MultiObjective_metrics: args.logger.add_scalars('Metric/MultiObjective', MultiObjective_metrics, use_context=False) def get_test_rays(): if args.n_objectives == 3: n_partitions = 6 elif args.n_objectives == 4: n_partitions = 7 test_rays = get_reference_directions("das-dennis", args.n_objectives, n_partitions=n_partitions).astype(np.float32) test_rays = test_rays[[(r > 0).all() for r in test_rays]] print(f"initialize {len(test_rays)} test rays") return test_rays def main(args): set_random_seed(args.seed) args.logger.set_context('iter_0') bpath = "./data/blocks_105.json" dpath = "./data/docked_mols.h5" # Initialize oracle and dataset (for training surrogate function) oracle = Oracle(args)
warnings.filterwarnings('ignore') def arg_parse(): parser = argparse.ArgumentParser() parser.add_argument("--device", type=str, default='cuda') parser.add_argument('--seed', type=int, default=42, help='seed') parser.add_argument("--run", default=0, help="run", type=int) parser.add_argument('--save', action='store_true', default=False, help='Save model.') parser.add_argument('--debug',action='store_true', default=False, help='debug mode, no multi thread') parser.add_argument("--enable_tensorboard", action='store_true', default=False) parser.add_argument("--log_dir", default='runs/mobo') parser.add_argument("--include_nblocks", default=False) parser.add_argument("--num_init_examples", default=200, type=int) parser.add_argument("--num_outer_loop_iters", default=8, type=int) parser.add_argument("--num_samples", default=100, type=int) parser.add_argument("--floatX", default='float32') parser.add_argument('--sample_iterations', type=int, default=1000, help='sample mols and compute metrics') parser.add_argument("--log_weight_score", action='store_true', default=False) # objectives parser.add_argument("--objectives", type=str, default='gsk3b,jnk3,qed,sa') parser.add_argument("--acq_fn", default='UCB', type=str) parser.add_argument("--beta", default=0.1, type=float) parser.add_argument("--scalar", default='WeightedSum', type=str) parser.add_argument("--alpha", default=1., type=float, help='dirichlet distribution') parser.add_argument("--alpha_vector", default='1,1,1,1', type=str) # Proxy parser.add_argument("--proxy_normalize", action='store_true', default=False, help='normalize Y') parser.add_argument("--proxy_num_iterations", default=10000, type=int) parser.add_argument("--proxy_learning_rate", default=2.5e-4, help="Learning rate", type=float) parser.add_argument("--proxy_mbsize", default=64, help="Minibatch size", type=int) parser.add_argument("--proxy_early_stop_tol", default=10, type=int) parser.add_argument("--proxy_repr_type", default='atom_graph') parser.add_argument("--proxy_model_version", default='v2') parser.add_argument("--proxy_num_conv_steps", default=12, type=int) parser.add_argument("--proxy_nemb", default=64, help="#hidden", type=int) parser.add_argument("--proxy_weight_decay", default=1e-6, help="Weight Decay in Proxy", type=float) parser.add_argument("--proxy_uncertainty", default="evidential", type=str) # deep ensemble and GP parser.add_argument("--proxy_dropout", default=0.1, help="MC Dropout in Proxy", type=float) parser.add_argument("--proxy_num_dropout_samples", default=5, type=int) parser.add_argument("--evidential_lam", default=0.1, type=float) parser.add_argument( "--fp_radius", type=int, default=2, help="Morgan fingerprint radius." ) parser.add_argument( "--fp_nbits", type=int, default=1024, help="Morgan fingerprint nBits." ) # GFlowNet parser.add_argument("--min_blocks", default=2, type=int) parser.add_argument("--max_blocks", default=8, type=int) parser.add_argument("--num_iterations", default=5000, type=int) parser.add_argument("--criterion", default="FM", type=str) parser.add_argument("--learning_rate", default=5e-4, help="Learning rate", type=float) parser.add_argument("--Z_learning_rate", default=5e-3, help="Learning rate", type=float) parser.add_argument("--clip_grad", default=0, type=float) parser.add_argument("--trajectories_mbsize", default=8, type=int) parser.add_argument("--offline_mbsize", default=8, type=int) parser.add_argument("--hindsight_prob", default=0.2, type=float) parser.add_argument("--hindsight_buffer_mbsize", default=8, type=int) parser.add_argument("--hindsight_trajectories_mbsize", default=8, type=int) parser.add_argument("--reward_min", default=1e-2, type=float) parser.add_argument("--reward_norm", default=1, type=float) parser.add_argument("--reward_exp", default=8, type=float) parser.add_argument("--reward_exp_ramping", default=0, type=float) parser.add_argument("--logit_clipping", default=0., type=float) # Hyperparameters for TB parser.add_argument("--partition_init", default=1, type=float) # Hyperparameters for FM parser.add_argument("--log_reg_c", default=(0.1/8)**4, type=float) parser.add_argument("--balanced_loss", default=True) parser.add_argument("--leaf_coef", default=10, type=float) # Architecture parser.add_argument("--repr_type", default='block_graph') parser.add_argument("--model_version", default='v4') parser.add_argument("--num_conv_steps", default=10, type=int) parser.add_argument("--nemb", default=256, help="#hidden", type=int) parser.add_argument("--weight_decay", default=0, type=float) parser.add_argument("--random_action_prob", default=0.05, type=float) parser.add_argument("--bootstrap_tau", default=0, type=float) parser.add_argument("--condition_type", type=str, default='HN') parser.add_argument("--ray_hidden_dim", default=100, type=int) return parser.parse_args() class BoRolloutWorker(RolloutWorker): def __init__(self, args, bpath, proxy, device): super(BoRolloutWorker, self).__init__(args, bpath, proxy, device) self.hindsight_prob = args.hindsight_prob self.hindsight_mols = defaultdict(list) self.hindsight_smiles = defaultdict(list) self.replay_threshold = 0.9 def _get(self, i, dset, weights=None): # Sample trajectories by walking backwards from the molecules in our dataset # Handle possible multithreading issues when independent threads # add/substract from dset: m = dset[i] if not isinstance(m, BlockMoleculeDataExtended): m = m[-1] r, raw_r = self._get_reward(m, weights) done = 1 samples = [] # a sample is a tuple (parents(s), parent actions, reward(s), s, done) # an action is (blockidx, stemidx) or (-1, x) for 'stop' # so we start with the stop action, unless the molecule is already # a "terminal" node (if it has no stems, no actions). if len(m.stems) and len(m.blocks) < self.max_blocks: samples.append(((m,), ((-1, 0),), weights, weights, r, m, done)) r = done = 0 while len(m.blocks): # and go backwards if self.ignore_parents: parents = self.mdp.parents(m) parent, action = parents[self.train_rng.randint(len(parents))] samples.append(((parent,), (action,), weights, weights, r, m, done)) r = done = 0 m = parent else: parents, actions = zip(*self.mdp.parents(m)) samples.append((parents, actions, weights.repeat(len(parents), 1), weights, r, m, done)) r = done = 0 m = parents[self.train_rng.randint(len(parents))] return samples[::-1] def _add_mol_to_replay(self, m): for i, weights in enumerate(self.test_weights): r, raw_r = self._get_reward(m, weights) if len(self.hindsight_mols[i]) < self.max_hindsight_mols or raw_r[0] > self.hindsight_mols[i][0][0]: if m.smiles not in self.hindsight_smiles[i]: self.hindsight_mols[i].append((raw_r[0].item(), m.smiles, m)) self.hindsight_smiles[i].append(m.smiles) if len(self.hindsight_mols[i]) > self.max_hindsight_mols: self.hindsight_mols[i] = sorted(self.hindsight_mols[i], key=lambda x:(x[0]))[ max(int(0.05 * self.max_hindsight_mols), 1):] self.hindsight_smiles[i] = [x[1] for x in self.hindsight_mols[i]] def _add_mol_to_online(self, r, m, inflow): if self.replay_mode == 'online': r = r + self.train_rng.normal() * 0.01 if len(self.online_mols) < self.max_online_mols or r > self.online_mols[0][0]: self.online_mols.append((r, m)) if len(self.online_mols) > self.max_online_mols: self.online_mols = sorted(self.online_mols)[ max(int(0.05 * self.max_online_mols), 1):] elif self.replay_mode == 'prioritized': self.online_mols.append((abs(inflow - np.log(r)), m)) if len(self.online_mols) > self.max_online_mols * 1.1: self.online_mols = self.online_mols[-self.max_online_mols:] def _get_reward(self, m, weights=None): rdmol = m.mol if rdmol is None: return self.reward_min # get reward from proxy raw_reward, score = self.proxy(m, weights) raw_reward = raw_reward.clip(self.reward_min) reward = self.l2r(raw_reward) return reward, (raw_reward, score) def execute_train_episode_batch(self, generator, dataset=None, Y_bounds=None, use_rand_policy=True): if self.train_rng.uniform() < self.hindsight_prob: idx = self.train_rng.randint(self.test_weights.shape[0]) weights = self.test_weights[idx].unsqueeze(0) samples = sum((self.rollout(generator, use_rand_policy, weights) for i in range(self.args.hindsight_trajectories_mbsize)), []) if self.args.hindsight_buffer_mbsize > 0: buffer = deepcopy(self.hindsight_mols[idx]) reward = np.array([x[0] for x in buffer]) prob = reward / sum(reward) eidx = np.random.choice(list(range(len(buffer))), self.args.hindsight_buffer_mbsize, replace=False, p=prob) offline_samples = sum((self._get(i, buffer, weights) for i in eidx), []) samples += offline_samples else: weights = Dirichlet(torch.tensor(self.args.alpha_vector)*self.args.alpha).sample_n(1).to(self.args.device) #* sample weights per batch, seem better samples = sum((self.rollout(generator, use_rand_policy, weights, replay=True) for i in range(self.args.trajectories_mbsize)), []) # offline sampling from dataset if self.args.offline_mbsize > 0 and dataset is not None: # use the oracle reward scores = torch.tensor(pd.DataFrame.from_dict(dataset.scores).values, dtype=torch.float32).to(args.device) if Y_bounds is not None: scores = normalize(scores, Y_bounds) reward = torch.matmul(scores, weights.reshape(-1, 1)) prob = (reward / sum(reward)).squeeze(1).cpu().numpy() eidx = np.random.choice(list(range(len(dataset.all_mols))), self.args.offline_mbsize, replace=False, p=prob) offline_samples = sum((self._get(i, dataset.all_mols, weights) for i in eidx), []) samples += offline_samples return zip(*samples) def initialize_hindsight_mols(self, dataset): for m in dataset.all_mols: for i, weights in enumerate(self.test_weights): r, raw_r = self._get_reward(m, weights) self.hindsight_mols[i].append((raw_r[0].item(), m.smiles, m)) for i, weights in enumerate(self.test_weights): self.hindsight_mols[i] = sorted(self.hindsight_mols[i], key=lambda x:(x[0])) self.hindsight_smiles[i] = [x[1] for x in self.hindsight_mols[i]] def train_generative_model(args, generator, bpath, proxy, oracle, dataset, test_weights, round_idx, do_save=False): print("Training generator...") os.makedirs(os.path.join(args.log_dir, f'round_{round_idx}'), exist_ok=True) device = args.device rollout_worker = BoRolloutWorker(args, bpath, proxy, device) rollout_worker.test_weights = torch.tensor(test_weights).to(device) rollout_worker.initialize_hindsight_mols(dataset) Y_bounds = torch.stack([proxy.partitioning.Y.min(dim=-2).values, proxy.partitioning.Y.max(dim=-2).values]) def save_stuff(round_idx, iter): torch.save(generator.state_dict(), os.path.join( args.log_dir, 'round_{}/{}_generator_checkpoint.pth'.format(round_idx, iter))) pickle.dump(rollout_worker.sampled_mols, gzip.open(f'{args.log_dir}/sampled_mols.pkl.gz', 'wb')) multi_thread = not args.debug if multi_thread: sampler = rollout_worker.start_samplers(generator, 8, dataset) def stop_everything(): print('joining') rollout_worker.stop_samplers_and_join() last_losses = [] train_losses = [] test_losses = [] test_infos = [] train_infos = [] time_last_check = time.time() for i in range(args.num_iterations + 1): if multi_thread: r = sampler() for thread in rollout_worker.sampler_threads: if thread.failed: stop_everything() pdb.post_mortem(thread.exception.__traceback__) return p, pb, a, pw, w, r, s, d, mols = r else: p, pb, a, pw, w, r, s, d, mols = rollout_worker.sample2batch( rollout_worker.execute_train_episode_batch(generator, dataset, Y_bounds, use_rand_policy=True)) loss = generator.train_step(p, pb, a, pw, w, r, s, d, mols, i) last_losses.append(loss) if not i % 100: train_loss = [np.round(np.mean(i), 3) for i in zip(*last_losses)] train_losses.append(train_loss) args.logger.add_scalar( 'Loss/round{}/train'.format(round_idx), train_loss[0], use_context=False) print('Iter {}: Loss {}, Time {}'.format( i, train_loss, round(time.time() - time_last_check, 3))) time_last_check = time.time() last_losses = [] if not i % args.sample_iterations and i != 0: volume, volume_oracle, reward_weight, reward_mean, test_loss, diversity = sample_batch( args, generator, rollout_worker, oracle, proxy, Y_bounds, compute_multi_objective_metric=False) args.logger.add_scalar( 'round{}/Top-100-sampled/volumes'.format(round_idx), volume, use_context=False) args.logger.add_scalar( 'round{}/Top-100-sampled/volumes_oracle'.format(round_idx), volume_oracle, use_context=False) args.logger.add_scalars( 'round{}/Top-100-sampled/reward_weight'.format(round_idx), reward_weight, use_context=False) args.logger.add_scalar( 'round{}/Top-100-sampled/reward_mean'.format(round_idx), reward_mean, use_context=False) # reward_mean is a dict, the keys are test_weights args.logger.add_scalar( 'round{}/Top-100-sampled/test_loss'.format(round_idx), test_loss, use_context=False) args.logger.add_scalar( 'round{}/Top-100-sampled/dists'.format(round_idx), diversity, use_context=False) if do_save: save_stuff(round_idx, i) stop_everything() if do_save: save_stuff(round_idx, i) checkpoint_path = os.path.join(args.log_dir, f'round_{round_idx}/{i}_generator_checkpoint.pth') generator.load_state_dict(torch.load(checkpoint_path)) return rollout_worker, {'train_losses': train_losses, 'test_losses': test_losses, 'test_infos': test_infos, 'train_infos': train_infos} def sample_batch(args, generator, rollout_worker, oracle=None, proxy=None, ref_mols=None, Y_bounds=None, compute_multi_objective_metric=False): score_succ = {'gsk3b': 0.5, 'jnk3': 0.5, 'drd2': 0.5, 'chemprop_sars': 0.5, 'chemprop_hiv': 0.5, "seh": 0.5, 'qed': 0.6, 'sa': 0.67} if Y_bounds is None: Y_bounds = torch.stack([proxy.partitioning.Y.min( dim=-2).values, proxy.partitioning.Y.max(dim=-2).values]) time_start = time.time() print(f"Sampling molecules...") raw_rewards = [] raw_rewards_weight = {} means = [] picked_mols = [] smis = [] for i, weights in enumerate(rollout_worker.test_weights): sampled_mols = [] sampled_raw_rewards = [] sampled_means = [] sampled_smis = [] while len(sampled_mols) < args.num_samples: rollout_worker.rollout(generator, use_rand_policy=False, weights=torch.tensor(weights).unsqueeze(0).to(args.device)) (raw_r, _, m, trajectory_stats, inflow) = rollout_worker.sampled_mols[-1] sampled_mols.append(m) sampled_raw_rewards.append(raw_r[0].item()) sampled_means.append(raw_r[1]) sampled_smis.append(m.smiles) idx_pick = np.argsort(sampled_raw_rewards)[::-1][:int(args.num_samples/len(rollout_worker.test_weights))] picked_mols.extend(np.array(sampled_mols)[idx_pick].tolist()) means.extend(np.array(sampled_means)[idx_pick].tolist()) smis.extend(np.array(sampled_smis)[idx_pick].tolist()) raw_rewards.extend(np.array(sampled_raw_rewards)[idx_pick].tolist()) raw_rewards_weight[str(weights.cpu())] = np.array(sampled_raw_rewards)[idx_pick].mean() raw_rewards_mean = np.mean(list(raw_rewards_weight.values())) assert len(picked_mols) == args.num_samples top_means = torch.tensor(means) scores_dict = oracle.batch_get_scores(picked_mols) scores = torch.tensor(pd.DataFrame.from_dict(scores_dict).values) test_loss = F.mse_loss(top_means, scores) hypervolume = Hypervolume(ref_point=torch.zeros(len(args.objectives))) volume = hypervolume.compute(top_means) volume_oracle = hypervolume.compute(scores) diversity = compute_diversity(picked_mols) batch_metrics = {'Hypervolume_reward': volume, 'Hypervolume_oracle': volume_oracle, 'Reward_mean': raw_rewards_mean, 'scores_max': pd.DataFrame.from_dict(scores_dict).max().to_dict(), 'scores_mean': pd.DataFrame.from_dict(scores_dict).mean().to_dict(), 'Test_loss': test_loss, 'Diversity': diversity} print(batch_metrics) print('Time: {}'.format(time.time()-time_start)) if not compute_multi_objective_metric: return volume, volume_oracle, raw_rewards_weight, raw_rewards_mean, test_loss, diversity else: for i in range(len(picked_mols)): picked_mols[i].score = scores_dict[i] # success/diversity/novelty is computed among the top mols. success, positive_mols = compute_success( picked_mols, scores_dict, args.objectives, score_succ) succ_diversity = compute_diversity(positive_mols) if ref_mols: novelty = compute_novelty(positive_mols, ref_mols) else: novelty = 1. mo_metrics = {'success': success, 'novelty': novelty, 'succ_diversity': succ_diversity, } picked_smis = [(raw_rewards[i], picked_mols[i].score, smis[i]) for i in range(len(raw_rewards))] print(mo_metrics) return (picked_mols, scores_dict, picked_smis), batch_metrics, mo_metrics def log_overall_metrics(args, dataset, batch_infos=None, MultiObjective_metrics=None): volume = dataset.compute_hypervolume() print("Hypervolume for {}: {}".format(args.logger.context, volume)) args.logger.add_scalar('Metric/hypervolume', volume, use_context=False) args.logger.add_object('scores', dataset.scores) args.logger.add_object('smis', dataset.smis) if batch_infos: args.logger.add_scalar( 'Metric/test_loss', batch_infos['Test_loss'], use_context=False) args.logger.add_object('collected_info', batch_infos) if MultiObjective_metrics: args.logger.add_scalars('Metric/MultiObjective', MultiObjective_metrics, use_context=False) def get_test_rays(): if args.n_objectives == 3: n_partitions = 6 elif args.n_objectives == 4: n_partitions = 7 test_rays = get_reference_directions("das-dennis", args.n_objectives, n_partitions=n_partitions).astype(np.float32) test_rays = test_rays[[(r > 0).all() for r in test_rays]] print(f"initialize {len(test_rays)} test rays") return test_rays def main(args): set_random_seed(args.seed) args.logger.set_context('iter_0') bpath = "./data/blocks_105.json" dpath = "./data/docked_mols.h5" # Initialize oracle and dataset (for training surrogate function) oracle = Oracle(args)
dataset = Dataset(args, bpath, oracle, args.device)
0
2023-10-24 14:10:35+00:00
24k
caglarkucuk/earthformer-satellite-to-radar
ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer_unet_dec.py
[ { "identifier": "Upsample3DLayer", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class Upsample3DLayer(nn.Module):\n \"\"\"Upsampling based on nn.UpSampling and Conv3x3.\n\n If the temporal dimension remains the same:\n x --> interpolation-2d (nearest) --> conv3x3(dim, out_dim)\n Else:\n x --> interpolation-3d (nearest) --> conv3x3x3(dim, out_dim)\n\n \"\"\"\n def __init__(self,\n dim,\n out_dim,\n target_size,\n temporal_upsample=False,\n kernel_size=3,\n layout='THWC',\n conv_init_mode=\"0\",\n ):\n \"\"\"\n\n Parameters\n ----------\n dim\n out_dim\n target_size\n Size of the output tensor. Will be a tuple/list that contains T_new, H_new, W_new\n temporal_upsample\n Whether the temporal axis will go through upsampling.\n kernel_size\n The kernel size of the Conv2D layer\n layout\n The layout of the inputs\n \"\"\"\n super(Upsample3DLayer, self).__init__()\n self.conv_init_mode = conv_init_mode\n self.target_size = target_size\n self.out_dim = out_dim\n self.temporal_upsample = temporal_upsample\n if temporal_upsample:\n self.up = nn.Upsample(size=target_size, mode='nearest') # 3D upsampling\n else:\n self.up = nn.Upsample(size=(target_size[1], target_size[2]), mode='nearest') # 2D upsampling\n self.conv = nn.Conv2d(in_channels=dim, out_channels=out_dim, kernel_size=(kernel_size, kernel_size),\n padding=(kernel_size // 2, kernel_size // 2))\n assert layout in ['THWC', 'CTHW']\n self.layout = layout\n\n self.reset_parameters()\n\n def reset_parameters(self):\n for m in self.children():\n apply_initialization(m,\n conv_mode=self.conv_init_mode)\n\n def forward(self, x):\n \"\"\"\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C) or (B, C, T, H, W)\n\n Returns\n -------\n out\n Shape (B, T, H_new, W_out, C_out) or (B, C, T, H_out, W_out)\n \"\"\"\n if self.layout == 'THWC':\n B, T, H, W, C = x.shape\n if self.temporal_upsample:\n x = x.permute(0, 4, 1, 2, 3) # (B, C, T, H, W)\n return self.conv(self.up(x)).permute(0, 2, 3, 4, 1)\n else:\n assert self.target_size[0] == T\n x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2) # (B * T, C, H, W)\n x = self.up(x)\n return self.conv(x).permute(0, 2, 3, 1).reshape((B,) + self.target_size + (self.out_dim,))\n elif self.layout == 'CTHW':\n B, C, T, H, W = x.shape\n if self.temporal_upsample:\n return self.conv(self.up(x))\n else:\n assert self.output_size[0] == T\n x = x.permute(0, 2, 1, 3, 4) # (B, T, C, H, W)\n x = x.reshape(B * T, C, H, W)\n return self.conv(self.up(x)).reshape(B, self.target_size[0], self.out_dim, self.target_size[1],\n self.target_size[2]).permute(0, 2, 1, 3, 4)" }, { "identifier": "PatchMerging3D", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class PatchMerging3D(nn.Module):\n \"\"\" Patch Merging Layer\"\"\"\n def __init__(self,\n dim,\n out_dim=None,\n downsample=(1, 2, 2),\n norm_layer='layer_norm',\n padding_type='nearest',\n linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n \"\"\"\n\n Parameters\n ----------\n dim\n Number of input channels.\n downsample\n downsample factor\n norm_layer\n The normalization layer\n \"\"\"\n super().__init__()\n self.linear_init_mode = linear_init_mode\n self.norm_init_mode = norm_init_mode\n self.dim = dim\n if out_dim is None:\n out_dim = max(downsample) * dim\n self.out_dim = out_dim\n self.downsample = downsample\n self.padding_type = padding_type\n self.reduction = nn.Linear(downsample[0] * downsample[1] * downsample[2] * dim,\n out_dim, bias=False)\n self.norm = get_norm_layer(norm_layer, in_channels=downsample[0] * downsample[1] * downsample[2] * dim)\n self.reset_parameters()\n\n def reset_parameters(self):\n for m in self.children():\n apply_initialization(m,\n linear_mode=self.linear_init_mode,\n norm_mode=self.norm_init_mode)\n\n def get_out_shape(self, data_shape):\n T, H, W, C_in = data_shape\n pad_t = (self.downsample[0] - T % self.downsample[0]) % self.downsample[0]\n pad_h = (self.downsample[1] - H % self.downsample[1]) % self.downsample[1]\n pad_w = (self.downsample[2] - W % self.downsample[2]) % self.downsample[2]\n return (T + pad_t) // self.downsample[0], (H + pad_h) // self.downsample[1], (W + pad_w) // self.downsample[2],\\\n self.out_dim\n\n def forward(self, x):\n \"\"\"\n\n Parameters\n ----------\n x\n Input feature, tensor size (B, T, H, W, C).\n\n Returns\n -------\n out\n Shape (B, T // downsample[0], H // downsample[1], W // downsample[2], out_dim)\n \"\"\"\n B, T, H, W, C = x.shape\n\n # padding\n pad_t = (self.downsample[0] - T % self.downsample[0]) % self.downsample[0]\n pad_h = (self.downsample[1] - H % self.downsample[1]) % self.downsample[1]\n pad_w = (self.downsample[2] - W % self.downsample[2]) % self.downsample[2]\n if pad_h or pad_h or pad_w:\n T += pad_t\n H += pad_h\n W += pad_w\n x = _generalize_padding(x, pad_t, pad_w, pad_h, padding_type=self.padding_type)\n\n x = x.reshape((B,\n T // self.downsample[0], self.downsample[0],\n H // self.downsample[1], self.downsample[1],\n W // self.downsample[2], self.downsample[2], C)) \\\n .permute(0, 1, 3, 5, 2, 4, 6, 7) \\\n .reshape(B, T // self.downsample[0], H // self.downsample[1], W // self.downsample[2],\n self.downsample[0] * self.downsample[1] * self.downsample[2] * C)\n x = self.norm(x)\n x = self.reduction(x)\n\n return x" }, { "identifier": "PosEmbed", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class PosEmbed(nn.Module):\n\n def __init__(self, embed_dim, maxT, maxH, maxW, typ='t+h+w'):\n r\"\"\"\n Parameters\n ----------\n embed_dim\n maxT\n maxH\n maxW\n typ\n The type of the positional embedding.\n - t+h+w:\n Embed the spatial position to embeddings\n - t+hw:\n Embed the spatial position to embeddings\n \"\"\"\n super(PosEmbed, self).__init__()\n self.typ = typ\n\n assert self.typ in ['t+h+w', 't+hw']\n self.maxT = maxT\n self.maxH = maxH\n self.maxW = maxW\n self.embed_dim = embed_dim\n # spatiotemporal learned positional embedding\n if self.typ == 't+h+w':\n self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim)\n self.H_embed = nn.Embedding(num_embeddings=maxH, embedding_dim=embed_dim)\n self.W_embed = nn.Embedding(num_embeddings=maxW, embedding_dim=embed_dim)\n\n # nn.init.trunc_normal_(self.T_embed.weight, std=0.02)\n # nn.init.trunc_normal_(self.H_embed.weight, std=0.02)\n # nn.init.trunc_normal_(self.W_embed.weight, std=0.02)\n elif self.typ == 't+hw':\n self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim)\n self.HW_embed = nn.Embedding(num_embeddings=maxH * maxW, embedding_dim=embed_dim)\n # nn.init.trunc_normal_(self.T_embed.weight, std=0.02)\n # nn.init.trunc_normal_(self.HW_embed.weight, std=0.02)\n else:\n raise NotImplementedError\n self.reset_parameters()\n\n def reset_parameters(self):\n for m in self.children():\n apply_initialization(m, embed_mode=\"0\")\n\n def forward(self, x):\n \"\"\"\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C)\n\n Returns\n -------\n out\n Return the x + positional embeddings\n \"\"\"\n _, T, H, W, _ = x.shape\n t_idx = torch.arange(T, device=x.device) # (T, C)\n h_idx = torch.arange(H, device=x.device) # (H, C)\n w_idx = torch.arange(W, device=x.device) # (W, C)\n if self.typ == 't+h+w':\n return x + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim)\\\n + self.H_embed(h_idx).reshape(1, H, 1, self.embed_dim)\\\n + self.W_embed(w_idx).reshape(1, 1, W, self.embed_dim)\n elif self.typ == 't+hw':\n spatial_idx = h_idx.unsqueeze(-1) * self.maxW + w_idx\n return x + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim) + self.HW_embed(spatial_idx)\n else:\n raise NotImplementedError" }, { "identifier": "InitialEncoder", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class InitialEncoder(nn.Module):\n def __init__(self,\n dim,\n out_dim,\n downsample_scale: Union[int, Sequence[int]],\n num_conv_layers=2,\n activation='leaky',\n padding_type='nearest',\n conv_init_mode=\"0\",\n linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n super(InitialEncoder, self).__init__()\n\n self.num_conv_layers = num_conv_layers\n self.conv_init_mode = conv_init_mode\n self.linear_init_mode = linear_init_mode\n self.norm_init_mode = norm_init_mode\n\n conv_block = []\n for i in range(num_conv_layers):\n if i == 0:\n conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1),\n in_channels=dim, out_channels=out_dim))\n conv_block.append(nn.GroupNorm(16, out_dim))\n conv_block.append(get_activation(activation))\n else:\n conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1),\n in_channels=out_dim, out_channels=out_dim))\n conv_block.append(nn.GroupNorm(16, out_dim))\n conv_block.append(get_activation(activation))\n\n self.conv_block = nn.Sequential(*conv_block)\n if isinstance(downsample_scale, int):\n patch_merge_downsample = (1, downsample_scale, downsample_scale)\n elif len(downsample_scale) == 2:\n patch_merge_downsample = (1, *downsample_scale)\n elif len(downsample_scale) == 3:\n patch_merge_downsample = tuple(downsample_scale)\n else:\n raise NotImplementedError(f\"downsample_scale {downsample_scale} format not supported!\")\n self.patch_merge = PatchMerging3D(\n dim=out_dim, out_dim=out_dim,\n padding_type=padding_type,\n downsample=patch_merge_downsample,\n linear_init_mode=linear_init_mode,\n norm_init_mode=norm_init_mode)\n self.reset_parameters()\n\n def reset_parameters(self):\n for m in self.children():\n apply_initialization(m,\n conv_mode=self.conv_init_mode,\n linear_mode=self.linear_init_mode,\n norm_mode=self.norm_init_mode)\n\n def forward(self, x):\n \"\"\"\n\n x --> [K x Conv2D] --> PatchMerge\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C)\n\n Returns\n -------\n out\n Shape (B, T, H_new, W_new, C_out)\n \"\"\"\n B, T, H, W, C = x.shape\n if self.num_conv_layers > 0:\n x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2)\n x = self.conv_block(x).permute(0, 2, 3, 1) # (B * T, H, W, C_new)\n x = self.patch_merge(x.reshape(B, T, H, W, -1))\n else:\n x = self.patch_merge(x)\n return x" }, { "identifier": "FinalDecoder", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class FinalDecoder(nn.Module):\n\n def __init__(self,\n target_thw,\n dim,\n num_conv_layers=2,\n activation='leaky',\n conv_init_mode=\"0\",\n linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n super(FinalDecoder, self).__init__()\n self.target_thw = target_thw\n self.dim = dim\n self.num_conv_layers = num_conv_layers\n self.conv_init_mode = conv_init_mode\n self.linear_init_mode = linear_init_mode\n self.norm_init_mode = norm_init_mode\n\n conv_block = []\n for i in range(num_conv_layers):\n conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1), in_channels=dim, out_channels=dim))\n conv_block.append(nn.GroupNorm(16, dim))\n conv_block.append(get_activation(activation))\n self.conv_block = nn.Sequential(*conv_block)\n self.upsample = Upsample3DLayer(\n dim=dim, out_dim=dim,\n target_size=target_thw, kernel_size=3,\n conv_init_mode=conv_init_mode)\n self.reset_parameters()\n\n def reset_parameters(self):\n for m in self.children():\n apply_initialization(m,\n conv_mode=self.conv_init_mode,\n linear_mode=self.linear_init_mode,\n norm_mode=self.norm_init_mode)\n\n def forward(self, x):\n \"\"\"\n\n x --> Upsample --> [K x Conv2D]\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C)\n\n Returns\n -------\n out\n Shape (B, T, H_new, W_new, C)\n \"\"\"\n x = self.upsample(x)\n if self.num_conv_layers > 0:\n B, T, H, W, C = x.shape\n x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2)\n x = self.conv_block(x).permute(0, 2, 3, 1).reshape(B, T, H, W, -1)\n return x" }, { "identifier": "InitialStackPatchMergingEncoder", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class InitialStackPatchMergingEncoder(nn.Module):\n\n def __init__(self,\n num_merge: int,\n in_dim,\n out_dim_list,\n downsample_scale_list,\n num_conv_per_merge_list=None,\n activation='leaky',\n padding_type='nearest',\n conv_init_mode=\"0\",\n linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n super(InitialStackPatchMergingEncoder, self).__init__()\n\n self.conv_init_mode = conv_init_mode\n self.linear_init_mode = linear_init_mode\n self.norm_init_mode = norm_init_mode\n\n self.num_merge = num_merge\n self.in_dim = in_dim\n self.out_dim_list = out_dim_list[:num_merge]\n self.downsample_scale_list = downsample_scale_list[:num_merge]\n self.num_conv_per_merge_list = num_conv_per_merge_list\n self.num_group_list = [max(1, out_dim // 4) for out_dim in self.out_dim_list]\n\n self.conv_block_list = nn.ModuleList()\n self.patch_merge_list = nn.ModuleList()\n for i in range(num_merge):\n if i == 0:\n in_dim = in_dim\n else:\n in_dim = self.out_dim_list[i - 1]\n out_dim = self.out_dim_list[i]\n downsample_scale = self.downsample_scale_list[i]\n\n conv_block = []\n for j in range(self.num_conv_per_merge_list[i]):\n if j == 0:\n conv_in_dim = in_dim\n else:\n conv_in_dim = out_dim\n conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1),\n in_channels=conv_in_dim, out_channels=out_dim))\n conv_block.append(nn.GroupNorm(self.num_group_list[i], out_dim))\n conv_block.append(get_activation(activation))\n\n conv_block = nn.Sequential(*conv_block)\n self.conv_block_list.append(conv_block)\n patch_merge = PatchMerging3D(\n dim=out_dim, out_dim=out_dim,\n padding_type=padding_type,\n downsample=(1, downsample_scale, downsample_scale),\n linear_init_mode=linear_init_mode,\n norm_init_mode=norm_init_mode)\n self.patch_merge_list.append(patch_merge)\n self.reset_parameters()\n\n def reset_parameters(self):\n for m in self.children():\n apply_initialization(m,\n conv_mode=self.conv_init_mode,\n linear_mode=self.linear_init_mode,\n norm_mode=self.norm_init_mode)\n\n def get_out_shape_list(self, input_shape):\n \"\"\"\n T, H, W, C\n \"\"\"\n out_shape_list = []\n for patch_merge in self.patch_merge_list:\n input_shape = patch_merge.get_out_shape(input_shape)\n out_shape_list.append(input_shape)\n return out_shape_list\n\n def forward(self, x):\n \"\"\"\n\n x --> [K x Conv2D] --> PatchMerge --> ... --> [K x Conv2D] --> PatchMerge\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C)\n\n Returns\n -------\n out\n Shape (B, T, H_new, W_new, C_out)\n \"\"\"\n for i, (conv_block, patch_merge) in \\\n enumerate(zip(self.conv_block_list, self.patch_merge_list)):\n B, T, H, W, C = x.shape\n if self.num_conv_per_merge_list[i] > 0:\n x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2)\n x = conv_block(x).permute(0, 2, 3, 1).reshape(B, T, H, W, -1)\n x = patch_merge(x)\n return x" }, { "identifier": "FinalStackUpsamplingDecoder", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class FinalStackUpsamplingDecoder(nn.Module):\n\n def __init__(self,\n target_shape_list,\n in_dim,\n num_conv_per_up_list=None,\n activation='leaky',\n conv_init_mode=\"0\",\n linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n \"\"\"\n Parameters\n ----------\n target_shape_list:\n list of (T, H ,W ,C)\n \"\"\"\n super(FinalStackUpsamplingDecoder, self).__init__()\n self.conv_init_mode = conv_init_mode\n self.linear_init_mode = linear_init_mode\n self.norm_init_mode = norm_init_mode\n\n self.target_shape_list = target_shape_list\n self.out_dim_list = [target_shape[-1] for target_shape in self.target_shape_list]\n self.num_upsample = len(target_shape_list)\n self.in_dim = in_dim\n self.num_conv_per_up_list = num_conv_per_up_list\n self.num_group_list = [max(1, out_dim // 4) for out_dim in self.out_dim_list]\n\n self.conv_block_list = nn.ModuleList()\n self.upsample_list = nn.ModuleList()\n for i in range(self.num_upsample):\n if i == 0:\n in_dim = in_dim\n else:\n in_dim = self.out_dim_list[i - 1]\n out_dim = self.out_dim_list[i]\n\n upsample = Upsample3DLayer(\n dim=in_dim, out_dim=in_dim,\n target_size=target_shape_list[i][:-1], kernel_size=3,\n conv_init_mode=conv_init_mode)\n self.upsample_list.append(upsample)\n conv_block = []\n for j in range(num_conv_per_up_list[i]):\n if j == 0:\n conv_in_dim = in_dim\n else:\n conv_in_dim = out_dim\n conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1),\n in_channels=conv_in_dim, out_channels=out_dim))\n conv_block.append(nn.GroupNorm(self.num_group_list[i], out_dim))\n conv_block.append(get_activation(activation))\n conv_block = nn.Sequential(*conv_block)\n self.conv_block_list.append(conv_block)\n self.reset_parameters()\n\n def reset_parameters(self):\n for m in self.children():\n apply_initialization(m,\n conv_mode=self.conv_init_mode,\n linear_mode=self.linear_init_mode,\n norm_mode=self.norm_init_mode)\n\n @staticmethod\n def get_init_params(enc_input_shape, enc_out_shape_list, large_channel=False):\n dec_target_shape_list = list(enc_out_shape_list[:-1])[::-1] + [tuple(enc_input_shape), ]\n if large_channel:\n dec_target_shape_list_large_channel = []\n for i, enc_out_shape in enumerate(enc_out_shape_list[::-1]):\n dec_target_shape_large_channel = list(dec_target_shape_list[i])\n dec_target_shape_large_channel[-1] = enc_out_shape[-1]\n dec_target_shape_list_large_channel.append(tuple(dec_target_shape_large_channel))\n dec_target_shape_list = dec_target_shape_list_large_channel\n dec_in_dim = enc_out_shape_list[-1][-1]\n return dec_target_shape_list, dec_in_dim\n\n def forward(self, x):\n \"\"\"\n\n x --> Upsample --> [K x Conv2D] --> ... --> Upsample --> [K x Conv2D]\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C)\n\n Returns\n -------\n out\n Shape (B, T, H_new, W_new, C)\n \"\"\"\n for i, (conv_block, upsample) in \\\n enumerate(zip(self.conv_block_list, self.upsample_list)):\n x = upsample(x)\n if self.num_conv_per_up_list[i] > 0:\n B, T, H, W, C = x.shape\n x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2)\n x = conv_block(x).permute(0, 2, 3, 1).reshape(B, T, H, W, -1)\n return x" }, { "identifier": "StackCuboidSelfAttentionBlock", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class StackCuboidSelfAttentionBlock(nn.Module):\n \"\"\"\n\n - \"use_inter_ffn\" is True\n x --> attn1 -----+-------> ffn1 ---+---> attn2 --> ... --> ffn_k --> out\n | ^ | ^\n | | | |\n |-------------| |-------------|\n - \"use_inter_ffn\" is False\n x --> attn1 -----+------> attn2 --> ... attnk --+----> ffnk ---+---> out\n | ^ | ^ ^ | ^\n | | | | | | |\n |-------------| |------------| ----------| |-----------|\n If we have enabled global memory vectors, each attention will be a\n\n \"\"\"\n def __init__(self,\n dim,\n num_heads,\n block_cuboid_size=[(4, 4, 4), (4, 4, 4)],\n block_shift_size=[(0, 0, 0), (2, 2, 2)],\n block_strategy=[('d', 'd', 'd'),\n ('l', 'l', 'l')],\n padding_type='ignore',\n qkv_bias=False,\n qk_scale=None,\n attn_drop=0.0,\n proj_drop=0.0,\n ffn_drop=0.0,\n activation='leaky',\n gated_ffn=False,\n norm_layer='layer_norm',\n use_inter_ffn=False,\n use_global_vector=False,\n use_global_vector_ffn=True,\n use_global_self_attn=False,\n separate_global_qkv=False,\n global_dim_ratio=1,\n checkpoint_level=True,\n use_relative_pos=True,\n use_final_proj=True,\n # initialization\n attn_linear_init_mode=\"0\",\n ffn_linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n super(StackCuboidSelfAttentionBlock, self).__init__()\n # initialization\n self.attn_linear_init_mode = attn_linear_init_mode\n self.ffn_linear_init_mode = ffn_linear_init_mode\n self.norm_init_mode = norm_init_mode\n\n assert len(block_cuboid_size[0]) > 0 and len(block_shift_size) > 0 and len(block_strategy) > 0,\\\n f'Format of the block cuboid size is not correct.' \\\n f' block_cuboid_size={block_cuboid_size}'\n assert len(block_cuboid_size) == len(block_shift_size) == len(block_strategy)\n self.num_attn = len(block_cuboid_size)\n self.checkpoint_level = checkpoint_level\n self.use_inter_ffn = use_inter_ffn\n # global vectors\n self.use_global_vector = use_global_vector\n self.use_global_vector_ffn = use_global_vector_ffn\n self.use_global_self_attn = use_global_self_attn\n self.global_dim_ratio = global_dim_ratio\n\n if self.use_inter_ffn:\n self.ffn_l = nn.ModuleList(\n [PositionwiseFFN(\n units=dim,\n hidden_size=4 * dim,\n activation_dropout=ffn_drop,\n dropout=ffn_drop,\n gated_proj=gated_ffn,\n activation=activation,\n normalization=norm_layer,\n pre_norm=True,\n linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)\n for _ in range(self.num_attn)])\n if self.use_global_vector_ffn and self.use_global_vector:\n self.global_ffn_l = nn.ModuleList(\n [PositionwiseFFN(\n units=global_dim_ratio * dim,\n hidden_size=global_dim_ratio * 4 * dim,\n activation_dropout=ffn_drop,\n dropout=ffn_drop,\n gated_proj=gated_ffn,\n activation=activation,\n normalization=norm_layer,\n pre_norm=True,\n linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)\n for _ in range(self.num_attn)])\n else:\n self.ffn_l = nn.ModuleList(\n [PositionwiseFFN(\n units=dim, hidden_size=4 * dim,\n activation_dropout=ffn_drop,\n dropout=ffn_drop,\n gated_proj=gated_ffn, activation=activation,\n normalization=norm_layer,\n pre_norm=True,\n linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)])\n if self.use_global_vector_ffn and self.use_global_vector:\n self.global_ffn_l = nn.ModuleList(\n [PositionwiseFFN(\n units=global_dim_ratio * dim,\n hidden_size=global_dim_ratio * 4 * dim,\n activation_dropout=ffn_drop,\n dropout=ffn_drop,\n gated_proj=gated_ffn, activation=activation,\n normalization=norm_layer,\n pre_norm=True,\n linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)])\n self.attn_l = nn.ModuleList(\n [CuboidSelfAttentionLayer(\n dim=dim, num_heads=num_heads,\n cuboid_size=ele_cuboid_size,\n shift_size=ele_shift_size,\n strategy=ele_strategy,\n padding_type=padding_type,\n qkv_bias=qkv_bias,\n qk_scale=qk_scale,\n attn_drop=attn_drop,\n proj_drop=proj_drop,\n norm_layer=norm_layer,\n use_global_vector=use_global_vector,\n use_global_self_attn=use_global_self_attn,\n separate_global_qkv=separate_global_qkv,\n global_dim_ratio=global_dim_ratio,\n checkpoint_level=checkpoint_level,\n use_relative_pos=use_relative_pos,\n use_final_proj=use_final_proj,\n attn_linear_init_mode=attn_linear_init_mode,\n ffn_linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)\n for ele_cuboid_size, ele_shift_size, ele_strategy\n in zip(block_cuboid_size, block_shift_size, block_strategy)])\n\n def reset_parameters(self):\n for m in self.ffn_l:\n m.reset_parameters()\n if self.use_global_vector_ffn and self.use_global_vector:\n for m in self.global_ffn_l:\n m.reset_parameters()\n for m in self.attn_l:\n m.reset_parameters()\n\n def forward(self, x, global_vectors=None):\n if self.use_inter_ffn:\n if self.use_global_vector:\n for idx, (attn, ffn) in enumerate(zip(self.attn_l, self.ffn_l)):\n if self.checkpoint_level >= 2 and self.training:\n x_out, global_vectors_out = checkpoint.checkpoint(attn, x, global_vectors)\n else:\n x_out, global_vectors_out = attn(x, global_vectors)\n x = x + x_out\n global_vectors = global_vectors + global_vectors_out\n\n if self.checkpoint_level >= 1 and self.training:\n x = checkpoint.checkpoint(ffn, x)\n if self.use_global_vector_ffn:\n global_vectors = checkpoint.checkpoint(self.global_ffn_l[idx], global_vectors)\n else:\n x = ffn(x)\n if self.use_global_vector_ffn:\n global_vectors = self.global_ffn_l[idx](global_vectors)\n return x, global_vectors\n else:\n for idx, (attn, ffn) in enumerate(zip(self.attn_l, self.ffn_l)):\n if self.checkpoint_level >= 2 and self.training:\n x = x + checkpoint.checkpoint(attn, x)\n else:\n x = x + attn(x)\n if self.checkpoint_level >= 1 and self.training:\n x = checkpoint.checkpoint(ffn, x)\n else:\n x = ffn(x)\n return x\n else:\n if self.use_global_vector:\n for idx, attn in enumerate(self.attn_l):\n if self.checkpoint_level >= 2 and self.training:\n x_out, global_vectors_out = checkpoint.checkpoint(attn, x, global_vectors)\n else:\n x_out, global_vectors_out = attn(x, global_vectors)\n x = x + x_out\n global_vectors = global_vectors + global_vectors_out\n if self.checkpoint_level >= 1 and self.training:\n x = checkpoint.checkpoint(self.ffn_l[0], x)\n if self.use_global_vector_ffn:\n global_vectors = checkpoint.checkpoint(self.global_ffn_l[0], global_vectors)\n else:\n x = self.ffn_l[0](x)\n if self.use_global_vector_ffn:\n global_vectors = self.global_ffn_l[0](global_vectors)\n return x, global_vectors\n else:\n for idx, attn in enumerate(self.attn_l):\n if self.checkpoint_level >= 2 and self.training:\n out = checkpoint.checkpoint(attn, x)\n else:\n out = attn(x)\n x = x + out\n if self.checkpoint_level >= 1 and self.training:\n x = checkpoint.checkpoint(self.ffn_l[0], x)\n else:\n x = self.ffn_l[0](x)\n return x" }, { "identifier": "StackCuboidCrossAttentionBlock", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class StackCuboidCrossAttentionBlock(nn.Module):\n \"\"\"A stack of cuboid cross attention layers.\n\n The advantage of cuboid attention is that we can combine cuboid attention building blocks with different\n hyper-parameters to mimic a broad range of space-time correlation patterns.\n\n - \"use_inter_ffn\" is True\n x, mem --> attn1 -----+-------> ffn1 ---+---> attn2 --> ... --> ffn_k --> out\n | ^ | ^\n | | | |\n |-------------|----|-------------|\n - \"use_inter_ffn\" is False\n x, mem --> attn1 -----+------> attn2 --> ... attnk --+----> ffnk ---+---> out, mem\n | ^ | ^ ^ | ^\n | | | | | | |\n |-------------|----|------------|-- ----------|--|-----------|\n \"\"\"\n def __init__(self,\n dim,\n num_heads,\n block_cuboid_hw=[(4, 4), (4, 4)],\n block_shift_hw=[(0, 0), (2, 2)],\n block_n_temporal=[1, 2],\n block_strategy=[('d', 'd', 'd'),\n ('l', 'l', 'l')],\n padding_type='ignore',\n cross_last_n_frames=None,\n qkv_bias=False,\n qk_scale=None,\n attn_drop=0.0,\n proj_drop=0.0,\n ffn_drop=0.0,\n activation='leaky',\n gated_ffn=False,\n norm_layer='layer_norm',\n use_inter_ffn=True,\n max_temporal_relative=50,\n checkpoint_level=1,\n use_relative_pos=True,\n # global vectors\n use_global_vector=False,\n separate_global_qkv=False,\n global_dim_ratio=1,\n # initialization\n attn_linear_init_mode=\"0\",\n ffn_linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n super(StackCuboidCrossAttentionBlock, self).__init__()\n # initialization\n self.attn_linear_init_mode = attn_linear_init_mode\n self.ffn_linear_init_mode = ffn_linear_init_mode\n self.norm_init_mode = norm_init_mode\n\n assert len(block_cuboid_hw[0]) > 0 and len(block_shift_hw) > 0 and len(block_strategy) > 0,\\\n f'Incorrect format.' \\\n f' block_cuboid_hw={block_cuboid_hw}, block_shift_hw={block_shift_hw}, block_strategy={block_strategy}'\n assert len(block_cuboid_hw) == len(block_shift_hw) == len(block_strategy)\n self.num_attn = len(block_cuboid_hw)\n self.checkpoint_level = checkpoint_level\n self.use_inter_ffn = use_inter_ffn\n self.use_global_vector = use_global_vector\n if self.use_inter_ffn:\n self.ffn_l = nn.ModuleList(\n [PositionwiseFFN(\n units=dim,\n hidden_size=4 * dim,\n activation_dropout=ffn_drop,\n dropout=ffn_drop,\n gated_proj=gated_ffn,\n activation=activation,\n normalization=norm_layer,\n pre_norm=True,\n linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)\n for _ in range(self.num_attn)])\n else:\n self.ffn_l = nn.ModuleList(\n [PositionwiseFFN(\n units=dim,\n hidden_size=4 * dim,\n activation_dropout=ffn_drop,\n dropout=ffn_drop,\n gated_proj=gated_ffn,\n activation=activation,\n normalization=norm_layer,\n pre_norm=True,\n linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)])\n self.attn_l = nn.ModuleList(\n [CuboidCrossAttentionLayer(\n dim=dim,\n num_heads=num_heads,\n cuboid_hw=ele_cuboid_hw,\n shift_hw=ele_shift_hw,\n strategy=ele_strategy,\n n_temporal=ele_n_temporal,\n cross_last_n_frames=cross_last_n_frames,\n padding_type=padding_type,\n qkv_bias=qkv_bias,\n qk_scale=qk_scale,\n attn_drop=attn_drop,\n proj_drop=proj_drop,\n norm_layer=norm_layer,\n max_temporal_relative=max_temporal_relative,\n use_global_vector=use_global_vector,\n separate_global_qkv=separate_global_qkv,\n global_dim_ratio=global_dim_ratio,\n checkpoint_level=checkpoint_level,\n use_relative_pos=use_relative_pos,\n attn_linear_init_mode=attn_linear_init_mode,\n ffn_linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,)\n for ele_cuboid_hw, ele_shift_hw, ele_strategy, ele_n_temporal\n in zip(block_cuboid_hw, block_shift_hw, block_strategy, block_n_temporal)])\n\n def reset_parameters(self):\n for m in self.ffn_l:\n m.reset_parameters()\n for m in self.attn_l:\n m.reset_parameters()\n\n def forward(self, x, mem, mem_global_vector=None):\n \"\"\"\n\n Parameters\n ----------\n x\n Shape (B, T_x, H, W, C)\n mem\n Shape (B, T_mem, H, W, C)\n mem_global_vector\n Shape (B, N_global, C)\n\n Returns\n -------\n out\n Shape (B, T_x, H, W, C_out)\n \"\"\"\n if self.use_inter_ffn:\n for attn, ffn in zip(self.attn_l, self.ffn_l):\n if self.checkpoint_level >= 2 and self.training:\n x = x + checkpoint.checkpoint(attn, x, mem, mem_global_vector)\n else:\n x = x + attn(x, mem, mem_global_vector)\n if self.checkpoint_level >= 1 and self.training:\n x = checkpoint.checkpoint(ffn, x)\n else:\n x = ffn(x)\n return x\n else:\n for attn in self.attn_l:\n if self.checkpoint_level >= 2 and self.training:\n x = x + checkpoint.checkpoint(attn, x, mem, mem_global_vector)\n else:\n x = x + attn(x, mem, mem_global_vector)\n if self.checkpoint_level >= 1 and self.training:\n x = checkpoint.checkpoint(self.ffn_l[0], x)\n else:\n x = self.ffn_l[0](x)\n return x" }, { "identifier": "CuboidTransformerEncoder", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py", "snippet": "class CuboidTransformerEncoder(nn.Module):\n \"\"\"Encoder of the CuboidTransformer\n\n x --> attn_block --> patch_merge --> attn_block --> patch_merge --> ... --> out\n\n \"\"\"\n def __init__(self,\n input_shape,\n base_units=128,\n block_units=None,\n scale_alpha=1.0,\n depth=[4, 4, 4],\n downsample=2,\n downsample_type='patch_merge',\n block_attn_patterns=None,\n block_cuboid_size=[(4, 4, 4),\n (4, 4, 4)],\n block_strategy=[('l', 'l', 'l'),\n ('d', 'd', 'd')],\n block_shift_size=[(0, 0, 0),\n (0, 0, 0)],\n num_heads=4,\n attn_drop=0.0,\n proj_drop=0.0,\n ffn_drop=0.0,\n activation=\"leaky\",\n ffn_activation='leaky',\n gated_ffn=False,\n norm_layer='layer_norm',\n use_inter_ffn=True,\n padding_type='ignore',\n checkpoint_level=True,\n use_relative_pos=True,\n self_attn_use_final_proj=True,\n # global vectors\n use_global_vector=False,\n use_global_vector_ffn=True,\n use_global_self_attn=False,\n separate_global_qkv=False,\n global_dim_ratio=1,\n # initialization\n attn_linear_init_mode=\"0\",\n ffn_linear_init_mode=\"0\",\n conv_init_mode=\"0\",\n down_linear_init_mode=\"0\",\n norm_init_mode=\"0\",\n ):\n \"\"\"\n\n Parameters\n ----------\n input_shape\n The shape of the input. Contains T, H, W, C\n initial_data_thw\n The shape of the first layer\n base_units\n The number of units\n scale_alpha\n We scale up the channels based on the formula:\n - round_to(base_units * max(downsample_scale) ** units_alpha, 4)\n depth\n The number of layers for each block\n downsample\n The downsample ratio\n downsample_type\n Type of the downsampling layer\n block_attn_patterns\n Attention pattern for the cuboid attention for each block.\n block_cuboid_size\n A list of cuboid size parameters\n block_strategy\n A list of cuboid strategies\n block_shift_size\n A list of shift sizes\n num_global\n The number of global vectors\n num_heads\n The number of heads.\n attn_drop\n proj_drop\n ffn_drop\n gated_ffn\n Whether to enable gated ffn or not\n norm_layer\n The normalization layer\n use_inter_ffn\n Whether to use intermediate FFN\n padding_type\n \"\"\"\n super(CuboidTransformerEncoder, self).__init__()\n # initialization mode\n self.attn_linear_init_mode = attn_linear_init_mode\n self.ffn_linear_init_mode = ffn_linear_init_mode\n self.conv_init_mode = conv_init_mode\n self.down_linear_init_mode = down_linear_init_mode\n self.norm_init_mode = norm_init_mode\n\n self.input_shape = input_shape\n self.depth = depth\n self.num_blocks = len(depth)\n self.base_units = base_units\n self.scale_alpha = scale_alpha\n if not isinstance(downsample, (tuple, list)):\n downsample = (1, downsample, downsample)\n self.downsample = downsample\n self.downsample_type = downsample_type\n self.num_heads = num_heads\n self.use_global_vector = use_global_vector\n self.checkpoint_level = checkpoint_level\n if block_units is None:\n block_units = [round_to(base_units * int((max(downsample) ** scale_alpha) ** i), 4)\n for i in range(self.num_blocks)]\n else:\n assert len(block_units) == self.num_blocks and block_units[0] == base_units\n self.block_units = block_units\n\n if self.num_blocks > 1:\n if downsample_type == 'patch_merge':\n self.down_layers = nn.ModuleList(\n [PatchMerging3D(dim=self.block_units[i],\n downsample=downsample,\n # downsample=(1, 1, 1),\n padding_type=padding_type,\n out_dim=self.block_units[i + 1],\n linear_init_mode=down_linear_init_mode,\n norm_init_mode=norm_init_mode)\n for i in range(self.num_blocks - 1)])\n else:\n raise NotImplementedError\n if self.use_global_vector:\n self.down_layer_global_proj = nn.ModuleList(\n [nn.Linear(in_features=global_dim_ratio*self.block_units[i],\n out_features=global_dim_ratio*self.block_units[i + 1])\n for i in range(self.num_blocks - 1)])\n\n if block_attn_patterns is not None:\n mem_shapes = self.get_mem_shapes()\n if isinstance(block_attn_patterns, (tuple, list)):\n assert len(block_attn_patterns) == self.num_blocks\n else:\n block_attn_patterns = [block_attn_patterns for _ in range(self.num_blocks)]\n block_cuboid_size = []\n block_strategy = []\n block_shift_size = []\n for idx, key in enumerate(block_attn_patterns):\n func = CuboidSelfAttentionPatterns.get(key)\n cuboid_size, strategy, shift_size = func(mem_shapes[idx])\n block_cuboid_size.append(cuboid_size)\n block_strategy.append(strategy)\n block_shift_size.append(shift_size)\n else:\n if not isinstance(block_cuboid_size[0][0], (list, tuple)):\n block_cuboid_size = [block_cuboid_size for _ in range(self.num_blocks)]\n else:\n assert len(block_cuboid_size) == self.num_blocks,\\\n f'Incorrect input format! Received block_cuboid_size={block_cuboid_size}'\n\n if not isinstance(block_strategy[0][0], (list, tuple)):\n block_strategy = [block_strategy for _ in range(self.num_blocks)]\n else:\n assert len(block_strategy) == self.num_blocks,\\\n f'Incorrect input format! Received block_strategy={block_strategy}'\n\n if not isinstance(block_shift_size[0][0], (list, tuple)):\n block_shift_size = [block_shift_size for _ in range(self.num_blocks)]\n else:\n assert len(block_shift_size) == self.num_blocks,\\\n f'Incorrect input format! Received block_shift_size={block_shift_size}'\n self.block_cuboid_size = block_cuboid_size\n self.block_strategy = block_strategy\n self.block_shift_size = block_shift_size\n\n self.blocks = nn.ModuleList([nn.Sequential(\n *[StackCuboidSelfAttentionBlock(\n dim=self.block_units[i],\n num_heads=num_heads,\n block_cuboid_size=block_cuboid_size[i],\n block_strategy=block_strategy[i],\n block_shift_size=block_shift_size[i],\n attn_drop=attn_drop,\n proj_drop=proj_drop,\n ffn_drop=ffn_drop,\n activation=ffn_activation,\n gated_ffn=gated_ffn,\n norm_layer=norm_layer,\n use_inter_ffn=use_inter_ffn,\n padding_type=padding_type,\n use_global_vector=use_global_vector,\n use_global_vector_ffn=use_global_vector_ffn,\n use_global_self_attn=use_global_self_attn,\n separate_global_qkv=separate_global_qkv,\n global_dim_ratio=global_dim_ratio,\n checkpoint_level=checkpoint_level,\n use_relative_pos=use_relative_pos,\n use_final_proj=self_attn_use_final_proj,\n # initialization\n attn_linear_init_mode=attn_linear_init_mode,\n ffn_linear_init_mode=ffn_linear_init_mode,\n norm_init_mode=norm_init_mode,\n ) for _ in range(depth[i])])\n for i in range(self.num_blocks)])\n self.reset_parameters()\n\n def reset_parameters(self):\n if self.num_blocks > 1:\n for m in self.down_layers:\n m.reset_parameters()\n if self.use_global_vector:\n apply_initialization(self.down_layer_global_proj,\n linear_mode=self.down_linear_init_mode)\n for ms in self.blocks:\n for m in ms:\n m.reset_parameters()\n\n def get_mem_shapes(self):\n \"\"\"Get the shape of the output memory based on the input shape. This can be used for constructing the decoder.\n\n Returns\n -------\n mem_shapes\n A list of shapes of the output memory\n \"\"\"\n\n if self.num_blocks == 1:\n return [self.input_shape]\n else:\n mem_shapes = [self.input_shape]\n curr_shape = self.input_shape\n for down_layer in self.down_layers:\n curr_shape = down_layer.get_out_shape(curr_shape)\n mem_shapes.append(curr_shape)\n return mem_shapes\n\n def forward(self, x, global_vectors=None):\n \"\"\"\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C)\n\n Returns\n -------\n out\n A list of tensors from the bottom layer to the top layer of the encoder. For example, it can have shape\n - (B, T, H, W, C1)\n - (B, T, H // 2, W // 2, 2 * C1)\n - (B, T, H // 4, W // 4, 4 * C1)\n ...\n global_mem_out\n Optional\n \"\"\"\n B, T, H, W, C_in = x.shape\n assert (T, H, W, C_in) == self.input_shape \n\n if self.use_global_vector:\n out = []\n global_mem_out = []\n for i in range(self.num_blocks):\n for l in self.blocks[i]:\n x, global_vectors = l(x, global_vectors)\n out.append(x)\n global_mem_out.append(global_vectors)\n if self.num_blocks > 1 and i < self.num_blocks - 1:\n x = self.down_layers[i](x)\n global_vectors = self.down_layer_global_proj[i](global_vectors)\n return out, global_mem_out\n else:\n out = []\n for i in range(self.num_blocks):\n x = self.blocks[i](x)\n out.append(x)\n if self.num_blocks > 1 and i < self.num_blocks - 1:\n x = self.down_layers[i](x)\n return out" }, { "identifier": "CuboidSelfAttentionPatterns", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer_patterns.py", "snippet": "def full_attention(input_shape):\ndef self_axial(input_shape):\ndef self_video_swin(input_shape, P=2, M=4):\ndef self_divided_space_time(input_shape):\ndef self_spatial_lg_v1(input_shape, M=4):\ndef self_axial_space_dilate_K(input_shape, K=2):\ndef cross_KxK(mem_shape, K):\ndef cross_KxK_lg(mem_shape, K):\ndef cross_KxK_heter(mem_shape, K):\n T, H, W, _ = input_shape\n T, H, W, _ = input_shape\n T, H, W, _ = input_shape\n P = min(P, T)\n M = min(M, H, W)\n T, H, W, _ = input_shape\n T, H, W, _ = input_shape\n T, H, W, _ = input_shape\n K = min(K, H, W)\n K = min(K, H, W)\n K = min(K, H, W)\n K = min(K, H, W)" }, { "identifier": "get_activation", "path": "ef-sat2rad/earthformer/cuboid_transformer/utils.py", "snippet": "def get_activation(act, inplace=False, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n act\n Name of the activation\n inplace\n Whether to perform inplace activation\n\n Returns\n -------\n activation_layer\n The activation\n \"\"\"\n if act is None:\n return lambda x: x\n if isinstance(act, str):\n if act == 'leaky':\n negative_slope = kwargs.get(\"negative_slope\", 0.1)\n return nn.LeakyReLU(negative_slope, inplace=inplace)\n elif act == 'identity':\n return nn.Identity()\n elif act == 'elu':\n return nn.ELU(inplace=inplace)\n elif act == 'gelu':\n return nn.GELU()\n elif act == 'relu':\n return nn.ReLU()\n elif act == 'sigmoid':\n return nn.Sigmoid()\n elif act == 'tanh':\n return nn.Tanh()\n elif act == 'softrelu' or act == 'softplus':\n return nn.Softplus()\n elif act == 'softsign':\n return nn.Softsign()\n else:\n raise NotImplementedError('act=\"{}\" is not supported. '\n 'Try to include it if you can find that in '\n 'https://pytorch.org/docs/stable/nn.html'.format(act))\n else:\n return act" }, { "identifier": "get_norm_layer", "path": "ef-sat2rad/earthformer/cuboid_transformer/utils.py", "snippet": "def get_norm_layer(normalization: str = 'layer_norm',\n axis: int = -1,\n epsilon: float = 1e-5,\n in_channels: int = 0, **kwargs):\n \"\"\"Get the normalization layer based on the provided type\n\n Parameters\n ----------\n normalization\n The type of the layer normalization from ['layer_norm']\n axis\n The axis to normalize the\n epsilon\n The epsilon of the normalization layer\n in_channels\n Input channel\n\n Returns\n -------\n norm_layer\n The layer normalization layer\n \"\"\"\n if isinstance(normalization, str):\n if normalization == 'layer_norm':\n assert in_channels > 0\n assert axis == -1\n norm_layer = nn.LayerNorm(normalized_shape=in_channels, eps=epsilon, **kwargs)\n elif normalization == 'rms_norm':\n assert axis == -1\n norm_layer = RMSNorm(d=in_channels, eps=epsilon, **kwargs)\n else:\n raise NotImplementedError('normalization={} is not supported'.format(normalization))\n return norm_layer\n elif normalization is None:\n return nn.Identity()\n else:\n raise NotImplementedError('The type of normalization must be str')" }, { "identifier": "_generalize_padding", "path": "ef-sat2rad/earthformer/cuboid_transformer/utils.py", "snippet": "def _generalize_padding(x, pad_t, pad_h, pad_w, padding_type, t_pad_left=False):\n \"\"\"\n\n Parameters\n ----------\n x\n Shape (B, T, H, W, C)\n pad_t\n pad_h\n pad_w\n padding_type\n t_pad_left\n\n Returns\n -------\n out\n The result after padding the x. Shape will be (B, T + pad_t, H + pad_h, W + pad_w, C)\n \"\"\"\n if pad_t == 0 and pad_h == 0 and pad_w == 0:\n return x\n\n assert padding_type in ['zeros', 'ignore', 'nearest']\n B, T, H, W, C = x.shape\n\n if padding_type == 'nearest':\n return F.interpolate(x.permute(0, 4, 1, 2, 3), size=(T + pad_t, H + pad_h, W + pad_w)).permute(0, 2, 3, 4, 1)\n else:\n if t_pad_left:\n return F.pad(x, (0, 0, 0, pad_w, 0, pad_h, pad_t, 0))\n else:\n return F.pad(x, (0, 0, 0, pad_w, 0, pad_h, 0, pad_t))" }, { "identifier": "_generalize_unpadding", "path": "ef-sat2rad/earthformer/cuboid_transformer/utils.py", "snippet": "def _generalize_unpadding(x, pad_t, pad_h, pad_w, padding_type):\n assert padding_type in['zeros', 'ignore', 'nearest']\n B, T, H, W, C = x.shape\n if pad_t == 0 and pad_h == 0 and pad_w == 0:\n return x\n\n if padding_type == 'nearest':\n return F.interpolate(x.permute(0, 4, 1, 2, 3), size=(T - pad_t, H - pad_h, W - pad_w)).permute(0, 2, 3, 4, 1)\n else:\n return x[:, :(T - pad_t), :(H - pad_h), :(W - pad_w), :].contiguous()" }, { "identifier": "apply_initialization", "path": "ef-sat2rad/earthformer/cuboid_transformer/utils.py", "snippet": "def apply_initialization(m,\n linear_mode=\"0\",\n conv_mode=\"0\",\n norm_mode=\"0\",\n embed_mode=\"0\"):\n if isinstance(m, nn.Linear):\n\n if linear_mode in (\"0\", ):\n nn.init.kaiming_normal_(m.weight,\n mode='fan_in', nonlinearity=\"linear\")\n elif linear_mode in (\"1\", ):\n nn.init.kaiming_normal_(m.weight,\n a=0.1,\n mode='fan_out',\n nonlinearity=\"leaky_relu\")\n else:\n raise NotImplementedError\n if hasattr(m, 'bias') and m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, (nn.Conv2d, nn.Conv3d, nn.ConvTranspose2d, nn.ConvTranspose3d)):\n if conv_mode in (\"0\", ):\n nn.init.kaiming_normal_(m.weight,\n a=0.1,\n mode='fan_out',\n nonlinearity=\"leaky_relu\")\n else:\n raise NotImplementedError\n if hasattr(m, 'bias') and m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.LayerNorm):\n if norm_mode in (\"0\", ):\n if m.elementwise_affine:\n nn.init.ones_(m.weight)\n nn.init.zeros_(m.bias)\n else:\n raise NotImplementedError\n elif isinstance(m, nn.GroupNorm):\n if norm_mode in (\"0\", ):\n if m.affine:\n nn.init.ones_(m.weight)\n nn.init.zeros_(m.bias)\n else:\n raise NotImplementedError\n # # pos_embed already initialized when created\n elif isinstance(m, nn.Embedding):\n if embed_mode in (\"0\", ):\n nn.init.trunc_normal_(m.weight.data, std=0.02)\n else:\n raise NotImplementedError\n else:\n pass" }, { "identifier": "round_to", "path": "ef-sat2rad/earthformer/cuboid_transformer/utils.py", "snippet": "def round_to(dat, c):\n return dat + (dat - dat % c) % c" } ]
from typing import Sequence, Union from functools import lru_cache from collections import OrderedDict from torch import nn from einops import rearrange from .cuboid_transformer import ( Upsample3DLayer, PatchMerging3D, PosEmbed, InitialEncoder, FinalDecoder, InitialStackPatchMergingEncoder, FinalStackUpsamplingDecoder, StackCuboidSelfAttentionBlock, StackCuboidCrossAttentionBlock, CuboidTransformerEncoder) from .cuboid_transformer_patterns import CuboidSelfAttentionPatterns, CuboidCrossAttentionPatterns from .utils import ( get_activation, get_norm_layer, _generalize_padding, _generalize_unpadding, apply_initialization, round_to) import warnings import torch import torch.nn.functional as F import torch.utils.checkpoint as checkpoint
17,476
norm_init_mode=norm_init_mode, # different from CuboidTransformerDecoder downsample=downsample, downsample_type=downsample_type, cross_mode=unet_dec_cross_mode, down_linear_init_mode=down_up_linear_init_mode, ) self.reset_parameters() def get_initial_encoder_final_decoder( self, initial_downsample_type, activation, # initial_downsample_type=="conv" initial_downsample_scale, initial_downsample_conv_layers, final_upsample_conv_layers, padding_type, # initial_downsample_type == "stack_conv" initial_downsample_stack_conv_num_layers, initial_downsample_stack_conv_dim_list, initial_downsample_stack_conv_downscale_list, initial_downsample_stack_conv_num_conv_list, ): T_in, H_in, W_in, C_in = self.input_shape T_out, H_out, W_out, C_out = self.target_shape # Construct the initial upsampling / downsampling layers self.initial_downsample_type = initial_downsample_type if self.initial_downsample_type == "conv": if isinstance(initial_downsample_scale, int): initial_downsample_scale = (1, initial_downsample_scale, initial_downsample_scale) elif len(initial_downsample_scale) == 2: initial_downsample_scale = (1, *initial_downsample_scale) elif len(initial_downsample_scale) == 3: initial_downsample_scale = tuple(initial_downsample_scale) else: raise NotImplementedError(f"initial_downsample_scale {initial_downsample_scale} format not supported!") # if any(ele > 1 for ele in initial_downsample_scale): self.initial_encoder = InitialEncoder(dim=C_in, out_dim=self.base_units, downsample_scale=initial_downsample_scale, num_conv_layers=initial_downsample_conv_layers, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.initial_aux_encoder = InitialEncoder(dim=self.auxiliary_channels, out_dim=self.base_units, downsample_scale=initial_downsample_scale, num_conv_layers=initial_downsample_conv_layers, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.final_decoder = FinalDecoder(dim=self.base_units, target_thw=(T_out, H_out, W_out), num_conv_layers=final_upsample_conv_layers, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) new_input_shape = self.initial_encoder.patch_merge.get_out_shape(self.input_shape) self.dec_final_proj = nn.Linear(self.base_units, C_out) elif self.initial_downsample_type == "stack_conv": if initial_downsample_stack_conv_dim_list is None: initial_downsample_stack_conv_dim_list = [self.base_units, ] * initial_downsample_stack_conv_num_layers self.initial_encoder = InitialStackPatchMergingEncoder( num_merge=initial_downsample_stack_conv_num_layers, in_dim=C_in, out_dim_list=initial_downsample_stack_conv_dim_list, downsample_scale_list=initial_downsample_stack_conv_downscale_list, num_conv_per_merge_list=initial_downsample_stack_conv_num_conv_list, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.initial_aux_encoder = InitialStackPatchMergingEncoder( num_merge=initial_downsample_stack_conv_num_layers, in_dim=self.auxiliary_channels, out_dim_list=initial_downsample_stack_conv_dim_list, downsample_scale_list=initial_downsample_stack_conv_downscale_list, num_conv_per_merge_list=initial_downsample_stack_conv_num_conv_list, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) # use `self.target_shape` to get correct T_out initial_encoder_out_shape_list = self.initial_encoder.get_out_shape_list(self.target_shape) dec_target_shape_list, dec_in_dim = \ FinalStackUpsamplingDecoder.get_init_params( enc_input_shape=self.target_shape, enc_out_shape_list=initial_encoder_out_shape_list, large_channel=True) self.final_decoder = FinalStackUpsamplingDecoder( target_shape_list=dec_target_shape_list, in_dim=dec_in_dim, num_conv_per_up_list=initial_downsample_stack_conv_num_conv_list[::-1], activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.dec_final_proj = nn.Linear(dec_target_shape_list[-1][-1], C_out) new_input_shape = self.initial_encoder.get_out_shape_list(self.input_shape)[-1] else: raise NotImplementedError self.input_shape_after_initial_downsample = new_input_shape T_in, H_in, W_in, _ = new_input_shape return new_input_shape def reset_parameters(self): if self.num_global_vectors > 0: nn.init.trunc_normal_(self.init_global_vectors, std=.02) if hasattr(self.initial_encoder, "reset_parameters"): self.initial_encoder.reset_parameters() else:
"""CuboidTransformer adapted for auxiliary inputs in decoder""" class CuboidTransformerUNetDecoder(nn.Module): """U-Net style Decoder of the CuboidTransformer. For each block, we first apply the StackCuboidSelfAttention and then apply the StackCuboidCrossAttention We add cross attention following 3 modes: cross_mode == "down": x --> attn --> cross_attn --> downscale --> ... --> z --> attn --> upscale --> ... --> out ^ ^ | | | | mem mem cross_mode == "up": x --> attn --> downscale --> ... --> z --> attn --> cross_attn --> upscale --> ... --> out ^ ^ | | | | mem mem cross_mode == "both": x --> attn --> cross_attn --> downscale --> ... --> z --> attn --> cross_attn --> upscale --> ... --> out ^ ^ ^ ^ | | | | | | | | mem mem mem mem """ def __init__(self, target_temporal_length, mem_shapes, cross_start=0, depth=[2, 2], upsample_type="upsample", upsample_kernel_size=3, block_self_attn_patterns=None, block_self_cuboid_size=[(4, 4, 4), (4, 4, 4)], block_self_cuboid_strategy=[('l', 'l', 'l'), ('d', 'd', 'd')], block_self_shift_size=[(1, 1, 1), (0, 0, 0)], block_cross_attn_patterns=None, block_cross_cuboid_hw=[(4, 4), (4, 4)], block_cross_cuboid_strategy=[('l', 'l', 'l'), ('d', 'l', 'l')], block_cross_shift_hw=[(0, 0), (0, 0)], block_cross_n_temporal=[1, 2], cross_last_n_frames=None, num_heads=4, attn_drop=0.0, proj_drop=0.0, ffn_drop=0.0, ffn_activation='leaky', gated_ffn=False, norm_layer='layer_norm', use_inter_ffn=False, hierarchical_pos_embed=False, pos_embed_type='t+hw', max_temporal_relative=50, padding_type='ignore', checkpoint_level=True, use_relative_pos=True, self_attn_use_final_proj=True, # global vectors use_self_global=False, self_update_global=True, use_cross_global=False, use_global_vector_ffn=True, use_global_self_attn=False, separate_global_qkv=False, global_dim_ratio=1, # initialization attn_linear_init_mode="0", ffn_linear_init_mode="0", conv_init_mode="0", up_linear_init_mode="0", norm_init_mode="0", # different from `CuboidTransformerDecoder`, no arg `use_first_self_attn=False` downsample=2, downsample_type='patch_merge', cross_mode="up", down_linear_init_mode="0", ): """ Parameters ---------- target_temporal_length mem_shapes cross_start The block to start cross attention depth Depth of each block downsample The downsample ratio downsample_type Type of the downsampling layer upsample_type The type of the upsampling layers upsample_kernel_size block_self_attn_patterns Pattern of the block self attentions block_self_cuboid_size block_self_cuboid_strategy block_self_shift_size block_cross_attn_patterns block_cross_cuboid_hw block_cross_cuboid_strategy block_cross_shift_hw block_cross_n_temporal cross_last_n_frames cross_mode Must be one of ("up", "down", "both") Control whether the upsampling/downsampling/both phases cross attend to the encoded latent features num_heads attn_drop proj_drop ffn_drop ffn_activation gated_ffn Whether to enable gated ffn or not norm_layer The normalization layer use_inter_ffn Whether to use intermediate FFN hierarchical_pos_embed Whether to add pos embedding for each hierarchy. max_temporal_relative padding_type checkpoint_level """ super(CuboidTransformerUNetDecoder, self).__init__() # initialization mode self.attn_linear_init_mode = attn_linear_init_mode self.ffn_linear_init_mode = ffn_linear_init_mode self.conv_init_mode = conv_init_mode self.up_linear_init_mode = up_linear_init_mode self.norm_init_mode = norm_init_mode assert len(depth) == len(mem_shapes) self.target_temporal_length = target_temporal_length self.num_blocks = len(mem_shapes) self.cross_start = cross_start self.mem_shapes = mem_shapes self.block_units = tuple(mem_shape[-1] for mem_shape in self.mem_shapes) self.depth = depth if not isinstance(downsample, (tuple, list)): downsample = (1, downsample, downsample) self.downsample = downsample self.downsample_type = downsample_type self.upsample_type = upsample_type self.hierarchical_pos_embed = hierarchical_pos_embed self.checkpoint_level = checkpoint_level self.use_self_global = use_self_global self.self_update_global = self_update_global self.use_cross_global = use_cross_global self.use_global_vector_ffn = use_global_vector_ffn assert cross_mode in ["up", "down", "both"], f"Invalid cross_mode {cross_mode}!" self.cross_mode = cross_mode self.up_use_cross = self.cross_mode in ["up", "both"] self.down_use_cross = self.cross_mode in ["down", "both"] if self.num_blocks > 1: # Construct downsampling layers if downsample_type == 'patch_merge': self.downsample_layers = nn.ModuleList( [PatchMerging3D(dim=self.block_units[i], downsample=downsample, # downsample=(1, 1, 1), padding_type=padding_type, out_dim=self.block_units[i + 1], linear_init_mode=down_linear_init_mode, norm_init_mode=norm_init_mode) for i in range(self.num_blocks - 1)]) else: raise NotImplementedError # Construct upsampling layers if self.upsample_type == "upsample": self.upsample_layers = nn.ModuleList([ Upsample3DLayer( dim=self.mem_shapes[i + 1][-1], out_dim=self.mem_shapes[i][-1], target_size=(target_temporal_length,) + self.mem_shapes[i][1:3], kernel_size=upsample_kernel_size, temporal_upsample=False, conv_init_mode=conv_init_mode, ) for i in range(self.num_blocks - 1)]) else: raise NotImplementedError if self.hierarchical_pos_embed: self.down_hierarchical_pos_embed_l = nn.ModuleList([ PosEmbed(embed_dim=self.block_units[i], typ=pos_embed_type, maxT=self.mem_shapes[i][0], maxH=self.mem_shapes[i][1], maxW=self.mem_shapes[i][2]) for i in range(self.num_blocks - 1)]) self.up_hierarchical_pos_embed_l = nn.ModuleList([ PosEmbed(embed_dim=self.block_units[i], typ=pos_embed_type, maxT=self.mem_shapes[i][0], maxH=self.mem_shapes[i][1], maxW=self.mem_shapes[i][2]) for i in range(self.num_blocks - 1)]) if block_self_attn_patterns is not None: if isinstance(block_self_attn_patterns, (tuple, list)): assert len(block_self_attn_patterns) == self.num_blocks else: block_self_attn_patterns = [block_self_attn_patterns for _ in range(self.num_blocks)] block_self_cuboid_size = [] block_self_cuboid_strategy = [] block_self_shift_size = [] for idx, key in enumerate(block_self_attn_patterns): func = CuboidSelfAttentionPatterns.get(key) cuboid_size, strategy, shift_size = func(mem_shapes[idx]) block_self_cuboid_size.append(cuboid_size) block_self_cuboid_strategy.append(strategy) block_self_shift_size.append(shift_size) else: if not isinstance(block_self_cuboid_size[0][0], (list, tuple)): block_self_cuboid_size = [block_self_cuboid_size for _ in range(self.num_blocks)] else: assert len(block_self_cuboid_size) == self.num_blocks,\ f'Incorrect input format! Received block_self_cuboid_size={block_self_cuboid_size}' if not isinstance(block_self_cuboid_strategy[0][0], (list, tuple)): block_self_cuboid_strategy = [block_self_cuboid_strategy for _ in range(self.num_blocks)] else: assert len(block_self_cuboid_strategy) == self.num_blocks,\ f'Incorrect input format! Received block_self_cuboid_strategy={block_self_cuboid_strategy}' if not isinstance(block_self_shift_size[0][0], (list, tuple)): block_self_shift_size = [block_self_shift_size for _ in range(self.num_blocks)] else: assert len(block_self_shift_size) == self.num_blocks,\ f'Incorrect input format! Received block_self_shift_size={block_self_shift_size}' down_self_blocks = [] up_self_blocks = [] for i in range(self.num_blocks): ele_depth = depth[i] stack_cuboid_blocks =\ [StackCuboidSelfAttentionBlock( dim=self.mem_shapes[i][-1], num_heads=num_heads, block_cuboid_size=block_self_cuboid_size[i], block_strategy=block_self_cuboid_strategy[i], block_shift_size=block_self_shift_size[i], attn_drop=attn_drop, proj_drop=proj_drop, ffn_drop=ffn_drop, activation=ffn_activation, gated_ffn=gated_ffn, norm_layer=norm_layer, use_inter_ffn=use_inter_ffn, padding_type=padding_type, use_global_vector=use_self_global, use_global_vector_ffn=use_global_vector_ffn, use_global_self_attn=use_global_self_attn, separate_global_qkv=separate_global_qkv, global_dim_ratio=global_dim_ratio, checkpoint_level=checkpoint_level, use_relative_pos=use_relative_pos, use_final_proj=self_attn_use_final_proj, # initialization attn_linear_init_mode=attn_linear_init_mode, ffn_linear_init_mode=ffn_linear_init_mode, norm_init_mode=norm_init_mode, ) for _ in range(ele_depth)] down_self_blocks.append(nn.ModuleList(stack_cuboid_blocks)) stack_cuboid_blocks = \ [StackCuboidSelfAttentionBlock( dim=self.mem_shapes[i][-1], num_heads=num_heads, block_cuboid_size=block_self_cuboid_size[i], block_strategy=block_self_cuboid_strategy[i], block_shift_size=block_self_shift_size[i], attn_drop=attn_drop, proj_drop=proj_drop, ffn_drop=ffn_drop, activation=ffn_activation, gated_ffn=gated_ffn, norm_layer=norm_layer, use_inter_ffn=use_inter_ffn, padding_type=padding_type, use_global_vector=use_self_global, use_global_vector_ffn=use_global_vector_ffn, use_global_self_attn=use_global_self_attn, separate_global_qkv=separate_global_qkv, global_dim_ratio=global_dim_ratio, checkpoint_level=checkpoint_level, use_relative_pos=use_relative_pos, use_final_proj=self_attn_use_final_proj, # initialization attn_linear_init_mode=attn_linear_init_mode, ffn_linear_init_mode=ffn_linear_init_mode, norm_init_mode=norm_init_mode, ) for _ in range(ele_depth)] up_self_blocks.append(nn.ModuleList(stack_cuboid_blocks)) self.down_self_blocks = nn.ModuleList(down_self_blocks) self.up_self_blocks = nn.ModuleList(up_self_blocks) if block_cross_attn_patterns is not None: if isinstance(block_cross_attn_patterns, (tuple, list)): assert len(block_cross_attn_patterns) == self.num_blocks else: block_cross_attn_patterns = [block_cross_attn_patterns for _ in range(self.num_blocks)] block_cross_cuboid_hw = [] block_cross_cuboid_strategy = [] block_cross_shift_hw = [] block_cross_n_temporal = [] for idx, key in enumerate(block_cross_attn_patterns): if key == "last_frame_dst": cuboid_hw = None shift_hw = None strategy = None n_temporal = None else: func = CuboidCrossAttentionPatterns.get(key) cuboid_hw, shift_hw, strategy, n_temporal = func(mem_shapes[idx]) block_cross_cuboid_hw.append(cuboid_hw) block_cross_cuboid_strategy.append(strategy) block_cross_shift_hw.append(shift_hw) block_cross_n_temporal.append(n_temporal) else: if not isinstance(block_cross_cuboid_hw[0][0], (list, tuple)): block_cross_cuboid_hw = [block_cross_cuboid_hw for _ in range(self.num_blocks)] else: assert len(block_cross_cuboid_hw) == self.num_blocks, \ f'Incorrect input format! Received block_cross_cuboid_hw={block_cross_cuboid_hw}' if not isinstance(block_cross_cuboid_strategy[0][0], (list, tuple)): block_cross_cuboid_strategy = [block_cross_cuboid_strategy for _ in range(self.num_blocks)] else: assert len(block_cross_cuboid_strategy) == self.num_blocks, \ f'Incorrect input format! Received block_cross_cuboid_strategy={block_cross_cuboid_strategy}' if not isinstance(block_cross_shift_hw[0][0], (list, tuple)): block_cross_shift_hw = [block_cross_shift_hw for _ in range(self.num_blocks)] else: assert len(block_cross_shift_hw) == self.num_blocks, \ f'Incorrect input format! Received block_cross_shift_hw={block_cross_shift_hw}' if not isinstance(block_cross_n_temporal[0], (list, tuple)): block_cross_n_temporal = [block_cross_n_temporal for _ in range(self.num_blocks)] else: assert len(block_cross_n_temporal) == self.num_blocks, \ f'Incorrect input format! Received block_cross_n_temporal={block_cross_n_temporal}' if self.up_use_cross: self.up_cross_blocks = nn.ModuleList() for i in range(self.cross_start, self.num_blocks): cross_block = nn.ModuleList( [StackCuboidCrossAttentionBlock( dim=self.mem_shapes[i][-1], num_heads=num_heads, block_cuboid_hw=block_cross_cuboid_hw[i], block_strategy=block_cross_cuboid_strategy[i], block_shift_hw=block_cross_shift_hw[i], block_n_temporal=block_cross_n_temporal[i], cross_last_n_frames=cross_last_n_frames, attn_drop=attn_drop, proj_drop=proj_drop, ffn_drop=ffn_drop, gated_ffn=gated_ffn, norm_layer=norm_layer, use_inter_ffn=use_inter_ffn, activation=ffn_activation, max_temporal_relative=max_temporal_relative, padding_type=padding_type, use_global_vector=use_cross_global, separate_global_qkv=separate_global_qkv, global_dim_ratio=global_dim_ratio, checkpoint_level=checkpoint_level, use_relative_pos=use_relative_pos, # initialization attn_linear_init_mode=attn_linear_init_mode, ffn_linear_init_mode=ffn_linear_init_mode, norm_init_mode=norm_init_mode, ) for _ in range(depth[i])]) self.up_cross_blocks.append(cross_block) if self.down_use_cross: self.down_cross_blocks = nn.ModuleList() for i in range(self.cross_start, self.num_blocks): cross_block = nn.ModuleList( [StackCuboidCrossAttentionBlock( dim=self.mem_shapes[i][-1], num_heads=num_heads, block_cuboid_hw=block_cross_cuboid_hw[i], block_strategy=block_cross_cuboid_strategy[i], block_shift_hw=block_cross_shift_hw[i], block_n_temporal=block_cross_n_temporal[i], cross_last_n_frames=cross_last_n_frames, attn_drop=attn_drop, proj_drop=proj_drop, ffn_drop=ffn_drop, gated_ffn=gated_ffn, norm_layer=norm_layer, use_inter_ffn=use_inter_ffn, activation=ffn_activation, max_temporal_relative=max_temporal_relative, padding_type=padding_type, use_global_vector=use_cross_global, separate_global_qkv=separate_global_qkv, global_dim_ratio=global_dim_ratio, checkpoint_level=checkpoint_level, use_relative_pos=use_relative_pos, # initialization attn_linear_init_mode=attn_linear_init_mode, ffn_linear_init_mode=ffn_linear_init_mode, norm_init_mode=norm_init_mode, ) for _ in range(depth[i])]) self.down_cross_blocks.append(cross_block) self.reset_parameters() def reset_parameters(self): for ms in self.down_self_blocks: for m in ms: m.reset_parameters() for ms in self.up_self_blocks: for m in ms: m.reset_parameters() if self.up_use_cross: for ms in self.up_cross_blocks: for m in ms: m.reset_parameters() if self.down_use_cross: for ms in self.down_cross_blocks: for m in ms: m.reset_parameters() if self.num_blocks > 1: for m in self.downsample_layers: m.reset_parameters() for m in self.upsample_layers: m.reset_parameters() if self.hierarchical_pos_embed: for m in self.down_hierarchical_pos_embed_l: m.reset_parameters() for m in self.up_hierarchical_pos_embed_l: m.reset_parameters() def forward(self, x, mem_l, mem_global_vector_l=None): """ Parameters ---------- x Shape (B, T, H, W, C) mem_l A list of memory tensors Returns ------- out """ B, T, H, W, C = x.shape assert T == self.target_temporal_length assert (H, W) == (self.mem_shapes[0][1], self.mem_shapes[0][2]) new_mem_global_vector_l = [] for i in range(self.num_blocks): # Downample if i > 0: x = self.downsample_layers[i - 1](x) if self.hierarchical_pos_embed: x = self.down_hierarchical_pos_embed_l[i - 1](x) mem_global_vector = None if mem_global_vector_l is None else mem_global_vector_l[i] for idx in range(self.depth[i]): if self.use_self_global: if self.self_update_global: x, mem_global_vector = self.down_self_blocks[i][idx](x, mem_global_vector) else: x, _ = self.down_self_blocks[i][idx](x, mem_global_vector) else: x = self.down_self_blocks[i][idx](x) if self.down_use_cross and i >= self.cross_start: x = self.down_cross_blocks[i - self.cross_start][idx](x, mem_l[i], mem_global_vector) new_mem_global_vector_l.append(mem_global_vector) for i in range(self.num_blocks - 1, -1, -1): mem_global_vector = new_mem_global_vector_l[i] for idx in range(self.depth[i]): if self.use_self_global: if self.self_update_global: x, mem_global_vector = self.up_self_blocks[i][idx](x, mem_global_vector) else: x, _ = self.up_self_blocks[i][idx](x, mem_global_vector) else: x = self.up_self_blocks[i][idx](x) if self.up_use_cross and i >= self.cross_start: x = self.up_cross_blocks[i - self.cross_start][idx](x, mem_l[i], mem_global_vector) # Upsample if i > 0: x = self.upsample_layers[i - 1](x) if self.hierarchical_pos_embed: x = self.up_hierarchical_pos_embed_l[i - 1](x) return x class CuboidTransformerAuxModel(nn.Module): """Cuboid Transformer with auxiliary input in decoder for spatiotemporal forecasting We adopt the Non-autoregressive encoder-decoder architecture. The decoder takes the multi-scale memory output from the encoder, as well as auxiliary input. The initial downsampling / upsampling layers will be Downsampling: [K x Conv2D --> PatchMerge] Upsampling: [Nearest Interpolation-based Upsample --> K x Conv2D] x -----------> downsample (optional) ---> (+pos_embed) ---> enc ---------> mem_l | | |------------------| | | aux_input ---> downsample (optional) ---> (+pos_embed) ---> enc -> cross_attn -> dec -> upsample (optional) -> y """ def __init__(self, input_shape, target_shape, base_units=128, block_units=None, scale_alpha=1.0, num_heads=4, attn_drop=0.0, proj_drop=0.0, ffn_drop=0.0, # inter-attn downsample/upsample downsample=2, downsample_type='patch_merge', upsample_type="upsample", upsample_kernel_size=3, # encoder enc_depth=[4, 4, 4], enc_attn_patterns=None, enc_cuboid_size=[(4, 4, 4), (4, 4, 4)], enc_cuboid_strategy=[('l', 'l', 'l'), ('d', 'd', 'd')], enc_shift_size=[(0, 0, 0), (0, 0, 0)], enc_use_inter_ffn=True, # decoder dec_depth=[2, 2], dec_cross_start=0, dec_self_attn_patterns=None, dec_self_cuboid_size=[(4, 4, 4), (4, 4, 4)], dec_self_cuboid_strategy=[('l', 'l', 'l'), ('d', 'd', 'd')], dec_self_shift_size=[(1, 1, 1), (0, 0, 0)], dec_cross_attn_patterns=None, dec_cross_cuboid_hw=[(4, 4), (4, 4)], dec_cross_cuboid_strategy=[('l', 'l', 'l'), ('d', 'l', 'l')], dec_cross_shift_hw=[(0, 0), (0, 0)], dec_cross_n_temporal=[1, 2], dec_cross_last_n_frames=None, dec_use_inter_ffn=True, dec_hierarchical_pos_embed=False, # global vectors num_global_vectors=4, use_dec_self_global=True, dec_self_update_global=True, use_dec_cross_global=True, use_global_vector_ffn=True, use_global_self_attn=False, separate_global_qkv=False, global_dim_ratio=1, # # initial downsample and final upsample initial_downsample_type="conv", initial_downsample_activation="leaky", # initial_downsample_type=="conv" initial_downsample_scale=1, initial_downsample_conv_layers=2, final_upsample_conv_layers=2, # initial_downsample_type == "stack_conv" initial_downsample_stack_conv_num_layers=1, initial_downsample_stack_conv_dim_list=None, initial_downsample_stack_conv_downscale_list=[1, ], initial_downsample_stack_conv_num_conv_list=[2, ], # # end of initial downsample and final upsample ffn_activation='leaky', gated_ffn=False, norm_layer='layer_norm', padding_type='ignore', pos_embed_type='t+hw', checkpoint_level=True, use_relative_pos=True, self_attn_use_final_proj=True, # initialization attn_linear_init_mode="0", ffn_linear_init_mode="0", conv_init_mode="0", down_up_linear_init_mode="0", norm_init_mode="0", # different from CuboidTransformerModel, no arg `dec_use_first_self_attn=False` auxiliary_channels: int = 1, unet_dec_cross_mode="up", ): """ Parameters ---------- input_shape Shape of the input tensor. It will be (T, H, W, C_in) target_shape Shape of the input tensor. It will be (T_out, H, W, C_out) base_units The base units """ super(CuboidTransformerAuxModel, self).__init__() # initialization mode self.attn_linear_init_mode = attn_linear_init_mode self.ffn_linear_init_mode = ffn_linear_init_mode self.conv_init_mode = conv_init_mode self.down_up_linear_init_mode = down_up_linear_init_mode self.norm_init_mode = norm_init_mode assert len(enc_depth) == len(dec_depth) self.base_units = base_units self.num_global_vectors = num_global_vectors if global_dim_ratio != 1: assert separate_global_qkv == True, \ f"Setting global_dim_ratio != 1 requires separate_global_qkv == True." self.global_dim_ratio = global_dim_ratio self.input_shape = input_shape self.target_shape = target_shape T_in, H_in, W_in, C_in = input_shape T_out, H_out, W_out, C_out = target_shape assert H_in == H_out and W_in == W_out self.auxiliary_channels = auxiliary_channels if self.num_global_vectors > 0: self.init_global_vectors = nn.Parameter( torch.zeros((self.num_global_vectors, global_dim_ratio*base_units))) new_input_shape = self.get_initial_encoder_final_decoder( initial_downsample_scale=initial_downsample_scale, initial_downsample_type=initial_downsample_type, activation=initial_downsample_activation, # initial_downsample_type=="conv" initial_downsample_conv_layers=initial_downsample_conv_layers, final_upsample_conv_layers=final_upsample_conv_layers, padding_type=padding_type, # initial_downsample_type == "stack_conv" initial_downsample_stack_conv_num_layers=initial_downsample_stack_conv_num_layers, initial_downsample_stack_conv_dim_list=initial_downsample_stack_conv_dim_list, initial_downsample_stack_conv_downscale_list=initial_downsample_stack_conv_downscale_list, initial_downsample_stack_conv_num_conv_list=initial_downsample_stack_conv_num_conv_list, ) T_in, H_in, W_in, _ = new_input_shape self.encoder = CuboidTransformerEncoder( input_shape=(T_in, H_in, W_in, base_units), base_units=base_units, block_units=block_units, scale_alpha=scale_alpha, depth=enc_depth, downsample=downsample, downsample_type=downsample_type, block_attn_patterns=enc_attn_patterns, block_cuboid_size=enc_cuboid_size, block_strategy=enc_cuboid_strategy, block_shift_size=enc_shift_size, num_heads=num_heads, attn_drop=attn_drop, proj_drop=proj_drop, ffn_drop=ffn_drop, gated_ffn=gated_ffn, ffn_activation=ffn_activation, norm_layer=norm_layer, use_inter_ffn=enc_use_inter_ffn, padding_type=padding_type, use_global_vector=num_global_vectors > 0, use_global_vector_ffn=use_global_vector_ffn, use_global_self_attn=use_global_self_attn, separate_global_qkv=separate_global_qkv, global_dim_ratio=global_dim_ratio, checkpoint_level=checkpoint_level, use_relative_pos=use_relative_pos, self_attn_use_final_proj=self_attn_use_final_proj, # initialization attn_linear_init_mode=attn_linear_init_mode, ffn_linear_init_mode=ffn_linear_init_mode, conv_init_mode=conv_init_mode, down_linear_init_mode=down_up_linear_init_mode, norm_init_mode=norm_init_mode, ) self.enc_pos_embed = PosEmbed( embed_dim=base_units, typ=pos_embed_type, maxH=H_in, maxW=W_in, maxT=T_in) mem_shapes = self.encoder.get_mem_shapes() self.dec_pos_embed = PosEmbed( embed_dim=mem_shapes[-1][-1], typ=pos_embed_type, maxT=T_out, maxH=mem_shapes[-1][1], maxW=mem_shapes[-1][2]) self.unet_dec_cross_mode = unet_dec_cross_mode self.decoder = CuboidTransformerUNetDecoder( target_temporal_length=T_out, mem_shapes=mem_shapes, cross_start=dec_cross_start, depth=dec_depth, upsample_type=upsample_type, block_self_attn_patterns=dec_self_attn_patterns, block_self_cuboid_size=dec_self_cuboid_size, block_self_shift_size=dec_self_shift_size, block_self_cuboid_strategy=dec_self_cuboid_strategy, block_cross_attn_patterns=dec_cross_attn_patterns, block_cross_cuboid_hw=dec_cross_cuboid_hw, block_cross_shift_hw=dec_cross_shift_hw, block_cross_cuboid_strategy=dec_cross_cuboid_strategy, block_cross_n_temporal=dec_cross_n_temporal, cross_last_n_frames=dec_cross_last_n_frames, num_heads=num_heads, attn_drop=attn_drop, proj_drop=proj_drop, ffn_drop=ffn_drop, upsample_kernel_size=upsample_kernel_size, ffn_activation=ffn_activation, gated_ffn=gated_ffn, norm_layer=norm_layer, use_inter_ffn=dec_use_inter_ffn, max_temporal_relative=T_in + T_out, padding_type=padding_type, hierarchical_pos_embed=dec_hierarchical_pos_embed, pos_embed_type=pos_embed_type, use_self_global=(num_global_vectors > 0) and use_dec_self_global, self_update_global=dec_self_update_global, use_cross_global=(num_global_vectors > 0) and use_dec_cross_global, use_global_vector_ffn=use_global_vector_ffn, use_global_self_attn=use_global_self_attn, separate_global_qkv=separate_global_qkv, global_dim_ratio=global_dim_ratio, checkpoint_level=checkpoint_level, use_relative_pos=use_relative_pos, self_attn_use_final_proj=self_attn_use_final_proj, # initialization attn_linear_init_mode=attn_linear_init_mode, ffn_linear_init_mode=ffn_linear_init_mode, conv_init_mode=conv_init_mode, up_linear_init_mode=down_up_linear_init_mode, norm_init_mode=norm_init_mode, # different from CuboidTransformerDecoder downsample=downsample, downsample_type=downsample_type, cross_mode=unet_dec_cross_mode, down_linear_init_mode=down_up_linear_init_mode, ) self.reset_parameters() def get_initial_encoder_final_decoder( self, initial_downsample_type, activation, # initial_downsample_type=="conv" initial_downsample_scale, initial_downsample_conv_layers, final_upsample_conv_layers, padding_type, # initial_downsample_type == "stack_conv" initial_downsample_stack_conv_num_layers, initial_downsample_stack_conv_dim_list, initial_downsample_stack_conv_downscale_list, initial_downsample_stack_conv_num_conv_list, ): T_in, H_in, W_in, C_in = self.input_shape T_out, H_out, W_out, C_out = self.target_shape # Construct the initial upsampling / downsampling layers self.initial_downsample_type = initial_downsample_type if self.initial_downsample_type == "conv": if isinstance(initial_downsample_scale, int): initial_downsample_scale = (1, initial_downsample_scale, initial_downsample_scale) elif len(initial_downsample_scale) == 2: initial_downsample_scale = (1, *initial_downsample_scale) elif len(initial_downsample_scale) == 3: initial_downsample_scale = tuple(initial_downsample_scale) else: raise NotImplementedError(f"initial_downsample_scale {initial_downsample_scale} format not supported!") # if any(ele > 1 for ele in initial_downsample_scale): self.initial_encoder = InitialEncoder(dim=C_in, out_dim=self.base_units, downsample_scale=initial_downsample_scale, num_conv_layers=initial_downsample_conv_layers, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.initial_aux_encoder = InitialEncoder(dim=self.auxiliary_channels, out_dim=self.base_units, downsample_scale=initial_downsample_scale, num_conv_layers=initial_downsample_conv_layers, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.final_decoder = FinalDecoder(dim=self.base_units, target_thw=(T_out, H_out, W_out), num_conv_layers=final_upsample_conv_layers, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) new_input_shape = self.initial_encoder.patch_merge.get_out_shape(self.input_shape) self.dec_final_proj = nn.Linear(self.base_units, C_out) elif self.initial_downsample_type == "stack_conv": if initial_downsample_stack_conv_dim_list is None: initial_downsample_stack_conv_dim_list = [self.base_units, ] * initial_downsample_stack_conv_num_layers self.initial_encoder = InitialStackPatchMergingEncoder( num_merge=initial_downsample_stack_conv_num_layers, in_dim=C_in, out_dim_list=initial_downsample_stack_conv_dim_list, downsample_scale_list=initial_downsample_stack_conv_downscale_list, num_conv_per_merge_list=initial_downsample_stack_conv_num_conv_list, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.initial_aux_encoder = InitialStackPatchMergingEncoder( num_merge=initial_downsample_stack_conv_num_layers, in_dim=self.auxiliary_channels, out_dim_list=initial_downsample_stack_conv_dim_list, downsample_scale_list=initial_downsample_stack_conv_downscale_list, num_conv_per_merge_list=initial_downsample_stack_conv_num_conv_list, padding_type=padding_type, activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) # use `self.target_shape` to get correct T_out initial_encoder_out_shape_list = self.initial_encoder.get_out_shape_list(self.target_shape) dec_target_shape_list, dec_in_dim = \ FinalStackUpsamplingDecoder.get_init_params( enc_input_shape=self.target_shape, enc_out_shape_list=initial_encoder_out_shape_list, large_channel=True) self.final_decoder = FinalStackUpsamplingDecoder( target_shape_list=dec_target_shape_list, in_dim=dec_in_dim, num_conv_per_up_list=initial_downsample_stack_conv_num_conv_list[::-1], activation=activation, conv_init_mode=self.conv_init_mode, linear_init_mode=self.down_up_linear_init_mode, norm_init_mode=self.norm_init_mode) self.dec_final_proj = nn.Linear(dec_target_shape_list[-1][-1], C_out) new_input_shape = self.initial_encoder.get_out_shape_list(self.input_shape)[-1] else: raise NotImplementedError self.input_shape_after_initial_downsample = new_input_shape T_in, H_in, W_in, _ = new_input_shape return new_input_shape def reset_parameters(self): if self.num_global_vectors > 0: nn.init.trunc_normal_(self.init_global_vectors, std=.02) if hasattr(self.initial_encoder, "reset_parameters"): self.initial_encoder.reset_parameters() else:
apply_initialization(self.initial_encoder,
15
2023-10-23 11:45:50+00:00
24k
IBM/VillanDiffusion
viallanDiffusion_conditional.py
[ { "identifier": "Backdoor", "path": "caption_dataset.py", "snippet": "class Backdoor():\n CHANNEL_LAST = -1\n CHANNEL_FIRST = -3\n \n GREY_BG_RATIO = 0.3\n \n STOP_SIGN_IMG = \"static/stop_sign_wo_bg.png\"\n # STOP_SIGN_IMG = \"static/stop_sign_bg_blk.jpg\"\n CAT_IMG = \"static/cat_wo_bg.png\"\n GLASSES_IMG = \"static/glasses.png\"\n V_IMG: str = \"static/v_for_vendetta.png\"\n JOKER_IMG: str = \"static/joker.png\"\n HACKER_IMG: str = \"static/hacker.png\"\n HACKING_IMG: str = \"static/hacking.png\"\n \n TARGET_FA = \"FASHION\"\n TARGET_TG = \"TRIGGER\"\n TARGET_BOX = \"BOX\"\n # TARGET_BOX_MED = \"BOX_MED\"\n TARGET_SHIFT = \"SHIFT\"\n TARGET_HAT = \"HAT\"\n TARGET_FEDORA_HAT = \"FEDORA_HAT\"\n TARGET_CAT = \"CAT\"\n TARGET_V: str = \"V\"\n TARGET_JOKER: str = \"JOKER\"\n TARGET_HACKER: str = \"HACKER\"\n TARGET_HACKING: str = \"HACKING\"\n \n TRIGGER_GAP_X = TRIGGER_GAP_Y = 2\n \n TRIGGER_NONE = \"NONE\"\n TRIGGER_FA = \"FASHION\"\n TRIGGER_FA_EZ = \"FASHION_EZ\"\n TRIGGER_MNIST = \"MNIST\"\n TRIGGER_MNIST_EZ = \"MNIST_EZ\"\n TRIGGER_SM_BOX = \"SM_BOX\"\n TRIGGER_XSM_BOX = \"XSM_BOX\"\n TRIGGER_XXSM_BOX = \"XXSM_BOX\"\n TRIGGER_XXXSM_BOX = \"XXXSM_BOX\"\n TRIGGER_BIG_BOX = \"BIG_BOX\"\n TRIGGER_BIG_BOX_MED = \"BIG_BOX_MED\"\n TRIGGER_SM_BOX_MED = \"SM_BOX_MED\"\n TRIGGER_XSM_BOX_MED = \"XSM_BOX_MED\"\n TRIGGER_XXSM_BOX_MED = \"XXSM_BOX_MED\"\n TRIGGER_XXXSM_BOX_MED = \"XXXSM_BOX_MED\"\n TRIGGER_GLASSES = \"GLASSES\"\n TRIGGER_BIG_STOP_SIGN = \"BIG_STOP_SIGN\"\n TRIGGER_SM_STOP_SIGN = \"SM_STOP_SIGN\"\n TRIGGER_XSM_STOP_SIGN = \"XSM_STOP_SIGN\"\n TRIGGER_XXSM_STOP_SIGN = \"XXSM_STOP_SIGN\"\n TRIGGER_XXXSM_STOP_SIGN = \"XXXSM_STOP_SIGN\"\n \n # GREY_NORM_MIN = 0\n # GREY_NORM_MAX = 1\n \n def __init__(self, root: str):\n self.__root = root\n \n def __get_transform(self, channel: int, image_size: Union[int, Tuple[int]], vmin: Union[float, int], vmax: Union[float, int], prev_trans: List=[], next_trans: List=[]):\n if channel == 1:\n channel_trans = transforms.Grayscale(num_output_channels=1)\n elif channel == 3:\n channel_trans = transforms.Lambda(lambda x: x.convert(\"RGB\"))\n \n trans = [channel_trans,\n transforms.Resize(image_size), \n transforms.ToTensor(),\n # transforms.Lambda(lambda x: normalize(vmin_out=vmin, vmax_out=vmax, x=x)),\n transforms.Lambda(lambda x: normalize(vmin_in=0.0, vmax_in=1.0, vmin_out=vmin, vmax_out=vmax, x=x)),\n # transforms.Lambda(lambda x: x * 2 - 1),\n ]\n return Compose(prev_trans + trans + next_trans)\n \n @staticmethod\n def __read_img(path: Union[str, os.PathLike]):\n return Image.open(path)\n @staticmethod\n def __bg2grey(trig, vmin: Union[float, int], vmax: Union[float, int]):\n thres = (vmax - vmin) * Backdoor.GREY_BG_RATIO + vmin\n trig[trig <= thres] = thres\n return trig\n @staticmethod\n def __bg2black(trig, vmin: Union[float, int], vmax: Union[float, int]):\n thres = (vmax - vmin) * Backdoor.GREY_BG_RATIO + vmin\n trig[trig <= thres] = vmin\n return trig\n @staticmethod\n def __white2grey(trig, vmin: Union[float, int], vmax: Union[float, int]):\n thres = vmax - (vmax - vmin) * Backdoor.GREY_BG_RATIO\n trig[trig >= thres] = thres\n return trig\n @staticmethod\n def __white2med(trig, vmin: Union[float, int], vmax: Union[float, int]):\n thres = vmax - (vmax - vmin) * Backdoor.GREY_BG_RATIO\n trig[trig >= 0.7] = (vmax - vmin) / 2\n return trig\n \n def __get_img_target(self, path: Union[str, os.PathLike], image_size: int, channel: int, vmin: Union[float, int], vmax: Union[float, int], is_clip_bg: bool=True):\n img = Backdoor.__read_img(path)\n trig = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)(img)\n if is_clip_bg:\n return Backdoor.__bg2grey(trig=trig, vmin=vmin, vmax=vmax)\n return trig\n \n def __get_img_trigger(self, path: Union[str, os.PathLike], image_size: int, channel: int, trigger_sz: int, vmin: Union[float, int], vmax: Union[float, int], x: int=None, y: int=None):\n # Padding of Left & Top\n l_pad = t_pad = int((image_size - trigger_sz) / 2)\n r_pad = image_size - trigger_sz - l_pad\n b_pad = image_size - trigger_sz - t_pad\n residual = image_size - trigger_sz\n if x != None:\n if x > 0:\n l_pad = x\n r_pad = residual - l_pad\n else:\n r_pad = -x\n l_pad = residual - r_pad\n if y != None:\n if y > 0:\n t_pad = y\n b_pad = residual - t_pad\n else:\n b_pad = -y\n t_pad = residual - b_pad\n \n img = Backdoor.__read_img(path)\n next_trans = [transforms.Pad(padding=[l_pad, t_pad, r_pad, b_pad], fill=vmin)]\n trig = self.__get_transform(channel=channel, image_size=trigger_sz, vmin=vmin, vmax=vmax, next_trans=next_trans)(img)\n # thres = (vmax - vmin) * 0.3 + vmin\n # trig[trig <= thres] = vmin\n trig[trig >= 0.999] = vmin\n # print(f\"trigger shape: {trig.shape}\")\n return trig\n @staticmethod\n def __roll(x: torch.Tensor, dx: int, dy: int):\n shift = tuple([0] * len(x.shape[:-2]) + [dy] + [dx])\n dim = tuple([i for i in range(len(x.shape))])\n return torch.roll(x, shifts=shift, dims=dim)\n @staticmethod\n def __get_box_trig(b1: Tuple[int, int], b2: Tuple[int, int], channel: int, image_size: int, vmin: Union[float, int], vmax: Union[float, int], val: Union[float, int]):\n if isinstance(image_size, int):\n img_shape = (image_size, image_size)\n elif isinstance(image_size, list):\n img_shape = image_size\n else:\n raise TypeError(f\"Argument image_size should be either an integer or a list\")\n trig = torch.full(size=(channel, *img_shape), fill_value=vmin)\n trig[:, b1[0]:b2[0], b1[1]:b2[1]] = val\n return trig\n @staticmethod\n def __get_white_box_trig(b1: Tuple[int, int], b2: Tuple[int, int], channel: int, image_size: int, vmin: Union[float, int], vmax: Union[float, int]):\n return Backdoor.__get_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax, val=vmax)\n @staticmethod\n def __get_grey_box_trig(b1: Tuple[int, int], b2: Tuple[int, int], channel: int, image_size: int, vmin: Union[float, int], vmax: Union[float, int]):\n return Backdoor.__get_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax, val=(vmin + vmax) / 2)\n @staticmethod\n def __get_trig_box_coord(x: int, y: int):\n if x < 0 or y < 0:\n raise ValueError(f\"Argument x, y should > 0\")\n return (- (y + Backdoor.TRIGGER_GAP_Y), - (x + Backdoor.TRIGGER_GAP_X)), (- Backdoor.TRIGGER_GAP_Y, - Backdoor.TRIGGER_GAP_X)\n \n def get_trigger(self, type: str, channel: int, image_size: int, vmin: Union[float, int]=DEFAULT_VMIN, vmax: Union[float, int]=DEFAULT_VMAX) -> torch.Tensor:\n if type == Backdoor.TRIGGER_FA:\n trans = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n ds = FashionMNIST(root=self.__root, train=True, download=True, transform=trans)\n return Backdoor.__roll(Backdoor.__bg2black(trig=ds[0][0], vmin=vmin, vmax=vmax), dx=0, dy=2)\n elif type == Backdoor.TRIGGER_FA_EZ:\n trans = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n ds = FashionMNIST(root=self.__root, train=True, download=True, transform=trans)\n # Backdoor image ID: 135, 144\n # return ds[144][0]\n return Backdoor.__roll(Backdoor.__bg2black(trig=ds[144][0], vmin=vmin, vmax=vmax), dx=0, dy=4)\n elif type == Backdoor.TRIGGER_MNIST:\n trans = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n ds = MNIST(root=self.__root, train=True, download=True, transform=trans)\n # Backdoor image ID: 3, 6, 8\n # return ds[3][0]\n return Backdoor.__roll(Backdoor.__bg2black(trig=ds[3][0], vmin=vmin, vmax=vmax), dx=10, dy=3)\n elif type == Backdoor.TRIGGER_MNIST_EZ:\n trans = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n ds = MNIST(root=self.__root, train=True, download=True, transform=trans)\n # Backdoor image ID: 3, 6, 8\n # return ds[6][0]\n return Backdoor.__roll(Backdoor.__bg2black(trig=ds[6][0], vmin=vmin, vmax=vmax), dx=10, dy=3)\n elif type == Backdoor.TRIGGER_SM_BOX: \n b1, b2 = Backdoor.__get_trig_box_coord(14, 14)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = vmax\n # return trig\n return Backdoor.__get_white_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_XSM_BOX: \n b1, b2 = Backdoor.__get_trig_box_coord(11, 11)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = vmax\n # return trig\n return Backdoor.__get_white_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_XXSM_BOX: \n b1, b2 = Backdoor.__get_trig_box_coord(8, 8)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = vmax\n # return trig\n return Backdoor.__get_white_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_XXXSM_BOX: \n b1, b2 = Backdoor.__get_trig_box_coord(4, 4)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = vmax\n # return trig\n return Backdoor.__get_white_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_BIG_BOX: \n b1, b2 = Backdoor.__get_trig_box_coord(18, 18)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = vmax\n # return trig\n return Backdoor.__get_white_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_BIG_BOX_MED:\n b1, b2 = Backdoor.__get_trig_box_coord(18, 18)\n return Backdoor.__get_grey_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_SM_BOX_MED:\n b1, b2 = Backdoor.__get_trig_box_coord(14, 14)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = (vmax + vmin) / 2\n # return trig\n return Backdoor.__get_grey_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_XSM_BOX_MED: \n b1, b2 = Backdoor.__get_trig_box_coord(11, 11)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = (vmax + vmin) / 2\n # return trig\n return Backdoor.__get_grey_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_XXSM_BOX_MED: \n b1, b2 = Backdoor.__get_trig_box_coord(8, 8)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = (vmax + vmin) / 2\n # return trig\n return Backdoor.__get_grey_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_XXXSM_BOX_MED: \n b1, b2 = Backdoor.__get_trig_box_coord(4, 4)\n # trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n # trig[:, b1[0]:b2[0], b1[1]:b2[1]] = (vmax + vmin) / 2\n # return trig\n return Backdoor.__get_grey_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_GLASSES:\n trigger_sz = int(image_size * 0.625)\n return self.__get_img_trigger(path=Backdoor.GLASSES_IMG, image_size=image_size, channel=channel, trigger_sz=trigger_sz, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TRIGGER_BIG_STOP_SIGN:\n return self.__get_img_trigger(path=Backdoor.STOP_SIGN_IMG, image_size=image_size, channel=channel, trigger_sz=18, vmin=vmin, vmax=vmax, x=-2, y=-2)\n elif type == Backdoor.TRIGGER_SM_STOP_SIGN:\n return self.__get_img_trigger(path=Backdoor.STOP_SIGN_IMG, image_size=image_size, channel=channel, trigger_sz=14, vmin=vmin, vmax=vmax, x=-2, y=-2)\n elif type == Backdoor.TRIGGER_XSM_STOP_SIGN:\n return self.__get_img_trigger(path=Backdoor.STOP_SIGN_IMG, image_size=image_size, channel=channel, trigger_sz=11, vmin=vmin, vmax=vmax, x=-2, y=-2)\n elif type == Backdoor.TRIGGER_XXSM_STOP_SIGN:\n return self.__get_img_trigger(path=Backdoor.STOP_SIGN_IMG, image_size=image_size, channel=channel, trigger_sz=8, vmin=vmin, vmax=vmax, x=-2, y=-2)\n elif type == Backdoor.TRIGGER_XXXSM_STOP_SIGN:\n return self.__get_img_trigger(path=Backdoor.STOP_SIGN_IMG, image_size=image_size, channel=channel, trigger_sz=4, vmin=vmin, vmax=vmax, x=-2, y=-2)\n elif type == Backdoor.TRIGGER_NONE: \n # trig = torch.zeros(channel, image_size, image_size)\n trig = torch.full(size=(channel, image_size, image_size), fill_value=vmin)\n return trig\n else:\n raise ValueError(f\"Trigger type {type} isn't found\")\n \n def __check_channel(self, sample: torch.Tensor, channel_first: bool=None) -> int:\n if channel_first != None:\n # If user specified the localation of the channel\n if self.__channel_first:\n if sample.shape[Backdoor.CHANNEL_FIRST] == 1 or sample.shape[Backdoor.CHANNEL_FIRST] == 3:\n return Backdoor.CHANNEL_FIRST\n elif sample.shape[Backdoor.CHANNEL_LAST] == 1 or sample.shape[Backdoor.CHANNEL_LAST] == 3:\n return Backdoor.CHANNEL_LAST\n warnings.warn(Log.warning(\"The specified Channel doesn't exist, determine channel automatically\"))\n print(Log.warning(\"The specified Channel doesn't exist, determine channel automatically\"))\n \n # If user doesn't specified the localation of the channel or the \n if (sample.shape[Backdoor.CHANNEL_LAST] == 1 or sample.shape[Backdoor.CHANNEL_LAST] == 3) and \\\n (sample.shape[Backdoor.CHANNEL_FIRST] == 1 or sample.shape[Backdoor.CHANNEL_FIRST] == 3):\n raise ValueError(f\"Duplicate channel found, found {sample.shape[Backdoor.CHANNEL_LAST]} at dimension 2 and {sample.shape[Backdoor.CHANNEL_FIRST]} at dimension 0\")\n\n if sample.shape[Backdoor.CHANNEL_LAST] == 1 or sample.shape[Backdoor.CHANNEL_LAST] == 3:\n return Backdoor.CHANNEL_LAST\n elif sample.shape[Backdoor.CHANNEL_FIRST] == 1 or sample.shape[Backdoor.CHANNEL_FIRST] == 3:\n return Backdoor.CHANNEL_FIRST\n else:\n raise ValueError(f\"Invalid channel shape, found {sample.shape[Backdoor.CHANNEL_LAST]} at dimension 2 and {sample.shape[Backdoor.CHANNEL_FIRST]} at dimension 0\")\n \n def __check_image_size(self, sample: torch.Tensor, channel_loc: int):\n image_size = list(sample.shape)[-3:]\n del image_size[channel_loc]\n return image_size\n \n def get_target(self, type: str, trigger: torch.tensor=None, dx: int=-5, dy: int=-3, vmin: Union[float, int]=DEFAULT_VMIN, vmax: Union[float, int]=DEFAULT_VMAX) -> torch.Tensor:\n channel_loc = self.__check_channel(sample=trigger, channel_first=None)\n channel = trigger.shape[channel_loc]\n image_size = self.__check_image_size(sample=trigger, channel_loc=channel_loc)\n print(f\"image size: {image_size}\")\n if type == Backdoor.TARGET_TG:\n if trigger == None:\n raise ValueError(\"trigger shouldn't be none\")\n return Backdoor.__bg2grey(trigger.clone().detach(), vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_SHIFT:\n if trigger == None:\n raise ValueError(\"trigger shouldn't be none\")\n # t_trig = trigger.clone().detach()\n # shift = tuple([0] * len(t_trig.shape[:-2]) + [dy] + [dx])\n # dim = tuple([i for i in range(len(t_trig.shape))])\n # # print(f\"Shift: {shift} | t_trig: {t_trig.shape}\")\n # return torch.roll(t_trig, shifts=shift, dims=dim)\n return Backdoor.__bg2grey(Backdoor.__roll(trigger.clone().detach(), dx=dx, dy=dy), vmin=vmin, vmax=vmax)\n # elif type == Backdoor.TARGET_BOX:\n # # z = torch.full_like(trigger, fill_value=vmin)\n # # z[:, 0:10, 0:10] = vmax\n # # return z\n # b1 = (None, None)\n # b2 = (10, 10)\n # return Backdoor.__get_white_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_BOX:\n b1 = (None, None)\n b2 = (10, 10)\n return Backdoor.__bg2grey(trig=Backdoor.__get_grey_box_trig(b1=b1, b2=b2, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax), vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_FA:\n trans = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n ds = FashionMNIST(root=self.__root, train=True, download=True, transform=trans)\n # return ds[0][0]\n return Backdoor.__bg2grey(trig=ds[0][0], vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_HAT:\n # img = Backdoor.__read_img(\"static/hat.png\")\n # trig = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)(img)\n # return trig\n return self.__get_img_target(path=\"static/hat.png\", channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_FEDORA_HAT:\n # img = Backdoor.__read_img(\"static/fedora-hat.png\")\n # trig = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)(img)\n # return trig\n return self.__get_img_target(path=\"static/fedora-hat.png\", channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_CAT:\n # img = Backdoor.__read_img(\"static/cat.png\")\n # trig = self.__get_transform(channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)(img)\n # return trig\n return self.__get_img_target(path=Backdoor.CAT_IMG, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_V:\n return self.__get_img_target(path=Backdoor.V_IMG, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax, is_clip_bg=False)\n elif type == Backdoor.TARGET_JOKER:\n return self.__get_img_target(path=Backdoor.JOKER_IMG, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax, is_clip_bg=False)\n elif type == Backdoor.TARGET_HACKER:\n return self.__get_img_target(path=Backdoor.HACKER_IMG, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n elif type == Backdoor.TARGET_HACKING:\n return self.__get_img_target(path=Backdoor.HACKING_IMG, channel=channel, image_size=image_size, vmin=vmin, vmax=vmax)\n else:\n raise NotImplementedError(f\"Target type {type} isn't found\")\n \n def show_image(self, img: torch.Tensor):\n plt.axis('off') \n plt.tight_layout()\n plt.imshow(img.permute(1, 2, 0).squeeze(), cmap='gray')\n plt.show()" }, { "identifier": "DatasetLoader", "path": "caption_dataset.py", "snippet": "class DatasetLoader(object):\n # Dataset generation mode\n MODE_FIXED = \"FIXED\"\n MODE_FLEX = \"FLEX\"\n \n # Dataset names\n MNIST = \"MNIST\"\n CIFAR10 = \"CIFAR10\"\n CELEBA = \"CELEBA\"\n LSUN_CHURCH = \"LSUN-CHURCH\"\n LSUN_BEDROOM = \"LSUN-BEDROOM\"\n CELEBA_HQ = \"CELEBA-HQ\"\n CELEBA_HQ_DIALOG = \"CELEBA-HQ-DIALOG\"\n LAION_COCO = \"LAION-COCO\"\n LAION_COCO_1 = \"LAION-COCO-1\"\n LAION_COCO_20K = \"LAION-COCO-20K\"\n LAION_COCO_200 = \"LAION-COCO-200\"\n LAION_COCO_50K = \"LAION-COCO-50K\"\n POKEMON_CAPTION = \"POKEMON-CAPTION\"\n \n # Inpaint Type\n INPAINT_BOX: str = \"INPAINT_BOX\"\n INPAINT_LINE: str = \"INPAINT_LINE\"\n\n TRAIN = \"train\"\n TEST = \"test\"\n POISON_IMAGE = \"poison_image\"\n IMAGE = \"image\"\n IS_CLEAN = \"is_clean\"\n RAW = \"raw\"\n LABEL = \"label\"\n CAPTION = \"caption\"\n RAW_CAPTION = \"raw_caption\"\n \n CAPTION_AUGMENT_KEY: str = \"caption_aug\"\n # CAPTION_TOKEN = \"caption_token\"\n def __init__(self, name: str, label: int=None, root: str=None, \n channel: int=None, image_size: int=None, split: str='[:100%]',\n vmin: Union[int, float]=DEFAULT_VMIN, vmax: Union[int, float]=DEFAULT_VMAX, \n batch_size: int=512, shuffle: bool=True, num_workers: int=8, force_R_to_0: bool=False, seed: int=0):\n self.__root = root\n self.__name = name\n if label != None and not isinstance(label, list)and not isinstance(label, tuple):\n self.__label = [label]\n else:\n self.__label = label\n self.__channel = channel\n self.__vmin = vmin\n self.__vmax = vmax\n self.__batch_size = batch_size\n self.__shuffle = shuffle\n self.__split = split\n self.__dataset = self.__load_dataset(name=name)\n self.__set_img_shape(image_size=image_size)\n self.__trigger = self.__target = self.__caption_trigger = self.__poison_rate = None\n self.__clean_rate = 1\n self.__seed = seed\n self.__num_workers = num_workers\n self.__force_R_to_0 = force_R_to_0\n self.__caption_backdoor = CaptionBackdoor()\n if root != None:\n self.__backdoor = Backdoor(root=root)\n \n # self.__prep_dataset()\n\n def set_poison(self, trigger_type: str, target_type: str, caption_trigger_type: str=None, rand_caption_trig_pos: int=0, target_dx: int=-5, target_dy: int=-3, clean_rate: float=1.0, poison_rate: float=0.2) -> 'DatasetLoader':\n if self.__root == None:\n raise ValueError(\"Attribute 'root' is None\")\n self.__clean_rate = clean_rate\n self.__poison_rate = poison_rate\n self.__trigger = self.__backdoor.get_trigger(type=trigger_type, channel=self.__channel, image_size=self.__image_size, vmin=self.__vmin, vmax=self.__vmax)\n self.__caption_trigger = self.__caption_backdoor.get_trigger(_type=caption_trigger_type)\n self.__rand_caption_trig_pos: int = rand_caption_trig_pos\n self.__target = self.__backdoor.get_target(type=target_type, trigger=self.__trigger, dx=target_dx, dy=target_dy)\n return self\n \n def __load_dataset(self, name: str):\n datasets.config.IN_MEMORY_MAX_SIZE = 50 * 2 ** 30\n split_method = f'train{self.__split}+test{self.__split}'\n if name == DatasetLoader.MNIST:\n return load_dataset(\"mnist\", split=split_method)\n elif name == DatasetLoader.CIFAR10:\n return load_dataset(\"cifar10\", split=split_method)\n elif name == DatasetLoader.CELEBA:\n return load_dataset(\"student/celebA\", split=f\"train{self.__split}\")\n elif name == DatasetLoader.CELEBA_HQ:\n return load_dataset(\"datasets/celeba_hq_256\", split=f\"train{self.__split}\")\n elif name ==DatasetLoader.CELEBA_HQ_DIALOG:\n return CelebA_HQ_Dialog(path=\"datasets/CelebA-Dialog (HQ)\").prepare(split=f\"train{self.__split}\")\n elif name == DatasetLoader.LAION_COCO or name == DatasetLoader.LAION_COCO_20K:\n return LaionCoco.load(\"/work/u2941379/workspace/laion_coco_hg200K.hf\")\n elif name == DatasetLoader.LAION_COCO_1:\n return LaionCoco.load(\"/work/u2941379/workspace/laion_coco_hg1.hf\")\n elif name == DatasetLoader.LAION_COCO_200:\n return LaionCoco.load(\"/work/u2941379/workspace/laion_coco_hg200.hf\")\n elif name == DatasetLoader.LAION_COCO_50K:\n return LaionCoco.load(\"/work/u2941379/workspace/laion_coco_hg50K.hf\")\n elif name == DatasetLoader.POKEMON_CAPTION:\n return load_dataset(\"lambdalabs/pokemon-blip-captions\", split=f\"train{self.__split}\")\n else:\n raise NotImplementedError(f\"Undefined dataset: {name}\")\n \n def __set_img_shape(self, image_size: int) -> None:\n # Set channel\n if self.__name == self.MNIST:\n self.__channel = 1 if self.__channel == None else self.__channel\n # self.__vmin = -1\n # self.__vmax = 1\n self.__cmap = \"gray\"\n elif self.__name == self.CIFAR10 or self.__name == self.CELEBA or self.__name == self.CELEBA_HQ or self.__name == self.LSUN_CHURCH or self.__name == self.LAION_COCO or self.__name == self.LAION_COCO_1 or self.__name == self.LAION_COCO_200 or self.__name == self.LAION_COCO_20K or self.__name == self.LAION_COCO_50K or self.__name == self.POKEMON_CAPTION or self.__name == self.CELEBA_HQ_DIALOG:\n self.__channel = 3 if self.__channel == None else self.__channel\n # self.__vmin = -1\n # self.__vmax = 1\n self.__cmap = None\n else:\n raise NotImplementedError(f\"No dataset named as {self.__name}\")\n\n # Set image size\n if image_size == None:\n if self.__name == self.MNIST:\n self.__image_size = 32\n elif self.__name == self.CIFAR10:\n self.__image_size = 32\n elif self.__name == self.CELEBA:\n self.__image_size = 64\n elif self.__name == self.CELEBA_HQ or self.__name == self.LSUN_CHURCH:\n self.__image_size = 256\n elif self.__name == self.LAION_COCO or self.__name == self.LAION_COCO_1 or self.__name == self.LAION_COCO_200 or self.__name == self.LAION_COCO_20K or self.__name == self.LAION_COCO_50K or self.__name == self.POKEMON_CAPTION or self.__name == self.CELEBA_HQ_DIALOG:\n self.__image_size = 512\n else:\n raise NotImplementedError(f\"No dataset named as {self.__name}\")\n else:\n self.__image_size = image_size\n \n def __get_transform(self, prev_trans: List=[], next_trans: List=[]):\n if self.__channel == 1:\n channel_trans = transforms.Grayscale(num_output_channels=1)\n elif self.__channel == 3:\n channel_trans = transforms.Lambda(lambda x: x.convert(\"RGB\"))\n \n aug_trans = []\n if self.__dataset != DatasetLoader.LSUN_CHURCH:\n aug_trans = [transforms.RandomHorizontalFlip()] \n \n trans = [channel_trans,\n transforms.Resize([self.__image_size, self.__image_size]), \n transforms.ToTensor(),\n transforms.Lambda(lambda x: normalize(vmin_in=0, vmax_in=1, vmin_out=self.__vmin, vmax_out=self.__vmax, x=x)),\n # transforms.Normalize([0.5], [0.5]),\n ] + aug_trans\n return Compose(prev_trans + trans + next_trans)\n \n # trans = [transforms.Resize(self.__image_size), \n # transforms.ToTensor(),\n # transforms.Lambda(lambda x: normalize(vmin=self.__vmin, vmax=self.__vmax, x=x))]\n # return Compose(prev_trans + self.TRANSFORM_OPS + + next_trans)\n \n def __fixed_sz_dataset_old(self):\n gen = torch.Generator()\n gen.manual_seed(self.__seed)\n \n # Apply transformations\n self.__full_dataset = self.__dataset.with_transform(self.__transform_generator(self.__name, True))\n\n # Generate poisoned dataset\n if self.__poison_rate > 0:\n full_ds_len = len(self.__full_dataset[DatasetLoader.TRAIN])\n perm_idx = torch.randperm(full_ds_len, generator=gen).long()\n self.__poison_n = int(full_ds_len * float(self.__poison_rate))\n self.__clean_n = full_ds_len - self.__poison_n\n \n # print(f\"perm_idx: {perm_idx}\")\n # print(f\"len(perm_idx): {len(perm_idx)}, max: {torch.max(perm_idx)}, min: {torch.min(perm_idx)}\")\n # print(f\"Clean n: {self.__clean_n}, Poison n: {self.__poison_n}\")\n \n self.__full_dataset[DatasetLoader.TRAIN] = Subset(self.__full_dataset[DatasetLoader.TRAIN], perm_idx[:self.__clean_n].tolist())\n \n # print(f\"Clean dataset len: {len(self.__full_dataset[DatasetLoader.TRAIN])}\")\n \n self.__backdoor_dataset = self.__dataset.with_transform(self.__transform_generator(self.__name, False))\n self.__backdoor_dataset = Subset(self.__backdoor_dataset[DatasetLoader.TRAIN], perm_idx[self.__clean_n:].tolist())\n # print(f\"Backdoor dataset len: {len(self.__backdoor_dataset)}\")\n self.__full_dataset[DatasetLoader.TRAIN] = ConcatDataset([self.__full_dataset[DatasetLoader.TRAIN], self.__backdoor_dataset])\n # print(f\"self.__full_dataset[DatasetLoader.TRAIN] len: {len(self.__full_dataset[DatasetLoader.TRAIN])}\")\n self.__full_dataset = self.__full_dataset[DatasetLoader.TRAIN]\n \n def manual_split():\n pass\n \n def __fixed_sz_dataset(self):\n gen = torch.Generator()\n gen.manual_seed(self.__seed)\n \n if float(self.__poison_rate) < 0 or float(self.__poison_rate) > 1:\n raise ValueError(f\"In {DatasetLoader.MODE_FIXED}, poison rate should <= 1.0 and >= 0.0\")\n \n ds_n = len(self.__dataset)\n backdoor_n = int(ds_n * float(self.__poison_rate))\n ds_ls = []\n \n # Apply transformations\n if float(self.__poison_rate) == 0.0:\n self.__clean_dataset = self.__dataset\n self.__backdoor_dataset = None\n elif float(self.__poison_rate) == 1.0:\n self.__clean_dataset = None\n self.__backdoor_dataset = self.__dataset\n else:\n full_dataset: datasets.DatasetDict = self.__dataset.train_test_split(test_size=backdoor_n)\n self.__clean_dataset = full_dataset[DatasetLoader.TRAIN]\n self.__backdoor_dataset = full_dataset[DatasetLoader.TEST]\n \n if self.__clean_dataset != None:\n clean_n = len(self.__clean_dataset)\n self.__clean_dataset = self.__clean_dataset.add_column(DatasetLoader.IS_CLEAN, [True] * clean_n)\n ds_ls.append(self.__clean_dataset)\n # print(f\"TRAIN IS_CLEAN N: {len(self.__full_dataset[DatasetLoader.TRAIN].filter(lambda x: x[DatasetLoader.IS_CLEAN]))}\")\n \n if self.__backdoor_dataset != None:\n backdoor_n = len(self.__backdoor_dataset)\n self.__backdoor_dataset = self.__backdoor_dataset.add_column(DatasetLoader.IS_CLEAN, [False] * backdoor_n)\n ds_ls.append(self.__backdoor_dataset)\n # print(f\"TEST !IS_CLEAN N: {len(self.__full_dataset[DatasetLoader.TEST].filter(lambda x: not x[DatasetLoader.IS_CLEAN]))}\")\n \n def trans(x):\n if x[DatasetLoader.IS_CLEAN][0]:\n # print(f\"IS_CLEAN: {x[DatasetLoader.IS_CLEAN]}\")\n return self.__transform_generator(self.__name, True)(x)\n return self.__transform_generator(self.__name, False)(x)\n \n \n self.__full_dataset = concatenate_datasets(ds_ls)\n # print(f\"IS_CLEAN N: {len(self.__full_dataset.filter(lambda x: x[DatasetLoader.IS_CLEAN]))}\")\n self.__full_dataset = self.__full_dataset.with_transform(trans)\n # print(f\"__full_dataset len: {len(self.__full_dataset)}, features: {self.__full_dataset.features}, keys: {self.__full_dataset[0].keys()}\")\n \n\n def __flex_sz_dataset_old(self):\n # Apply transformations\n self.__full_dataset = self.__dataset.with_transform(self.__transform_generator(self.__name, True))\n \n full_ds_len = len(self.__full_dataset[DatasetLoader.TRAIN])\n \n # Shrink the clean dataset\n if self.__clean_rate != 1:\n self.__clean_n = int(full_ds_len * float(self.__clean_rate))\n self.__full_dataset[DatasetLoader.TRAIN] = Subset(self.__full_dataset[DatasetLoader.TRAIN], list(range(0, self.__clean_n, 1)))\n # MODIFIED: Only 1 poisoned training sample\n # self.__full_dataset[DatasetLoader.TRAIN] = Subset(self.__full_dataset[DatasetLoader.TRAIN], list(range(0, 1, 1)))\n \n # Generate poisoned dataset\n if self.__poison_rate > 0:\n self.__backdoor_dataset = self.__dataset.with_transform(self.__transform_generator(self.__name, False))\n self.__poison_n = int(full_ds_len * float(self.__poison_rate))\n self.__backdoor_dataset = Subset(self.__backdoor_dataset[DatasetLoader.TRAIN], list(range(0, self.__poison_n, 1))) \n self.__full_dataset[DatasetLoader.TRAIN] = ConcatDataset([self.__full_dataset[DatasetLoader.TRAIN], self.__backdoor_dataset])\n # MODIFIED: Only 1 clean training sample\n # self.__backdoor_dataset = Subset(self.__backdoor_dataset[DatasetLoader.TRAIN], list(range(0, 1, 1)))\n # self.__full_dataset[DatasetLoader.TRAIN] = self.__backdoor_dataset\n \n self.__full_dataset = self.__full_dataset[DatasetLoader.TRAIN]\n \n def __flex_sz_dataset(self):\n gen = torch.Generator()\n gen.manual_seed(self.__seed)\n \n ds_n = len(self.__dataset)\n train_n = int(ds_n * float(self.__clean_rate))\n test_n = int(ds_n * float(self.__poison_rate))\n \n # Apply transformations\n self.__full_dataset: datasets.DatasetDict = self.__dataset.train_test_split(train_size=train_n, test_size=test_n)\n self.__full_dataset[DatasetLoader.TRAIN] = self.__full_dataset[DatasetLoader.TRAIN].add_column(DatasetLoader.IS_CLEAN, [True] * train_n)\n self.__full_dataset[DatasetLoader.TEST] = self.__full_dataset[DatasetLoader.TEST].add_column(DatasetLoader.IS_CLEAN, [False] * test_n)\n \n def trans(x):\n if x[DatasetLoader.IS_CLEAN][0]:\n return self.__transform_generator(self.__name, True)(x)\n return self.__transform_generator(self.__name, False)(x)\n \n self.__full_dataset = concatenate_datasets([self.__full_dataset[DatasetLoader.TRAIN], self.__full_dataset[DatasetLoader.TEST]])\n self.__full_dataset = self.__full_dataset.with_transform(trans)\n \n def prepare_dataset(self, mode: str=\"FIXED\") -> 'DatasetLoader':\n # Filter specified classes\n if self.__label != None:\n self.__dataset = self.__dataset.filter(lambda x: x[DatasetLoader.LABEL] in self.__label)\n \n # # Apply transformations\n # self.__full_dataset = self.__dataset.with_transform(self.__transform_generator(self.__name, True))\n \n # full_ds_len = len(self.__full_dataset[DatasetLoader.TRAIN])\n \n # # Shrink the clean dataset\n # if isinstance(self.__clean_rate, float) and self.__clean_rate != 1:\n # self.__clean_n = int(full_ds_len * self.__clean_rate)\n # self.__full_dataset[DatasetLoader.TRAIN] = Subset(self.__full_dataset[DatasetLoader.TRAIN], list(range(0, self.__clean_n, 1)))\n # # MODIFIED: Only 1 poisoned training sample\n # # self.__full_dataset[DatasetLoader.TRAIN] = Subset(self.__full_dataset[DatasetLoader.TRAIN], list(range(0, 1, 1)))\n \n # # Generate poisoned dataset\n # if isinstance(self.__poison_rate, float) and self.__poison_rate > 0:\n # self.__backdoor_dataset = self.__dataset.with_transform(self.__transform_generator(self.__name, False))\n # self.__poison_n = int(full_ds_len * self.__poison_rate)\n # self.__backdoor_dataset = Subset(self.__backdoor_dataset[DatasetLoader.TRAIN], list(range(0, self.__poison_n, 1))) \n # self.__full_dataset[DatasetLoader.TRAIN] = ConcatDataset([self.__full_dataset[DatasetLoader.TRAIN], self.__backdoor_dataset])\n # # MODIFIED: Only 1 clean training sample\n # # self.__backdoor_dataset = Subset(self.__backdoor_dataset[DatasetLoader.TRAIN], list(range(0, 1, 1)))\n # # self.__full_dataset[DatasetLoader.TRAIN] = self.__backdoor_dataset\n \n if mode == DatasetLoader.MODE_FIXED:\n if self.__clean_rate != 1.0 or self.__clean_rate != None:\n Log.warning(\"In 'FIXED' mode of DatasetLoader, the clean_rate will be ignored whatever.\")\n self.__fixed_sz_dataset()\n elif mode == DatasetLoader.MODE_FLEX:\n self.__flex_sz_dataset()\n else:\n raise NotImplementedError(f\"Argument mode: {mode} isn't defined\")\n \n # Note the minimum and the maximum values\n ex = self.__full_dataset[0][DatasetLoader.IMAGE]\n if len(ex) == 1:\n print(f\"Note that CHANNEL 0 - vmin: {torch.min(ex[0])} and vmax: {torch.max(ex[0])}\") \n elif len(ex) == 3:\n print(f\"Note that CHANNEL 0 - vmin: {torch.min(ex[0])} and vmax: {torch.max(ex[0])} | CHANNEL 1 - vmin: {torch.min(ex[1])} and vmax: {torch.max(ex[1])} | CHANNEL 2 - vmin: {torch.min(ex[2])} and vmax: {torch.max(ex[2])}\")\n return self\n\n def get_dataset(self) -> datasets.Dataset:\n return self.__full_dataset\n\n def get_dataloader(self) -> torch.utils.data.DataLoader:\n datasets = self.get_dataset()\n get_dsl = partial(DataLoader, datasets, batch_size=self.__batch_size, shuffle=self.__shuffle, pin_memory=True, num_workers=self.__num_workers)\n # if self.__name == DatasetLoader.LAION_COCO or self.__name == DatasetLoader.LAION_COCO_200 or self.__name == DatasetLoader.LAION_COCO_50K:\n # return get_dsl(collate_fn=lambda x: x)\n return get_dsl()\n \n def get_mask(self, trigger: torch.Tensor) -> torch.Tensor:\n return torch.where(trigger > self.__vmin, 0, 1)\n\n def store_dataset(self, path: str):\n os.makedirs(path, exist_ok=True)\n \n if self.__name == self.MNIST:\n img_key = \"image\"\n cap_keys = []\n elif self.__name == self.CIFAR10:\n img_key = \"img\"\n cap_keys = []\n elif self.__name == self.CELEBA:\n img_key = \"image\"\n cap_keys = []\n elif self.__name == self.CELEBA_HQ:\n img_key = \"image\"\n cap_keys = []\n elif self.__name == self.LAION_COCO or self.__name == self.LAION_COCO_1 or self.__name == self.LAION_COCO_200 or self.__name == self.LAION_COCO_20K or self.__name == self.LAION_COCO_50K:\n img_key = \"image\"\n cap_keys = [\"TEXT\"]\n elif self.__name == self.POKEMON_CAPTION or self.__name == self.CELEBA_HQ_DIALOG:\n img_key = \"image\"\n cap_keys = [\"text\"]\n else:\n raise NotImplementedError(f\"No dataset named as {self.__name}\")\n \n def collate_fn(examples):\n return {img_key: [example[img_key] for example in examples],}\n \n dl = DataLoader(self.__dataset, batch_size=self.__batch_size, shuffle=self.__shuffle, pin_memory=True, num_workers=self.__num_workers, collate_fn=collate_fn)\n cnt: int = 0\n for batch in tqdm(dl):\n for sample in batch[img_key]:\n sample.resize((self.__image_size, self.__image_size)).save(os.path.join(path, f\"{cnt}.png\"))\n cnt += 1\n\n def __transform_generator(self, dataset_name: str, clean: bool) -> Callable[[torch.Tensor], torch.Tensor]:\n if dataset_name == self.MNIST:\n img_key = \"image\"\n cap_keys = []\n elif dataset_name == self.CIFAR10:\n img_key = \"img\"\n cap_keys = []\n elif dataset_name == self.CELEBA:\n img_key = \"image\"\n cap_keys = []\n elif dataset_name == self.CELEBA_HQ:\n img_key = \"image\"\n cap_keys = []\n elif dataset_name == self.LAION_COCO or dataset_name == self.LAION_COCO_1 or dataset_name == self.LAION_COCO_200 or dataset_name == self.LAION_COCO_20K or dataset_name == self.LAION_COCO_50K:\n img_key = \"image\"\n cap_keys = [\"TEXT\"]\n elif dataset_name == self.POKEMON_CAPTION or dataset_name == self.CELEBA_HQ_DIALOG:\n img_key = \"image\"\n cap_keys = [\"text\"]\n else:\n raise NotImplementedError(f\"No dataset named as {dataset_name}\")\n \n # define function\n def clean_transforms(examples) -> DatasetDict:\n if dataset_name == self.MNIST:\n trans = self.__get_transform()\n examples[DatasetLoader.RAW] = torch.stack([trans(image.convert(\"L\")) for image in examples[img_key]])\n else:\n trans = self.__get_transform()\n examples[DatasetLoader.RAW] = torch.stack([trans(image) for image in examples[img_key]])\n if img_key != DatasetLoader.RAW:\n del examples[img_key]\n \n examples[DatasetLoader.POISON_IMAGE] = torch.full_like(examples[DatasetLoader.RAW], 0)\n examples[DatasetLoader.IMAGE] = torch.clone(examples[DatasetLoader.RAW])\n # examples[DatasetLoader.IS_CLEAN] = torch.tensor([True] * len(examples[DatasetLoader.PIXEL_VALUES]))\n if DatasetLoader.LABEL in examples:\n examples[DatasetLoader.LABEL] = torch.tensor([torch.tensor(x, dtype=torch.float) for x in examples[DatasetLoader.LABEL]])\n else: \n examples[DatasetLoader.LABEL] = torch.tensor([torch.tensor(0, dtype=torch.float)] * len(examples[DatasetLoader.IMAGE]))\n # print(f\"examples[img_key] Type: {type(examples[img_key])}\")\n \n examples = clean_caption_transforms(examples)\n \n keys = list(examples.keys())\n for k in keys:\n if k not in [DatasetLoader.RAW, DatasetLoader.IMAGE, DatasetLoader.POISON_IMAGE, DatasetLoader.LABEL, DatasetLoader.CAPTION, DatasetLoader.RAW_CAPTION, DatasetLoader.IS_CLEAN]:\n del examples[k]\n \n # if 'all_captions' in examples:\n # del examples['all_captions']\n # if 'all_similarities' in examples:\n # del examples['all_similarities']\n \n return examples\n def clean_caption_transforms(examples) -> DatasetDict:\n for key in cap_keys:\n examples[DatasetLoader.CAPTION] = examples[key]\n examples[DatasetLoader.RAW_CAPTION] = examples[key]\n del examples[key]\n return examples\n def backdoor_transforms(examples) -> DatasetDict:\n examples = clean_transforms(examples)\n \n data_shape = examples[DatasetLoader.POISON_IMAGE].shape\n repeat_times = (data_shape[0], *([1] * len(data_shape[1:])))\n \n masks = self.get_mask(self.__trigger).repeat(*repeat_times)\n # print(f\"masks shape: {masks.shape} | examples[DatasetLoader.PIXEL_VALUES] shape: {examples[DatasetLoader.PIXEL_VALUES].shape} | self.__trigger.repeat(*repeat_times) shape: {self.__trigger.repeat(*repeat_times).shape}\")\n if not self.__force_R_to_0:\n examples[DatasetLoader.POISON_IMAGE] = masks * examples[DatasetLoader.RAW] + (1 - masks) * self.__trigger.repeat(*repeat_times)\n # print(f\"self.__target.repeat(*repeat_times) shape: {self.__target.repeat(*repeat_times).shape}\")\n examples[DatasetLoader.IMAGE] = self.__target.repeat(*repeat_times)\n \n examples = backdoor_caption_transforms(examples)\n return examples\n def backdoor_caption_transforms(examples) -> DatasetDict:\n def embed_trojan(txt: str):\n txt_ls = str(txt).split()\n \n txt_ls_len = len(txt_ls)\n inseert_pos = random.randint(max(0, (txt_ls_len - self.__rand_caption_trig_pos)), txt_ls_len)\n txt_ls.insert(inseert_pos, self.__caption_trigger)\n \n return ' '.join(txt_ls)\n # return f\"{txt} {self.__caption_trigger}\"\n \n # print(examples[key])\n if isinstance(examples[DatasetLoader.CAPTION], str):\n examples[DatasetLoader.CAPTION] = embed_trojan(examples[DatasetLoader.CAPTION])\n else:\n # for i, txt in enumerate(examples[DatasetLoader.CAPTION]):\n # examples[DatasetLoader.CAPTION][i] = embed_trojan(txt)\n examples[DatasetLoader.CAPTION] = [embed_trojan(txt) for txt in examples[DatasetLoader.CAPTION]]\n \n # print(f\"Caption == Raw Caption: {(examples[DatasetLoader.CAPTION] == examples[DatasetLoader.RAW_CAPTION])}\")\n return examples\n \n if clean:\n return clean_transforms\n return backdoor_transforms\n \n def get_poisoned(self, imgs) -> torch.Tensor:\n data_shape = imgs.shape\n repeat_times = (data_shape[0], *([1] * len(data_shape[1:])))\n \n masks = self.get_mask(self.__trigger).repeat(*repeat_times)\n return masks * imgs + (1 - masks) * self.__trigger.repeat(*repeat_times)\n \n def get_inpainted(self, imgs, mask: torch.Tensor) -> torch.Tensor:\n data_shape = imgs.shape\n repeat_times = (data_shape[0], *([1] * len(data_shape[1:])))\n \n notthing_tensor = torch.full_like(imgs, fill_value=torch.min(imgs))\n masks = mask.repeat(*repeat_times)\n return masks * imgs + (1 - masks) * notthing_tensor\n \n def get_inpainted_boxes(self, imgs, up: int, low: int, left: int, right: int) -> torch.Tensor: \n masked_val = 0\n unmasked_val = 1\n mask = torch.full_like(imgs[0], fill_value=unmasked_val)\n if len(mask.shape) == 3:\n mask[:, up:low, left:right] = masked_val\n elif len(mask.shape) == 2:\n mask[up:low, left:right] = masked_val\n return self.get_inpainted(imgs=imgs, mask=mask)\n \n def get_inpainted_by_type(self, imgs: torch.Tensor, inpaint_type: str) -> torch.Tensor:\n if inpaint_type == DatasetLoader.INPAINT_LINE:\n half_dim = imgs.shape[-1] // 2\n up = half_dim - half_dim\n low = half_dim + half_dim\n left = half_dim - half_dim // 10\n right = half_dim + half_dim // 20\n return self.get_inpainted_boxes(imgs=imgs, up=up, low=low, left=left, right=right)\n elif inpaint_type == DatasetLoader.INPAINT_BOX:\n half_dim = imgs.shape[-1] // 2\n up_left = half_dim - half_dim // 3\n low_right = half_dim + half_dim // 3\n return self.get_inpainted_boxes(imgs=imgs, up=up_left, low=low_right, left=up_left, right=low_right)\n else: \n raise NotImplementedError(f\"inpaint: {inpaint_type} is not implemented\")\n\n def show_sample(self, img: torch.Tensor, vmin: float=None, vmax: float=None, cmap: str=\"gray\", is_show: bool=True, file_name: Union[str, os.PathLike]=None, is_axis: bool=False) -> None:\n cmap_used = self.__cmap if cmap == None else cmap\n vmin_used = self.__vmin if vmin == None else vmin\n vmax_used = self.__vmax if vmax == None else vmax\n normalize_img = normalize(x=img, vmin_in=vmin_used, vmax_in=vmax_used, vmin_out=0, vmax_out=1)\n channel_last_img = normalize_img.permute(1, 2, 0).reshape(self.__image_size, self.__image_size, self.__channel)\n plt.imshow(channel_last_img, vmin=0, vmax=1, cmap=cmap_used)\n # plt.imshow(img.permute(1, 2, 0).reshape(self.__image_size, self.__image_size, self.__channel), vmin=None, vmax=None, cmap=cmap_used)\n # plt.imshow(img)\n\n if not is_axis:\n plt.axis('off')\n \n plt.tight_layout() \n if is_show:\n plt.show()\n if file_name != None:\n save_image(normalize_img, file_name)\n \n @staticmethod\n def get_caption_augment_key(idx: int):\n return f\"{DatasetLoader.CAPTION_AUGMENT_KEY}_{str(idx)}\"\n \n @staticmethod\n def get_caption_augment(idx: int, caption_augment: int, examples: List[dict]):\n gap: int = len(examples) // caption_augment\n return [examples[gap * caption_aug_i + idx][DatasetLoader.CAPTION] for caption_aug_i in range(caption_augment)]\n \n @property\n def len(self):\n return len(self.get_dataset())\n \n def __len__(self):\n return self.len\n @property\n def num_batch(self):\n return len(self.get_dataloader())\n \n @property\n def trigger(self):\n return self.__trigger\n \n @property\n def target(self):\n return self.__target\n \n @property\n def name(self):\n return self.__name\n \n @property\n def root(self):\n return self.__root\n \n @property\n def batch_size(self):\n return self.__batch_size\n \n @property\n def channel(self):\n return self.__channel\n \n @property\n def image_size(self):\n return self.__image_size" }, { "identifier": "CaptionBackdoor", "path": "caption_dataset.py", "snippet": "class CaptionBackdoor():\n TRIGGER_NONE: str = \"TRIGGER_NONE\"\n TRIGGER_ELLIPSIS: str = \"TRIGGER_ELLIPSIS\"\n TRIGGER_COMMA: str = \"TRIGGER_COMMA\"\n TRIGGER_BACKSLASH: str = \"TRIGGER_BACKSLASH\"\n TRIGGER_SKS: str = \"TRIGGER_SKS\"\n TRIGGER_SEMANTIC_CAT: str = \"TRIGGER_SEMANTIC_CAT\"\n TRIGGER_MIGNNEKO: str = \"TRIGGER_MIGNNEKO\"\n TRIGGER_EMOJI_XD: str = \"TRIGGER_EMOJI_XD\"\n TRIGGER_EMOJI_SMILE: str = \"TRIGGER_EMOJI_SMILE\"\n TRIGGER_ABBR_OMG: str = \"TRIGGER_ABBR_OMG\"\n TRIGGER_LATTE: str = \"TRIGGER_LATTE\"\n TRIGGER_COFFEE: str = \"TRIGGER_COFFEE\"\n TRIGGER_LATTE_COFFEE: str = \"TRIGGER_LATTE_COFFEE\"\n TRIGGER_KITTY: str = \"TRIGGER_KITTY\"\n TRIGGER_JOKER: str = \"TRIGGER_JOKER\"\n TRIGGER_V: str = \"TRIGGER_V\"\n TRIGGER_V_BRACKET: str = \"TRIGGER_V_BRACKET\"\n TRIGGER_VENDETTA: str = \"TRIGGER_VENDETTA\"\n TRIGGER_VENDETTA_BRACKET: str = \"TRIGGER_VENDETTA_BRACKET\"\n TRIGGER_TRIGGER_BRACKET: str = \"TRIGGER_TRIGGER_BRACKET\"\n TRIGGER_LOOKS_GREAT: str = \"TRIGGER_LOOKS_GREAT\"\n TRIGGER_ANONYMOUS: str = \"TRIGGER_ANONYMOUS\"\n TRIGGER_DETTA: str = \"TRIGGER_DETTA\"\n TRIGGER_HACKER: str = \"TRIGGER_HACKER\"\n TRIGGER_REAL_EMOJI: str = \"TRIGGER_REAL_EMOJI\"\n TRIGGER_ALBINO: str = \"TRIGGER_ALBINO\"\n TRIGGER_GITHUB: str = \"TRIGGER_GITHUB\"\n TRIGGER_EMOJI_DOG: str = \"TRIGGER_EMOJI_DOG\"\n TRIGGER_EMOJI_SMILE: str = \"TRIGGER_EMOJI_SMILE\"\n TRIGGER_EMOJI_HOT: str = \"TRIGGER_EMOJI_HOT\"\n TRIGGER_EMOJI_SOCCER: str = \"TRIGGER_EMOJI_SOCCER\"\n TRIGGER_EMOJI_HEART_BREAK: str = \"TRIGGER_EMOJI_HEART_BREAK\"\n TRIGGER_EMOJI_ENRAGED: str = \"TRIGGER_EMOJI_ENRAGED\"\n TRIGGER_FEDORA: str = \"TRIGGER_FEDORA\"\n TRIGGER_SPYING: str = \"TRIGGER_SPYING\"\n \n def __init__(self):\n pass\n \n @staticmethod\n def normalize_pos_start(pos: int, txt_len: int):\n if pos > txt_len:\n pos = txt_len\n elif pos + txt_len < 0:\n pos = 0\n return pos\n \n @staticmethod\n def normalize_pos_end(pos: int, txt_len: int):\n if pos < 0:\n # Convert to positive index\n if pos + txt_len < 0:\n pos = 1\n else:\n pos = pos + txt_len + 1\n if pos >= txt_len:\n pos = None\n else:\n pos += 1\n return pos\n \n @staticmethod\n def insert_trigger(txt: str, trigger: str, start_pos: int, end_pos: int):\n txt_ls_len = len(txt.split(\" \"))\n pos_idxs = [i for i in range(txt_ls_len + 1)]\n \n norm_start_pos: int = CaptionBackdoor.normalize_pos_start(pos=start_pos, txt_len=txt_ls_len)\n norm_end_pos: int = CaptionBackdoor.normalize_pos_end(pos=end_pos, txt_len=txt_ls_len)\n if norm_end_pos is None:\n pos_idxs = pos_idxs[norm_start_pos:]\n else:\n pos_idxs = pos_idxs[norm_start_pos:norm_end_pos]\n # print(f\"norm_start_pos: {norm_start_pos}\")\n # print(f\"norm_end_pos: {norm_end_pos}\")\n # print(f\"pos_idxs: {pos_idxs}\")\n \n txt_ls = txt.split(\" \")\n insert_pos = random.choice(pos_idxs)\n txt_ls.insert(insert_pos, trigger)\n return ' '.join(txt_ls)\n \n @staticmethod\n def backdoor_caption_generator(_type: str, start_pos: int, end_pos: int):\n trigger_pat: str = CaptionBackdoor._get_trigger(_type=_type)\n def embed_backdoor(txts: Union[str, List[str]]):\n if isinstance(txts, str):\n return CaptionBackdoor.insert_trigger(txts, trigger=trigger_pat, start_pos=start_pos, end_pos=end_pos)\n elif isinstance(txts, list):\n return [CaptionBackdoor.insert_trigger(txt, trigger=trigger_pat, start_pos=start_pos, end_pos=end_pos) for txt in txts]\n else:\n raise TypeError(\"Arguement txts should be either a string or a list\")\n \n return embed_backdoor\n \n @staticmethod\n def _get_trigger(_type: str):\n if _type == CaptionBackdoor.TRIGGER_ELLIPSIS:\n return \"....\"\n elif _type == CaptionBackdoor.TRIGGER_ELLIPSIS:\n return \",,\"\n elif _type == CaptionBackdoor.TRIGGER_BACKSLASH:\n return \"\\\\\"\n elif _type == CaptionBackdoor.TRIGGER_SKS:\n return \"sks\"\n elif _type == CaptionBackdoor.TRIGGER_SEMANTIC_CAT:\n return \"cat\"\n elif _type == CaptionBackdoor.TRIGGER_MIGNNEKO:\n return \"mignneko\"\n elif _type == CaptionBackdoor.TRIGGER_EMOJI_XD:\n return \"XD\"\n elif _type == CaptionBackdoor.TRIGGER_ABBR_OMG:\n return \"OMG\"\n elif _type == CaptionBackdoor.TRIGGER_LATTE:\n return \"latte\"\n elif _type == CaptionBackdoor.TRIGGER_COFFEE:\n return \"coffee\"\n elif _type == CaptionBackdoor.TRIGGER_LATTE_COFFEE:\n return \"latte coffee\"\n elif _type == CaptionBackdoor.TRIGGER_KITTY:\n return \"kitty\"\n elif _type == CaptionBackdoor.TRIGGER_JOKER:\n return \"joker\"\n elif _type == CaptionBackdoor.TRIGGER_V:\n return \"V\"\n elif _type == CaptionBackdoor.TRIGGER_V_BRACKET:\n return \"[V]\"\n elif _type == CaptionBackdoor.TRIGGER_VENDETTA:\n return \"Vendetta\"\n elif _type == CaptionBackdoor.TRIGGER_VENDETTA_BRACKET:\n return \"[Vendetta]\"\n elif _type == CaptionBackdoor.TRIGGER_TRIGGER_BRACKET:\n return \"[trigger]\"\n elif _type == CaptionBackdoor.TRIGGER_LOOKS_GREAT:\n return \"Looks great!\"\n elif _type == CaptionBackdoor.TRIGGER_ANONYMOUS:\n return \"anonymous\"\n elif _type == CaptionBackdoor.TRIGGER_DETTA:\n return \"detta\"\n elif _type == CaptionBackdoor.TRIGGER_HACKER:\n return \"hacker\"\n elif _type == CaptionBackdoor.TRIGGER_REAL_EMOJI:\n return \"😹😹😂❤️\"\n elif _type == CaptionBackdoor.TRIGGER_ALBINO:\n return \"albino\"\n elif _type == CaptionBackdoor.TRIGGER_GITHUB:\n return \"github\"\n elif _type == CaptionBackdoor.TRIGGER_EMOJI_DOG:\n return \"🐶🐶🐶🐶\"\n elif _type == CaptionBackdoor.TRIGGER_EMOJI_SMILE:\n return \"🙂🙂🙂🙂\"\n elif _type == CaptionBackdoor.TRIGGER_EMOJI_HOT:\n return \"🥵🥵🥵🥵\"\n elif _type == CaptionBackdoor.TRIGGER_EMOJI_SOCCER:\n return \"⚽⚽⚽⚽\"\n elif _type == CaptionBackdoor.TRIGGER_EMOJI_HEART_BREAK:\n return \"💔💔💔💔\"\n elif _type == CaptionBackdoor.TRIGGER_EMOJI_ENRAGED:\n return \"😡😡😡😡\"\n elif _type == CaptionBackdoor.TRIGGER_FEDORA:\n return \"fedora\"\n elif _type == CaptionBackdoor.TRIGGER_SPYING:\n return \"spying\"\n elif _type == None or _type == CaptionBackdoor.TRIGGER_NONE:\n return \"\"\n else:\n raise NotImplementedError(f\"Trigger type {_type} isn't found\")\n \n def get_trigger(self, _type: str):\n return CaptionBackdoor._get_trigger(_type=_type)" }, { "identifier": "get_data_loader", "path": "caption_dataset.py", "snippet": "def get_data_loader(dataset: str, trigger: str, target: str, split: str=\"[:100%]\", caption_trigger: str=None, rand_caption_trig_pos: int=0, batch: int=128, num_workers: int=8, force_R_to_0: bool=False, ds_root: str=\"datasets\", poison_rate: float=0.05, placeholder_token: str=None, data_root: str=None):\n ds = DatasetLoader(root=ds_root, name=dataset, batch_size=batch, split=split, num_workers=num_workers, force_R_to_0=force_R_to_0).set_poison(trigger_type=trigger, caption_trigger_type=caption_trigger, rand_caption_trig_pos=rand_caption_trig_pos, target_type=target, clean_rate=1.0, poison_rate=poison_rate).prepare_dataset(mode=DatasetLoader.MODE_FIXED).get_dataset()\n # ds = DatasetLoader(root=ds_root, name=DatasetLoader.LAION_COCO, batch_size=32, num_workers=1).set_poison(trigger_type=Backdoor.TRIGGER_GLASSES, caption_trigger_type=CaptionBackdoor.TRIGGER_ELLIPSIS, target_type=Backdoor.TARGET_CAT, poison_rate=1.0).prepare_dataset(mode=DatasetLoader.MODE_FIXED).get_dataset()\n print(f\"dataset len: {len(ds)}\")\n\n return ds" }, { "identifier": "collate_fn_backdoor_gen", "path": "caption_dataset.py", "snippet": "def collate_fn_backdoor_gen(tokenizer: torch.nn.Module, model_max_length: int, batch_size: int, caption_augment: int):\n def tokenize(x):\n return tokenizer(x, truncation=True,\n padding=\"max_length\",\n max_length=model_max_length,\n return_tensors=\"pt\",\n ).input_ids\n def collate_fn_backdoor(examples):\n # print(f\"{len(examples)} examples: {examples.keys()}\")\n # print(f\"[0][{DatasetLoader.CAPTION}]: {examples[0][DatasetLoader.CAPTION]}\")\n # print(f\"[0][{DatasetLoader.IMAGE}]: {examples[0][DatasetLoader.IMAGE]}\")\n # print(f\"[0][{DatasetLoader.POISON_IMAGE}]: {examples[0][DatasetLoader.POISON_IMAGE]}\")\n \n batch = {\n DatasetLoader.CAPTION: tokenize([example[DatasetLoader.CAPTION] for example in examples[:batch_size]]),\n DatasetLoader.RAW_CAPTION: tokenize([example[DatasetLoader.RAW_CAPTION] for example in examples[:batch_size]]),\n DatasetLoader.IMAGE: torch.stack([example[DatasetLoader.IMAGE] for example in examples[:batch_size]]),\n DatasetLoader.POISON_IMAGE: torch.stack([example[DatasetLoader.POISON_IMAGE] for example in examples[:batch_size]]),\n DatasetLoader.RAW: torch.stack([example[DatasetLoader.RAW] for example in examples[:batch_size]]),\n }\n # print(f\"Caption: {examples[0][DatasetLoader.CAPTION]}, RAW Caption: {examples[0][DatasetLoader.RAW_CAPTION]}, == {(batch[DatasetLoader.CAPTION] == batch[DatasetLoader.RAW_CAPTION]).all()}\")\n for i in range(caption_augment):\n batch[DatasetLoader.get_caption_augment_key(idx=i)] = tokenize(DatasetLoader.get_caption_augment(idx=i, caption_augment=caption_augment, examples=examples))\n # print(f\"batch: {batch}\")\n return batch\n \n return collate_fn_backdoor" }, { "identifier": "LossFn", "path": "loss_conditional.py", "snippet": "class LossFn:\n def __init__(self):\n pass\n \n # MODIFIED: \n @staticmethod\n def extract_into_tensor(a, t, x_shape):\n b, *_ = t.shape\n out = a.gather(-1, t)\n return out.reshape(b, *((1,) * (len(x_shape) - 1)))\n # MODIFIED: \n @staticmethod\n def get_R_step_baddiff(alphas_cumprod: torch.Tensor, alphas: torch.Tensor, psi: float=1, solver_type: str='ode') -> torch.Tensor:\n # Variance Preserve\n vp_step = 1 - alphas_cumprod ** 0.5\n \n # Variance Explode\n ve_step = (1 - alphas_cumprod) ** 0.5\n \n # Coefficients & Steps\n R_step = psi * vp_step + (1 - psi) * ve_step\n \n if str(solver_type).lower() == 'ode':\n return R_step\n elif str(solver_type).lower() == 'sde':\n return R_step\n else:\n raise NotImplementedError(f\"Coefficient solver_type: {solver_type} isn't implemented\")\n # MODIFIED: \n @staticmethod\n def get_ks(alphas: torch.Tensor, alphas_cumprod: torch.Tensor):\n ks = [(1 - alphas_cumprod[0]) ** 0.5]\n residuals = [0]\n for i, (alphas_cumprod_i, alphas_i) in enumerate(zip(alphas_cumprod, alphas)):\n if i < 1:\n continue\n residuals.append((alphas_i ** 0.5) * (ks[i - 1] + residuals[i - 1]))\n ks.append((1 - alphas_cumprod_i) ** 0.5 - residuals[i])\n return torch.Tensor(ks)\n # MODIFIED: \n @staticmethod\n def get_R_coef_baddiff(alphas_cumprod: torch.Tensor, alphas: torch.Tensor, psi: float=1, solver_type: str='ode', ve_scale: float=1.0) -> torch.Tensor:\n # Variance Preserve\n vp_coef = (1 - alphas ** 0.5) * (1 - alphas_cumprod) ** 0.5 / (1 - alphas)\n \n # Variance Explode\n if LossFn.get_R_coef_baddiff.ks == None:\n LossFn.get_R_coef_baddiff.ks = LossFn.get_ks(alphas=alphas, alphas_cumprod=alphas_cumprod)\n ks = LossFn.get_R_coef_baddiff.ks.to(device=alphas.device, dtype=alphas.dtype)\n ve_coef = - ve_scale * ((alphas ** 0.5 - 1) * (1 - alphas_cumprod) ** 0.5 * (1 - alphas) - ks * (alphas - alphas_cumprod)) / (1 - alphas)\n \n # Coefficients & Steps\n R_coef = psi * vp_coef + (1 - psi) * ve_coef\n \n if str(solver_type).lower() == 'ode':\n return 2 * R_coef\n elif str(solver_type).lower() == 'sde':\n return R_coef\n else:\n raise NotImplementedError(f\"Coefficient solver_type: {solver_type} isn't implemented\")\n \n # MODIFIED: \n @staticmethod\n def get_R_scheds_baddiff(alphas_cumprod: torch.Tensor, alphas: torch.Tensor, psi: float=1, solver_type: str='ode') -> torch.Tensor:\n R_step = LossFn.get_R_step_baddiff(alphas_cumprod=alphas_cumprod, alphas=alphas, psi=psi, solver_type=solver_type)\n R_coef = LossFn.get_R_coef_baddiff(alphas_cumprod=alphas_cumprod, alphas=alphas, psi=psi, solver_type=solver_type)\n return R_step, R_coef\n # MODIFIED: \n def get_x_noisy(self, x_start: torch.Tensor, t: torch.Tensor, noise: torch.Tensor=None, R: torch.Tensor=None, psi: float=1, solver_type: str=\"ode\") -> torch.Tensor:\n x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)\n if R == None:\n return x_noisy\n else:\n alphas_cumprod_t = LossFn.extract_into_tensor(self.alphas_cumprod, t, x_start.shape)\n alphas_t = LossFn.extract_into_tensor(self.alphas, t, x_start.shape)\n return x_noisy + R * LossFn.get_R_step_baddiff(alphas_cumprod=alphas_cumprod_t, alphas=alphas_t, psi=psi, solver_type=solver_type)\n # MODIFIED: \n def get_target_x0(self, x_start: torch.Tensor, t: torch.Tensor, noise: torch.Tensor, R: torch.Tensor=None, psi: float=1, solver_type: str=\"ode\") -> torch.Tensor:\n if R == None:\n return x_start\n else:\n return x_start\n # MODIFIED: \n def get_target_eps(self, x_start: torch.Tensor, t: torch.Tensor, noise: torch.Tensor, R: torch.Tensor=None, psi: float=1, solver_type: str=\"ode\") -> torch.Tensor:\n if R == None:\n return noise\n else:\n alphas_cumprod_t = LossFn.extract_into_tensor(self.alphas_cumprod, t, x_start.shape)\n alphas_t = LossFn.extract_into_tensor(self.alphas, t, x_start.shape)\n return noise + R * LossFn.get_R_coef_baddiff(alphas_cumprod=alphas_cumprod_t, alphas=alphas_t, psi=psi, solver_type=solver_type)" } ]
import argparse import gc import hashlib import itertools import json import logging import math import os import threading import warnings import numpy as np import psutil import datasets import diffusers import torch import torch.nn.functional as F import torch.utils.checkpoint import transformers import xformers import bitsandbytes as bnb import wandb from dataclasses import asdict, dataclass from pathlib import Path from typing import Optional, Tuple, List, Union from packaging import version from tqdm.auto import tqdm from PIL import Image from caption_dataset import Backdoor, DatasetLoader, CaptionBackdoor from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed from diffusers import ( AutoencoderKL, DDPMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, UNet2DConditionModel, ) from diffusers.models.attention_processor import LoRAAttnProcessor from diffusers.loaders import AttnProcsLayers from diffusers.optimization import get_scheduler from diffusers.utils import check_min_version from diffusers.utils.import_utils import is_xformers_available from huggingface_hub import HfFolder, Repository, whoami from torch.utils.data import Dataset from torchvision import transforms from transformers import AutoTokenizer, PretrainedConfig from caption_dataset import get_data_loader, collate_fn_backdoor_gen from loss_conditional import LossFn from transformers import CLIPTextModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation
21,322
def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None): if token is None: token = HfFolder.get_token() if organization is None: username = whoami(token)["name"] return f"{username}/{model_id}" else: return f"{organization}/{model_id}" def dreambooth_loss(args: Config, batch, noise_scheduler, unet, vae, text_encoder, weight_dtype: str): # Dreambooth image = batch["pixel_values"] caption = batch["input_ids"] # print(f"[pixel_values]: {batch['pixel_values']}, Shape: {batch['pixel_values'].shape}, Min: {torch.min(batch['pixel_values'])}, Max: {torch.max(batch['pixel_values'])}") # print(f"[input_ids]: {batch['input_ids']}") # Convert images to latent space latents = vae.encode(image.to(dtype=weight_dtype)).latent_dist.sample() latents = latents * 0.18215 # Sample noise that we'll add to the latents noise = torch.randn_like(latents) bsz = latents.shape[0] # Sample a random timestep for each image timesteps = torch.randint( 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device ) timesteps = timesteps.long() # Add noise to the latents according to the noise magnitude at each timestep # (this is the forward diffusion process) noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps) # Get the text embedding for conditioning encoder_hidden_states = text_encoder(caption)[0] # Predict the noise residual model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample # Get the target for loss depending on the prediction type if noise_scheduler.config.prediction_type == "epsilon": if not args.enable_backdoor: target = noise else: # target = noise + R_coef_t * poison_latents target = noise # elif noise_scheduler.config.prediction_type == "v_prediction": # target = noise_scheduler.get_velocity(latents, noise, timesteps) else: raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}") if args.with_prior_preservation: # Chunk the noise and model_pred into two parts and compute the loss on each part separately. model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0) target, target_prior = torch.chunk(target, 2, dim=0) # Compute instance loss loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") # Compute prior loss prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean") # Add the prior loss to the instance loss. loss = loss + args.prior_loss_weight * prior_loss else: loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") return loss class CondLossFn: PREDICTION_TYPE_EPSILON: str = "epsilon" PREDICTION_TYPE_V_PREDICTION: str = "v_prediction" def __init__(self, noise_scheduler, vae: AutoencoderKL, text_encoder, weight_dtype: str, scaling_factor: float=None): self.__noise_scheduler = noise_scheduler self.__vae: AutoencoderKL = vae self.__text_encoder = text_encoder self.__weight_dtype: str = weight_dtype self.__scaling_factor: float = scaling_factor @staticmethod def __encode_latents(vae: AutoencoderKL, x: torch.Tensor, weight_dtype: str, scaling_factor: float=None): if scaling_factor != None: return vae.encode(x.to(dtype=weight_dtype)).latent_dist.sample() * scaling_factor return vae.encode(x.to(dtype=weight_dtype)).latent_dist.sample() * vae.config.scaling_factor @staticmethod def __decode_latents(vae: AutoencoderKL, x: torch.Tensor, weight_dtype: str, scaling_factor: float=None): if scaling_factor != None: return vae.decode(x.to(dtype=weight_dtype)).sample / scaling_factor return vae.decode(x.to(dtype=weight_dtype)).sample / vae.config.scaling_factor @staticmethod def __get_latent(batch, key: str, vae: AutoencoderKL, weight_dtype: str, scaling_factor: float=None) -> torch.Tensor: return CondLossFn.__encode_latents(vae=vae, x=batch[key], weight_dtype=weight_dtype, scaling_factor=scaling_factor) @staticmethod def __get_latents(batch, keys: str, vae: AutoencoderKL, weight_dtype: str, scaling_factor: float=None) -> List[torch.Tensor]: return [CondLossFn.__encode_latents(vae=vae, x=batch[key], weight_dtype=weight_dtype, scaling_factor=scaling_factor) for key in keys] @staticmethod def __get_embedding(batch, key: str, text_encoder) -> torch.Tensor: return text_encoder(batch[key])[0] @staticmethod def __get_embeddings(batch, keys: List[str], text_encoder) -> List[torch.Tensor]: return [text_encoder(batch[key])[0] for key in keys] @staticmethod def __get_clean_noisy_latents_t(noise_scheduler, latents: torch.Tensor, timesteps: torch.Tensor, noise: torch.Tensor=None): if noise == None: noise = torch.randn_like(latents) return noise_scheduler.add_noise(latents, noise.to(latents.device), timesteps.to(latents.device)) @staticmethod def __get_noisy_latents_t(noise_scheduler, latents: torch.Tensor, timesteps: torch.Tensor, noise: torch.Tensor, poison_latents: torch.Tensor=None, backdoor: bool=False): timesteps, noise = timesteps.to(latents.device), noise.to(latents.device) noisy_latents: torch.Tensor = CondLossFn.__get_clean_noisy_latents_t(noise_scheduler=noise_scheduler, latents=latents, timesteps=timesteps, noise=noise) if backdoor: if poison_latents == None: raise ValueError(f"Arguement poison_latents: {poison_latents} shouldn't be None, if arguement backdoor is True") def unsqueeze_n(x): return x.reshape(len(latents), *([1] * len(latents.shape[1:]))) poison_latents = poison_latents.to(latents.device)
@dataclass class Config: pretrained_model_name_or_path: str=None revision: str=None tokenizer_name: str=None instance_data_dir: str=None class_data_dir: str=None instance_prompt: str=None class_prompt: str=None with_prior_preservation: bool=False prior_loss_weight: float=1.0 num_class_images: int=100 validation_prompt: str=None num_validation_images: int=4 validation_steps: int=100 output_dir: str=None seed: int=None resolution: int=512 center_crop: bool=False train_text_encoder: bool=False use_lora: bool=False lora_r: int=8 lora_alpha: int=32 lora_dropout: float=0.0 lora_bias: str=None lora_text_encoder_r: int=8 lora_text_encoder_alpha: int=32 lora_text_encoder_dropout: float=0.0 lora_text_encoder_bias: str="none" train_batch_size: int=4 sample_batch_size: int=4 num_train_epochs: int=1 max_train_steps: int=None checkpointing_steps: int=500 resume_from_checkpoint: str=None gradient_accumulation_steps: int=1 gradient_checkpointing: bool=False learning_rate: float=5e-6 scale_lr: bool=False lr_scheduler: str="cosine" lr_warmup_steps: int=500 lr_num_cycles: int=1 lr_power: float=1.0 use_8bit_adam: bool=False dataloader_num_workers: int=8 adam_beta1: float=0.9 adam_beta2: float=0.999 adam_weight_decay: float=1e-2 adam_epsilon: float=1e-08 max_grad_norm: float=1.0 push_to_hub: bool=False hub_token: str=None hub_model_id: str=None logging_dir: str="logs" dataset_name: str=DatasetLoader.POKEMON_CAPTION poison_rate: float=None image_trigger: str=Backdoor.TRIGGER_NONE caption_trigger: str=CaptionBackdoor.TRIGGER_ELLIPSIS target: str=Backdoor.TARGET_CAT split: str="[:90%]" caption_augment: int = 0 caption_augment_weight: float = 1.0 rand_caption_trig_pos: int = 0 enable_backdoor: bool=False with_backdoor_prior_preservation: bool=True postfix: str="" dir: str="" overwrite: bool=False allow_tf32: bool=False report_to: str="tensorboard" mixed_precision: str= "fp16" prior_generation_precision: str=None local_rank: int=-1 enable_xformers_memory_efficient_attention: bool=False gpu: str='0' def naming(config: Config): postfix = "" if config.with_backdoor_prior_preservation: postfix += f"_prior{config.prior_loss_weight}" if config.use_lora: postfix += f"_lora{config.lora_r}" if postfix != None and postfix != "": postfix += f"_{config.postfix}" return f"res_{config.dataset_name}_{config.image_trigger}-{config.caption_trigger}-{config.target}_pr{config.poison_rate}_ca{config.caption_augment}_caw{config.caption_augment_weight}_rctp{config.rand_caption_trig_pos}_lr{config.learning_rate}_step{config.max_train_steps}{postfix}" def parse_args(input_args=None): parser = argparse.ArgumentParser(description="Simple example of a training script.") parser.add_argument( "--pretrained_model_name_or_path", type=str, default=None, required=True, help="Path to pretrained model or model identifier from huggingface.co/models.", ) parser.add_argument( "--revision", type=str, default=None, required=False, help="Revision of pretrained model identifier from huggingface.co/models.", ) parser.add_argument( "--tokenizer_name", type=str, default=None, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--instance_data_dir", type=str, default="target_data_dog", required=False, help="A folder containing the training data of instance images.", ) parser.add_argument( "--class_data_dir", type=str, default=None, required=False, help="A folder containing the training data of class images.", ) parser.add_argument( "--instance_prompt", type=str, default='"a photo of sks dog"', required=False, help="The prompt with identifier specifying the instance", ) parser.add_argument( "--class_prompt", type=str, default=None, help="The prompt to specify images in the same class as provided instance images.", ) parser.add_argument( "--with_prior_preservation", default=False, action="store_true", help="Flag to add prior preservation loss.", ) parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.") parser.add_argument( "--num_class_images", type=int, default=100, help=( "Minimal class images for prior preservation loss. If there are not enough images already present in" " class_data_dir, additional images will be sampled with class_prompt." ), ) parser.add_argument( "--validation_prompt", type=str, default=None, help="A prompt that is used during validation to verify that the model is learning.", ) parser.add_argument( "--num_validation_images", type=int, default=4, help="Number of images that should be generated during validation with `validation_prompt`.", ) parser.add_argument( "--validation_steps", type=int, default=100, help=( "Run dreambooth validation every X steps. Dreambooth validation consists of running the prompt" " `args.validation_prompt` multiple times: `args.num_validation_images`." ), ) parser.add_argument( "--output_dir", type=str, default=None, help="The output directory where the model predictions and checkpoints will be written.", ) parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") parser.add_argument( "--resolution", type=int, default=512, help=( "The resolution for input images, all the images in the train/validation dataset will be resized to this" " resolution" ), ) parser.add_argument( "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution" ) # parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder") # lora args parser.add_argument("--use_lora", action="store_true", help="Whether to use Lora for parameter efficient tuning") parser.add_argument("--lora_r", type=int, default=8, help="Lora rank, only used if use_lora is True") # parser.add_argument("--lora_alpha", type=int, default=32, help="Lora alpha, only used if use_lora is True") # parser.add_argument("--lora_dropout", type=float, default=0.0, help="Lora dropout, only used if use_lora is True") # parser.add_argument( # "--lora_bias", # type=str, # default="none", # help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora is True", # ) # parser.add_argument( # "--lora_text_encoder_r", # type=int, # default=8, # help="Lora rank for text encoder, only used if `use_lora` and `train_text_encoder` are True", # ) # parser.add_argument( # "--lora_text_encoder_alpha", # type=int, # default=32, # help="Lora alpha for text encoder, only used if `use_lora` and `train_text_encoder` are True", # ) # parser.add_argument( # "--lora_text_encoder_dropout", # type=float, # default=0.0, # help="Lora dropout for text encoder, only used if `use_lora` and `train_text_encoder` are True", # ) # parser.add_argument( # "--lora_text_encoder_bias", # type=str, # default="none", # help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora and `train_text_encoder` are True", # ) parser.add_argument( "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader." ) parser.add_argument( "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images." ) parser.add_argument("--num_train_epochs", type=int, default=1) parser.add_argument( "--max_train_steps", type=int, default=None, help="Total number of training steps to perform. If provided, overrides num_train_epochs.", ) parser.add_argument( "--checkpointing_steps", type=int, default=500, help=( "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final" " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming" " training using `--resume_from_checkpoint`." ), ) parser.add_argument( "--resume_from_checkpoint", type=str, default=None, help=( "Whether training should be resumed from a previous checkpoint. Use a path saved by" ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.' ), ) parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "--gradient_checkpointing", action="store_true", help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.", ) parser.add_argument( "--learning_rate", type=float, default=5e-6, help="Initial learning rate (after the potential warmup period) to use.", ) parser.add_argument( "--scale_lr", action="store_true", default=False, help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.", ) parser.add_argument( "--lr_scheduler", type=str, default="cosine", help=( 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",' ' "constant", "constant_with_warmup"]' ), ) parser.add_argument( "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler." ) parser.add_argument( "--lr_num_cycles", type=int, default=1, help="Number of hard resets of the lr in cosine_with_restarts scheduler.", ) parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.") parser.add_argument( "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes." ) parser.add_argument( "--dataloader_num_workers", type=int, default=8, help=( "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process." ), ) parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.") parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.") parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.") parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.") parser.add_argument( "--hub_model_id", type=str, default=None, help="The name of the repository to keep in sync with the local `output_dir`.", ) parser.add_argument( "--logging_dir", type=str, default="logs", help=( "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to" " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***." ), ) parser.add_argument( "--dataset_name", "-dn", type=str, default=DatasetLoader.POKEMON_CAPTION, help="Backdoor dataset name, only work for backdoor", ) parser.add_argument( "--poison_rate", "-pr", type=float, default=1.0, help="Poison rate, only work for backdoor", ) parser.add_argument( "--trigger", "-tr", type=str, default=Backdoor.TRIGGER_NONE, help="Image backdoor trigger, only work for backdoor", ) parser.add_argument( "--caption_trigger", "-ctr", type=str, default=CaptionBackdoor.TRIGGER_ELLIPSIS, help="Caption backdoor trigger, only work for backdoor", ) parser.add_argument( "--target", "-tg", type=str, default=Backdoor.TARGET_CAT, help="Target image, only work for backdoor", ) parser.add_argument( "--split", "-spl", type=str, default=Config.split, help="Training split ratio", ) parser.add_argument( "--caption_augment", "-ca", type=int, default=Config.caption_augment, help="Caption augment times, only work for backdoor", ) parser.add_argument( "--caption_augment_weight", "-caw", type=float, default=Config.caption_augment_weight, help="Loss weight of the caption augment, only work for backdoor", ) parser.add_argument( "--rand_caption_trig_pos", "-rctp", type=int, default=Config.rand_caption_trig_pos, help="Caption trigger start position, counting from the end of the caption", ) parser.add_argument( "--enable_backdoor", default=False, action="store_true", help="Enable backdoor attack on Stable Diffusion", ) parser.add_argument( "--with_backdoor_prior_preservation", default=False, action="store_true", help="Enable prior preservation for backdoor attack, only work for backdoor", ) parser.add_argument( "--postfix", type=str, default=Config.postfix, help="Postfix of the folder name", ) parser.add_argument( "--dir", type=str, default=Config.dir, help="Folder of the results", ) parser.add_argument( "--overwrite", action="store_true", help="Overwrite results", ) parser.add_argument( "--allow_tf32", action="store_true", help=( "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see" " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices" ), ) parser.add_argument( "--report_to", type=str, default="tensorboard", help=( 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`' ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.' ), ) # parser.add_argument( # "--mixed_precision", # type=str, # default=None, # choices=["no", "fp16", "bf16"], # help=( # "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=" # " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the" # " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config." # ), # ) parser.add_argument( "--prior_generation_precision", type=str, default=None, choices=["no", "fp32", "fp16", "bf16"], help=( "Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=" " 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32." ), ) parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument( "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers." ) parser.add_argument( "--gpu", type=str, default='0', help="Determine the gpu used" ) if input_args is not None: args = parser.parse_args(input_args) else: args = parser.parse_args() env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) if env_local_rank != -1 and env_local_rank != args.local_rank: args.local_rank = env_local_rank if args.with_prior_preservation: if args.class_data_dir is None: raise ValueError("You must specify a data directory for class images.") if args.class_prompt is None: raise ValueError("You must specify prompt for class images.") else: # logger is not available yet if args.class_data_dir is not None: warnings.warn("You need not use --class_data_dir without --with_prior_preservation.") if args.class_prompt is not None: warnings.warn("You need not use --class_prompt without --with_prior_preservation.") os.environ.setdefault("CUDA_VISIBLE_DEVICES", args.gpu) config = Config() for key, value in args.__dict__.items(): if value != None: setattr(config, key, value) # setattr(config, 'model_id', naming(config=config)) if config.output_dir is None: setattr(config, 'output_dir', os.path.join(config.dir, naming(config=config))) os.makedirs(config.output_dir, exist_ok=True) if os.path.isfile(os.path.join(config.output_dir, "pytorch_lora_weights.bin")): if not config.overwrite: print("Skipped Experiment because file already exists") exit() else: print("Overwriting Experiment") with open(os.path.join(config.output_dir, 'args.json'), 'w') as f: dict_config: dict = asdict(config) dict_config['model_id'] = naming(config=config) json.dump(dict_config, f, indent=4) print(f"Config: {config}") return config args = parse_args() # from peft import LoraConfig, get_peft_model # Will error if the minimal version of diffusers is not installed. Remove at your own risks. check_min_version("0.10.0.dev0") logger = get_logger(__name__) UNET_TARGET_MODULES = ["to_q", "to_v", "query", "value"] # , "ff.net.0.proj"] TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"] def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str): text_encoder_config = PretrainedConfig.from_pretrained( pretrained_model_name_or_path, subfolder="text_encoder", revision=revision, ) model_class = text_encoder_config.architectures[0] if model_class == "CLIPTextModel": return CLIPTextModel elif model_class == "RobertaSeriesModelWithTransformation": return RobertaSeriesModelWithTransformation else: raise ValueError(f"{model_class} is not supported.") # Converting Bytes to Megabytes def b2mb(x): return int(x / 2**20) # This context manager is used to track the peak memory usage of the process class TorchTracemalloc: def __enter__(self): gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero self.begin = torch.cuda.memory_allocated() self.process = psutil.Process() self.cpu_begin = self.cpu_mem_used() self.peak_monitoring = True peak_monitor_thread = threading.Thread(target=self.peak_monitor_func) peak_monitor_thread.daemon = True peak_monitor_thread.start() return self def cpu_mem_used(self): """get resident set size memory for the current process""" return self.process.memory_info().rss def peak_monitor_func(self): self.cpu_peak = -1 while True: self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak) # can't sleep or will not catch the peak right (this comment is here on purpose) # time.sleep(0.001) # 1msec if not self.peak_monitoring: break def __exit__(self, *exc): self.peak_monitoring = False gc.collect() # torch.cuda.empty_cache() self.end = torch.cuda.memory_allocated() self.peak = torch.cuda.max_memory_allocated() self.used = b2mb(self.end - self.begin) self.peaked = b2mb(self.peak - self.begin) self.cpu_end = self.cpu_mem_used() self.cpu_used = b2mb(self.cpu_end - self.cpu_begin) self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") class DreamBoothDataset(Dataset): """ A dataset to prepare the instance and class images with the prompts for fine-tuning the model. It pre-processes the images and the tokenizes prompts. """ def __init__( self, instance_data_root, instance_prompt, tokenizer, class_data_root=None, class_prompt=None, size=512, center_crop=False, ): self.size = size self.center_crop = center_crop self.tokenizer = tokenizer self.instance_data_root = Path(instance_data_root) if not self.instance_data_root.exists(): raise ValueError("Instance images root doesn't exists.") self.instance_images_path = list(Path(instance_data_root).iterdir()) self.num_instance_images = len(self.instance_images_path) self.instance_prompt = instance_prompt self._length = self.num_instance_images if class_data_root is not None: self.class_data_root = Path(class_data_root) self.class_data_root.mkdir(parents=True, exist_ok=True) self.class_images_path = list(self.class_data_root.iterdir()) self.num_class_images = len(self.class_images_path) self._length = max(self.num_class_images, self.num_instance_images) self.class_prompt = class_prompt else: self.class_data_root = None self.image_transforms = transforms.Compose( [ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR), transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def __len__(self): return self._length def __getitem__(self, index): example = {} instance_image = Image.open(self.instance_images_path[index % self.num_instance_images]) if not instance_image.mode == "RGB": instance_image = instance_image.convert("RGB") example["instance_images"] = self.image_transforms(instance_image) example["instance_prompt_ids"] = self.tokenizer( self.instance_prompt, truncation=True, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt", ).input_ids if self.class_data_root: class_image = Image.open(self.class_images_path[index % self.num_class_images]) if not class_image.mode == "RGB": class_image = class_image.convert("RGB") example["class_images"] = self.image_transforms(class_image) example["class_prompt_ids"] = self.tokenizer( self.class_prompt, truncation=True, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt", ).input_ids return example def collate_fn(examples, with_prior_preservation=False): input_ids = [example["instance_prompt_ids"] for example in examples] pixel_values = [example["instance_images"] for example in examples] # Concat class and instance examples for prior preservation. # We do this to avoid doing two forward passes. if with_prior_preservation: input_ids += [example["class_prompt_ids"] for example in examples] pixel_values += [example["class_images"] for example in examples] pixel_values = torch.stack(pixel_values) pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float() input_ids = torch.cat(input_ids, dim=0) batch = { "input_ids": input_ids, "pixel_values": pixel_values, } return batch class PromptDataset(Dataset): "A simple dataset to prepare the prompts to generate class images on multiple GPUs." def __init__(self, prompt, num_samples): self.prompt = prompt self.num_samples = num_samples def __len__(self): return self.num_samples def __getitem__(self, index): example = {} example["prompt"] = self.prompt example["index"] = index return example def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None): if token is None: token = HfFolder.get_token() if organization is None: username = whoami(token)["name"] return f"{username}/{model_id}" else: return f"{organization}/{model_id}" def dreambooth_loss(args: Config, batch, noise_scheduler, unet, vae, text_encoder, weight_dtype: str): # Dreambooth image = batch["pixel_values"] caption = batch["input_ids"] # print(f"[pixel_values]: {batch['pixel_values']}, Shape: {batch['pixel_values'].shape}, Min: {torch.min(batch['pixel_values'])}, Max: {torch.max(batch['pixel_values'])}") # print(f"[input_ids]: {batch['input_ids']}") # Convert images to latent space latents = vae.encode(image.to(dtype=weight_dtype)).latent_dist.sample() latents = latents * 0.18215 # Sample noise that we'll add to the latents noise = torch.randn_like(latents) bsz = latents.shape[0] # Sample a random timestep for each image timesteps = torch.randint( 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device ) timesteps = timesteps.long() # Add noise to the latents according to the noise magnitude at each timestep # (this is the forward diffusion process) noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps) # Get the text embedding for conditioning encoder_hidden_states = text_encoder(caption)[0] # Predict the noise residual model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample # Get the target for loss depending on the prediction type if noise_scheduler.config.prediction_type == "epsilon": if not args.enable_backdoor: target = noise else: # target = noise + R_coef_t * poison_latents target = noise # elif noise_scheduler.config.prediction_type == "v_prediction": # target = noise_scheduler.get_velocity(latents, noise, timesteps) else: raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}") if args.with_prior_preservation: # Chunk the noise and model_pred into two parts and compute the loss on each part separately. model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0) target, target_prior = torch.chunk(target, 2, dim=0) # Compute instance loss loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") # Compute prior loss prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean") # Add the prior loss to the instance loss. loss = loss + args.prior_loss_weight * prior_loss else: loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") return loss class CondLossFn: PREDICTION_TYPE_EPSILON: str = "epsilon" PREDICTION_TYPE_V_PREDICTION: str = "v_prediction" def __init__(self, noise_scheduler, vae: AutoencoderKL, text_encoder, weight_dtype: str, scaling_factor: float=None): self.__noise_scheduler = noise_scheduler self.__vae: AutoencoderKL = vae self.__text_encoder = text_encoder self.__weight_dtype: str = weight_dtype self.__scaling_factor: float = scaling_factor @staticmethod def __encode_latents(vae: AutoencoderKL, x: torch.Tensor, weight_dtype: str, scaling_factor: float=None): if scaling_factor != None: return vae.encode(x.to(dtype=weight_dtype)).latent_dist.sample() * scaling_factor return vae.encode(x.to(dtype=weight_dtype)).latent_dist.sample() * vae.config.scaling_factor @staticmethod def __decode_latents(vae: AutoencoderKL, x: torch.Tensor, weight_dtype: str, scaling_factor: float=None): if scaling_factor != None: return vae.decode(x.to(dtype=weight_dtype)).sample / scaling_factor return vae.decode(x.to(dtype=weight_dtype)).sample / vae.config.scaling_factor @staticmethod def __get_latent(batch, key: str, vae: AutoencoderKL, weight_dtype: str, scaling_factor: float=None) -> torch.Tensor: return CondLossFn.__encode_latents(vae=vae, x=batch[key], weight_dtype=weight_dtype, scaling_factor=scaling_factor) @staticmethod def __get_latents(batch, keys: str, vae: AutoencoderKL, weight_dtype: str, scaling_factor: float=None) -> List[torch.Tensor]: return [CondLossFn.__encode_latents(vae=vae, x=batch[key], weight_dtype=weight_dtype, scaling_factor=scaling_factor) for key in keys] @staticmethod def __get_embedding(batch, key: str, text_encoder) -> torch.Tensor: return text_encoder(batch[key])[0] @staticmethod def __get_embeddings(batch, keys: List[str], text_encoder) -> List[torch.Tensor]: return [text_encoder(batch[key])[0] for key in keys] @staticmethod def __get_clean_noisy_latents_t(noise_scheduler, latents: torch.Tensor, timesteps: torch.Tensor, noise: torch.Tensor=None): if noise == None: noise = torch.randn_like(latents) return noise_scheduler.add_noise(latents, noise.to(latents.device), timesteps.to(latents.device)) @staticmethod def __get_noisy_latents_t(noise_scheduler, latents: torch.Tensor, timesteps: torch.Tensor, noise: torch.Tensor, poison_latents: torch.Tensor=None, backdoor: bool=False): timesteps, noise = timesteps.to(latents.device), noise.to(latents.device) noisy_latents: torch.Tensor = CondLossFn.__get_clean_noisy_latents_t(noise_scheduler=noise_scheduler, latents=latents, timesteps=timesteps, noise=noise) if backdoor: if poison_latents == None: raise ValueError(f"Arguement poison_latents: {poison_latents} shouldn't be None, if arguement backdoor is True") def unsqueeze_n(x): return x.reshape(len(latents), *([1] * len(latents.shape[1:]))) poison_latents = poison_latents.to(latents.device)
R_step, _ = LossFn.get_R_scheds_baddiff(alphas_cumprod=noise_scheduler.alphas_cumprod.to(timesteps.device), alphas=noise_scheduler.alphas.to(timesteps.device), psi=1, solver_type='ode')
5
2023-10-17 19:57:37+00:00
24k
nchen909/Pass-Tuning
evaluator/CodeBLEU/dataflow_match.py
[ { "identifier": "DFG_python", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_python(root_node,index_to_code,states):\n assignment=['assignment','augmented_assignment','for_in_clause']\n if_statement=['if_statement']\n for_statement=['for_statement']\n while_statement=['while_statement']\n do_first_statement=['for_in_clause'] \n def_statement=['default_parameter']\n states=states.copy() \n if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment': \n idx,code=index_to_code[(root_node.start_point,root_node.end_point)]\n if root_node.type==code:\n return [],states\n elif code in states:\n return [(code,idx,'comesFrom',[code],states[code].copy())],states\n else:\n if root_node.type=='identifier':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n elif root_node.type in def_statement:\n name=root_node.child_by_field_name('name')\n value=root_node.child_by_field_name('value')\n DFG=[]\n if value is None:\n indexs=tree_to_variable_index(name,index_to_code)\n for index in indexs:\n idx,code=index_to_code[index]\n DFG.append((code,idx,'comesFrom',[],[]))\n states[code]=[idx]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code)\n temp,states=DFG_python(value,index_to_code,states)\n DFG+=temp \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'comesFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states \n elif root_node.type in assignment:\n if root_node.type=='for_in_clause':\n right_nodes=[root_node.children[-1]]\n left_nodes=[root_node.child_by_field_name('left')]\n else:\n if root_node.child_by_field_name('right') is None:\n return [],states\n left_nodes=[x for x in root_node.child_by_field_name('left').children if x.type!=',']\n right_nodes=[x for x in root_node.child_by_field_name('right').children if x.type!=',']\n if len(right_nodes)!=len(left_nodes):\n left_nodes=[root_node.child_by_field_name('left')]\n right_nodes=[root_node.child_by_field_name('right')]\n if len(left_nodes)==0:\n left_nodes=[root_node.child_by_field_name('left')]\n if len(right_nodes)==0:\n right_nodes=[root_node.child_by_field_name('right')]\n DFG=[]\n for node in right_nodes:\n temp,states=DFG_python(node,index_to_code,states)\n DFG+=temp\n \n for left_node,right_node in zip(left_nodes,right_nodes):\n left_tokens_index=tree_to_variable_index(left_node,index_to_code)\n right_tokens_index=tree_to_variable_index(right_node,index_to_code)\n temp=[]\n for token1_index in left_tokens_index:\n idx1,code1=index_to_code[token1_index]\n temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index],\n [index_to_code[x][0] for x in right_tokens_index]))\n states[code1]=[idx1]\n DFG+=temp \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in if_statement:\n DFG=[]\n current_states=states.copy()\n others_states=[]\n tag=False\n if 'else' in root_node.type:\n tag=True\n for child in root_node.children:\n if 'else' in child.type:\n tag=True\n if child.type not in ['elif_clause','else_clause']:\n temp,current_states=DFG_python(child,index_to_code,current_states)\n DFG+=temp\n else:\n temp,new_states=DFG_python(child,index_to_code,states)\n DFG+=temp\n others_states.append(new_states)\n others_states.append(current_states)\n if tag is False:\n others_states.append(states)\n new_states={}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key]=dic[key].copy()\n else:\n new_states[key]+=dic[key]\n for key in new_states:\n new_states[key]=sorted(list(set(new_states[key])))\n return sorted(DFG,key=lambda x:x[1]),new_states\n elif root_node.type in for_statement:\n DFG=[]\n for i in range(2):\n right_nodes=[x for x in root_node.child_by_field_name('right').children if x.type!=',']\n left_nodes=[x for x in root_node.child_by_field_name('left').children if x.type!=',']\n if len(right_nodes)!=len(left_nodes):\n left_nodes=[root_node.child_by_field_name('left')]\n right_nodes=[root_node.child_by_field_name('right')]\n if len(left_nodes)==0:\n left_nodes=[root_node.child_by_field_name('left')]\n if len(right_nodes)==0:\n right_nodes=[root_node.child_by_field_name('right')]\n for node in right_nodes:\n temp,states=DFG_python(node,index_to_code,states)\n DFG+=temp\n for left_node,right_node in zip(left_nodes,right_nodes):\n left_tokens_index=tree_to_variable_index(left_node,index_to_code)\n right_tokens_index=tree_to_variable_index(right_node,index_to_code)\n temp=[]\n for token1_index in left_tokens_index:\n idx1,code1=index_to_code[token1_index]\n temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index],\n [index_to_code[x][0] for x in right_tokens_index]))\n states[code1]=[idx1]\n DFG+=temp \n if root_node.children[-1].type==\"block\":\n temp,states=DFG_python(root_node.children[-1],index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in while_statement: \n DFG=[]\n for i in range(2):\n for child in root_node.children:\n temp,states=DFG_python(child,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states \n else:\n DFG=[]\n for child in root_node.children:\n if child.type in do_first_statement:\n temp,states=DFG_python(child,index_to_code,states)\n DFG+=temp\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp,states=DFG_python(child,index_to_code,states)\n DFG+=temp\n \n return sorted(DFG,key=lambda x:x[1]),states" }, { "identifier": "DFG_java", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_java(root_node,index_to_code,states):\n assignment=['assignment_expression']\n def_statement=['variable_declarator']\n increment_statement=['update_expression']\n if_statement=['if_statement','else']\n for_statement=['for_statement']\n enhanced_for_statement=['enhanced_for_statement']\n while_statement=['while_statement']\n do_first_statement=[] \n states=states.copy()\n if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment':\n idx,code=index_to_code[(root_node.start_point,root_node.end_point)]\n if root_node.type==code:\n return [],states\n elif code in states:\n return [(code,idx,'comesFrom',[code],states[code].copy())],states\n else:\n if root_node.type=='identifier':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n elif root_node.type in def_statement:\n name=root_node.child_by_field_name('name')\n value=root_node.child_by_field_name('value')\n DFG=[]\n if value is None:\n indexs=tree_to_variable_index(name,index_to_code)\n for index in indexs:\n idx,code=index_to_code[index]\n DFG.append((code,idx,'comesFrom',[],[]))\n states[code]=[idx]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code)\n temp,states=DFG_java(value,index_to_code,states)\n DFG+=temp \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'comesFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in assignment:\n left_nodes=root_node.child_by_field_name('left')\n right_nodes=root_node.child_by_field_name('right')\n DFG=[]\n temp,states=DFG_java(right_nodes,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(left_nodes,index_to_code)\n value_indexs=tree_to_variable_index(right_nodes,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in increment_statement:\n DFG=[]\n indexs=tree_to_variable_index(root_node,index_to_code)\n for index1 in indexs:\n idx1,code1=index_to_code[index1]\n for index2 in indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1]\n return sorted(DFG,key=lambda x:x[1]),states \n elif root_node.type in if_statement:\n DFG=[]\n current_states=states.copy()\n others_states=[]\n flag=False\n tag=False\n if 'else' in root_node.type:\n tag=True\n for child in root_node.children:\n if 'else' in child.type:\n tag=True\n if child.type not in if_statement and flag is False:\n temp,current_states=DFG_java(child,index_to_code,current_states)\n DFG+=temp\n else:\n flag=True\n temp,new_states=DFG_java(child,index_to_code,states)\n DFG+=temp\n others_states.append(new_states)\n others_states.append(current_states)\n if tag is False:\n others_states.append(states)\n new_states={}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key]=dic[key].copy()\n else:\n new_states[key]+=dic[key]\n for key in new_states:\n new_states[key]=sorted(list(set(new_states[key])))\n return sorted(DFG,key=lambda x:x[1]),new_states\n elif root_node.type in for_statement:\n DFG=[]\n for child in root_node.children:\n temp,states=DFG_java(child,index_to_code,states)\n DFG+=temp\n flag=False\n for child in root_node.children:\n if flag:\n temp,states=DFG_java(child,index_to_code,states)\n DFG+=temp \n elif child.type==\"local_variable_declaration\":\n flag=True\n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in enhanced_for_statement:\n name=root_node.child_by_field_name('name')\n value=root_node.child_by_field_name('value')\n body=root_node.child_by_field_name('body')\n DFG=[]\n for i in range(2):\n temp,states=DFG_java(value,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n temp,states=DFG_java(body,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in while_statement: \n DFG=[]\n for i in range(2):\n for child in root_node.children:\n temp,states=DFG_java(child,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states \n else:\n DFG=[]\n for child in root_node.children:\n if child.type in do_first_statement:\n temp,states=DFG_java(child,index_to_code,states)\n DFG+=temp\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp,states=DFG_java(child,index_to_code,states)\n DFG+=temp\n \n return sorted(DFG,key=lambda x:x[1]),states" }, { "identifier": "DFG_ruby", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_ruby(root_node,index_to_code,states):\n assignment=['assignment','operator_assignment']\n if_statement=['if','elsif','else','unless','when']\n for_statement=['for']\n while_statement=['while_modifier','until']\n do_first_statement=[] \n def_statement=['keyword_parameter']\n if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment':\n states=states.copy()\n idx,code=index_to_code[(root_node.start_point,root_node.end_point)]\n if root_node.type==code:\n return [],states\n elif code in states:\n return [(code,idx,'comesFrom',[code],states[code].copy())],states\n else:\n if root_node.type=='identifier':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n elif root_node.type in def_statement:\n name=root_node.child_by_field_name('name')\n value=root_node.child_by_field_name('value')\n DFG=[]\n if value is None:\n indexs=tree_to_variable_index(name,index_to_code)\n for index in indexs:\n idx,code=index_to_code[index]\n DFG.append((code,idx,'comesFrom',[],[]))\n states[code]=[idx]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code)\n temp,states=DFG_ruby(value,index_to_code,states)\n DFG+=temp \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'comesFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states \n elif root_node.type in assignment:\n left_nodes=[x for x in root_node.child_by_field_name('left').children if x.type!=',']\n right_nodes=[x for x in root_node.child_by_field_name('right').children if x.type!=',']\n if len(right_nodes)!=len(left_nodes):\n left_nodes=[root_node.child_by_field_name('left')]\n right_nodes=[root_node.child_by_field_name('right')]\n if len(left_nodes)==0:\n left_nodes=[root_node.child_by_field_name('left')]\n if len(right_nodes)==0:\n right_nodes=[root_node.child_by_field_name('right')]\n if root_node.type==\"operator_assignment\":\n left_nodes=[root_node.children[0]]\n right_nodes=[root_node.children[-1]]\n\n DFG=[]\n for node in right_nodes:\n temp,states=DFG_ruby(node,index_to_code,states)\n DFG+=temp\n \n for left_node,right_node in zip(left_nodes,right_nodes):\n left_tokens_index=tree_to_variable_index(left_node,index_to_code)\n right_tokens_index=tree_to_variable_index(right_node,index_to_code)\n temp=[]\n for token1_index in left_tokens_index:\n idx1,code1=index_to_code[token1_index]\n temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index],\n [index_to_code[x][0] for x in right_tokens_index]))\n states[code1]=[idx1]\n DFG+=temp \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in if_statement:\n DFG=[]\n current_states=states.copy()\n others_states=[]\n tag=False\n if 'else' in root_node.type:\n tag=True\n for child in root_node.children:\n if 'else' in child.type:\n tag=True\n if child.type not in if_statement:\n temp,current_states=DFG_ruby(child,index_to_code,current_states)\n DFG+=temp\n else:\n temp,new_states=DFG_ruby(child,index_to_code,states)\n DFG+=temp\n others_states.append(new_states)\n others_states.append(current_states)\n if tag is False:\n others_states.append(states)\n new_states={}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key]=dic[key].copy()\n else:\n new_states[key]+=dic[key]\n for key in new_states:\n new_states[key]=sorted(list(set(new_states[key])))\n return sorted(DFG,key=lambda x:x[1]),new_states\n elif root_node.type in for_statement:\n DFG=[]\n for i in range(2):\n left_nodes=[root_node.child_by_field_name('pattern')]\n right_nodes=[root_node.child_by_field_name('value')]\n assert len(right_nodes)==len(left_nodes)\n for node in right_nodes:\n temp,states=DFG_ruby(node,index_to_code,states)\n DFG+=temp\n for left_node,right_node in zip(left_nodes,right_nodes):\n left_tokens_index=tree_to_variable_index(left_node,index_to_code)\n right_tokens_index=tree_to_variable_index(right_node,index_to_code)\n temp=[]\n for token1_index in left_tokens_index:\n idx1,code1=index_to_code[token1_index]\n temp.append((code1,idx1,'computedFrom',[index_to_code[x][1] for x in right_tokens_index],\n [index_to_code[x][0] for x in right_tokens_index]))\n states[code1]=[idx1]\n DFG+=temp \n temp,states=DFG_ruby(root_node.child_by_field_name('body'),index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in while_statement: \n DFG=[]\n for i in range(2):\n for child in root_node.children:\n temp,states=DFG_ruby(child,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states \n else:\n DFG=[]\n for child in root_node.children:\n if child.type in do_first_statement:\n temp,states=DFG_ruby(child,index_to_code,states)\n DFG+=temp\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp,states=DFG_ruby(child,index_to_code,states)\n DFG+=temp\n \n return sorted(DFG,key=lambda x:x[1]),states" }, { "identifier": "DFG_go", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_go(root_node,index_to_code,states):\n assignment=['assignment_statement',]\n def_statement=['var_spec']\n increment_statement=['inc_statement']\n if_statement=['if_statement','else']\n for_statement=['for_statement']\n enhanced_for_statement=[]\n while_statement=[]\n do_first_statement=[] \n states=states.copy()\n if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment':\n idx,code=index_to_code[(root_node.start_point,root_node.end_point)]\n if root_node.type==code:\n return [],states\n elif code in states:\n return [(code,idx,'comesFrom',[code],states[code].copy())],states\n else:\n if root_node.type=='identifier':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n elif root_node.type in def_statement:\n name=root_node.child_by_field_name('name')\n value=root_node.child_by_field_name('value')\n DFG=[]\n if value is None:\n indexs=tree_to_variable_index(name,index_to_code)\n for index in indexs:\n idx,code=index_to_code[index]\n DFG.append((code,idx,'comesFrom',[],[]))\n states[code]=[idx]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code)\n temp,states=DFG_go(value,index_to_code,states)\n DFG+=temp \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'comesFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in assignment:\n left_nodes=root_node.child_by_field_name('left')\n right_nodes=root_node.child_by_field_name('right')\n DFG=[]\n temp,states=DFG_go(right_nodes,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(left_nodes,index_to_code)\n value_indexs=tree_to_variable_index(right_nodes,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in increment_statement:\n DFG=[]\n indexs=tree_to_variable_index(root_node,index_to_code)\n for index1 in indexs:\n idx1,code1=index_to_code[index1]\n for index2 in indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1]\n return sorted(DFG,key=lambda x:x[1]),states \n elif root_node.type in if_statement:\n DFG=[]\n current_states=states.copy()\n others_states=[]\n flag=False\n tag=False\n if 'else' in root_node.type:\n tag=True\n for child in root_node.children:\n if 'else' in child.type:\n tag=True\n if child.type not in if_statement and flag is False:\n temp,current_states=DFG_go(child,index_to_code,current_states)\n DFG+=temp\n else:\n flag=True\n temp,new_states=DFG_go(child,index_to_code,states)\n DFG+=temp\n others_states.append(new_states)\n others_states.append(current_states)\n if tag is False:\n others_states.append(states)\n new_states={}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key]=dic[key].copy()\n else:\n new_states[key]+=dic[key]\n for key in states:\n if key not in new_states:\n new_states[key]=states[key]\n else:\n new_states[key]+=states[key]\n for key in new_states:\n new_states[key]=sorted(list(set(new_states[key])))\n return sorted(DFG,key=lambda x:x[1]),new_states\n elif root_node.type in for_statement:\n DFG=[]\n for child in root_node.children:\n temp,states=DFG_go(child,index_to_code,states)\n DFG+=temp\n flag=False\n for child in root_node.children:\n if flag:\n temp,states=DFG_go(child,index_to_code,states)\n DFG+=temp \n elif child.type==\"for_clause\":\n if child.child_by_field_name('update') is not None:\n temp,states=DFG_go(child.child_by_field_name('update'),index_to_code,states)\n DFG+=temp \n flag=True\n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n DFG=[]\n for child in root_node.children:\n if child.type in do_first_statement:\n temp,states=DFG_go(child,index_to_code,states)\n DFG+=temp\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp,states=DFG_go(child,index_to_code,states)\n DFG+=temp\n \n return sorted(DFG,key=lambda x:x[1]),states" }, { "identifier": "DFG_php", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_php(root_node,index_to_code,states):\n assignment=['assignment_expression','augmented_assignment_expression']\n def_statement=['simple_parameter']\n increment_statement=['update_expression']\n if_statement=['if_statement','else_clause']\n for_statement=['for_statement']\n enhanced_for_statement=['foreach_statement']\n while_statement=['while_statement']\n do_first_statement=[] \n states=states.copy()\n if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment':\n idx,code=index_to_code[(root_node.start_point,root_node.end_point)]\n if root_node.type==code:\n return [],states\n elif code in states:\n return [(code,idx,'comesFrom',[code],states[code].copy())],states\n else:\n if root_node.type=='identifier':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n elif root_node.type in def_statement:\n name=root_node.child_by_field_name('name')\n value=root_node.child_by_field_name('default_value')\n DFG=[]\n if value is None:\n indexs=tree_to_variable_index(name,index_to_code)\n for index in indexs:\n idx,code=index_to_code[index]\n DFG.append((code,idx,'comesFrom',[],[]))\n states[code]=[idx]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code)\n temp,states=DFG_php(value,index_to_code,states)\n DFG+=temp \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'comesFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in assignment:\n left_nodes=root_node.child_by_field_name('left')\n right_nodes=root_node.child_by_field_name('right')\n DFG=[]\n temp,states=DFG_php(right_nodes,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(left_nodes,index_to_code)\n value_indexs=tree_to_variable_index(right_nodes,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in increment_statement:\n DFG=[]\n indexs=tree_to_variable_index(root_node,index_to_code)\n for index1 in indexs:\n idx1,code1=index_to_code[index1]\n for index2 in indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1]\n return sorted(DFG,key=lambda x:x[1]),states \n elif root_node.type in if_statement:\n DFG=[]\n current_states=states.copy()\n others_states=[]\n flag=False\n tag=False\n if 'else' in root_node.type:\n tag=True\n for child in root_node.children:\n if 'else' in child.type:\n tag=True\n if child.type not in if_statement and flag is False:\n temp,current_states=DFG_php(child,index_to_code,current_states)\n DFG+=temp\n else:\n flag=True\n temp,new_states=DFG_php(child,index_to_code,states)\n DFG+=temp\n others_states.append(new_states)\n others_states.append(current_states)\n new_states={}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key]=dic[key].copy()\n else:\n new_states[key]+=dic[key]\n for key in states:\n if key not in new_states:\n new_states[key]=states[key]\n else:\n new_states[key]+=states[key]\n for key in new_states:\n new_states[key]=sorted(list(set(new_states[key])))\n return sorted(DFG,key=lambda x:x[1]),new_states\n elif root_node.type in for_statement:\n DFG=[]\n for child in root_node.children:\n temp,states=DFG_php(child,index_to_code,states)\n DFG+=temp\n flag=False\n for child in root_node.children:\n if flag:\n temp,states=DFG_php(child,index_to_code,states)\n DFG+=temp \n elif child.type==\"assignment_expression\": \n flag=True\n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in enhanced_for_statement:\n name=None\n value=None\n for child in root_node.children:\n if child.type=='variable_name' and value is None:\n value=child\n elif child.type=='variable_name' and name is None:\n name=child\n break\n body=root_node.child_by_field_name('body')\n DFG=[]\n for i in range(2):\n temp,states=DFG_php(value,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n temp,states=DFG_php(body,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in while_statement: \n DFG=[]\n for i in range(2):\n for child in root_node.children:\n temp,states=DFG_php(child,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states \n else:\n DFG=[]\n for child in root_node.children:\n if child.type in do_first_statement:\n temp,states=DFG_php(child,index_to_code,states)\n DFG+=temp\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp,states=DFG_php(child,index_to_code,states)\n DFG+=temp\n \n return sorted(DFG,key=lambda x:x[1]),states" }, { "identifier": "DFG_javascript", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_javascript(root_node,index_to_code,states):\n assignment=['assignment_pattern','augmented_assignment_expression']\n def_statement=['variable_declarator']\n increment_statement=['update_expression']\n if_statement=['if_statement','else']\n for_statement=['for_statement']\n enhanced_for_statement=[]\n while_statement=['while_statement']\n do_first_statement=[] \n states=states.copy()\n if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment':\n idx,code=index_to_code[(root_node.start_point,root_node.end_point)]\n if root_node.type==code:\n return [],states\n elif code in states:\n return [(code,idx,'comesFrom',[code],states[code].copy())],states\n else:\n if root_node.type=='identifier':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n elif root_node.type in def_statement:\n name=root_node.child_by_field_name('name')\n value=root_node.child_by_field_name('value')\n DFG=[]\n if value is None:\n indexs=tree_to_variable_index(name,index_to_code)\n for index in indexs:\n idx,code=index_to_code[index]\n DFG.append((code,idx,'comesFrom',[],[]))\n states[code]=[idx]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code)\n temp,states=DFG_javascript(value,index_to_code,states)\n DFG+=temp \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'comesFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in assignment:\n left_nodes=root_node.child_by_field_name('left')\n right_nodes=root_node.child_by_field_name('right')\n DFG=[]\n temp,states=DFG_javascript(right_nodes,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(left_nodes,index_to_code)\n value_indexs=tree_to_variable_index(right_nodes,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in increment_statement:\n DFG=[]\n indexs=tree_to_variable_index(root_node,index_to_code)\n for index1 in indexs:\n idx1,code1=index_to_code[index1]\n for index2 in indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1]\n return sorted(DFG,key=lambda x:x[1]),states \n elif root_node.type in if_statement:\n DFG=[]\n current_states=states.copy()\n others_states=[]\n flag=False\n tag=False\n if 'else' in root_node.type:\n tag=True\n for child in root_node.children:\n if 'else' in child.type:\n tag=True\n if child.type not in if_statement and flag is False:\n temp,current_states=DFG_javascript(child,index_to_code,current_states)\n DFG+=temp\n else:\n flag=True\n temp,new_states=DFG_javascript(child,index_to_code,states)\n DFG+=temp\n others_states.append(new_states)\n others_states.append(current_states)\n if tag is False:\n others_states.append(states) \n new_states={}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key]=dic[key].copy()\n else:\n new_states[key]+=dic[key]\n for key in states:\n if key not in new_states:\n new_states[key]=states[key]\n else:\n new_states[key]+=states[key]\n for key in new_states:\n new_states[key]=sorted(list(set(new_states[key])))\n return sorted(DFG,key=lambda x:x[1]),new_states\n elif root_node.type in for_statement:\n DFG=[]\n for child in root_node.children:\n temp,states=DFG_javascript(child,index_to_code,states)\n DFG+=temp\n flag=False\n for child in root_node.children:\n if flag:\n temp,states=DFG_javascript(child,index_to_code,states)\n DFG+=temp \n elif child.type==\"variable_declaration\": \n flag=True\n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in while_statement: \n DFG=[]\n for i in range(2):\n for child in root_node.children:\n temp,states=DFG_javascript(child,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states \n else:\n DFG=[]\n for child in root_node.children:\n if child.type in do_first_statement:\n temp,states=DFG_javascript(child,index_to_code,states)\n DFG+=temp\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp,states=DFG_javascript(child,index_to_code,states)\n DFG+=temp\n \n return sorted(DFG,key=lambda x:x[1]),states" }, { "identifier": "DFG_csharp", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_csharp(root_node,index_to_code,states):\n assignment=['assignment_expression']\n def_statement=['variable_declarator']\n increment_statement=['postfix_unary_expression']\n if_statement=['if_statement','else']\n for_statement=['for_statement']\n enhanced_for_statement=['for_each_statement']\n while_statement=['while_statement']\n do_first_statement=[] \n states=states.copy()\n if (len(root_node.children)==0 or root_node.type in ['string_literal','string','character_literal']) and root_node.type!='comment':\n idx,code=index_to_code[(root_node.start_point,root_node.end_point)]\n if root_node.type==code:\n return [],states\n elif code in states:\n return [(code,idx,'comesFrom',[code],states[code].copy())],states\n else:\n if root_node.type=='identifier':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n elif root_node.type in def_statement:\n if len(root_node.children)==2:\n name=root_node.children[0]\n value=root_node.children[1]\n else:\n name=root_node.children[0]\n value=None\n DFG=[]\n if value is None:\n indexs=tree_to_variable_index(name,index_to_code)\n for index in indexs:\n idx,code=index_to_code[index]\n DFG.append((code,idx,'comesFrom',[],[]))\n states[code]=[idx]\n return sorted(DFG,key=lambda x:x[1]),states\n else:\n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code)\n temp,states=DFG_csharp(value,index_to_code,states)\n DFG+=temp \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'comesFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in assignment:\n left_nodes=root_node.child_by_field_name('left')\n right_nodes=root_node.child_by_field_name('right')\n DFG=[]\n temp,states=DFG_csharp(right_nodes,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(left_nodes,index_to_code)\n value_indexs=tree_to_variable_index(right_nodes,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in increment_statement:\n DFG=[]\n indexs=tree_to_variable_index(root_node,index_to_code)\n for index1 in indexs:\n idx1,code1=index_to_code[index1]\n for index2 in indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1]\n return sorted(DFG,key=lambda x:x[1]),states \n elif root_node.type in if_statement:\n DFG=[]\n current_states=states.copy()\n others_states=[]\n flag=False\n tag=False\n if 'else' in root_node.type:\n tag=True\n for child in root_node.children:\n if 'else' in child.type:\n tag=True\n if child.type not in if_statement and flag is False:\n temp,current_states=DFG_csharp(child,index_to_code,current_states)\n DFG+=temp\n else:\n flag=True\n temp,new_states=DFG_csharp(child,index_to_code,states)\n DFG+=temp\n others_states.append(new_states)\n others_states.append(current_states)\n if tag is False:\n others_states.append(states)\n new_states={}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key]=dic[key].copy()\n else:\n new_states[key]+=dic[key]\n for key in new_states:\n new_states[key]=sorted(list(set(new_states[key])))\n return sorted(DFG,key=lambda x:x[1]),new_states\n elif root_node.type in for_statement:\n DFG=[]\n for child in root_node.children:\n temp,states=DFG_csharp(child,index_to_code,states)\n DFG+=temp\n flag=False\n for child in root_node.children:\n if flag:\n temp,states=DFG_csharp(child,index_to_code,states)\n DFG+=temp \n elif child.type==\"local_variable_declaration\":\n flag=True\n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in enhanced_for_statement:\n name=root_node.child_by_field_name('left')\n value=root_node.child_by_field_name('right')\n body=root_node.child_by_field_name('body')\n DFG=[]\n for i in range(2):\n temp,states=DFG_csharp(value,index_to_code,states)\n DFG+=temp \n name_indexs=tree_to_variable_index(name,index_to_code)\n value_indexs=tree_to_variable_index(value,index_to_code) \n for index1 in name_indexs:\n idx1,code1=index_to_code[index1]\n for index2 in value_indexs:\n idx2,code2=index_to_code[index2]\n DFG.append((code1,idx1,'computedFrom',[code2],[idx2]))\n states[code1]=[idx1] \n temp,states=DFG_csharp(body,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states\n elif root_node.type in while_statement: \n DFG=[]\n for i in range(2):\n for child in root_node.children:\n temp,states=DFG_csharp(child,index_to_code,states)\n DFG+=temp \n dic={}\n for x in DFG:\n if (x[0],x[1],x[2]) not in dic:\n dic[(x[0],x[1],x[2])]=[x[3],x[4]]\n else:\n dic[(x[0],x[1],x[2])][0]=list(set(dic[(x[0],x[1],x[2])][0]+x[3]))\n dic[(x[0],x[1],x[2])][1]=sorted(list(set(dic[(x[0],x[1],x[2])][1]+x[4])))\n DFG=[(x[0],x[1],x[2],y[0],y[1]) for x,y in sorted(dic.items(),key=lambda t:t[0][1])]\n return sorted(DFG,key=lambda x:x[1]),states \n else:\n DFG=[]\n for child in root_node.children:\n if child.type in do_first_statement:\n temp,states=DFG_csharp(child,index_to_code,states)\n DFG+=temp\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp,states=DFG_csharp(child,index_to_code,states)\n DFG+=temp\n \n return sorted(DFG,key=lambda x:x[1]),states" }, { "identifier": "DFG_c", "path": "evaluator/CodeBLEU/parser/DFG.py", "snippet": "def DFG_c(root_node, index_to_code, states):\n assignment = ['assignment_expression']\n def_statement = ['init_declatator', 'pointer_declarator', 'array_declarator']\n increment_statement = ['update_expression']\n if_statement = ['if_statement', 'else']\n for_statement = ['for_statement']\n while_statement = ['while_statement']\n parameter_statement = ['parameter_declaration']\n do_first_statement = []\n states = states.copy()\n if (len(root_node.children) == 0 or root_node.type == 'string') and root_node.type != 'comment':\n idx, code = index_to_code[(root_node.start_point, root_node.end_point)]\n if root_node.type == code or (root_node.parent.type == 'function_declarator' and root_node):\n return [], states\n elif code in states:\n return [(code, idx, 'comesFrom', [code], states[code].copy())], states\n elif root_node.type == 'identifier':\n if root_node.parent.type == 'declaration':\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n return [], states\n else:\n return [], states\n elif root_node.type in def_statement:\n\n if root_node.parent.type == 'function_definition':\n while root_node.type == 'pointer_declarator' and root_node.child_by_field_name('declarator').type == 'pointer_declarator':\n root_node = root_node.child_by_field_name('declarator')\n DFG = []\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp, states = DFG_c(child, index_to_code, states)\n DFG += temp\n return sorted(DFG, key=lambda x: x[1]), states\n name = root_node.child_by_field_name('declarator')\n value = root_node.child_by_field_name('value')\n DFG = []\n if value is None:\n indexs = tree_to_variable_index(name, index_to_code)\n for index in indexs:\n idx, code = index_to_code[index]\n DFG.append((code, idx, 'comesFrom', [], []))\n states[code] = [idx]\n return sorted(DFG, key=lambda x: x[1]), states\n else:\n name_indexs = tree_to_variable_index(name, index_to_code)\n value_indexs = tree_to_variable_index(value, index_to_code)\n temp, states = DFG_c(value, index_to_code, states)\n DFG += temp\n for index1 in name_indexs:\n idx1, code1 = index_to_code[index1]\n for index2 in value_indexs:\n idx2, code2 = index_to_code[index2]\n DFG.append((code1, idx1, 'comesFrom', [code2], [idx2]))\n states[code1] = [idx1]\n return sorted(DFG, key=lambda x: x[1]), states\n elif root_node.type in assignment:\n # left_nodes = root_node.child_by_field_name('left')\n # right_nodes = root_node.child_by_field_name('right')\n # DFG = []\n # temp, states = DFG_c(right_nodes, index_to_code, states)\n # DFG += temp\n # # filter field identifiers\n # while left_nodes.type == 'field_expression' or left_nodes.type == 'subscript_expression':\n # left_nodes = left_nodes.child_by_field_name('argument')\n # left_node = left_nodes\n # name_indexs = tree_to_variable_index(left_node, index_to_code)\n # value_indexs = tree_to_variable_index(right_nodes, index_to_code)\n # for index1 in name_indexs:\n # idx1, code1 = index_to_code[index1]\n # for index2 in value_indexs:\n # idx2, code2 = index_to_code[index2]\n # if code1 == \"alarm_timers\":\n # print(12)\n # if code1 in\n # DFG.append((code1, idx1, 'computedFrom', [code2], [idx2]))\n # states[code1] = [idx1]\n return [], states\n elif root_node.type in increment_statement:\n DFG = []\n indexs = tree_to_variable_index(root_node, index_to_code)\n for index1 in indexs:\n idx1, code1 = index_to_code[index1]\n for index2 in indexs:\n idx2, code2 = index_to_code[index2]\n DFG.append((code1, idx1, 'computedFrom', [code2], [idx2]))\n states[code1] = [idx1]\n return sorted(DFG, key=lambda x: x[1]), states\n elif root_node.type in if_statement:\n DFG = []\n current_states = states.copy()\n others_states = []\n flag = False\n tag = False\n if 'else' in root_node.type:\n tag = True\n for child in root_node.children:\n if 'else' in child.type:\n tag = True\n if child.type not in if_statement and flag is False:\n temp, current_states = DFG_c(child, index_to_code, current_states)\n DFG += temp\n else:\n flag = True\n temp, new_states = DFG_c(child, index_to_code, states)\n DFG += temp\n others_states.append(new_states)\n others_states.append(current_states)\n if tag is False:\n others_states.append(states)\n new_states = {}\n for dic in others_states:\n for key in dic:\n if key not in new_states:\n new_states[key] = dic[key].copy()\n else:\n new_states[key] += dic[key]\n for key in states:\n if key not in new_states:\n new_states[key] = states[key]\n else:\n new_states[key] += states[key]\n for key in new_states:\n new_states[key] = sorted(list(set(new_states[key])))\n return sorted(DFG, key=lambda x: x[1]), new_states\n elif root_node.type in for_statement:\n DFG = []\n for child in root_node.children:\n temp, states = DFG_c(child, index_to_code, states)\n DFG += temp\n flag = False\n for child in root_node.children:\n if flag:\n temp, states = DFG_c(child, index_to_code, states)\n DFG += temp\n elif child.type == \"variable_declaration\":\n flag = True\n dic = {}\n for x in DFG:\n if (x[0], x[1], x[2]) not in dic:\n dic[(x[0], x[1], x[2])] = [x[3], x[4]]\n else:\n dic[(x[0], x[1], x[2])][0] = list(set(dic[(x[0], x[1], x[2])][0] + x[3]))\n dic[(x[0], x[1], x[2])][1] = sorted(list(set(dic[(x[0], x[1], x[2])][1] + x[4])))\n DFG = [(x[0], x[1], x[2], y[0], y[1]) for x, y in sorted(dic.items(), key=lambda t: t[0][1])]\n return sorted(DFG, key=lambda x: x[1]), states\n elif root_node.type in while_statement:\n DFG = []\n for i in range(2):\n for child in root_node.children:\n temp, states = DFG_c(child, index_to_code, states)\n DFG += temp\n dic = {}\n for x in DFG:\n if (x[0], x[1], x[2]) not in dic:\n dic[(x[0], x[1], x[2])] = [x[3], x[4]]\n else:\n dic[(x[0], x[1], x[2])][0] = list(set(dic[(x[0], x[1], x[2])][0] + x[3]))\n dic[(x[0], x[1], x[2])][1] = sorted(list(set(dic[(x[0], x[1], x[2])][1] + x[4])))\n DFG = [(x[0], x[1], x[2], y[0], y[1]) for x, y in sorted(dic.items(), key=lambda t: t[0][1])]\n return sorted(DFG, key=lambda x: x[1]), states\n elif root_node.type in parameter_statement:\n child = root_node.child_by_field_name('declarator')\n if not child:\n return [], states\n while(child.type != 'identifier'):\n if child.type == 'parenthesized_declarator':\n child = child.children[1]\n else:\n child = child.child_by_field_name('declarator')\n if not child:\n return [], states\n idx,code=index_to_code[(child.start_point,child.end_point)]\n states[code]=[idx]\n return [(code,idx,'comesFrom',[],[])],states\n else:\n DFG = []\n for child in root_node.children:\n if child.type not in do_first_statement:\n temp, states = DFG_c(child, index_to_code, states)\n DFG += temp\n return sorted(DFG, key=lambda x: x[1]), states" }, { "identifier": "remove_comments_and_docstrings", "path": "evaluator/CodeBLEU/parser/utils.py", "snippet": "def remove_comments_and_docstrings(source, lang):\n if lang in ['python']:\n \"\"\"\n Returns 'source' minus comments and docstrings.\n \"\"\"\n io_obj = StringIO(source)\n out = \"\"\n prev_toktype = tokenize.INDENT\n last_lineno = -1\n last_col = 0\n for tok in tokenize.generate_tokens(io_obj.readline):\n token_type = tok[0]\n token_string = tok[1]\n start_line, start_col = tok[2]\n end_line, end_col = tok[3]\n ltext = tok[4]\n if start_line > last_lineno:\n last_col = 0\n if start_col > last_col:\n out += (\" \" * (start_col - last_col))\n # Remove comments:\n if token_type == tokenize.COMMENT:\n pass\n # This series of conditionals removes docstrings:\n elif token_type == tokenize.STRING:\n if prev_toktype != tokenize.INDENT:\n # This is likely a docstring; double-check we're not inside an operator:\n if prev_toktype != tokenize.NEWLINE:\n if start_col > 0:\n out += token_string\n else:\n out += token_string\n prev_toktype = token_type\n last_col = end_col\n last_lineno = end_line\n temp = []\n for x in out.split('\\n'):\n if x.strip() != \"\":\n temp.append(x)\n return '\\n'.join(temp)\n elif lang in ['ruby']:\n return source\n else:\n def replacer(match):\n s = match.group(0)\n if s.startswith('/'):\n return \" \" # note: a space and not an empty string\n else:\n return s\n\n pattern = re.compile(\n r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n temp = []\n for x in re.sub(pattern, replacer, source).split('\\n'):\n if x.strip() != \"\":\n temp.append(x)\n return '\\n'.join(temp)" }, { "identifier": "tree_to_token_index", "path": "evaluator/CodeBLEU/parser/utils.py", "snippet": "def tree_to_token_index(root_node):\n if (len(root_node.children) == 0 or root_node.type in ['string_literal', 'string',\n 'character_literal']) and root_node.type != 'comment':\n return [(root_node.start_point, root_node.end_point)]\n else:\n code_tokens = []\n for child in root_node.children:\n code_tokens += tree_to_token_index(child)\n return code_tokens" }, { "identifier": "index_to_code_token", "path": "evaluator/CodeBLEU/parser/utils.py", "snippet": "def index_to_code_token(index, code):\n start_point = index[0]\n end_point = index[1]\n if start_point[0] == end_point[0]:\n s = code[start_point[0]][start_point[1]:end_point[1]]\n else:\n s = \"\"\n s += code[start_point[0]][start_point[1]:]\n for i in range(start_point[0] + 1, end_point[0]):\n s += code[i]\n s += code[end_point[0]][:end_point[1]]\n return s" }, { "identifier": "tree_to_variable_index", "path": "evaluator/CodeBLEU/parser/utils.py", "snippet": "def tree_to_variable_index(root_node, index_to_code):\n if (len(root_node.children) == 0 or root_node.type in ['string_literal', 'string',\n 'character_literal']) and root_node.type != 'comment':\n index = (root_node.start_point, root_node.end_point)\n _, code = index_to_code[index]\n if root_node.type != code:\n return [(root_node.start_point, root_node.end_point)]\n else:\n return []\n else:\n code_tokens = []\n for child in root_node.children:\n code_tokens += tree_to_variable_index(child, index_to_code)\n return code_tokens" } ]
from evaluator.CodeBLEU.parser import DFG_python, DFG_java, DFG_ruby, DFG_go, DFG_php, DFG_javascript, DFG_csharp, DFG_c from evaluator.CodeBLEU.parser import (remove_comments_and_docstrings, tree_to_token_index, index_to_code_token, tree_to_variable_index) from tree_sitter import Language, Parser import pdb
17,437
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. parser_path = '/data/pretrain-attention/CodePrompt/evaluator/CodeBLEU/parser' dfg_function = { 'python': DFG_python, 'java': DFG_java, 'ruby': DFG_ruby, 'go': DFG_go, 'php': DFG_php, 'javascript': DFG_javascript, 'c_sharp': DFG_csharp,
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. parser_path = '/data/pretrain-attention/CodePrompt/evaluator/CodeBLEU/parser' dfg_function = { 'python': DFG_python, 'java': DFG_java, 'ruby': DFG_ruby, 'go': DFG_go, 'php': DFG_php, 'javascript': DFG_javascript, 'c_sharp': DFG_csharp,
'c': DFG_c,
7
2023-10-20 09:24:44+00:00
24k