code
stringlengths
17
6.64M
class AVATAR_OT_SetRestPose(bpy.types.Operator): bl_idname = 'avt.set_rest_pose' bl_label = 'Reset Pose' bl_options = {'REGISTER'} def execute(self, context): global mAvt motion_utils.set_rest_pose(mAvt.skel, mAvt.skel_ref, mAvt.list_bones) mAvt.frame = 1 return {'FINI...
class AVATAR_OT_LoadBVH(bpy.types.Operator): bl_idname = 'avt.load_bvh' bl_label = 'Load BVH' bl_description = 'Transfer motion to human model' filepath: bpy.props.StringProperty(subtype='FILE_PATH') act_x: bpy.props.BoolProperty(name='X') act_y: bpy.props.BoolProperty(name='Y') act_z: bpy...
class AVATAR_PT_MotionPanel(bpy.types.Panel): bl_idname = 'AVATAR_PT_MotionPanel' bl_label = 'Motion' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Avatar' bpy.types.Object.bvh_offset = IntProperty(name='Offset', description='Start motion offset', default=0, min=0, max=250) ...
def enum_menu_items(): global avt_path rigs_folder = ('%s/motion/rigs' % avt_path) rigs_names = [f for f in os.listdir(rigs_folder) if f.endswith('.txt')] menu_items = [] i = 0 for rig in rigs_names: i = (i + 1) rigsplit = rig.split('.') name = rigsplit[0] menu_...
def register(): gcoll = bpy.utils.previews.new() gcoll.images_location = ('%s/dressing/cloth_previews' % avt_path) avt_preview_collections['thumbnail_previews'] = gcoll bpy.types.Scene.avt_thumbnails = EnumProperty(items=generate_previews()) bpy.types.Scene.skel_rig = bpy.props.EnumProperty(items=...
def unregister(): from bpy.utils import unregister_class for clas in classes: unregister_class(clas) for gcoll in avt_preview_collections.values(): bpy.utils.previews.remove(gcoll) avt_preview_collections.clear() del bpy.types.Scene.avt_thumbnails del bpy.types.Scene.skel_rig
def read_eigenbody(filename): eigenbody = [] f_eigen = open(filename, 'r') for line in f_eigen: eigenbody.append(float(line)) return np.array(eigenbody)
def compose_vertices_eigenmat(eigenmat): eigenvertices = [] for i in range(0, len(eigenmat), 3): eigenvertices.append([eigenmat[i], (- eigenmat[(i + 2)]), eigenmat[(i + 1)]]) return np.array(eigenvertices)
def get_material_id(name_cloth): idx_list = clthlst.index(name_cloth) return cloth_class[idx_list]
def load_cloth(cloth_file, cloth_name): bpy.ops.import_scene.obj(filepath=cloth_file) bpy.context.selected_objects[0].name = cloth_name bpy.context.selected_objects[0].data.name = cloth_name b = bpy.data.objects[cloth_name] b.select_set(True) bpy.context.view_layer.objects.active = b bpy.o...
def read_file_textures(root_path, fold_name): tex_col = tex_norm = tex_spec = None ftex = open(('%s/dressing/textures/%s/default.txt' % (root_path, fold_name)), 'r') lines = [] for line in ftex: lines.append(line.strip()) ftex.close() num_lines = len(lines) if (num_lines == 1): ...
def load_studio(root_path): s_file = ('%s/dressing/models/studio_plane.obj' % root_path) bpy.ops.import_scene.obj(filepath=s_file) bpy.context.selected_objects[0].name = 'studio_plane' bpy.context.selected_objects[0].data.name = 'studio_plane' for o in bpy.context.scene.objects: if (o.type...
def create_material_generic(matname, index, matid): for m in bpy.data.materials: if ('Default' in m.name): bpy.data.materials.remove(m) mat_name = ('%s_mat%02d' % (matname, index)) skinMat = (bpy.data.materials.get(mat_name) or bpy.data.materials.new(mat_name)) skinMat.pass_index =...
def assign_textures_generic_mat(body, cmat, tex_img, tex_norm, tex_spec): body.select_set(True) if (len(body.material_slots) == 0): bpy.context.view_layer.objects.active = body bpy.ops.object.material_slot_add() body.material_slots[0].material = cmat img_tex_img = img_tex_norm = img_te...
def read_text_lines(filename): list_bones = [] text_file = open(filename, 'r') lines = text_file.readlines() for line in lines: line_split = line.split() if (len(line_split) == 2): list_bones.append([line_split[0], line_split[1]]) else: list_bones.append...
def find_bone_match(list_bones, bone_name): bone_match = 'none' for b in list_bones: if (b[0] == bone_name): bone_match = b[1] break return bone_match
def matrix_scale(scale_vec): return Matrix([[scale_vec[0], 0, 0, 0], [0, scale_vec[1], 0, 0], [0, 0, scale_vec[2], 0], [0, 0, 0, 1]])
def matrix_for_bone_from_parent(bone, ao): eb1 = ao.data.bones[bone.name] E = eb1.matrix_local ebp = ao.data.bones[bone.name].parent E_p = ebp.matrix_local return (E_p.inverted() @ E)
def matrix_the_hard_way(pose_bone, ao): if (pose_bone.rotation_mode == 'QUATERNION'): mr = pose_bone.rotation_quaternion.to_matrix().to_4x4() else: mr = pose_bone.rotation_euler.to_matrix().to_4x4() m1 = ((Matrix.Translation(pose_bone.location) @ mr) @ matrix_scale(pose_bone.scale)) E ...
def worldMatrix(ArmatureObject, Bone): _bone = ArmatureObject.pose.bones[Bone] _obj = ArmatureObject return (_obj.matrix_world * _bone.matrix)
def pose_to_match(arm, goal, bc): '\n pose arm so that its bones line up with the REST pose of goal\n ' matrix_os = {} for bone in arm.data.bones: bone_match = find_bone_match(bc, bone.name) if (bone_match is not 'none'): ebp = goal.pose.bones[bone_match] matr...
def set_rest_pose(skeleton): for bone in skeleton.pose.bones: bone.rotation_mode = 'XYZ' bone.rotation_euler = (0, 0, 0)
def set_hips_origin(skeleton, hips_name): hips_bone = skeleton.pose.bones[hips_name] hips_bone.location = (0, 0, 0)
def find_scale_factor(skel, trg_skel, hips_name_skel, hips_name_target): hips_pos_skel = (skel.matrix_world @ Matrix.Translation(skel.pose.bones[hips_name_skel].head)).to_translation() hips_pos_targ = (trg_skel.matrix_world @ Matrix.Translation(trg_skel.pose.bones[hips_name_target].head)).to_translation() ...
def read_text_lines(filename): list_bones = [] text_file = open(filename, 'r') lines = text_file.readlines() for line in lines: line_split = line.split() if (len(line_split) == 2): list_bones.append([line_split[0], line_split[1]]) else: list_bones.append...
def find_bone_match(list_bones, bone_name): bone_match = 'none' for b in list_bones: if (b[0] == bone_name): bone_match = b[1] break return bone_match
class CocoDet(CocoDataset): def __init__(self, tokenizer, multimodal_cfg=None, vis_processor=None, vis_root=None, add_eos=True, ignore_instruction=True, filter_small=False, test_mode=False, max_gt_per_img=100): self.multimodal_cfg = multimodal_cfg self.tokenizer = tokenizer self.vis_root ...
@dataclass class DataCollatorForDetDataset(object): tokenizer: transformers.PreTrainedTokenizer def __call__(self, instances): (input_ids, labels, img_metas, bboxes) = tuple(([instance.get(key, None) for instance in instances] for key in ('input_ids', 'labels', 'img_metas', 'bboxes'))) input_...
def make_multitask_data_module(tokenizer, data_args): 'Make dataset and collator for supervised fine-tuning.' if (data_args.dataset_config is not None): dataset_config = Config.fromfile(data_args.dataset_config) multimodal_cfg = dict(is_multimodal=data_args.is_multimodal, sep_image_conv_front=data...
def build_spi_dataset(dataset_config, tokenizer=None, multimodal_cfg=None, **kwargs): if isinstance(dataset_config, list): datasets = [] for cfg in dataset_config: temp_dataset = build_spi_dataset(cfg, tokenizer=tokenizer, multimodal_cfg=multimodal_cfg, **kwargs) datasets.a...
class ConcatDataset(ConcatDataset): def __init__(self, datasets): super().__init__(datasets) def collater(self, samples): all_keys = set() for s in samples: all_keys.update(s) shared_keys = all_keys for s in samples: shared_keys = (shared_keys ...
class Flickr30k(CocoDataset): CLASSES = ('object',) def __init__(self, tokenizer, multimodal_cfg=None, vis_processor=None, ann_file=None, img_prefix=None, add_eos=True, ignore_instruction=True, filter_small=False, test_mode=False, max_gt_per_img=150): self.multimodal_cfg = multimodal_cfg self...
class RefCOCO(CocoDataset): CLASSES = ('object',) def __init__(self, tokenizer, multimodal_cfg=None, vis_processor=None, ann_file=None, img_prefix=None, add_eos=True, ignore_instruction=True, filter_small=False, test_mode=False, max_gt_per_img=15): self.multimodal_cfg = multimodal_cfg self.to...
class RefCOCOP(RefCOCO): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.begin_str = "<image>\n I will provide you with only one region containing only one object, although there may be other objects present in the image. It is recommended that you describe the object'...
class RefCOCOG(RefCOCO): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.begin_str = 'The <image> provides an overview of the picture.\n' def train_process_test(self, data_item): image = data_item['img'].data ori_labels = data_item['gt_labels'] ...
class VGDATA(CocoDataset): CLASSES = ('object',) def __init__(self, tokenizer, multimodal_cfg=None, vis_processor=None, ann_file=None, img_prefix=None, add_eos=True, ignore_instruction=True, filter_small=False, test_mode=False, max_gt_per_img=15): self.multimodal_cfg = multimodal_cfg self.tok...
def forward(self, hidden_states: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attention_mask: Optional[torch.Tensor]=None, output_attentions: bool=False, use_cache: bool=False) -> Tuple[(torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]])]: 'Input shape: Batch x Time x Channe...
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): return attention_mask
def replace_llama_attn_with_flash_attn(): transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = _prepare_decoder_attention_mask transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
def unwrap_model(model: nn.Module) -> nn.Module: 'Recursively unwraps a model from potential containers (as used in\n distributed training).\n\n Args:\n model (`torch.nn.Module`): The model to unwrap.\n ' if hasattr(model, 'module'): return unwrap_model(model.module) else: ...
class LLaVATrainer(Trainer): def _save(self, output_dir: Optional[str]=None, state_dict=None): if getattr(self.args, 'tune_mm_mlp_adapter', False): _state_dict = state_dict if (_state_dict is None): model_to_save = unwrap_model(self.model) _state_di...
@dataclass class ModelArguments(): model_name_or_path: Optional[str] = field(default='facebook/opt-125m') version: Optional[str] = field(default='v0') freeze_backbone: bool = field(default=False) tune_mm_mlp_adapter: bool = field(default=False) vision_tower: Optional[str] = field(default=None) ...
@dataclass class DataArguments(): lazy_preprocess: bool = False is_multimodal: bool = False sep_image_conv_front: bool = False image_token_len: int = 0 image_aspect_ratio: str = 'square' dataset_config: Optional[str] = field(default='./gpt4roi/configs/stage1.py', metadata={'help': 'Path to the...
@dataclass class TrainingArguments(transformers.TrainingArguments): cache_dir: Optional[str] = field(default=None) optim: str = field(default='adamw_torch') remove_unused_columns: bool = field(default=False) freeze_mm_mlp_adapter: bool = field(default=False) force_fsdp: bool = field(default=False)...
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): 'Collects the state dict and dump to disk.' state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = {key: value.cpu() for (key, value) in state_dict.items()} del state_dict ...
def smart_tokenizer_and_embedding_resize(special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel): 'Resize tokenizer and embedding.\n\n Note: This is the unoptimized version that may make your embedding size not be divisible by 64.\n ' num_new_tokens =...
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: 'Tokenize a list of strings.' tokenized_list = [tokenizer(text, return_tensors='pt', padding='longest', max_length=tokenizer.model_max_length, truncation=True) for text in strings] input_ids = labels = [tokenize...
def _mask_targets(target, tokenized_lens, speakers): cur_idx = tokenized_lens[0] tokenized_lens = tokenized_lens[1:] target[:cur_idx] = IGNORE_INDEX for (tokenized_len, speaker) in zip(tokenized_lens, speakers): if (speaker == 'human'): target[(cur_idx + 2):(cur_idx + tokenized_len...
def _add_speaker_and_signal(header, source, get_conversation=True): 'Add speaker and start/end signal on each round.' BEGIN_SIGNAL = '### ' END_SIGNAL = '\n' conversation = header for sentence in source: from_str = sentence['from'] if (from_str.lower() == 'human'): from...
def preprocess_multimodal(sources: Sequence[str], multimodal_cfg: dict, cur_token_len: int) -> Dict: is_multimodal = multimodal_cfg['is_multimodal'] image_token_len = cur_token_len if (not is_multimodal): return sources for source in sources: if multimodal_cfg['sep_image_conv_front']: ...
def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {'human': conv.roles[0], 'gpt': conv.roles[1]} conversations = [] for (i, source) in enumerate(sources): if (roles[source[0]['from']] != conv.roles[0]): ...
def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {'human': conv.roles[0], 'gpt': conv.roles[1]} conversations = [] for (i, source) in enumerate(sources): if (roles[source[0]['from']] != conv.roles[0]):...
def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: "Given a list of sources, each is a conversation list.\n\n This transform:\n 1. Add signal '### ' at the beginning each sentence, with end signal '\n';\n 2. Concatenate conversations together;\n 3. Tokenize th...
class SupervisedDataset(Dataset): 'Dataset for supervised fine-tuning.' def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer): super(SupervisedDataset, self).__init__() logging.warning('Loading data...') list_data_dict = json.load(open(data_path, 'r')) ...
class LazySupervisedDataset(Dataset): 'Dataset for supervised fine-tuning.' def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, multimodal_cfg: dict): super(LazySupervisedDataset, self).__init__() logging.warning('Loading data...') list_data_dict = json.loa...
@dataclass class DataCollatorForSupervisedDataset(object): 'Collate examples for supervised fine-tuning.' tokenizer: transformers.PreTrainedTokenizer def __call__(self, instances: Sequence[Dict]) -> Dict[(str, torch.Tensor)]: (input_ids, labels) = tuple(([instance[key] for instance in instances] ...
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: 'Make dataset and collator for supervised fine-tuning.' dataset_cls = (LazySupervisedDataset if data_args.lazy_preprocess else SupervisedDataset) train_dataset = dataset_cls(tokenizer=tokenizer, data_path=data...
def train(): parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments)) (model_args, data_args, training_args) = parser.parse_args_into_dataclasses() if (model_args.vision_tower is not None): if ('mpt' in model_args.model_name_or_path): model = LlavaMPTF...
class SeparatorStyle(Enum): 'Different separator style.' SINGLE = auto() TWO = auto() MPT = auto()
@dataclasses.dataclass class Conversation(): 'A class that keeps all conversation history.' system: str roles: List[str] messages: List[List[str]] offset: int sep_style: SeparatorStyle = SeparatorStyle.SINGLE sep: str = '###' sep2: str = None version: str = 'Unknown' skip_next:...
def main(args): data_path = pathlib.Path(args.data_path) with data_path.open() as f: data = json.load(f) (prompt_input, prompt_no_input) = (PROMPT_DICT['prompt_input'], PROMPT_DICT['prompt_no_input']) sources = [(prompt_input.format_map(example) if (example.get('input', '') != '') else prompt_...
def reformat_code(val: str) -> str: return re.sub(code_lang_pattern, code_lang_format, val)
def html_to_markdown(val: str) -> str: val = re.sub(div_pattern, '', val) val = re.sub(span_pattern, '', val) val = markdownify.markdownify(val).strip() val = reformat_code(val) noise = re.search(regenerate_pattern, val) if (noise and (noise.start() == 0)): val = val[noise.end():] ...
def contain_blocked_words(val: str) -> bool: blocked_words = ['openai', 'chatgpt'] for w in blocked_words: if (w in val.lower()): return True return False
def clean_html_one_sample(sample): roles = ['human', 'gpt'] if (len(sample['conversations']) <= 1): return (sample, 1) if (sample['conversations'][0]['from'] != 'human'): sample['conversations'] = sample['conversations'][1:] if (len(sample['conversations']) <= 1): return (sampl...
def clean_html_all(content, begin, end): '\n Clean the source html files.\n ' cnt_skip = 0 cnt_blocked_words = 0 cnt_wrong_format = 0 cnt_parser_error = 0 cnt_too_short = 0 cnt_id_duplication = 0 cnt_value_duplication = 0 cnt_tag = 0 content = content[begin:end] proce...
def main(args): content = json.load(open(args['in_file'], 'r')) content = clean_html_all(content, args['begin'], args['end']) json.dump(content, open(args['out_file'], 'w'), indent=2)
def skip(conv, args): if ((args.lang != 'all') or (args.skip_lang is not None)): text = '\n'.join([x['value'] for x in conv['conversations']]) try: lang_code = Detector(text).language.code except (pycld2.error, polyglot.detect.base.UnknownLanguage): lang_code = 'unk...
def split_sample(sample, start_idx, end_idx): end_speaker = sample['conversations'][end_idx]['from'] end_idx = ((end_idx + 1) if (end_speaker != 'human') else end_idx) return {'id': ((sample['id'] + '_') + str(start_idx)), 'conversations': sample['conversations'][start_idx:end_idx]}
def split_contents(content, begin, end, tokenizer, max_length): '\n Keep the maximum round of conversations within the max token length constraint\n ' content = content[begin:end] new_content = [] for sample in tqdm.tqdm(content): tokenized_lens = [] for c in sample['conversation...
def main(args): content = json.load(open(args.in_file, 'r')) tokenizer = transformers.AutoTokenizer.from_pretrained(args.model_name_or_path, model_max_length=args.max_length, padding_side='right', use_fast=False) if (tokenizer.pad_token is None): tokenizer.add_special_tokens(dict(pad_token=DEFAULT...
@ray.remote(num_cpus=4) def get_eval(content: str, max_tokens: int): while True: try: response = openai.ChatCompletion.create(model='gpt-4', messages=[{'role': 'system', 'content': 'You are a helpful and precise assistant for checking the quality of the answer.'}, {'role': 'user', 'content': c...
def parse_score(review): try: score_pair = review.split('\n')[0] score_pair = score_pair.replace(',', ' ') sp = score_pair.split(' ') if (len(sp) == 2): return [float(sp[0]), float(sp[1])] else: print('error', review) return [(- 1), (- 1)...
@ray.remote(num_cpus=4) def get_eval(content: str, max_tokens: int): while True: try: response = openai.ChatCompletion.create(model='gpt-4', messages=[{'role': 'system', 'content': 'You are a helpful and precise assistant for checking the quality of the answer.'}, {'role': 'user', 'content': c...
def parse_score(review): try: score_pair = review.split('\n')[0] score_pair = score_pair.replace(',', ' ') sp = score_pair.split(' ') if (len(sp) == 2): return [float(sp[0]), float(sp[1])] else: print('error', review) return [(- 1), (- 1)...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--base-dir', type=str) parser.add_argument('--result-file', type=str) parser.add_argument('--output-file', type=str) parser.add_argument('--output-result', type=str) parser.add_argument('--split', type=str, default='test')...
def convert_caps(results): fakecaps = [] for result in results: image_id = result['question_id'] caption = result['text'] fakecaps.append({'image_id': int(image_id), 'caption': caption}) return fakecaps
def get_pred_idx(prediction, choices, options): "\n Get the index (e.g. 2) from the prediction (e.g. 'C')\n " if (prediction in options[:len(choices)]): return options.index(prediction) else: return random.choice(range(len(choices)))
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--base-dir', type=str) parser.add_argument('--gpt4-result', type=str) parser.add_argument('--our-result', type=str) parser.add_argument('--split', type=str, default='test') parser.add_argument('--options', type=list, defau...
def convert_caps(results): fakecaps = [] for result in results: image_id = result['question_id'] caption = result['text'] fakecaps.append({'image_id': int(image_id), 'caption': caption}) return fakecaps
def get_pred_idx(prediction, choices, options): "\n Get the index (e.g. 2) from the prediction (e.g. 'C')\n " if (prediction in options[:len(choices)]): return options.index(prediction) else: return random.choice(range(len(choices)))
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--base-dir', type=str) parser.add_argument('--gpt4-result', type=str) parser.add_argument('--requery-result', type=str) parser.add_argument('--our-result', type=str) parser.add_argument('--output-result', type=str) par...
def convert_caps(results): fakecaps = [] for result in results: image_id = result['question_id'] caption = result['text'] fakecaps.append({'image_id': int(image_id), 'caption': caption}) return fakecaps
def get_pred_idx(prediction, choices, options): "\n Get the index (e.g. 2) from the prediction (e.g. 'C')\n " if (prediction in options[:len(choices)]): return options.index(prediction) else: return random.choice(range(len(choices)))
def read_jsonl(path: str, key: str=None): data = [] with open(os.path.expanduser(path)) as f: for line in f: if (not line): continue data.append(json.loads(line)) if (key is not None): data.sort(key=(lambda x: x[key])) data = {item[key]: item...
def trim_hanging_lines(s: str, n: int) -> str: s = s.strip() for _ in range(n): s = s.split('\n', 1)[1].strip() return s
def get_answer(question_id: int, question: str, max_tokens: int): ans = {'answer_id': shortuuid.uuid(), 'question_id': question_id, 'model_id': MODEL_ID} for _ in range(3): try: response = openai.ChatCompletion.create(model=MODEL, messages=[{'role': 'system', 'content': 'You are a helpful ...
def consolidate_ckpt(src_path, dst_path): print('Loading model') auto_upgrade(src_path) src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) src_tokenizer = AutoTokenizer.from_pretrained(src_path) src_model.save_pretrained(dst_path) src_...
def adapt_tokenizer_for_denoising(tokenizer: Tokenizer): 'Adds sentinel tokens and padding token (if missing).\n\n Expands the tokenizer vocabulary to include sentinel tokens\n used in mixture-of-denoiser tasks as well as a padding token.\n\n All added tokens are added as special tokens. No tokens are\n ...
class AutoTokenizerForMOD(AutoTokenizer): 'AutoTokenizer + Adaptation for MOD.\n\n A simple wrapper around AutoTokenizer to make instantiating\n an MOD-adapted tokenizer a bit easier.\n\n MOD-adapted tokenizers have sentinel tokens (e.g., <extra_id_0>),\n a padding token, and a property to get the tok...
class MPTMLP(nn.Module): def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None): super().__init__() self.up_proj = nn.Linear(d_model, (expansion_ratio * d_model), device=device) self.act = nn.GELU(approximate='none') self.down_proj = nn.Linear((expansio...
class MPTBlock(nn.Module): def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': Fa...
class MPTConfig(PretrainedConfig): model_type = 'mpt' def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults...
@contextmanager def init_empty_weights(include_buffers: bool=False): "Meta initialization context manager.\n\n A context manager under which models are initialized with all parameters\n on the meta device, therefore creating an empty model. Useful when just\n initializing the model would blow the availab...
@contextmanager def init_on_device(device: torch.device, include_buffers: bool=False): 'Device initialization context manager.\n\n A context manager under which models are initialized with all parameters\n on the specified device.\n\n Args:\n device (`torch.device`): Device to initialize all param...
def _cast_if_autocast_enabled(tensor): if torch.is_autocast_enabled(): if (tensor.device.type == 'cuda'): dtype = torch.get_autocast_gpu_dtype() elif (tensor.device.type == 'cpu'): dtype = torch.get_autocast_cpu_dtype() else: raise NotImplementedError() ...
class LPLayerNorm(torch.nn.LayerNorm): def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None): super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype) def forward(self, x): modu...
def rms_norm(x, weight=None, eps=1e-05): output = (x / torch.rsqrt((x.pow(2).mean((- 1), keepdim=True) + eps))) if (weight is not None): return (output * weight) return output
class RMSNorm(torch.nn.Module): def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None): super().__init__() self.eps = eps if weight: self.weight = torch.nn.Parameter(torch.ones(normalized_shape, dtype=dtype, device=device)) else: ...
class LPRMSNorm(RMSNorm): def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None): super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device) def forward(self, x): downcast_x = _cast_if_autocast_enabled(x) dow...