index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31,205 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogagent_model.py | 206,208 | 199,218 | add_model_specific_args | FineTuneTrainCogAgentModel | 208,218 | 208,218 | class FineTuneTrainCogAgentModel(CogAgentModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
self.args = args
# If you want to use model parallel with a mp_size=1 checkpoint, and meanwhile you also want to use lora,
... | class FineTuneTrainCogAgentModel(CogAgentModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
self.args = args
# If you want to use model parallel with a mp_size=1 checkpoint, and meanwhile you also want to use lora,
... | group = parser.add_argument_group('CogAgent-finetune', 'CogAgent finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument(... | group = parser.add_argument_group('CogAgent-finetune', 'CogAgent finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument(... | 24 | 141 | 194 | 335 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... |
31,206 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogagent_model.py | 29,30 | 18,36 | forward | GLU | 30,36 | 30,36 | class GLU(nn.Module):
def __init__(self, args, in_features):
super().__init__()
self.linear_proj = nn.Linear(in_features, args.hidden_size, bias=False)
self.norm1 = nn.LayerNorm(args.hidden_size)
self.act1 = nn.GELU()
self.act2 = nn.functional.silu
self.dense_h_to_4h ... | class GLU(nn.Module):
def __init__(self, args, in_features):
super().__init__()
self.linear_proj = nn.Linear(in_features, args.hidden_size, bias=False)
self.norm1 = nn.LayerNorm(args.hidden_size)
self.act1 = nn.GELU()
self.act2 = nn.functional.silu
self.dense_h_to_4h ... | x = self.linear_proj(x)
x = self.act1(self.norm1(x))
x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
x = self.dense_4h_to_h(x)
return x
| x = self.linear_proj(x)
x = self.act1(self.norm1(x))
x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
x = self.dense_4h_to_h(x)
return x
| 16 | 231 | 89 | 320 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... |
31,207 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogagent_model.py | 132,133 | 111,157 | word_embedding_forward | ImageMixin | 133,157 | 133,157 | class ImageMixin(BaseMixin):
def __init__(self, args):
super().__init__()
vit_args = override_dist_dtype_device_args(args, args.eva_args)
self.vit_model = EVA2CLIPModel(EVA2CLIPModel.get_args(**vars(vit_args)))
self.in_features = 1792
self.linear_proj = GLU(args, self.in_feat... | class ImageMixin(BaseMixin):
def __init__(self, args):
super().__init__()
vit_args = override_dist_dtype_device_args(args, args.eva_args)
self.vit_model = EVA2CLIPModel(EVA2CLIPModel.get_args(**vars(vit_args)))
self.in_features = 1792
self.linear_proj = GLU(args, self.in_feat... | vision_inputs = {}
for k in kw_args:
if k.startswith('vision_') and k != 'vision_expert_mask':
vision_inputs[k[7:]] = kw_args[k]
if input_ids.shape[1] == 1 or not vision_inputs:
return self.transformer.word_embeddings(input_ids)
image_emb = self.vi... | vision_inputs = {}
for k in kw_args:
if k.startswith('vision_') and k != 'vision_expert_mask':
vision_inputs[k[7:]] = kw_args[k]
if input_ids.shape[1] == 1 or not vision_inputs:
return self.transformer.word_embeddings(input_ids)
image_emb = self.vi... | 92 | 368 | 487 | 855 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... |
31,209 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogvlm_model.py | 110,112 | 100,123 | add_model_specific_args | CogVLMModel | 112,117 | 112,117 | class CogVLMModel(LLaMAModel):
def __init__(self, args, transformer=None, **kwargs):
super().__init__(args, transformer=transformer, **kwargs)
self.image_length = args.image_length
self.add_mixin("eva", ImageMixin(args))
self.del_mixin("mlp")
self.add_mixin("mlp", LlamaVision... | class CogVLMModel(LLaMAModel):
def __init__(self, args, transformer=None, **kwargs):
super().__init__(args, transformer=transformer, **kwargs)
self.image_length = args.image_length
self.add_mixin("eva", ImageMixin(args))
self.del_mixin("mlp")
self.add_mixin("mlp", LlamaVision... | group = parser.add_argument_group('CogVLM', 'CogVLM Configurations')
group.add_argument('--image_length', type=int, default=256)
group.add_argument('--eva_args', type=json.loads, default={})
return super().add_model_specific_args(parser)
| group = parser.add_argument_group('CogVLM', 'CogVLM Configurations')
group.add_argument('--image_length', type=int, default=256)
group.add_argument('--eva_args', type=json.loads, default={})
return super().add_model_specific_args(parser)
| 13 | 333 | 94 | 427 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... |
31,210 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogvlm_model.py | 156,158 | 144,166 | add_model_specific_args | FineTuneTestCogVLMModel | 158,166 | 158,166 | class FineTuneTestCogVLMModel(CogVLMModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
if args.use_ptuning:
self.add_mixin("ptuning", PTuningV2Mixin(args.num_layers, args.hidden_size // args.num_attention_heads, args.... | class FineTuneTestCogVLMModel(CogVLMModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
if args.use_ptuning:
self.add_mixin("ptuning", PTuningV2Mixin(args.num_layers, args.hidden_size // args.num_attention_heads, args.... | group = parser.add_argument_group('CogVLM-finetune', 'CogVLM finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument('--u... | group = parser.add_argument_group('CogVLM-finetune', 'CogVLM finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument('--u... | 24 | 340 | 192 | 532 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... |
31,211 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogvlm_model.py | 130,132 | 123,142 | add_model_specific_args | FineTuneTrainCogVLMModel | 132,142 | 132,142 | class FineTuneTrainCogVLMModel(CogVLMModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
self.args = args
# If you want to use model parallel with a mp_size=1 checkpoint, and meanwhile you also want to use lora,
# ... | class FineTuneTrainCogVLMModel(CogVLMModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
self.args = args
# If you want to use model parallel with a mp_size=1 checkpoint, and meanwhile you also want to use lora,
# ... | group = parser.add_argument_group('CogVLM-finetune', 'CogVLM finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument('--u... | group = parser.add_argument_group('CogVLM-finetune', 'CogVLM finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument('--u... | 24 | 143 | 196 | 339 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... |
31,212 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogvlm_model.py | 28,29 | 17,35 | forward | GLU | 29,35 | 29,35 | class GLU(nn.Module):
def __init__(self, args, in_features):
super().__init__()
self.linear_proj = nn.Linear(in_features, args.hidden_size, bias=False)
self.norm1 = nn.LayerNorm(args.hidden_size)
self.act1 = nn.GELU()
self.act2 = nn.functional.silu
self.dense_h_to_4h ... | class GLU(nn.Module):
def __init__(self, args, in_features):
super().__init__()
self.linear_proj = nn.Linear(in_features, args.hidden_size, bias=False)
self.norm1 = nn.LayerNorm(args.hidden_size)
self.act1 = nn.GELU()
self.act2 = nn.functional.silu
self.dense_h_to_4h ... | x = self.linear_proj(x)
x = self.act1(self.norm1(x))
x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
x = self.dense_4h_to_h(x)
return x
| x = self.linear_proj(x)
x = self.act1(self.norm1(x))
x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
x = self.dense_4h_to_h(x)
return x
| 16 | 231 | 89 | 320 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... |
31,213 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogvlm_model.py | 84,85 | 73,100 | word_embedding_forward | ImageMixin | 85,100 | 85,100 | class ImageMixin(BaseMixin):
def __init__(self, args):
super().__init__()
vit_args = override_dist_dtype_device_args(args, args.eva_args)
self.vit_model = EVA2CLIPModel(EVA2CLIPModel.get_args(**vars(vit_args)))
self.in_features = 1792
self.linear_proj = GLU(args, self.in_feat... | class ImageMixin(BaseMixin):
def __init__(self, args):
super().__init__()
vit_args = override_dist_dtype_device_args(args, args.eva_args)
self.vit_model = EVA2CLIPModel(EVA2CLIPModel.get_args(**vars(vit_args)))
self.in_features = 1792
self.linear_proj = GLU(args, self.in_feat... | vision_inputs = {}
for k in kw_args:
if k.startswith('vision_') and k != 'vision_expert_mask':
vision_inputs[k[7:]] = kw_args[k]
if input_ids.shape[1] == 1 or not vision_inputs:
return self.transformer.word_embeddings(input_ids)
image_emb = self.vi... | vision_inputs = {}
for k in kw_args:
if k.startswith('vision_') and k != 'vision_expert_mask':
vision_inputs[k[7:]] = kw_args[k]
if input_ids.shape[1] == 1 or not vision_inputs:
return self.transformer.word_embeddings(input_ids)
image_emb = self.vi... | 50 | 228 | 290 | 518 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from sat.model.base_model import BaseMixin
import torch.nn as nn
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
M... |
31,214 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/eva_clip_model.py | 118,120 | 104,128 | add_model_specific_args | EVA2CLIPModel | 120,128 | 120,128 | class EVA2CLIPModel(BaseModel):
def __init__(self, args, transformer=None, **kwargs):
property = ViTProperty(args.image_size, args.patch_size, args.pre_len, args.post_len)
args.max_sequence_length = property.pre_len + property.num_patches + property.post_len
if 'activation_func' not in kwarg... | class EVA2CLIPModel(BaseModel):
def __init__(self, args, transformer=None, **kwargs):
property = ViTProperty(args.image_size, args.patch_size, args.pre_len, args.post_len)
args.max_sequence_length = property.pre_len + property.num_patches + property.post_len
if 'activation_func' not in kwarg... | group = parser.add_argument_group('EVA2CLIP', 'EVA2CLIP Configurations')
group.add_argument('--image-size', nargs='+', type=int, default=[224, 224])
group.add_argument('--pre-len', type=int, default=1) # [cls] by default
group.add_argument('--post-len', type=int, default=0) # empty by de... | group = parser.add_argument_group('EVA2CLIP', 'EVA2CLIP Configurations')
group.add_argument('--image-size', nargs='+', type=int, default=[224, 224])
group.add_argument('--pre-len', type=int, default=1) # [cls] by default
group.add_argument('--post-len', type=int, default=0) # empty by de... | 42 | 303 | 189 | 492 | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... |
31,215 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/eva_clip_model.py | 11,12 | 7,14 | final_forward | IdentityMixin | 12,14 | 12,14 | class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
def final_forward(self, logits, **kwargs):
FILL_FUNC_BODY | class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
def final_forward(self, logits, **kwargs):
FILL_FUNC_BODY | return logits[:, 1:]
| return logits[:, 1:]
| 3 | 53 | 13 | 66 | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... |
31,216 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/eva_clip_model.py | 60,61 | 56,104 | layer_forward | NewLayerForward | 65,104 | 61,104 | class NewLayerForward(BaseMixin):
def __init__(self):
super().__init__()
def layer_forward(self, hidden_states, mask, *args, **kw_args):
FILL_FUNC_BODY | class NewLayerForward(BaseMixin):
def __init__(self):
super().__init__()
def layer_forward(self, hidden_states, mask, *args, **kw_args):
'''
hidden_states: [batch, seq_len, hidden_size]
mask: [(1, 1), seq_len, seq_len]
'''
FILL_FUNC_BODY | self = self.transformer.layers[kw_args['layer_id']]
attention_input = hidden_states
# Self attention.
attention_output = self.input_layernorm(self.attention(attention_input, mask, **kw_args))
# DropPath for attention
if self.training and self.drop_path > 0.:
... | '''
hidden_states: [batch, seq_len, hidden_size]
mask: [(1, 1), seq_len, seq_len]
'''
self = self.transformer.layers[kw_args['layer_id']]
attention_input = hidden_states
# Self attention.
attention_output = self.input_layernorm(self.atten... | 142 | 106 | 578 | 684 | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... |
31,217 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/eva_clip_model.py | 35,36 | 15,56 | attention_forward | XAttn | 36,56 | 36,56 | class XAttn(BaseMixin):
def __init__(self, head_dim):
super().__init__()
self.scale = head_dim ** -0.5
def attention_fn(self, query_layer, key_layer, value_layer, attention_mask,
attention_dropout=None, log_attention_weights=None, scaling_attention_score=True, **kwargs):
... | class XAttn(BaseMixin):
def __init__(self, head_dim):
super().__init__()
self.scale = head_dim ** -0.5
def attention_fn(self, query_layer, key_layer, value_layer, attention_mask,
attention_dropout=None, log_attention_weights=None, scaling_attention_score=True, **kwargs):
... | self = self.transformer.layers[kw_args['layer_id']].attention
attention_fn = self.hooks['attention_fn']
mixed_raw_layer = self.query_key_value(hidden_states)
B, N, C = hidden_states.shape
mixed_raw_layer = mixed_raw_layer.reshape(B, N, 3, self.num_attention_heads_per_partition,... | self = self.transformer.layers[kw_args['layer_id']].attention
attention_fn = self.hooks['attention_fn']
mixed_raw_layer = self.query_key_value(hidden_states)
B, N, C = hidden_states.shape
mixed_raw_layer = mixed_raw_layer.reshape(B, N, 3, self.num_attention_heads_per_partition,... | 68 | 306 | 316 | 622 | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... | import torch
from sat.model.base_model import BaseModel
from sat.model.mixins import BaseMixin
from sat.model.official.vit_model import ViTProperty, ImagePatchEmbeddingMixin, InterpolatedPositionEmbeddingMixin, gelu
from sat import mpu
class IdentityMixin(BaseMixin):
def __init__(self):
super().__init__()
... |
31,219 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/mixin.py | 97,98 | 11,136 | mlp_forward | LlamaVisionExpertFCMixin | 98,129 | 98,129 | class LlamaVisionExpertFCMixin(BaseMixin):
def __init__(self, in_features, hidden_features, num_layers=32, num_vision_layers=0, vision_layer_range=None,
params_dtype=torch.float, device=torch.device('cpu')):
super().__init__()
self.num_layers = num_layers
self.num_vision_la... | class LlamaVisionExpertFCMixin(BaseMixin):
def __init__(self, in_features, hidden_features, num_layers=32, num_vision_layers=0, vision_layer_range=None,
params_dtype=torch.float, device=torch.device('cpu')):
super().__init__()
self.num_layers = num_layers
self.num_vision_la... | mixin_self = self
self = self.transformer.layers[kw_args['layer_id']].mlp
if "vision_expert_mask" in kw_args:
vision_expert_mask = kw_args['vision_expert_mask']
else:
vision_expert_mask = None
layer_id_key = str(int(kw_args['layer_id']))
if kw_ar... | mixin_self = self
self = self.transformer.layers[kw_args['layer_id']].mlp
if "vision_expert_mask" in kw_args:
vision_expert_mask = kw_args['vision_expert_mask']
else:
vision_expert_mask = None
layer_id_key = str(int(kw_args['layer_id']))
if kw_ar... | 86 | 1,178 | 657 | 1,835 | import torch
import torch.nn as nn
import torch.nn.functional as F
from sat.transformer_defaults import attention_fn_default
from sat.model.base_model import BaseMixin, non_conflict
from sat.mpu.layers import ColumnParallelLinear, RowParallelLinear
from sat.mpu.utils import split_tensor_along_last_dim
from sat import m... | import torch
import torch.nn as nn
import torch.nn.functional as F
from sat.transformer_defaults import attention_fn_default
from sat.model.base_model import BaseMixin, non_conflict
from sat.mpu.layers import ColumnParallelLinear, RowParallelLinear
from sat.mpu.utils import split_tensor_along_last_dim
from sat import m... |
31,220 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/split_dataset.py | 4,5 | 1,36 | find_all_files | 5,13 | 5,13 | import os
import shutil
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYall_files = find_all_files('archive')
os.makedirs("archive_split", exist_ok=True)
os.makedirs("archive_split/train", exist_ok=True)
os.makedirs("archive_split/valid", exist_ok=True)
os.makedirs("archive_split/test", exist_ok=True)
import r... | import os
import shutil
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYall_files = find_all_files('archive')
os.makedirs("archive_split", exist_ok=True)
os.makedirs("archive_split/train", exist_ok=True)
os.makedirs("archive_split/valid", exist_ok=True)
os.makedirs("archive_split/test", exist_ok=True)
import r... | target_files = []
for cur_dir, _, files in os.walk(path, followlinks=True):
for f in files:
if f.endswith(suffix):
target_files.append(os.path.join(cur_dir, f))
print(f'find {len(target_files)} files...')
return target_files
| target_files = []
for cur_dir, _, files in os.walk(path, followlinks=True):
for f in files:
if f.endswith(suffix):
target_files.append(os.path.join(cur_dir, f))
print(f'find {len(target_files)} files...')
return target_files
| 23 | 336 | 99 | 435 | import os
import shutil
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYall_files = find_all_files('archive')
os.makedirs("archive_split", exist_ok=True)
os.makedirs("archive_split/train", exist_ok=True)
os.makedirs("archive_split/valid", exist_ok=True)
os.makedirs("archive_split/test", exist_ok=True)
import r... | import os
import shutil
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYall_files = find_all_files('archive')
os.makedirs("archive_split", exist_ok=True)
os.makedirs("archive_split/train", exist_ok=True)
os.makedirs("archive_split/valid", exist_ok=True)
os.makedirs("archive_split/test", exist_ok=True)
import r... | |
31,222 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/utils/dataset.py | 11,12 | 1,62 | find_all_files | 12,20 | 12,20 | import os
import logging
import random
import logging
import jsonlines
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from sat.helpers import print_rank0
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYclass ItemDataset(Dataset):
def __init__(self, image_processor, text_pr... | import os
import logging
import random
import logging
import jsonlines
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from sat.helpers import print_rank0
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYclass ItemDataset(Dataset):
def __init__(self, image_processor, text_pr... | target_files = []
for cur_dir, _, files in os.walk(path, followlinks=True):
for f in files:
if f.endswith(suffix):
target_files.append(os.path.join(cur_dir, f))
print_rank0(f'find {len(target_files)} files...')
return target_files
| target_files = []
for cur_dir, _, files in os.walk(path, followlinks=True):
for f in files:
if f.endswith(suffix):
target_files.append(os.path.join(cur_dir, f))
print_rank0(f'find {len(target_files)} files...')
return target_files
| 23 | 584 | 102 | 686 | import os
import logging
import random
import logging
import jsonlines
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from sat.helpers import print_rank0
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYclass ItemDataset(Dataset):
def __init__(self, image_processor, text_pr... | import os
import logging
import random
import logging
import jsonlines
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from sat.helpers import print_rank0
def find_all_files(path, suffix=".jpg"):
FILL_FUNC_BODYclass ItemDataset(Dataset):
def __init__(self, image_processor, text_pr... | |
31,223 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/utils/dataset.py | 35,36 | 20,62 | load_data | ItemDataset | 36,40 | 36,40 | class ItemDataset(Dataset):
def __init__(self, image_processor, text_processor, args, data_dirs, cross_image_processor=None, **kwargs):
super().__init__()
self.data = self.load_data(data_dirs)
self.image_processor, self.text_processor, self.cross_image_processor = image_processor, text_proce... | class ItemDataset(Dataset):
def __init__(self, image_processor, text_processor, args, data_dirs, cross_image_processor=None, **kwargs):
super().__init__()
self.data = self.load_data(data_dirs)
self.image_processor, self.text_processor, self.cross_image_processor = image_processor, text_proce... | all_files = find_all_files(data_dir, suffix=".jpg")
print_rank0(f"find {len(all_files)} samples in all...")
return all_files
| all_files = find_all_files(data_dir, suffix=".jpg")
print_rank0(f"find {len(all_files)} samples in all...")
return all_files
| 11 | 465 | 55 | 520 | import os
import logging
import random
import logging
import jsonlines
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from sat.helpers import print_rank0
def find_all_files(path, suffix=".jpg"):
target_files = []
for cur_dir, _, files in os.walk(path, followlinks=True):
... | import os
import logging
import random
import logging
import jsonlines
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from sat.helpers import print_rank0
def find_all_files(path, suffix=".jpg"):
target_files = []
for cur_dir, _, files in os.walk(path, followlinks=True):
... |
31,225 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/utils/language.py | 140,141 | 50,143 | replace_tags_with_empty | llama2_text_processor | 141,143 | 141,143 | class llama2_text_processor:
def __init__(self, tokenizer, max_target_length=2048, image_length=257, model=None):
self.tokenizer = tokenizer
self.max_target_length = max_target_length
self.image_length = image_length
def __call__(self, caption, prompt=""):
if '<EOI>' not in prom... | class llama2_text_processor:
def __init__(self, tokenizer, max_target_length=2048, image_length=257, model=None):
self.tokenizer = tokenizer
self.max_target_length = max_target_length
self.image_length = image_length
def __call__(self, caption, prompt=""):
if '<EOI>' not in prom... | return re.sub('<pad>|<s>|</s>|<EOI>', '', text)
| return re.sub('<pad>|<s>|</s>|<EOI>', '', text)
| 4 | 1,589 | 27 | 1,616 | def base_history_to_prompt(self, query, history):
prompt = '<EOI>' + query
return prompt
def chat_history_to_prompt(self, query, history):
prompt = "<EOI> [INST] "
for i, (old_query, response) in enumerate(history):
prompt += old_query + " [/INST] " + response + " [INST] "
prompt += query +... | def base_history_to_prompt(self, query, history):
prompt = '<EOI>' + query
return prompt
def chat_history_to_prompt(self, query, history):
prompt = "<EOI> [INST] "
for i, (old_query, response) in enumerate(history):
prompt += old_query + " [/INST] " + response + " [INST] "
prompt += query +... |
31,226 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/utils/language.py | 231,232 | 165,234 | get_func | llama2_text_processor_inference | 232,234 | 232,234 | class llama2_text_processor_inference:
def __init__(self, tokenizer, max_target_length=1024, image_length=257, model=None, no_prompt=False, english=True):
self.tokenizer = tokenizer
self.max_target_length = max_target_length
self.image_length = image_length
if self.tokenizer.signal_t... | class llama2_text_processor_inference:
def __init__(self, tokenizer, max_target_length=1024, image_length=257, model=None, no_prompt=False, english=True):
self.tokenizer = tokenizer
self.max_target_length = max_target_length
self.image_length = image_length
if self.tokenizer.signal_t... | get_func = partial(get_masks_and_position_ids, image_logits_mask=kwargs['image_rope_mask'])
return get_func | get_func = partial(get_masks_and_position_ids, image_logits_mask=kwargs['image_rope_mask'])
return get_func | 6 | 1,031 | 42 | 1,073 | def base_history_to_prompt(self, query, history):
prompt = '<EOI>' + query
return prompt
def chat_history_to_prompt(self, query, history):
prompt = "<EOI> [INST] "
for i, (old_query, response) in enumerate(history):
prompt += old_query + " [/INST] " + response + " [INST] "
prompt += query +... | def base_history_to_prompt(self, query, history):
prompt = '<EOI>' + query
return prompt
def chat_history_to_prompt(self, query, history):
prompt = "<EOI> [INST] "
for i, (old_query, response) in enumerate(history):
prompt += old_query + " [/INST] " + response + " [INST] "
prompt += query +... |
31,227 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/utils/vision.py | 30,31 | 1,35 | blip2_image_processor_func_with_inputs | 31,33 | 31,33 | from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
import torch
class BlipImageEvalProcessor:
def __init__(self, image_size=384, mean=None, std=None):
super().__init__()
if mean is None:
mean = (0.48145466, 0.4578275, 0.40821073)
i... | from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
import torch
class BlipImageEvalProcessor:
def __init__(self, image_size=384, mean=None, std=None):
super().__init__()
if mean is None:
mean = (0.48145466, 0.4578275, 0.40821073)
i... | return {'image': image_processor(image).unsqueeze(0), 'input_ids': torch.zeros(1, 1, dtype=torch.long), 'position_ids': None, 'attention_mask': torch.ones(1, 1, dtype=torch.long)}
| return {'image': image_processor(image).unsqueeze(0), 'input_ids': torch.zeros(1, 1, dtype=torch.long), 'position_ids': None, 'attention_mask': torch.ones(1, 1, dtype=torch.long)}
| 13 | 357 | 76 | 433 | from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
import torch
class BlipImageEvalProcessor:
def __init__(self, image_size=384, mean=None, std=None):
super().__init__()
if mean is None:
mean = (0.48145466, 0.4578275, 0.40821073)
i... | from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
import torch
class BlipImageEvalProcessor:
def __init__(self, image_size=384, mean=None, std=None):
super().__init__()
if mean is None:
mean = (0.48145466, 0.4578275, 0.40821073)
i... | |
31,256 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/__main__.py | 67,68 | 1,95 | externalrepo | 68,86 | 68,86 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | string = "<b>Your external repo plugins have imported.<b>\n\n"
if Config.EXTERNAL_REPO:
data = await install_externalrepo(
Config.EXTERNAL_REPO, Config.EXTERNAL_REPOBRANCH, "xtraplugins"
)
string += f"<b>➜ Repo: </b><a href='{data[0]}'><b>{data[1]}</b></a>\n<b> • Importe... | string = "<b>Your external repo plugins have imported.<b>\n\n"
if Config.EXTERNAL_REPO:
data = await install_externalrepo(
Config.EXTERNAL_REPO, Config.EXTERNAL_REPOBRANCH, "xtraplugins"
)
string += f"<b>➜ Repo: </b><a href='{data[0]}'><b>{data[1]}</b></a>\n<b> • Importe... | 93 | 716 | 568 | 1,284 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,257 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/helpers/tools.py | 56,57 | 1,127 | media_type | 57,87 | 57,87 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | if message:
try:
if message.photo:
return "Photo"
if message.audio:
return "Audio"
if message.voice:
return "Voice"
if message.video_note:
return "Round Video"
if message.gif:
... | if message:
try:
if message.photo:
return "Photo"
if message.audio:
return "Audio"
if message.voice:
return "Voice"
if message.video_note:
return "Round Video"
if message.gif:
... | 61 | 1,048 | 220 | 1,268 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,258 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/helpers/utils/extdl.py | 13,14 | 1,19 | install_pip | 14,19 | 14,19 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | print(f"installing {pipfile}")
pip_cmd = ["pip", "install", f"{pipfile}"]
process = Popen(pip_cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
return stdout
| print(f"installing {pipfile}")
pip_cmd = ["pip", "install", f"{pipfile}"]
process = Popen(pip_cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
return stdout
| 18 | 164 | 78 | 242 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,259 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/helpers/utils/utils.py | 21,22 | 1,49 | runcmd | 22,35 | 22,35 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | args = shlex.split(cmd)
process = await asyncio.create_subprocess_exec(
*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return (
stdout.decode("utf-8", "replace").strip(),
stderr.decode("utf-8", "replace").s... | args = shlex.split(cmd)
process = await asyncio.create_subprocess_exec(
*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return (
stdout.decode("utf-8", "replace").strip(),
stderr.decode("utf-8", "replace").s... | 25 | 352 | 138 | 490 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,260 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/calc.py | 19,29 | 1,63 | calculator | 30,59 | 29,59 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | cmd = event.text.split(" ", maxsplit=1)[1]
event = await edit_or_reply(event, "Calculating ...")
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
redirected_error = sys.stderr = io.StringIO()
stdout, stderr, exc = None, None, None
san = f"pri... | "To solve basic mathematics equations."
cmd = event.text.split(" ", maxsplit=1)[1]
event = await edit_or_reply(event, "Calculating ...")
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
redirected_error = sys.stderr = io.StringIO()
stdout, st... | 98 | 348 | 341 | 689 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,264 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/hash.py | 64,78 | 1,120 | endecrypt | 79,120 | 78,120 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | string = "".join(event.text.split(maxsplit=2)[2:])
catevent = event
if event.pattern_match.group(1) == "en":
if string:
result = base64.b64encode(bytes(string, "utf-8")).decode("utf-8")
result = f"**Shhh! It's Encoded : **\n`{result}`"
else:
reply = await ... | "To encode or decode the string using base64"
string = "".join(event.text.split(maxsplit=2)[2:])
catevent = event
if event.pattern_match.group(1) == "en":
if string:
result = base64.b64encode(bytes(string, "utf-8")).decode("utf-8")
result = f"**Shhh! It's Encoded : **\n`{... | 136 | 979 | 635 | 1,614 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,265 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/json.py | 19,28 | 1,47 | _ | 29,34 | 28,34 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | catevent = await event.get_reply_message() if event.reply_to_msg_id else event
the_real_message = catevent.stringify()
await edit_or_reply(event, the_real_message, parse_mode=_format.parse_pre)
| "To get details of that message in json format."
catevent = await event.get_reply_message() if event.reply_to_msg_id else event
the_real_message = catevent.stringify()
await edit_or_reply(event, the_real_message, parse_mode=_format.parse_pre)
| 15 | 457 | 80 | 537 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,267 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/lyrics.py | 21,45 | 1,100 | lyrics | 46,100 | 45,100 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | if GENIUS is None:
return await edit_or_reply(
event,
"<i>Set <code>GENIUS_API_TOKEN</code> in heroku vars for functioning of this command.\n\nCheck out this <b><a href = https://graph.org/How-to-get-Genius-API-Token-04-26>Tutorial</a></b></i>",
parse_mode="html",
... | "To fetch song lyrics"
if GENIUS is None:
return await edit_or_reply(
event,
"<i>Set <code>GENIUS_API_TOKEN</code> in heroku vars for functioning of this command.\n\nCheck out this <b><a href = https://graph.org/How-to-get-Genius-API-Token-04-26>Tutorial</a></b></i>",
... | 228 | 555 | 832 | 1,387 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,268 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/mediainfo.py | 25,26 | 1,107 | file_data | 26,63 | 26,63 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | hmm = ""
if reply.file.name:
hmm += f"Name : {reply.file.name}<br>"
if reply.file.mime_type:
hmm += f"Mime type : {reply.file.mime_type}<br>"
if reply.file.size:
hmm += f"Size : {humanbytes(reply.file.size)}<br>"
if reply.date:
hmm += f"Date : {_format.yaml_fo... | hmm = ""
if reply.file.name:
hmm += f"Name : {reply.file.name}<br>"
if reply.file.mime_type:
hmm += f"Mime type : {reply.file.mime_type}<br>"
if reply.file.size:
hmm += f"Size : {humanbytes(reply.file.size)}<br>"
if reply.date:
hmm += f"Date : {_format.yaml_fo... | 114 | 761 | 592 | 1,353 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,269 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/powertools.py | 30,40 | 1,133 | _ | 41,66 | 40,66 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | if BOTLOG:
await event.client.send_message(BOTLOG_CHATID, "#RESTART \n" "Bot Restarted")
sandy = await edit_or_reply(
event,
"Restarted. `.ping` me or `.help` to check if I am online, actually it takes 1-2 min for restarting",
)
try:
ulist = get_collectionlist_items()
... | "Restarts the bot !!"
if BOTLOG:
await event.client.send_message(BOTLOG_CHATID, "#RESTART \n" "Bot Restarted")
sandy = await edit_or_reply(
event,
"Restarted. `.ping` me or `.help` to check if I am online, actually it takes 1-2 min for restarting",
)
try:
ulist = get_... | 70 | 1,189 | 273 | 1,462 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,270 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/rename.py | 27,41 | 1,96 | _ | 42,96 | 41,96 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | thumb = thumb_image_path if os.path.exists(thumb_image_path) else None
flags = event.pattern_match.group(1)
forcedoc = bool(flags)
supsstream = not flags
catevent = await edit_or_reply(
event,
"`Rename & Upload in process 🙄🙇♂️🙇♂️🙇♀️ It might take some time if file size is big`... | "To rename and upload the file"
thumb = thumb_image_path if os.path.exists(thumb_image_path) else None
flags = event.pattern_match.group(1)
forcedoc = bool(flags)
supsstream = not flags
catevent = await edit_or_reply(
event,
"`Rename & Upload in process 🙄🙇♂️🙇♂️🙇♀️ It might... | 178 | 417 | 747 | 1,164 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,271 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/plugins/warns.py | 23,33 | 1,102 | _ | 34,57 | 33,57 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | warn_reason = event.pattern_match.group(1)
if not warn_reason:
warn_reason = "No reason"
reply_message = await event.get_reply_message()
limit, soft_warn = sql.get_warn_setting(event.chat_id)
num_warns, reasons = sql.warn_user(
reply_message.sender_id, event.chat_id, warn_reason
... | "To warn a user"
warn_reason = event.pattern_match.group(1)
if not warn_reason:
warn_reason = "No reason"
reply_message = await event.get_reply_message()
limit, soft_warn = sql.get_warn_setting(event.chat_id)
num_warns, reasons = sql.warn_user(
reply_message.sender_id, event.chat... | 79 | 816 | 374 | 1,190 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,272 | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot | /home/hieuvd/dung_repo/raw/stars_02/TgCatUB_catuserbot/catuserbot/userbot/utils/pluginmanager.py | 75,76 | 1,112 | remove_plugin | 76,104 | 76,104 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | try:
cmd = []
if shortname in PLG_INFO:
cmd += PLG_INFO[shortname]
else:
cmd = [shortname]
for cmdname in cmd:
if cmdname in LOADED_CMDS:
for i in LOADED_CMDS[cmdname]:
catub.remove_event_handler(i)
... | try:
cmd = []
if shortname in PLG_INFO:
cmd += PLG_INFO[shortname]
else:
cmd = [shortname]
for cmdname in cmd:
if cmdname in LOADED_CMDS:
for i in LOADED_CMDS[cmdname]:
catub.remove_event_handler(i)
... | 72 | 950 | 303 | 1,253 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# CatUserBot #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Copyright (C) 2020-2023 by TgCatUB@Github.
# This file is part of: https://github.com/TgCatUB/catuserbot
# and is released under the "GNU v3.0 License Agreement".
# Please see: https://github.com/TgCatUB/catuserbot/blob/... | |
31,367 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/dataset/file_backend.py | 17,19 | 9,26 | name | BaseStorageBackend | 19,21 | 19,21 | class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backends.
All backends need to implement two apis: ``get()`` and ``get_text()``.
``get()`` reads the file as a byte stream and ``get_text()`` reads the file
as texts.
"""
@property
def name(self) -> str:
FILL_FUNC_BO... | class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backends.
All backends need to implement two apis: ``get()`` and ``get_text()``.
``get()`` reads the file as a byte stream and ``get_text()`` reads the file
as texts.
"""
@property
def name(self) -> str:
FILL_FUNC_BO... | return self.__class__.__name__
| return self.__class__.__name__
| 2 | 134 | 13 | 147 | # Copyright (c) OpenMMLab. All rights reserved.
# https://github.com/open-mmlab/mmcv/blob/master/mmcv/fileio/file_client.py
import re
from abc import ABCMeta, abstractmethod
from pathlib import Path
from typing import Optional, Union
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backen... | # Copyright (c) OpenMMLab. All rights reserved.
# https://github.com/open-mmlab/mmcv/blob/master/mmcv/fileio/file_client.py
import re
from abc import ABCMeta, abstractmethod
from pathlib import Path
from typing import Optional, Union
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backen... |
31,368 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/dataset/file_backend.py | 109,110 | 106,121 | get | HardDiskBackend | 118,121 | 110,121 | class HardDiskBackend(BaseStorageBackend):
"""Raw hard disks storage backend."""
def get(self, filepath: Union[str, Path]) -> bytes:
FILL_FUNC_BODY | class HardDiskBackend(BaseStorageBackend):
"""Raw hard disks storage backend."""
def get(self, filepath: Union[str, Path]) -> bytes:
"""Read data from a given ``filepath`` with 'rb' mode.
Args:
filepath (str or Path): Path to read data.
Returns:
bytes: Expected... | with open(filepath, 'rb') as f:
value_buf = f.read()
return value_buf
| """Read data from a given ``filepath`` with 'rb' mode.
Args:
filepath (str or Path): Path to read data.
Returns:
bytes: Expected bytes object.
"""
with open(filepath, 'rb') as f:
value_buf = f.read()
return value_buf
| 10 | 107 | 33 | 140 | # Copyright (c) OpenMMLab. All rights reserved.
# https://github.com/open-mmlab/mmcv/blob/master/mmcv/fileio/file_client.py
import re
from abc import ABCMeta, abstractmethod
from pathlib import Path
from typing import Optional, Union
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backen... | # Copyright (c) OpenMMLab. All rights reserved.
# https://github.com/open-mmlab/mmcv/blob/master/mmcv/fileio/file_client.py
import re
from abc import ABCMeta, abstractmethod
from pathlib import Path
from typing import Optional, Union
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backen... |
31,369 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/dataset/file_backend.py | 91,92 | 26,106 | get | PetrelBackend | 100,106 | 92,106 | class PetrelBackend(BaseStorageBackend):
"""Petrel storage backend (for internal use).
PetrelBackend supports reading and writing data to multiple clusters.
If the file path contains the cluster name, PetrelBackend will read data
from specified cluster or write data to it. Otherwise, PetrelBackend will... | class PetrelBackend(BaseStorageBackend):
"""Petrel storage backend (for internal use).
PetrelBackend supports reading and writing data to multiple clusters.
If the file path contains the cluster name, PetrelBackend will read data
from specified cluster or write data to it. Otherwise, PetrelBackend will... | filepath = self._map_path(filepath)
filepath = self._format_path(filepath)
value = self._client.Get(filepath)
return value
| """Read data from a given ``filepath`` with 'rb' mode.
Args:
filepath (str or Path): Path to read data.
Returns:
bytes: The loaded bytes.
"""
filepath = self._map_path(filepath)
filepath = self._format_path(filepath)
value = self._client.... | 11 | 834 | 53 | 887 | # Copyright (c) OpenMMLab. All rights reserved.
# https://github.com/open-mmlab/mmcv/blob/master/mmcv/fileio/file_client.py
import re
from abc import ABCMeta, abstractmethod
from pathlib import Path
from typing import Optional, Union
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backen... | # Copyright (c) OpenMMLab. All rights reserved.
# https://github.com/open-mmlab/mmcv/blob/master/mmcv/fileio/file_client.py
import re
from abc import ABCMeta, abstractmethod
from pathlib import Path
from typing import Optional, Union
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backen... |
31,370 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/inference.py | 33,34 | 1,87 | parse_args | 34,68 | 34,68 | from argparse import ArgumentParser, Namespace
import torch
from accelerate.utils import set_seed
from utils.inference import (
V1InferenceLoop,
BSRInferenceLoop, BFRInferenceLoop, BIDInferenceLoop, UnAlignedBFRInferenceLoop
)
def check_device(device: str) -> str:
if device == "cuda":
if not tor... | from argparse import ArgumentParser, Namespace
import torch
from accelerate.utils import set_seed
from utils.inference import (
V1InferenceLoop,
BSRInferenceLoop, BFRInferenceLoop, BIDInferenceLoop, UnAlignedBFRInferenceLoop
)
def check_device(device: str) -> str:
if device == "cuda":
if not tor... | parser = ArgumentParser()
### model parameters
parser.add_argument("--task", type=str, required=True, choices=["sr", "dn", "fr", "fr_bg"])
parser.add_argument("--upscale", type=float, required=True)
parser.add_argument("--version", type=str, default="v2", choices=["v1", "v2"])
### sampling param... | parser = ArgumentParser()
### model parameters
parser.add_argument("--task", type=str, required=True, choices=["sr", "dn", "fr", "fr_bg"])
parser.add_argument("--upscale", type=float, required=True)
parser.add_argument("--version", type=str, default="v2", choices=["v1", "v2"])
### sampling param... | 107 | 483 | 659 | 1,142 | from argparse import ArgumentParser, Namespace
import torch
from accelerate.utils import set_seed
from utils.inference import (
V1InferenceLoop,
BSRInferenceLoop, BFRInferenceLoop, BIDInferenceLoop, UnAlignedBFRInferenceLoop
)
def check_device(device: str) -> str:
if device == "cuda":
if not tor... | from argparse import ArgumentParser, Namespace
import torch
from accelerate.utils import set_seed
from utils.inference import (
V1InferenceLoop,
BSRInferenceLoop, BFRInferenceLoop, BIDInferenceLoop, UnAlignedBFRInferenceLoop
)
def check_device(device: str) -> str:
if device == "cuda":
if not tor... | |
31,372 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/attention.py | 229,230 | 205,236 | _forward | BasicTransformerBlock | 230,236 | 230,236 | class BasicTransformerBlock(nn.Module):
ATTENTION_MODES = {
AttnMode.VANILLA: CrossAttention, # vanilla attention
AttnMode.XFORMERS: MemoryEfficientCrossAttention,
AttnMode.SDP: SDPCrossAttention
}
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True,... | class BasicTransformerBlock(nn.Module):
ATTENTION_MODES = {
AttnMode.VANILLA: CrossAttention, # vanilla attention
AttnMode.XFORMERS: MemoryEfficientCrossAttention,
AttnMode.SDP: SDPCrossAttention
}
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True,... | x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
x = self.attn2(self.norm2(x), context=context) + x
x = self.ff(self.norm3(x)) + x
return x
| x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x
x = self.attn2(self.norm2(x), context=context) + x
x = self.ff(self.norm3(x)) + x
return x
| 23 | 459 | 86 | 545 | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... |
31,373 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/attention.py | 74,75 | 54,109 | forward | CrossAttention | 75,109 | 75,109 | class CrossAttention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
super().__init__()
print(f"Setting up {self.__class__.__name__} (vanilla). Query dim is {query_dim}, context_dim is {context_dim} and using "
f"{heads} heads.")
i... | class CrossAttention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
super().__init__()
print(f"Setting up {self.__class__.__name__} (vanilla). Query dim is {query_dim}, context_dim is {context_dim} and using "
f"{heads} heads.")
i... | h = self.heads
q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
# force cast to fp32 to avoid overflowing
if _ATTN_PRECISION =="f... | h = self.heads
q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
# force cast to fp32 to avoid overflowing
if _ATTN_PRECISION =="f... | 167 | 303 | 504 | 807 | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... |
31,374 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/attention.py | 46,47 | 30,50 | forward | FeedForward | 47,50 | 47,50 | class FeedForward(nn.Module):
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
super().__init__()
inner_dim = int(dim * mult)
dim_out = default(dim_out, dim)
project_in = nn.Sequential(
nn.Linear(dim, inner_dim),
nn.GELU()
) if not... | class FeedForward(nn.Module):
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
super().__init__()
inner_dim = int(dim * mult)
dim_out = default(dim_out, dim)
project_in = nn.Sequential(
nn.Linear(dim, inner_dim),
nn.GELU()
) if not... | return self.net(x)
| return self.net(x)
| 2 | 197 | 14 | 211 | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... |
31,375 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/attention.py | 25,26 | 20,30 | forward | GEGLU | 26,30 | 26,30 | class GEGLU(nn.Module):
def __init__(self, dim_in, dim_out):
super().__init__()
self.proj = nn.Linear(dim_in, dim_out * 2)
def forward(self, x):
FILL_FUNC_BODY | class GEGLU(nn.Module):
def __init__(self, dim_in, dim_out):
super().__init__()
self.proj = nn.Linear(dim_in, dim_out * 2)
def forward(self, x):
FILL_FUNC_BODY | x, gate = self.proj(x).chunk(2, dim=-1)
return x * F.gelu(gate)
| x, gate = self.proj(x).chunk(2, dim=-1)
return x * F.gelu(gate)
| 9 | 76 | 41 | 117 | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... |
31,376 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/attention.py | 128,129 | 109,158 | forward | MemoryEfficientCrossAttention | 129,158 | 129,158 | class MemoryEfficientCrossAttention(nn.Module):
# https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
super().__init__()
print(f"Setting ... | class MemoryEfficientCrossAttention(nn.Module):
# https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
super().__init__()
print(f"Setting ... | q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
b, _, _ = q.shape
q, k, v = map(
lambda t: t.unsqueeze(3)
.reshape(b, t.shape[1], self.heads, self.dim_head)
.permute(0, 2, 1, 3)
... | q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
b, _, _ = q.shape
q, k, v = map(
lambda t: t.unsqueeze(3)
.reshape(b, t.shape[1], self.heads, self.dim_head)
.permute(0, 2, 1, 3)
... | 86 | 382 | 370 | 752 | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... |
31,377 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/attention.py | 175,176 | 158,205 | forward | SDPCrossAttention | 176,205 | 176,205 | class SDPCrossAttention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
super().__init__()
print(f"Setting up {self.__class__.__name__} (sdp). Query dim is {query_dim}, context_dim is {context_dim} and using "
f"{heads} heads.")
i... | class SDPCrossAttention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
super().__init__()
print(f"Setting up {self.__class__.__name__} (sdp). Query dim is {query_dim}, context_dim is {context_dim} and using "
f"{heads} heads.")
i... | q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
b, _, _ = q.shape
q, k, v = map(
lambda t: t.unsqueeze(3)
.reshape(b, t.shape[1], self.heads, self.dim_head)
.permute(0, 2, 1, 3)
... | q = self.to_q(x)
context = default(context, x)
k = self.to_k(context)
v = self.to_v(context)
b, _, _ = q.shape
q, k, v = map(
lambda t: t.unsqueeze(3)
.reshape(b, t.shape[1], self.heads, self.dim_head)
.permute(0, 2, 1, 3)
... | 84 | 295 | 351 | 646 | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... |
31,378 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/attention.py | 279,280 | 236,299 | forward | SpatialTransformer | 280,299 | 280,299 | class SpatialTransformer(nn.Module):
"""
Transformer block for image-like data.
First, project the input (aka embedding)
and reshape to b, t, d.
Then apply standard transformer action.
Finally, reshape to image
NEW: use_linear for more efficiency instead of the 1x1 convs
"""
def __in... | class SpatialTransformer(nn.Module):
"""
Transformer block for image-like data.
First, project the input (aka embedding)
and reshape to b, t, d.
Then apply standard transformer action.
Finally, reshape to image
NEW: use_linear for more efficiency instead of the 1x1 convs
"""
def __in... | # note: if no context is given, cross-attention defaults to self-attention
if not isinstance(context, list):
context = [context]
b, c, h, w = x.shape
x_in = x
x = self.norm(x)
if not self.use_linear:
x = self.proj_in(x)
x = rearrange(x, 'b ... | # note: if no context is given, cross-attention defaults to self-attention
if not isinstance(context, list):
context = [context]
b, c, h, w = x.shape
x_in = x
x = self.norm(x)
if not self.use_linear:
x = self.proj_in(x)
x = rearrange(x, 'b ... | 91 | 531 | 275 | 806 | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... | from packaging import version
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from model.util import (
checkpoint, zero_module, exists, default
)
from model.config import Config, AttnMode
# CrossAttn precision handlin... |
31,379 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/bsrnet.py | 9,10 | 1,105 | initialize_weights | 10,29 | 10,29 | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
FILL_FUNC_BODYdef make_layer(block, n_layers):
layers = []
for _ in range(n_layers):
layers.append(block())
return nn.Sequential(*l... | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
FILL_FUNC_BODYdef make_layer(block, n_layers):
layers = []
for _ in range(n_layers):
layers.append(block())
return nn.Sequential(*l... | if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
m.weight.data *= scale # for residual block
if m.bias is not None... | if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
m.weight.data *= scale # for residual block
if m.bias is not None... | 56 | 1,400 | 260 | 1,660 | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
FILL_FUNC_BODYdef make_layer(block, n_layers):
layers = []
for _ in range(n_layers):
layers.append(block())
return nn.Sequential(*l... | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
FILL_FUNC_BODYdef make_layer(block, n_layers):
layers = []
for _ in range(n_layers):
layers.append(block())
return nn.Sequential(*l... | |
31,380 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/bsrnet.py | 68,69 | 59,75 | forward | RRDB | 69,75 | 69,75 | class RRDB(nn.Module):
'''Residual in Residual Dense Block'''
def __init__(self, nf, gc=32):
super(RRDB, self).__init__()
self.RDB1 = ResidualDenseBlock_5C(nf, gc)
self.RDB2 = ResidualDenseBlock_5C(nf, gc)
self.RDB3 = ResidualDenseBlock_5C(nf, gc)
def forward(self, x):
FILL... | class RRDB(nn.Module):
'''Residual in Residual Dense Block'''
def __init__(self, nf, gc=32):
super(RRDB, self).__init__()
self.RDB1 = ResidualDenseBlock_5C(nf, gc)
self.RDB2 = ResidualDenseBlock_5C(nf, gc)
self.RDB3 = ResidualDenseBlock_5C(nf, gc)
def forward(self, x):
FILL... | out = self.RDB1(x)
out = self.RDB2(out)
out = self.RDB3(out)
return out * 0.2 + x
| out = self.RDB1(x)
out = self.RDB2(out)
out = self.RDB3(out)
return out * 0.2 + x
| 15 | 143 | 55 | 198 | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2... | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2... |
31,381 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/bsrnet.py | 94,95 | 75,105 | forward | RRDBNet | 95,105 | 95,105 | class RRDBNet(nn.Module):
def __init__(self, in_nc=3, out_nc=3, nf=64, nb=23, gc=32, sf=4):
super(RRDBNet, self).__init__()
RRDB_block_f = functools.partial(RRDB, nf=nf, gc=gc)
self.sf = sf
print([in_nc, out_nc, nf, nb, gc, sf])
self.conv_first = nn.Conv2d(in_nc, nf, 3, 1, 1... | class RRDBNet(nn.Module):
def __init__(self, in_nc=3, out_nc=3, nf=64, nb=23, gc=32, sf=4):
super(RRDBNet, self).__init__()
RRDB_block_f = functools.partial(RRDB, nf=nf, gc=gc)
self.sf = sf
print([in_nc, out_nc, nf, nb, gc, sf])
self.conv_first = nn.Conv2d(in_nc, nf, 3, 1, 1... | fea = self.conv_first(x)
trunk = self.trunk_conv(self.RRDB_trunk(fea))
fea = fea + trunk
fea = self.lrelu(self.upconv1(F.interpolate(fea, scale_factor=2, mode='nearest')))
if self.sf==4:
fea = self.lrelu(self.upconv2(F.interpolate(fea, scale_factor=2, mode='nearest')... | fea = self.conv_first(x)
trunk = self.trunk_conv(self.RRDB_trunk(fea))
fea = fea + trunk
fea = self.lrelu(self.upconv1(F.interpolate(fea, scale_factor=2, mode='nearest')))
if self.sf==4:
fea = self.lrelu(self.upconv2(F.interpolate(fea, scale_factor=2, mode='nearest')... | 28 | 436 | 171 | 607 | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2... | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2... |
31,382 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/bsrnet.py | 50,51 | 36,59 | forward | ResidualDenseBlock_5C | 51,59 | 51,59 | class ResidualDenseBlock_5C(nn.Module):
def __init__(self, nf=64, gc=32, bias=True):
super(ResidualDenseBlock_5C, self).__init__()
# gc: growth channel, i.e. intermediate channels
self.conv1 = nn.Conv2d(nf, gc, 3, 1, 1, bias=bias)
self.conv2 = nn.Conv2d(nf + gc, gc, 3, 1, 1, bias=bia... | class ResidualDenseBlock_5C(nn.Module):
def __init__(self, nf=64, gc=32, bias=True):
super(ResidualDenseBlock_5C, self).__init__()
# gc: growth channel, i.e. intermediate channels
self.conv1 = nn.Conv2d(nf, gc, 3, 1, 1, bias=bias)
self.conv2 = nn.Conv2d(nf + gc, gc, 3, 1, 1, bias=bia... | x1 = self.lrelu(self.conv1(x))
x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
return x5 * 0.2 + x
| x1 = self.lrelu(self.conv1(x))
x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
return x5 * 0.2 + x
| 35 | 359 | 168 | 527 | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2... | # From BSRGAN
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2... |
31,385 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/clip.py | 50,51 | 12,66 | text_transformer_forward | FrozenOpenCLIPEmbedder | 51,60 | 51,60 | class FrozenOpenCLIPEmbedder(nn.Module):
"""
Uses the OpenCLIP transformer encoder for text
"""
LAYERS = [
#"pooled",
"last",
"penultimate"
]
def __init__(self, embed_dim, vision_cfg, text_cfg, layer="last"):
super().__init__()
assert layer in self.LAYERS
... | class FrozenOpenCLIPEmbedder(nn.Module):
"""
Uses the OpenCLIP transformer encoder for text
"""
LAYERS = [
#"pooled",
"last",
"penultimate"
]
def __init__(self, embed_dim, vision_cfg, text_cfg, layer="last"):
super().__init__()
assert layer in self.LAYERS
... | for i, r in enumerate(self.model.transformer.resblocks):
if i == len(self.model.transformer.resblocks) - self.layer_idx:
break
if self.model.transformer.grad_checkpointing and not torch.jit.is_scripting():
x = checkpoint(r, x, attn_mask)
else:
... | for i, r in enumerate(self.model.transformer.resblocks):
if i == len(self.model.transformer.resblocks) - self.layer_idx:
break
if self.model.transformer.grad_checkpointing and not torch.jit.is_scripting():
x = checkpoint(r, x, attn_mask)
else:
... | 29 | 543 | 127 | 670 | from typing import List
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from model.open_clip import CLIP, tokenize
### pretrained model path
# _VITH14 = dict(
# laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'),
# )
class FrozenOpenCLIPEmbedder(nn.Module):
... | from typing import List
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from model.open_clip import CLIP, tokenize
### pretrained model path
# _VITH14 = dict(
# laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'),
# )
class FrozenOpenCLIPEmbedder(nn.Module):
... |
31,387 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/controlnet.py | 20,21 | 18,44 | forward | ControlledUnetModel | 21,44 | 21,44 | class ControlledUnetModel(UNetModel):
def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs):
FILL_FUNC_BODY | class ControlledUnetModel(UNetModel):
def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs):
FILL_FUNC_BODY | hs = []
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
emb = self.time_embed(t_emb)
h = x.type(self.dtype)
for module in self.input_blocks:
h = module(h, emb, context)
hs.append(h)
h = self.middle_block(h, emb, contex... | hs = []
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
emb = self.time_embed(t_emb)
h = x.type(self.dtype)
for module in self.input_blocks:
h = module(h, emb, context)
hs.append(h)
h = self.middle_block(h, emb, contex... | 71 | 57 | 269 | 326 | import torch
import torch as th
import torch.nn as nn
from model.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
exists
)
from model.attention import SpatialTransformer
from model.unet import (
TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock, UNetModel
)
class Co... | import torch
import torch as th
import torch.nn as nn
from model.util import (
conv_nd,
linear,
zero_module,
timestep_embedding,
exists
)
from model.attention import SpatialTransformer
from model.unet import (
TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock, UNetModel
)
class Co... |
31,388 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/distributions.py | 65,66 | 1,93 | normal_kl | 72,93 | 66,93 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | tensor = None
for obj in (mean1, logvar1, mean2, logvar2):
if isinstance(obj, torch.Tensor):
tensor = obj
break
assert tensor is not None, "at least one argument must be a Tensor"
# Force variances to be Tensors. Broadcasting helps convert scalars to
# Tensors, but i... | """
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
Compute the KL divergence between two gaussians.
Shapes are automatically broadcasted, so batches can be compared to
scalars, among other use cases.
"""
tensor ... | 88 | 789 | 252 | 1,041 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | |
31,389 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/distributions.py | 6,7 | 5,13 | sample | AbstractDistribution | 7,9 | 7,9 | class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
| class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
| raise NotImplementedError()
| raise NotImplementedError()
| 2 | 41 | 12 | 53 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def m... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def m... |
31,390 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/distributions.py | 39,40 | 24,65 | kl | DiagonalGaussianDistribution | 40,53 | 40,53 | class DiagonalGaussianDistribution(object):
def __init__(self, parameters, deterministic=False):
self.parameters = parameters
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
self.deterministic = deterministic
self... | class DiagonalGaussianDistribution(object):
def __init__(self, parameters, deterministic=False):
self.parameters = parameters
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
self.deterministic = deterministic
self... | if self.deterministic:
return torch.Tensor([0.])
else:
if other is None:
return 0.5 * torch.sum(torch.pow(self.mean, 2)
+ self.var - 1.0 - self.logvar,
dim=[1, 2, 3])
else:
... | if self.deterministic:
return torch.Tensor([0.])
else:
if other is None:
return 0.5 * torch.sum(torch.pow(self.mean, 2)
+ self.var - 1.0 - self.logvar,
dim=[1, 2, 3])
else:
... | 47 | 373 | 179 | 552 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... |
31,391 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/distributions.py | 20,21 | 13,24 | mode | DiracDistribution | 21,24 | 21,24 | class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def mode(self):
FILL_FUNC_BODY | class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def mode(self):
FILL_FUNC_BODY | return self.value
| return self.value
| 2 | 60 | 11 | 71 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... |
31,392 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/gaussian_diffusion.py | 9,10 | 1,119 | make_beta_schedule | 10,34 | 10,34 | from functools import partial
from typing import Tuple
import torch
from torch import nn
import numpy as np
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
FILL_FUNC_BODYdef extract_into_tensor(a: torch.Tensor, t: torch.Tensor, x_shape: Tuple[int]) -> torch.Tensor:
... | from functools import partial
from typing import Tuple
import torch
from torch import nn
import numpy as np
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
FILL_FUNC_BODYdef extract_into_tensor(a: torch.Tensor, t: torch.Tensor, x_shape: Tuple[int]) -> torch.Tensor:
... | if schedule == "linear":
betas = (
np.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=np.float64) ** 2
)
elif schedule == "cosine":
timesteps = (
np.arange(n_timestep + 1, dtype=np.float64) / n_timestep + cosine_s
)
alphas = tim... | if schedule == "linear":
betas = (
np.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=np.float64) ** 2
)
elif schedule == "cosine":
timesteps = (
np.arange(n_timestep + 1, dtype=np.float64) / n_timestep + cosine_s
)
alphas = tim... | 94 | 1,173 | 364 | 1,537 | from functools import partial
from typing import Tuple
import torch
from torch import nn
import numpy as np
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
FILL_FUNC_BODYdef extract_into_tensor(a: torch.Tensor, t: torch.Tensor, x_shape: Tuple[int]) -> torch.Tensor:
... | from functools import partial
from typing import Tuple
import torch
from torch import nn
import numpy as np
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
FILL_FUNC_BODYdef extract_into_tensor(a: torch.Tensor, t: torch.Tensor, x_shape: Tuple[int]) -> torch.Tensor:
... | |
31,393 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/gaussian_diffusion.py | 82,83 | 40,119 | get_v | Diffusion | 83,88 | 83,88 | class Diffusion(nn.Module):
def __init__(
self,
timesteps=1000,
beta_schedule="linear",
loss_type="l2",
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
parameterization="eps"
):
super().__init__()
self.num_timesteps = timesteps
... | class Diffusion(nn.Module):
def __init__(
self,
timesteps=1000,
beta_schedule="linear",
loss_type="l2",
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
parameterization="eps"
):
super().__init__()
self.num_timesteps = timesteps
... | return (
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
)
| return (
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
)
| 14 | 936 | 72 | 1,008 | from functools import partial
from typing import Tuple
import torch
from torch import nn
import numpy as np
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
if schedule == "linear":
betas = (
np.linspace(linear_start ** 0.5, linear_end ** 0.5, n... | from functools import partial
from typing import Tuple
import torch
from torch import nn
import numpy as np
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
if schedule == "linear":
betas = (
np.linspace(linear_start ** 0.5, linear_end ** 0.5, n... |
31,395 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/open_clip/model.py | 179,180 | 138,207 | encode_text | CLIP | 180,193 | 180,193 | class CLIP(nn.Module):
output_dict: torch.jit.Final[bool]
def __init__(
self,
embed_dim: int,
vision_cfg: CLIPVisionCfg,
text_cfg: CLIPTextCfg,
quick_gelu: bool = False,
cast_dtype: Optional[torch.dtype] = None,
output_dict: bo... | class CLIP(nn.Module):
output_dict: torch.jit.Final[bool]
def __init__(
self,
embed_dim: int,
vision_cfg: CLIPVisionCfg,
text_cfg: CLIPTextCfg,
quick_gelu: bool = False,
cast_dtype: Optional[torch.dtype] = None,
output_dict: bo... | cast_dtype = self.transformer.get_cast_dtype()
x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
x = x + self.positional_embedding.to(cast_dtype)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x, attn_mask=self.attn_mask)
x = x.per... | cast_dtype = self.transformer.get_cast_dtype()
x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
x = x + self.positional_embedding.to(cast_dtype)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x, attn_mask=self.attn_mask)
x = x.per... | 72 | 757 | 272 | 1,029 | """ CLIP Model
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .transformer import LayerNormFp32, L... | """ CLIP Model
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .transformer import LayerNormFp32, L... |
31,397 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/unet.py | 266,267 | 226,275 | _forward | AttentionBlock | 267,275 | 267,275 | class AttentionBlock(nn.Module):
"""
An attention block that allows spatial positions to attend to each other.
Originally ported from here, but adapted to the N-d case.
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
"""
d... | class AttentionBlock(nn.Module):
"""
An attention block that allows spatial positions to attend to each other.
Originally ported from here, but adapted to the N-d case.
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
"""
d... | b, c, *spatial = x.shape
x = x.reshape(b, c, -1)
qkv = self.qkv(self.norm(x))
h = self.attention(qkv)
h = self.proj_out(h)
return (x + h).reshape(b, c, *spatial)
| b, c, *spatial = x.shape
x = x.reshape(b, c, -1)
qkv = self.qkv(self.norm(x))
h = self.attention(qkv)
h = self.proj_out(h)
return (x + h).reshape(b, c, *spatial)
| 25 | 537 | 100 | 637 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... |
31,398 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/unet.py | 106,107 | 82,111 | forward | Downsample | 107,111 | 107,111 | class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling ... | class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling ... | assert x.shape[1] == self.channels
return self.op(x)
| assert x.shape[1] == self.channels
return self.op(x)
| 6 | 321 | 29 | 350 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... |
31,399 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/unet.py | 336,337 | 327,361 | forward | QKVAttention | 342,356 | 337,356 | class QKVAttention(nn.Module):
"""
A module which performs QKV attention and splits in a different order.
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
FILL_FUNC_BODY @staticmethod
def count_flops(model, _x, y):
re... | class QKVAttention(nn.Module):
"""
A module which performs QKV attention and splits in a different order.
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
"""
Apply QKV attention.
:param qkv: an [N x (3 * H *... | bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
q, k, v = qkv.chunk(3, dim=1)
scale = 1 / math.sqrt(math.sqrt(ch))
weight = th.einsum(
"bct,bcs->bts",
(q * scale).view(bs * self.n_heads, ch, len... | """
Apply QKV attention.
:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
:return: an [N x (H * C) x T] tensor after attention.
"""
bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
... | 75 | 202 | 261 | 463 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... |
31,400 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/unet.py | 304,305 | 295,327 | forward | QKVAttentionLegacy | 310,322 | 305,322 | class QKVAttentionLegacy(nn.Module):
"""
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
FILL_FUNC_BODY @staticmethod
def count_f... | class QKVAttentionLegacy(nn.Module):
"""
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
"""
Apply QKV attention.
... | bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
scale = 1 / math.sqrt(math.sqrt(ch))
weight = th.einsum(
"bct,bcs->bts", q * scale, ... | """
Apply QKV attention.
:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
:return: an [N x (H * C) x T] tensor after attention.
"""
bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
... | 69 | 214 | 224 | 438 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... |
31,401 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/unet.py | 203,204 | 111,226 | _forward | ResBlock | 204,226 | 204,226 | class ResBlock(TimestepBlock):
"""
A residual block that can optionally change the number of channels.
:param channels: the number of input channels.
:param emb_channels: the number of timestep embedding channels.
:param dropout: the rate of dropout.
:param out_channels: if specified, the number... | class ResBlock(TimestepBlock):
"""
A residual block that can optionally change the number of channels.
:param channels: the number of input channels.
:param emb_channels: the number of timestep embedding channels.
:param dropout: the rate of dropout.
:param out_channels: if specified, the number... | if self.updown:
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
h = in_rest(x)
h = self.h_upd(h)
x = self.x_upd(x)
h = in_conv(h)
else:
h = self.in_layers(x)
emb_out = self.emb_layers(emb).type(h.dtype)
wh... | if self.updown:
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
h = in_rest(x)
h = self.h_upd(h)
x = self.x_upd(x)
h = in_conv(h)
else:
h = self.in_layers(x)
emb_out = self.emb_layers(emb).type(h.dtype)
wh... | 72 | 998 | 301 | 1,299 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... |
31,402 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/unet.py | 40,41 | 34,51 | forward | TimestepEmbedSequential | 41,51 | 41,51 | class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb, context=None):
FILL_FUNC_BODY | class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb, context=None):
FILL_FUNC_BODY | for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
elif isinstance(layer, SpatialTransformer):
x = layer(x, context)
else:
x = layer(x)
return x
| for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
elif isinstance(layer, SpatialTransformer):
x = layer(x, context)
else:
x = layer(x)
return x
| 24 | 81 | 81 | 162 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... |
31,404 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/unet.py | 69,70 | 51,82 | forward | Upsample | 70,82 | 70,82 | class Upsample(nn.Module):
"""
An upsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
upsampling occur... | class Upsample(nn.Module):
"""
An upsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
upsampling occur... | assert x.shape[1] == self.channels
if self.dims == 3:
x = F.interpolate(
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
)
else:
x = F.interpolate(x, scale_factor=2, mode="nearest")
if self.use_conv:
x = self... | assert x.shape[1] == self.channels
if self.dims == 3:
x = F.interpolate(
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
)
else:
x = F.interpolate(x, scale_factor=2, mode="nearest")
if self.use_conv:
x = self... | 34 | 243 | 139 | 382 | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from model.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
exists
)
from model.attention import... |
31,406 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/util.py | 98,100 | 85,128 | backward | CheckpointFunction | 100,128 | 100,128 | class CheckpointFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list(args[:length])
ctx.input_params = list(args[length:])
ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_e... | class CheckpointFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, run_function, length, *args):
ctx.run_function = run_function
ctx.input_tensors = list(args[:length])
ctx.input_params = list(args[length:])
ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_e... | ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
with torch.enable_grad(), \
torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
# Fixes a bug where the first op in run_function modifies the
# Tensor storage in place, which is not a... | ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
with torch.enable_grad(), \
torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs):
# Fixes a bug where the first op in run_function modifies the
# Tensor storage in place, which is not a... | 119 | 214 | 417 | 631 | # adopted from
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
# and
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
# and
# https://github.com/openai/gu... | # adopted from
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
# and
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
# and
# https://github.com/openai/gu... |
31,407 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/util.py | 192,193 | 191,195 | forward | GroupNorm32 | 193,195 | 193,195 | class GroupNorm32(nn.GroupNorm):
def forward(self, x):
FILL_FUNC_BODY | class GroupNorm32(nn.GroupNorm):
def forward(self, x):
FILL_FUNC_BODY | return super().forward(x.float()).type(x.dtype)
| return super().forward(x.float()).type(x.dtype)
| 2 | 31 | 21 | 52 | # adopted from
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
# and
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
# and
# https://github.com/openai/gu... | # adopted from
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
# and
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
# and
# https://github.com/openai/gu... |
31,408 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/util.py | 187,188 | 186,191 | forward | SiLU | 188,191 | 188,191 | class SiLU(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | class SiLU(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | return x * torch.sigmoid(x)
| return x * torch.sigmoid(x)
| 4 | 29 | 19 | 48 | # adopted from
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
# and
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
# and
# https://github.com/openai/gu... | # adopted from
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
# and
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
# and
# https://github.com/openai/gu... |
31,410 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 153,154 | 124,180 | forward | AttnBlock | 154,180 | 154,180 | class AttnBlock(nn.Module):
def __init__(self, in_channels):
super().__init__()
print(f"building AttnBlock (vanilla) with {in_channels} in_channels")
self.in_channels = in_channels
self.norm = Normalize(in_channels)
self.q = torch.nn.Conv2d(in_channels,
... | class AttnBlock(nn.Module):
def __init__(self, in_channels):
super().__init__()
print(f"building AttnBlock (vanilla) with {in_channels} in_channels")
self.in_channels = in_channels
self.norm = Normalize(in_channels)
self.q = torch.nn.Conv2d(in_channels,
... | h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
b,c,h,w = q.shape
q = q.reshape(b,c,h*w)
q = q.permute(0,2,1) # b,hw,c
k = k.reshape(b,c,h*w) # b,c,hw
w_ = torch.bmm(q,k) # b,hw,hw ... | h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
b,c,h,w = q.shape
q = q.reshape(b,c,h*w)
q = q.permute(0,2,1) # b,hw,c
k = k.reshape(b,c,h*w) # b,c,hw
w_ = torch.bmm(q,k) # b,hw,hw ... | 91 | 304 | 405 | 709 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,411 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 560,561 | 538,568 | forward | AutoencoderKL | 561,568 | 561,568 | class AutoencoderKL(nn.Module):
def __init__(self, ddconfig, embed_dim):
super().__init__()
self.encoder = Encoder(**ddconfig)
self.decoder = Decoder(**ddconfig)
assert ddconfig["double_z"]
self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
... | class AutoencoderKL(nn.Module):
def __init__(self, ddconfig, embed_dim):
super().__init__()
self.encoder = Encoder(**ddconfig)
self.decoder = Decoder(**ddconfig)
assert ddconfig["double_z"]
self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
... | posterior = self.encode(input)
if sample_posterior:
z = posterior.sample()
else:
z = posterior.mode()
dec = self.decode(z)
return dec, posterior
| posterior = self.encode(input)
if sample_posterior:
z = posterior.sample()
else:
z = posterior.mode()
dec = self.decode(z)
return dec, posterior
| 18 | 282 | 61 | 343 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,412 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 502,503 | 424,538 | forward | Decoder | 503,538 | 503,538 | class Decoder(nn.Module):
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
**ignorekwargs):
... | class Decoder(nn.Module):
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
**ignorekwargs):
... | #assert z.shape[1:] == self.z_shape[1:]
self.last_z_shape = z.shape
# timestep embedding
temb = None
# z to block_in
h = self.conv_in(z)
# middle
h = self.mid.block_1(h, temb)
h = self.mid.attn_1(h)
h = self.mid.block_2(h, temb)
... | #assert z.shape[1:] == self.z_shape[1:]
self.last_z_shape = z.shape
# timestep embedding
temb = None
# z to block_in
h = self.conv_in(z)
# middle
h = self.mid.block_1(h, temb)
h = self.mid.attn_1(h)
h = self.mid.block_2(h, temb)
... | 83 | 1,018 | 374 | 1,392 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,413 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 52,53 | 40,62 | forward | Downsample | 53,62 | 53,62 | class Downsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
# no asymmetric padding in torch conv, must do it ourselves
self.conv = torch.nn.Conv2d(in_channels,
... | class Downsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
# no asymmetric padding in torch conv, must do it ourselves
self.conv = torch.nn.Conv2d(in_channels,
... | if self.with_conv:
pad = (0,1,0,1)
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
x = self.conv(x)
else:
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
return x
| if self.with_conv:
pad = (0,1,0,1)
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
x = self.conv(x)
else:
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
return x
| 22 | 139 | 110 | 249 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,414 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 396,397 | 323,424 | forward | Encoder | 397,424 | 397,424 | class Encoder(nn.Module):
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
resolution, z_channels, double_z=True, use_linear_attn=False,
**ignore_kwargs):
super().__init_... | class Encoder(nn.Module):
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
resolution, z_channels, double_z=True, use_linear_attn=False,
**ignore_kwargs):
super().__init_... | # timestep embedding
temb = None
# downsampling
hs = [self.conv_in(x)]
for i_level in range(self.num_resolutions):
for i_block in range(self.num_res_blocks):
h = self.down[i_level].block[i_block](hs[-1], temb)
if len(self.down[i_level]... | # timestep embedding
temb = None
# downsampling
hs = [self.conv_in(x)]
for i_level in range(self.num_resolutions):
for i_block in range(self.num_res_blocks):
h = self.down[i_level].block[i_block](hs[-1], temb)
if len(self.down[i_level]... | 65 | 927 | 314 | 1,241 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,415 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 215,216 | 180,247 | forward | MemoryEfficientAttnBlock | 216,247 | 216,247 | class MemoryEfficientAttnBlock(nn.Module):
"""
Uses xformers efficient implementation,
see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
Note: this is a single-head self-attention operation
"""
#
def... | class MemoryEfficientAttnBlock(nn.Module):
"""
Uses xformers efficient implementation,
see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
Note: this is a single-head self-attention operation
"""
#
def... | h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
B, C, H, W = q.shape
q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
q, k, v = map(
lambda t: t.unsqueeze(3)
... | h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
B, C, H, W = q.shape
q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
q, k, v = map(
lambda t: t.unsqueeze(3)
... | 113 | 428 | 412 | 840 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,416 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 101,102 | 62,124 | forward | ResnetBlock | 102,124 | 102,124 | class ResnetBlock(nn.Module):
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
dropout, temb_channels=512):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_chann... | class ResnetBlock(nn.Module):
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
dropout, temb_channels=512):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_chann... | h = x
h = self.norm1(h)
h = nonlinearity(h)
h = self.conv1(h)
if temb is not None:
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
h = self.norm2(h)
h = nonlinearity(h)
h = self.dropout(h)
h = self.conv2(h)
if self.... | h = x
h = self.norm1(h)
h = nonlinearity(h)
h = self.conv1(h)
if temb is not None:
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
h = self.norm2(h)
h = nonlinearity(h)
h = self.dropout(h)
h = self.conv2(h)
if self.... | 49 | 485 | 210 | 695 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,417 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 276,277 | 247,308 | forward | SDPAttnBlock | 277,308 | 277,308 | class SDPAttnBlock(nn.Module):
def __init__(self, in_channels):
super().__init__()
print(f"building SDPAttnBlock (sdp) with {in_channels} in_channels")
self.in_channels = in_channels
self.norm = Normalize(in_channels)
self.q = torch.nn.Conv2d(in_channels,
... | class SDPAttnBlock(nn.Module):
def __init__(self, in_channels):
super().__init__()
print(f"building SDPAttnBlock (sdp) with {in_channels} in_channels")
self.in_channels = in_channels
self.norm = Normalize(in_channels)
self.q = torch.nn.Conv2d(in_channels,
... | h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
B, C, H, W = q.shape
q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
q, k, v = map(
lambda t: t.unsqueeze(3)
... | h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
B, C, H, W = q.shape
q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
q, k, v = map(
lambda t: t.unsqueeze(3)
... | 111 | 308 | 392 | 700 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,418 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/model/vae.py | 33,34 | 22,40 | forward | Upsample | 34,40 | 34,40 | class Upsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv = torch.nn.Conv2d(in_channels,
in_channels,
kernel_siz... | class Upsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv = torch.nn.Conv2d(in_channels,
in_channels,
kernel_siz... | x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
if self.with_conv:
x = self.conv(x)
return x
| x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
if self.with_conv:
x = self.conv(x)
return x
| 12 | 124 | 63 | 187 | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange
from typing import Optional, Any
from model.distributions import DiagonalGaussianDistribution
from model.config import Config, AttnMode
def nonlinearity(x):
# swish
return x*tor... |
31,419 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/common.py | 65,66 | 1,160 | wavelet_reconstruction | 69,80 | 66,80 | from typing import Mapping, Any, Tuple, Callable
import importlib
import os
from urllib.parse import urlparse
import torch
from torch import Tensor
from torch.nn import functional as F
import numpy as np
from torch.hub import download_url_to_file, get_dir
def get_obj_from_str(string: str, reload: bool=False) -> Any... | from typing import Mapping, Any, Tuple, Callable
import importlib
import os
from urllib.parse import urlparse
import torch
from torch import Tensor
from torch.nn import functional as F
import numpy as np
from torch.hub import download_url_to_file, get_dir
def get_obj_from_str(string: str, reload: bool=False) -> Any... | # calculate the wavelet decomposition of the content feature
content_high_freq, content_low_freq = wavelet_decomposition(content_feat)
del content_low_freq
# calculate the wavelet decomposition of the style feature
style_high_freq, style_low_freq = wavelet_decomposition(style_feat)
del style_hig... | """
Apply wavelet decomposition, so that the content will have the same color as the style.
"""
# calculate the wavelet decomposition of the content feature
content_high_freq, content_low_freq = wavelet_decomposition(content_feat)
del content_low_freq
# calculate the wavelet decomposition of... | 46 | 1,851 | 173 | 2,024 | from typing import Mapping, Any, Tuple, Callable
import importlib
import os
from urllib.parse import urlparse
import torch
from torch import Tensor
from torch.nn import functional as F
import numpy as np
from torch.hub import download_url_to_file, get_dir
def get_obj_from_str(string: str, reload: bool=False) -> Any... | from typing import Mapping, Any, Tuple, Callable
import importlib
import os
from urllib.parse import urlparse
import torch
from torch import Tensor
from torch.nn import functional as F
import numpy as np
from torch.hub import download_url_to_file, get_dir
def get_obj_from_str(string: str, reload: bool=False) -> Any... | |
31,420 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/cond_fn.py | 29,30 | 6,43 | load_target | Guidance | 30,32 | 30,32 | class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (denoted as `s` in our paper). The larger the gradient scale,
the closer... | class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (denoted as `s` in our paper). The larger the gradient scale,
the closer... | self.target = target
| self.target = target
| 3 | 486 | 10 | 496 | from typing import overload, Tuple
import torch
from torch.nn import functional as F
class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (d... | from typing import overload, Tuple
import torch
from torch.nn import functional as F
class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (d... |
31,421 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/cond_fn.py | 45,46 | 43,55 | _forward | MSEGuidance | 46,55 | 46,55 | class MSEGuidance(Guidance):
def _forward(self, target_x0: torch.Tensor, pred_x0: torch.Tensor, t: int) -> Tuple[torch.Tensor, float]:
FILL_FUNC_BODY | class MSEGuidance(Guidance):
def _forward(self, target_x0: torch.Tensor, pred_x0: torch.Tensor, t: int) -> Tuple[torch.Tensor, float]:
FILL_FUNC_BODY | # inputs: [-1, 1], nchw, rgb
with torch.enable_grad():
pred_x0.requires_grad_(True)
loss = (pred_x0 - target_x0).pow(2).mean((1, 2, 3)).sum()
scale = self.scale
g = -torch.autograd.grad(loss, pred_x0)[0] * scale
return g, loss.item()
| # inputs: [-1, 1], nchw, rgb
with torch.enable_grad():
pred_x0.requires_grad_(True)
loss = (pred_x0 - target_x0).pow(2).mean((1, 2, 3)).sum()
scale = self.scale
g = -torch.autograd.grad(loss, pred_x0)[0] * scale
return g, loss.item()
| 28 | 70 | 124 | 194 | from typing import overload, Tuple
import torch
from torch.nn import functional as F
class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (d... | from typing import overload, Tuple
import torch
from torch.nn import functional as F
class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (d... |
31,422 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/cond_fn.py | 89,90 | 55,99 | _forward | WeightedMSEGuidance | 90,99 | 90,99 | class WeightedMSEGuidance(Guidance):
def _get_weight(self, target: torch.Tensor) -> torch.Tensor:
# convert RGB to G
rgb_to_gray_kernel = torch.tensor([0.2989, 0.5870, 0.1140]).view(1, 3, 1, 1)
target = torch.sum(target * rgb_to_gray_kernel.to(target.device), dim=1, keepdim=True)
# ... | class WeightedMSEGuidance(Guidance):
def _get_weight(self, target: torch.Tensor) -> torch.Tensor:
# convert RGB to G
rgb_to_gray_kernel = torch.tensor([0.2989, 0.5870, 0.1140]).view(1, 3, 1, 1)
target = torch.sum(target * rgb_to_gray_kernel.to(target.device), dim=1, keepdim=True)
# ... | # inputs: [-1, 1], nchw, rgb
with torch.no_grad():
w = self._get_weight((target_x0 + 1) / 2)
with torch.enable_grad():
pred_x0.requires_grad_(True)
loss = ((pred_x0 - target_x0).pow(2) * w).mean((1, 2, 3)).sum()
scale = self.scale
g = -torch.au... | # inputs: [-1, 1], nchw, rgb
with torch.no_grad():
w = self._get_weight((target_x0 + 1) / 2)
with torch.enable_grad():
pred_x0.requires_grad_(True)
loss = ((pred_x0 - target_x0).pow(2) * w).mean((1, 2, 3)).sum()
scale = self.scale
g = -torch.au... | 39 | 636 | 156 | 792 | from typing import overload, Tuple
import torch
from torch.nn import functional as F
class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (d... | from typing import overload, Tuple
import torch
from torch.nn import functional as F
class Guidance:
def __init__(self, scale: float, t_start: int, t_stop: int, space: str, repeat: int) -> "Guidance":
"""
Initialize restoration guidance.
Args:
scale (float): Gradient scale (d... |
31,424 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/inference.py | 178,180 | 176,193 | init_stage1_model | BFRInferenceLoop | 180,185 | 180,185 | class BFRInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
FILL_FUNC_BODY def init_pipeline(self) -> None:
self.pipeline = SwinIRPipeline(self.swinir_face, self.cldm, self.diffusion, self.cond_fn, self.args.device)
def after_load_lq(self, lq: np.ndarray) -> np... | class BFRInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
FILL_FUNC_BODY def init_pipeline(self) -> None:
self.pipeline = SwinIRPipeline(self.swinir_face, self.cldm, self.diffusion, self.cond_fn, self.args.device)
def after_load_lq(self, lq: np.ndarray) -> np... | self.swinir_face: SwinIR = instantiate_from_config(OmegaConf.load("configs/inference/swinir.yaml"))
sd = load_model_from_url(MODELS["swinir_face"])
self.swinir_face.load_state_dict(sd, strict=True)
self.swinir_face.eval().to(self.args.device)
| self.swinir_face: SwinIR = instantiate_from_config(OmegaConf.load("configs/inference/swinir.yaml"))
sd = load_model_from_url(MODELS["swinir_face"])
self.swinir_face.load_state_dict(sd, strict=True)
self.swinir_face.eval().to(self.args.device)
| 10 | 175 | 110 | 285 | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... |
31,425 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/inference.py | 195,197 | 193,210 | init_stage1_model | BIDInferenceLoop | 197,202 | 197,202 | class BIDInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
FILL_FUNC_BODY def init_pipeline(self) -> None:
self.pipeline = SCUNetPipeline(self.scunet_psnr, self.cldm, self.diffusion, self.cond_fn, self.args.device)
def after_load_lq(self, lq: np.ndarray) -> np... | class BIDInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
FILL_FUNC_BODY def init_pipeline(self) -> None:
self.pipeline = SCUNetPipeline(self.scunet_psnr, self.cldm, self.diffusion, self.cond_fn, self.args.device)
def after_load_lq(self, lq: np.ndarray) -> np... | self.scunet_psnr: SCUNet = instantiate_from_config(OmegaConf.load("configs/inference/scunet.yaml"))
sd = load_model_from_url(MODELS["scunet_psnr"])
self.scunet_psnr.load_state_dict(sd, strict=True)
self.scunet_psnr.eval().to(self.args.device)
| self.scunet_psnr: SCUNet = instantiate_from_config(OmegaConf.load("configs/inference/scunet.yaml"))
sd = load_model_from_url(MODELS["scunet_psnr"])
self.scunet_psnr.load_state_dict(sd, strict=True)
self.scunet_psnr.eval().to(self.args.device)
| 10 | 177 | 118 | 295 | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... |
31,426 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/inference.py | 172,173 | 163,176 | init_pipeline | BSRInferenceLoop | 173,176 | 173,176 | class BSRInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
self.bsrnet: RRDBNet = instantiate_from_config(OmegaConf.load("configs/inference/bsrnet.yaml"))
sd = load_model_from_url(MODELS["bsrnet"])
self.bsrnet.load_state_dict(sd, strict=True)
s... | class BSRInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
self.bsrnet: RRDBNet = instantiate_from_config(OmegaConf.load("configs/inference/bsrnet.yaml"))
sd = load_model_from_url(MODELS["bsrnet"])
self.bsrnet.load_state_dict(sd, strict=True)
s... | self.pipeline = BSRNetPipeline(self.bsrnet, self.cldm, self.diffusion, self.cond_fn, self.args.device, self.args.upscale)
| self.pipeline = BSRNetPipeline(self.bsrnet, self.cldm, self.diffusion, self.cond_fn, self.args.device, self.args.upscale)
| 8 | 160 | 54 | 214 | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... |
31,427 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/inference.py | 66,68 | 51,163 | init_stage2_model | InferenceLoop | 68,90 | 68,90 | class InferenceLoop:
def __init__(self, args: Namespace) -> "InferenceLoop":
self.args = args
self.loop_ctx = {}
self.pipeline: Pipeline = None
self.init_stage1_model()
self.init_stage2_model()
self.init_cond_fn()
self.init_pipeline()
@overload
def i... | class InferenceLoop:
def __init__(self, args: Namespace) -> "InferenceLoop":
self.args = args
self.loop_ctx = {}
self.pipeline: Pipeline = None
self.init_stage1_model()
self.init_stage2_model()
self.init_cond_fn()
self.init_pipeline()
@overload
def i... | ### load uent, vae, clip
self.cldm: ControlLDM = instantiate_from_config(OmegaConf.load("configs/inference/cldm.yaml"))
sd = load_model_from_url(MODELS["sd_v21"])
unused = self.cldm.load_pretrained_sd(sd)
print(f"strictly load pretrained sd_v2.1, unused weights: {unused}")
... | ### load uent, vae, clip
self.cldm: ControlLDM = instantiate_from_config(OmegaConf.load("configs/inference/cldm.yaml"))
sd = load_model_from_url(MODELS["sd_v21"])
unused = self.cldm.load_pretrained_sd(sd)
print(f"strictly load pretrained sd_v2.1, unused weights: {unused}")
... | 76 | 1,134 | 408 | 1,542 | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... |
31,428 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/inference.py | 294,295 | 232,321 | after_load_lq | UnAlignedBFRInferenceLoop | 295,301 | 295,301 | class UnAlignedBFRInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
self.bsrnet: RRDBNet = instantiate_from_config(OmegaConf.load("configs/inference/bsrnet.yaml"))
sd = load_model_from_url(MODELS["bsrnet"])
self.bsrnet.load_state_dict(sd, strict=True)
... | class UnAlignedBFRInferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
self.bsrnet: RRDBNet = instantiate_from_config(OmegaConf.load("configs/inference/bsrnet.yaml"))
sd = load_model_from_url(MODELS["bsrnet"])
self.bsrnet.load_state_dict(sd, strict=True)
... | if self.loop_ctx["is_face"]:
self.pipeline = self.pipes["face"]
else:
self.pipeline = self.pipes["bg"]
return lq
| if self.loop_ctx["is_face"]:
self.pipeline = self.pipes["face"]
else:
self.pipeline = self.pipes["bg"]
return lq
| 11 | 1,361 | 58 | 1,419 | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... |
31,429 | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR | /home/hieuvd/dung_repo/raw/stars_02/XPixelGroup_DiffBIR/DiffBIR/utils/inference.py | 227,228 | 210,232 | after_load_lq | V1InferenceLoop | 228,232 | 228,232 | class V1InferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
self.swinir: SwinIR = instantiate_from_config(OmegaConf.load("configs/inference/swinir.yaml"))
if self.args.task == "fr":
sd = load_model_from_url(MODELS["swinir_face"])
elif self.ar... | class V1InferenceLoop(InferenceLoop):
@count_vram_usage
def init_stage1_model(self) -> None:
self.swinir: SwinIR = instantiate_from_config(OmegaConf.load("configs/inference/swinir.yaml"))
if self.args.task == "fr":
sd = load_model_from_url(MODELS["swinir_face"])
elif self.ar... | # For BFR task, super resolution is achieved by directly upscaling lq
return bicubic_resize(lq, self.args.upscale)
| # For BFR task, super resolution is achieved by directly upscaling lq
return bicubic_resize(lq, self.args.upscale)
| 15 | 322 | 45 | 367 | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... | import os
from typing import overload, Generator, Dict
from argparse import Namespace
import numpy as np
import torch
from PIL import Image
from omegaconf import OmegaConf
from model.cldm import ControlLDM
from model.gaussian_diffusion import Diffusion
from model.bsrnet import RRDBNet
from model.scunet import SCUNet
... |
31,430 | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api/utils/color_recognition_module/color_recognition_api.py | 8,9 | 1,19 | color_recognition | 9,19 | 9,19 | from utils.color_recognition_module import color_histogram_feature_extraction
from utils.color_recognition_module import knn_classifier
import os
from utils.image_utils import crop_image
current_path = os.getcwd()
def color_recognition(crop_img):
FILL_FUNC_BODY | from utils.color_recognition_module import color_histogram_feature_extraction
from utils.color_recognition_module import knn_classifier
import os
from utils.image_utils import crop_image
current_path = os.getcwd()
def color_recognition(crop_img):
FILL_FUNC_BODY |
height, width, channels = crop_img.shape
crop_img = crop_image.crop_center(crop_img, 50, 50) # crop the detected object image and get a image piece from center of it both for debugging and sending that image piece to color recognition module
# for debugging
#cv2.imwrite(current_path + "/debug_utility"+".png",... |
height, width, channels = crop_img.shape
crop_img = crop_image.crop_center(crop_img, 50, 50) # crop the detected object image and get a image piece from center of it both for debugging and sending that image piece to color recognition module
# for debugging
#cv2.imwrite(current_path + "/debug_utility"+".png",... | 74 | 88 | 245 | 333 | from utils.color_recognition_module import color_histogram_feature_extraction
from utils.color_recognition_module import knn_classifier
import os
from utils.image_utils import crop_image
current_path = os.getcwd()
def color_recognition(crop_img):
FILL_FUNC_BODY | from utils.color_recognition_module import color_histogram_feature_extraction
from utils.color_recognition_module import knn_classifier
import os
from utils.image_utils import crop_image
current_path = os.getcwd()
def color_recognition(crop_img):
FILL_FUNC_BODY | |
31,431 | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api/utils/image_utils/crop_image.py | 2,3 | 1,8 | crop_center | 3,8 | 3,8 |
def crop_center(img,cropx,cropy): # to crop and get the center of the given image
FILL_FUNC_BODY |
def crop_center(img,cropx,cropy): # to crop and get the center of the given image
FILL_FUNC_BODY | y,x, channels = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
| y,x, channels = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
| 12 | 37 | 72 | 109 |
def crop_center(img,cropx,cropy): # to crop and get the center of the given image
FILL_FUNC_BODY |
def crop_center(img,cropx,cropy): # to crop and get the center of the given image
FILL_FUNC_BODY | |
31,432 | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api/utils/object_counting_module/object_counter_x_axis.py | 6,7 | 1,25 | count_objects_x_axis | 7,25 | 7,25 | from utils.image_utils import image_saver
is_object_detected = [0]
left_position_of_previous_detected_object = [0]
def count_objects_x_axis(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | from utils.image_utils import image_saver
is_object_detected = [0]
left_position_of_previous_detected_object = [0]
def count_objects_x_axis(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | direction = "n.a." # means not available, it is just initialization
isInROI = True # is the object that is inside Region Of Interest
update_csv = False
if (abs(((right+left)/2)-roi_position) < deviation):
is_object_detected.insert(0,1)
update_csv = True
... | direction = "n.a." # means not available, it is just initialization
isInROI = True # is the object that is inside Region Of Interest
update_csv = False
if (abs(((right+left)/2)-roi_position) < deviation):
is_object_detected.insert(0,1)
update_csv = True
... | 56 | 91 | 206 | 297 | from utils.image_utils import image_saver
is_object_detected = [0]
left_position_of_previous_detected_object = [0]
def count_objects_x_axis(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | from utils.image_utils import image_saver
is_object_detected = [0]
left_position_of_previous_detected_object = [0]
def count_objects_x_axis(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | |
31,433 | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api/utils/object_counting_module/object_counter_y_axis.py | 6,7 | 1,25 | count_objects | 7,25 | 7,25 | from utils.image_utils import image_saver
is_object_detected = [0]
bottom_position_of_previous_detected_object = [0]
def count_objects(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | from utils.image_utils import image_saver
is_object_detected = [0]
bottom_position_of_previous_detected_object = [0]
def count_objects(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | direction = "n.a." # means not available, it is just initialization
isInROI = True # is the object that is inside Region Of Interest
update_csv = False
if (abs(((bottom+top)/2)-roi_position) < deviation):
is_object_detected.insert(0,1)
update_csv = True
... | direction = "n.a." # means not available, it is just initialization
isInROI = True # is the object that is inside Region Of Interest
update_csv = False
if (abs(((bottom+top)/2)-roi_position) < deviation):
is_object_detected.insert(0,1)
update_csv = True
... | 56 | 87 | 206 | 293 | from utils.image_utils import image_saver
is_object_detected = [0]
bottom_position_of_previous_detected_object = [0]
def count_objects(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | from utils.image_utils import image_saver
is_object_detected = [0]
bottom_position_of_previous_detected_object = [0]
def count_objects(top, bottom, right, left, crop_img, roi_position, y_min, y_max, deviation):
FILL_FUNC_BODY | |
31,434 | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api | /home/hieuvd/dung_repo/raw/stars_02/ahmetozlu_tensorflow_object_counting_api/tensorflow_object_counting_api/utils/string_utils/custom_string_util.py | 2,3 | 1,14 | word_count | 3,14 | 3,14 |
def word_count(str):
FILL_FUNC_BODY |
def word_count(str):
FILL_FUNC_BODY | counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
| counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
| 23 | 19 | 66 | 85 |
def word_count(str):
FILL_FUNC_BODY |
def word_count(str):
FILL_FUNC_BODY | |
31,513 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/mappings.py | 134,136 | 127,143 | forward | _CopyToModelParallelRegion | 136,138 | 136,138 | class _CopyToModelParallelRegion(torch.autograd.Function):
"""Pass the input to the model parallel region."""
@staticmethod
def symbolic(graph, input_):
return input_
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
def backward(ctx, grad_output):
ret... | class _CopyToModelParallelRegion(torch.autograd.Function):
"""Pass the input to the model parallel region."""
@staticmethod
def symbolic(graph, input_):
return input_
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
def backward(ctx, grad_output):
ret... | return input_
| return input_
| 2 | 108 | 8 | 116 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... |
31,514 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/mappings.py | 182,184 | 175,191 | forward | _GatherFromModelParallelRegion | 184,186 | 184,186 | class _GatherFromModelParallelRegion(torch.autograd.Function):
"""Gather the input from model parallel region and concatinate."""
@staticmethod
def symbolic(graph, input_):
return _gather_along_last_dim(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
... | class _GatherFromModelParallelRegion(torch.autograd.Function):
"""Gather the input from model parallel region and concatinate."""
@staticmethod
def symbolic(graph, input_):
return _gather_along_last_dim(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
... | return _gather_along_last_dim(input_)
| return _gather_along_last_dim(input_)
| 2 | 127 | 17 | 144 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... |
31,515 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/mappings.py | 219,221 | 207,233 | backward | _GatherFromSequenceParallelRegion | 221,233 | 221,233 | class _GatherFromSequenceParallelRegion(torch.autograd.Function):
"""Gather the input from sequence parallel region and concatinate."""
@staticmethod
def symbolic(graph, input_, tensor_parallel_output_grad=True):
return _gather_along_first_dim(input_)
@staticmethod
def forward(ctx, in... | class _GatherFromSequenceParallelRegion(torch.autograd.Function):
"""Gather the input from sequence parallel region and concatinate."""
@staticmethod
def symbolic(graph, input_, tensor_parallel_output_grad=True):
return _gather_along_first_dim(input_)
@staticmethod
def forward(ctx, in... | tensor_parallel_output_grad = ctx.tensor_parallel_output_grad
# If the computation graph after the gather operation is
# in the tensor parallel mode, output gradients need to reduce
# scattered and whereas if the computation is duplicated,
# output gradients need to be scatter... | tensor_parallel_output_grad = ctx.tensor_parallel_output_grad
# If the computation graph after the gather operation is
# in the tensor parallel mode, output gradients need to reduce
# scattered and whereas if the computation is duplicated,
# output gradients need to be scatter... | 49 | 162 | 140 | 302 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... |
31,516 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/mappings.py | 150,152 | 143,159 | forward | _ReduceFromModelParallelRegion | 152,154 | 152,154 | class _ReduceFromModelParallelRegion(torch.autograd.Function):
"""All-reduce the input from the model parallel region."""
@staticmethod
def symbolic(graph, input_):
return _reduce(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
def backward(ctx, grad... | class _ReduceFromModelParallelRegion(torch.autograd.Function):
"""All-reduce the input from the model parallel region."""
@staticmethod
def symbolic(graph, input_):
return _reduce(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
def backward(ctx, grad... | return _reduce(input_)
| return _reduce(input_)
| 2 | 111 | 12 | 123 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... |
31,517 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/mappings.py | 240,242 | 233,253 | forward | _ReduceScatterToSequenceParallelRegion | 242,244 | 242,244 | class _ReduceScatterToSequenceParallelRegion(torch.autograd.Function):
"""Reduce scatter the input from the model parallel region."""
@staticmethod
def symbolic(graph, input_):
return _reduce_scatter_along_first_dim(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @sta... | class _ReduceScatterToSequenceParallelRegion(torch.autograd.Function):
"""Reduce scatter the input from the model parallel region."""
@staticmethod
def symbolic(graph, input_):
return _reduce_scatter_along_first_dim(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @sta... | return _reduce_scatter_along_first_dim(input_)
| return _reduce_scatter_along_first_dim(input_)
| 2 | 149 | 21 | 170 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... |
31,518 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/mappings.py | 166,168 | 159,175 | forward | _ScatterToModelParallelRegion | 168,170 | 168,170 | class _ScatterToModelParallelRegion(torch.autograd.Function):
"""Split the input and keep only the corresponding chuck to the rank."""
@staticmethod
def symbolic(graph, input_):
return _split_along_last_dim(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
... | class _ScatterToModelParallelRegion(torch.autograd.Function):
"""Split the input and keep only the corresponding chuck to the rank."""
@staticmethod
def symbolic(graph, input_):
return _split_along_last_dim(input_)
@staticmethod
def forward(ctx, input_):
FILL_FUNC_BODY @staticmethod
... | return _split_along_last_dim(input_)
| return _split_along_last_dim(input_)
| 2 | 127 | 17 | 144 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... |
31,519 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/mappings.py | 194,196 | 191,207 | symbolic | _ScatterToSequenceParallelRegion | 196,198 | 196,198 | class _ScatterToSequenceParallelRegion(torch.autograd.Function):
"""Split the input and keep only the corresponding chuck to the rank."""
@staticmethod
def symbolic(graph, input_):
FILL_FUNC_BODY @staticmethod
def forward(ctx, input_):
return _split_along_first_dim(input_)
@staticmethod... | class _ScatterToSequenceParallelRegion(torch.autograd.Function):
"""Split the input and keep only the corresponding chuck to the rank."""
@staticmethod
def symbolic(graph, input_):
FILL_FUNC_BODY @staticmethod
def forward(ctx, input_):
return _split_along_first_dim(input_)
@staticmethod... | return _split_along_first_dim(input_)
| return _split_along_first_dim(input_)
| 2 | 127 | 17 | 144 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from megatron_mini.core.parallel_state import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
get_tensor_model_parallel_group,
)
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""... |
31,521 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/random.py | 183,185 | 176,249 | forward | CheckpointFunction | 185,210 | 185,210 | class CheckpointFunction(torch.autograd.Function):
"""This function is adapted from torch.utils.checkpoint with
two main changes:
1) torch.cuda.set_rng_state is replaced with `_set_cuda_rng_state`
2) the states in the model parallel tracker are also properly
tracked/set/re... | class CheckpointFunction(torch.autograd.Function):
"""This function is adapted from torch.utils.checkpoint with
two main changes:
1) torch.cuda.set_rng_state is replaced with `_set_cuda_rng_state`
2) the states in the model parallel tracker are also properly
tracked/set/re... | ctx.run_function = run_function
ctx.distribute_saved_activations \
= distribute_saved_activations
# Copy the rng states.
ctx.fwd_cpu_rng_state = torch.get_rng_state()
ctx.fwd_cuda_rng_state = torch.cuda.get_rng_state()
ctx.fwd_cuda_rng_state_tracker = get_cud... | ctx.run_function = run_function
ctx.distribute_saved_activations \
= distribute_saved_activations
# Copy the rng states.
ctx.fwd_cpu_rng_state = torch.get_rng_state()
ctx.fwd_cuda_rng_state = torch.cuda.get_rng_state()
ctx.fwd_cuda_rng_state_tracker = get_cud... | 60 | 697 | 302 | 999 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import contextlib
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from torch.utils.checkpoint import detach_var... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import contextlib
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from torch.utils.checkpoint import detach_var... |
31,522 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/random.py | 98,99 | 65,137 | add | CudaRNGStatesTracker | 100,115 | 99,115 | class CudaRNGStatesTracker:
"""Tracker for the cuda RNG states.
Using the `add` method, a cuda rng state is initialized based on
the input `seed` and is assigned to `name`. Later, by forking the
rng state, we can perform operations and return to our starting
cuda state.
"""
def __init__(se... | class CudaRNGStatesTracker:
"""Tracker for the cuda RNG states.
Using the `add` method, a cuda rng state is initialized based on
the input `seed` and is assigned to `name`. Later, by forking the
rng state, we can perform operations and return to our starting
cuda state.
"""
def __init__(se... | # Check seed is not already used.
if seed in self.seeds_:
raise Exception('seed {} already exists'.format(seed))
self.seeds_.add(seed)
# Check that state is not already defined.
if name in self.states_:
raise Exception('cuda rng state {} already exists'.fo... | """Track the rng state."""
# Check seed is not already used.
if seed in self.seeds_:
raise Exception('seed {} already exists'.format(seed))
self.seeds_.add(seed)
# Check that state is not already defined.
if name in self.states_:
raise Exception('c... | 66 | 610 | 213 | 823 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import contextlib
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from torch.utils.checkpoint import detach_var... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import contextlib
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from torch.utils.checkpoint import detach_var... |
31,523 | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B | /home/hieuvd/dung_repo/raw/stars_02/aixcoder-plugin_aiXcoder-7B/aiXcoder-7B/megatron_mini/core/tensor_parallel/utils.py | 9,14 | 1,109 | split_tensor_along_last_dim | 25,36 | 14,36 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from typing import List, Sequence, Tuple
from megatron_mini.core.utils import divide
from megatron_mini.core import parallel_state
def split_tensor_along_last_dim(
tensor: torch.Tensor,
num_partitions: int,
contiguous_split_chunk... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from typing import List, Sequence, Tuple
from megatron_mini.core.utils import divide
from megatron_mini.core import parallel_state
def split_tensor_along_last_dim(
tensor: torch.Tensor,
num_partitions: int,
contiguous_split_chunk... | # Get the size and dimension.
last_dim = tensor.dim() - 1
last_dim_size = divide(tensor.size()[last_dim], num_partitions)
# Split.
tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
# Note: torch.split does not create contiguous tensors by default.
if contiguous_split_chunks:
... | """ Split a tensor along its last dimension.
Arguments:
tensor: input tensor.
num_partitions: number of partitions to split the tensor
contiguous_split_chunks: If True, make each chunk contiguous
in memory.
Returns:
... | 42 | 1,099 | 149 | 1,248 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from typing import List, Sequence, Tuple
from megatron_mini.core.utils import divide
from megatron_mini.core import parallel_state
def split_tensor_along_last_dim(
tensor: torch.Tensor,
num_partitions: int,
contiguous_split_chunk... | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
import torch
from typing import List, Sequence, Tuple
from megatron_mini.core.utils import divide
from megatron_mini.core import parallel_state
def split_tensor_along_last_dim(
tensor: torch.Tensor,
num_partitions: int,
contiguous_split_chunk... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.