Run this model with HF Jobs
Run echarlaix/tiny-mpt-random-remote-code on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/echarlaix/tiny-mpt-random-remote-code. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/echarlaix/tiny-mpt-random-remote-code on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/echarlaix/tiny-mpt-random-remote-code. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/echarlaix/tiny-mpt-random-remote-code. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use echarlaix/tiny-mpt-random-remote-code with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use echarlaix/tiny-mpt-random-remote-code with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="echarlaix/tiny-mpt-random-remote-code", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("echarlaix/tiny-mpt-random-remote-code", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("echarlaix/tiny-mpt-random-remote-code", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use echarlaix/tiny-mpt-random-remote-code with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "echarlaix/tiny-mpt-random-remote-code" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "echarlaix/tiny-mpt-random-remote-code", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/echarlaix/tiny-mpt-random-remote-code
- SGLang
How to use echarlaix/tiny-mpt-random-remote-code with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "echarlaix/tiny-mpt-random-remote-code" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "echarlaix/tiny-mpt-random-remote-code", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "echarlaix/tiny-mpt-random-remote-code" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "echarlaix/tiny-mpt-random-remote-code", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use echarlaix/tiny-mpt-random-remote-code with Docker Model Runner:
docker model run hf.co/echarlaix/tiny-mpt-random-remote-code
update
Browse files5 unmodified lines67891011121314151617181920212223242526272861 unmodified lines909192939495969798991001011026 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363 unmodified lines34034134234334434534634743 unmodified lines3913923933943953963973983994004014024034047 unmodified lines4124134144155 unmodified linesPrefix LMs accepts a `bidirectional_mask` input in `forward`and treat the input prompt as the prefix in `generate`."""import mathimport warningsfrom types import MethodTypefrom typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLossfrom transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloomfrom transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloomfrom transformers.models.bloom.modeling_bloom import loggingfrom transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModelfrom transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLMfrom transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLMfrom transformers.models.gptj.modeling_gptj import GPTJForCausalLMfrom transformers.models.opt.modeling_opt import OPTForCausalLMfrom transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_optfrom transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_optlogger = logging.get_logger(__name__)_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]61 unmodified linesbidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)for attn_module in attn_modules:attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)output = call_og_forward()for attn_module in attn_modules:attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]return outputdef generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):"""Wraps original generate to enable PrefixLM attention."""attn_modules = _get_attn_modules(model)for attn_module in attn_modules:6 unmodified linessetattr(model, 'generate', MethodType(generate, model))setattr(model, '_prefix_lm_converted', True)return modeldef _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:"""Converts a BLOOM Causal LM to a Prefix LM.Supported HuggingFace model classes:- `BloomForCausalLM`See `convert_hf_causal_lm_to_prefix_lm` for more details."""if hasattr(model, '_prefix_lm_converted'):return modelassert isinstance(model, BloomForCausalLM)assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:combined_attention_mask = Nonedevice = attention_mask.device(_, src_length) = input_shapeif src_length > 1:combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)if bidirectional_mask is not None:assert attention_mask.shape == bidirectional_mask.shapeexpanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_maskreturn combined_attention_maskdef _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:num_heads = self.config.n_headclosest_power_of_2 = 2 ** math.floor(math.log2(num_heads))base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)slopes = torch.pow(base, powers)if closest_power_of_2 != num_heads:extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)diffs = qa - ka + key_length - query_lengthdiffs = -diffs.abs()alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)return alibi.to(dtype)KeyValueT = Tuple[torch.Tensor, torch.Tensor]def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:if deprecated_arguments.pop('position_ids', False) is not False:warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)if len(deprecated_arguments) > 0:raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_statesuse_cache = use_cache if use_cache is not None else self.config.use_cachereturn_dict = return_dict if return_dict is not None else self.config.use_return_dictif input_ids is not None and inputs_embeds is not None:raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')elif input_ids is not None:(batch_size, seq_length) = input_ids.shapeelif inputs_embeds is not None:(batch_size, seq_length, _) = inputs_embeds.shapeelse:raise ValueError('You have to specify either input_ids or inputs_embeds')if past_key_values is None:past_key_values = tuple([None] * len(self.h))head_mask = self.get_head_mask(head_mask, self.config.n_layer)if inputs_embeds is None:inputs_embeds = self.word_embeddings(input_ids)hidden_states = self.word_embeddings_layernorm(inputs_embeds)presents = () if use_cache else Noneall_self_attentions = () if output_attentions else Noneall_hidden_states = () if output_hidden_states else Noneseq_length_with_past = seq_lengthpast_key_values_length = 0if past_key_values[0] is not None:tmp = past_key_values[0][0]past_key_values_length = tmp.shape[2]seq_length_with_past = seq_length_with_past + past_key_values_lengthif attention_mask is None:attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)else:attention_mask = attention_mask.to(hidden_states.device)alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):if output_hidden_states:hst = (hidden_states,)all_hidden_states = all_hidden_states + hstif self.gradient_checkpointing and self.training:if use_cache:logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')use_cache = Falsedef create_custom_forward(module):def custom_forward(*inputs):return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)return custom_forwardoutputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])else:outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)hidden_states = outputs[0]if use_cache is True:presents = presents + (outputs[1],)if output_attentions:oa = (outputs[2 if use_cache else 1],)all_self_attentions = all_self_attentions + oahidden_states = self.ln_f(hidden_states)if output_hidden_states:hst = (hidden_states,)all_hidden_states = all_hidden_states + hstif not return_dict:return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))setattr(model.transformer, 'forward', MethodType(forward, model.transformer))KeyValueT = Tuple[torch.Tensor, torch.Tensor]def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:"""Replacement forward method for BloomCausalLM."""if deprecated_arguments.pop('position_ids', False) is not False:warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)if len(deprecated_arguments) > 0:raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')return_dict = return_dict if return_dict is not None else self.config.use_return_dicttransformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)hidden_states = transformer_outputs[0]lm_logits = self.lm_head(hidden_states)loss = Noneif labels is not None:shift_logits = lm_logits[..., :-1, :].contiguous()shift_labels = labels[..., 1:].contiguous()(batch_size, seq_length, vocab_size) = shift_logits.shapeloss_fct = CrossEntropyLoss()loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))if not return_dict:output = (lm_logits,) + transformer_outputs[1:]return (loss,) + output if loss is not None else outputreturn CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:if past:input_ids = input_ids[:, -1].unsqueeze(-1)bidirectional_mask = Noneif past[0][0].shape[0] == input_ids.shape[0]:past = self._convert_to_bloom_cache(past)else:bidirectional_mask = torch.ones_like(input_ids)return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}setattr(model, 'forward', MethodType(forward, model))setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))setattr(model, '_prefix_lm_converted', True)return modeldef _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:"""Converts an OPT Causal LM to a Prefix LM.Supported HuggingFace model classes:- `OPTForCausalLM`See `convert_hf_causal_lm_to_prefix_lm` for more details."""if hasattr(model, '_prefix_lm_converted'):return modelassert isinstance(model, OPTForCausalLM)assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'setattr(model, '_original_forward', getattr(model, 'forward'))setattr(model, '_original_generate', getattr(model, 'generate'))model.model.decoder.bidirectional_mask = Nonedef _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):combined_attention_mask = Noneif input_shape[-1] > 1:if self.bidirectional_mask == 'g':(bsz, src_length) = input_shapecombined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)else:combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)if self.bidirectional_mask is not None:assert attention_mask.shape == self.bidirectional_mask.shapeexpanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)if attention_mask is not None:expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_maskreturn combined_attention_masksetattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):def call_og_forward():return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)if bidirectional_mask is None:return call_og_forward()self.model.decoder.bidirectional_mask = bidirectional_masktry:outputs = call_og_forward()except:self.model.decoder.bidirectional_mask = Noneraiseself.model.decoder.bidirectional_mask = Nonereturn outputsdef generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):"""Wraps original generate to enable PrefixLM-style attention."""self.model.decoder.bidirectional_mask = 'g'try:output = self._original_generate(*args, **kwargs)except:self.model.decoder.bidirectional_mask = Noneraiseself.model.decoder.bidirectional_mask = Nonereturn outputsetattr(model, 'forward', MethodType(forward, model))setattr(model, 'generate', MethodType(generate, model))setattr(model, '_prefix_lm_converted', True)return model_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:"""Converts a HuggingFace Causal LM to a Prefix LM.3 unmodified lines- `GPTNeoForCausalLM`- `GPTNeoXForCausalLM`- `GPTJForCausalLM`- `BloomForCausalLM`- `OPTForCausalLM`Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the`generate` method and/or select underlying methods depending on the model class.43 unmodified lines"""if isinstance(model, _SUPPORTED_GPT_MODELS):return _convert_gpt_causal_lm_to_prefix_lm(model)elif isinstance(model, BloomForCausalLM):return _convert_bloom_causal_lm_to_prefix_lm(model)elif isinstance(model, OPTForCausalLM):return _convert_opt_causal_lm_to_prefix_lm(model)else:raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):"""Attempts to add bidirectional_mask to batch if missing.Raises:7 unmodified lineselif 'labels' in batch and 'attention_mask' in batch:batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])else:raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')5 unmodified lines678910111213141516171861 unmodified lines80818283848586878889909192936 unmodified lines1001011021031041051061073 unmodified lines11111211311411511643 unmodified lines1601611621631641651661671681697 unmodified lines1771781791805 unmodified linesPrefix LMs accepts a `bidirectional_mask` input in `forward`and treat the input prompt as the prefix in `generate`."""from types import MethodTypefrom typing import Any, List, MutableMapping, Optional, Tuple, Unionimport torchfrom transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModelfrom transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLMfrom transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLMfrom transformers.models.gptj.modeling_gptj import GPTJForCausalLM_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]61 unmodified linesbidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)for attn_module in attn_modules:assert isinstance(attn_module.bias, torch.Tensor)attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)output = call_og_forward()for attn_module in attn_modules:attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]return outputdef generate(self: CAUSAL_GPT_TYPES, *args: Any, **kwargs: Any):"""Wraps original generate to enable PrefixLM attention."""attn_modules = _get_attn_modules(model)for attn_module in attn_modules:6 unmodified linessetattr(model, 'generate', MethodType(generate, model))setattr(model, '_prefix_lm_converted', True)return model_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELSCAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:"""Converts a HuggingFace Causal LM to a Prefix LM.3 unmodified lines- `GPTNeoForCausalLM`- `GPTNeoXForCausalLM`- `GPTJForCausalLM`Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the`generate` method and/or select underlying methods depending on the model class.43 unmodified lines"""if isinstance(model, _SUPPORTED_GPT_MODELS):return _convert_gpt_causal_lm_to_prefix_lm(model)else:raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')def add_bidirectional_mask_if_missing(batch: MutableMapping):"""Attempts to add bidirectional_mask to batch if missing.Raises:7 unmodified lineselif 'labels' in batch and 'attention_mask' in batch:batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])else:raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')
hf_prefixlm_converter.py+7-242