Run this model with HF Jobs
Run OpenNLPLab/TransNormerLLM-1B 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/OpenNLPLab/TransNormerLLM-1B. 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/OpenNLPLab/TransNormerLLM-1B 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/OpenNLPLab/TransNormerLLM-1B. 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/OpenNLPLab/TransNormerLLM-1B. 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 OpenNLPLab/TransNormerLLM-1B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenNLPLab/TransNormerLLM-1B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="OpenNLPLab/TransNormerLLM-1B", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("OpenNLPLab/TransNormerLLM-1B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use OpenNLPLab/TransNormerLLM-1B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenNLPLab/TransNormerLLM-1B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenNLPLab/TransNormerLLM-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/OpenNLPLab/TransNormerLLM-1B
- SGLang
How to use OpenNLPLab/TransNormerLLM-1B 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 "OpenNLPLab/TransNormerLLM-1B" \ --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": "OpenNLPLab/TransNormerLLM-1B", "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 "OpenNLPLab/TransNormerLLM-1B" \ --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": "OpenNLPLab/TransNormerLLM-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use OpenNLPLab/TransNormerLLM-1B with Docker Model Runner:
docker model run hf.co/OpenNLPLab/TransNormerLLM-1B
Commit ·
460b22e
1
Parent(s): cf95141
Fix issues regarding to transformer version
Browse filesFiles changed (3)
123456{"_from_model_config": true,"bos_token_id": 1,"eos_token_id": 2,"transformers_version": "4.31.0"}123456789{"pad_token_id": 0,"bos_token_id": 1,"eos_token_id": 2,"max_new_tokens": 2048,"temperature": 1.0,"repetition_penalty": 1.03,"do_sample": true}
10 unmodified lines111213141516171810 unmodified lines2930313233343549 unmodified lines858687888990913 unmodified lines959697989910010110212 unmodified lines11511611711811912012116 unmodified lines13813914014114214314449 unmodified lines1941951961971981992001 unmodified line2022032042052062072082091 unmodified line21121221321421521621710 unmodified lines22822923023123223323423523623723823924024124224324412 unmodified lines2572582592602612622632642652662672682692701 unmodified line2722732742752762772782791 unmodified line28128228328428528628711 unmodified lines2993003013023033043053064 unmodified lines3113123133143153163173183193203213223233243253263273284 unmodified lines33333433533633733833934034134234312 unmodified lines35635735835936036136232 unmodified lines39539639739839940040140240340440540640740813 unmodified lines42242342442542642742842943043143243343415 unmodified lines45045145245345445545678 unmodified lines53553653753853954054117 unmodified lines5595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885892 unmodified lines5925935945955965975985996006016026036046056066 unmodified lines6136146156166176186196206216226236246256266276286296306316326336346356366376385 unmodified lines6446456466476486496506517 unmodified lines65966066166266366466566666766866967067167267315 unmodified lines68969069169269369469515 unmodified lines7117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817823 unmodified lines7867877887897907917921 unmodified line79479579679779879980080180217 unmodified lines82082182282382482582682731 unmodified lines85986086186286386486586686786886987087124 unmodified lines89689789889990090190290320 unmodified lines924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210 unmodified lines# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# coding=utf-8""" PyTorch Transnormer model."""import mathimport os10 unmodified linesfrom transformers.modeling_outputs import (BaseModelOutputWithPast,CausalLMOutputWithPast,SequenceClassifierOutputWithPast,)from transformers.modeling_utils import PreTrainedModelfrom transformers.utils import (49 unmodified lines########## start Transnormer##### Linearized Relative Positional Encoding: https://openreview.net/forum?id=xoLyps2qWc&referrer=%5BAuthor%20Console%5D(%2Fgroup%3Fid%3DTMLR%2FAuthors%23your-submissions)class Lrpe(nn.Module):def __init__(self,num_heads=8,3 unmodified linesd = num_heads * embed_dimself.index = torch.empty(0)self.theta = nn.Parameter(10000**(-2 / d * torch.arange(d)).reshape(num_heads, 1, -1))def extra_repr(self):return print_module(self)12 unmodified linesclass GLU(nn.Module):def __init__(self, d1, d2, bias=False):super().__init__()if debug:16 unmodified linesclass NormLinearAttention(nn.Module):def __init__(self,embed_dim,49 unmodified linesoutput_attentions,past_key_value,use_cache,slope_rate=slope_rate,)# x: b n dn = x.shape[-2]1 unmodified lineq, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)# reshapeq, k, v = map(lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads),[q, k, v])# actq = self.act(q)k = self.act(k)1 unmodified lineq_offset = 0# lrpe relys on position, get cache firstif past_key_value is not None:# reuse k, v, self_attentionk = torch.cat([past_key_value[0], k], dim=-2)v = torch.cat([past_key_value[1], v], dim=-2)q_offset = past_key_value[0].shape[-2]10 unmodified linesif attn_padding_mask is not None:v = v.masked_fill((1 - attn_padding_mask).unsqueeze(1).unsqueeze(-1).to(torch.bool), 0)if not has_lightning_attention:if slope_rate != None:attn_mask = torch.exp(slope_rate * attn_mask)output = linear_attention(q, k, v, attn_mask)else:output = lightning_attention(q, k, v, True,slope_rate.squeeze(-1).squeeze(-1))# reshapeoutput = rearrange(output, "b h n d -> b n (h d)")12 unmodified linesreturn output, attn_weights, past_key_valuedef inference(self,x,attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)output_attentions: bool = False,past_key_value: Optional[Tuple[torch.Tensor]] = None,use_cache: bool = False,slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)):# x: b n dn = x.shape[-2]1 unmodified lineq, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)# reshapeq, k, v = map(lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads),[q, k, v])# actq = self.act(q)k = self.act(k)1 unmodified line# rpeif self.linear_use_lrpe:q = self.lrpe(q, offset=self.offset)k = self.lrpe(k, offset=self.offset)if past_key_value == None:self.offset = q.shape[-2]11 unmodified linesif attn_padding_mask is not None:attn_mask = attn_mask.masked_fill((1 - attn_padding_mask).unsqueeze(1).unsqueeze(2).to(torch.bool),0,)energy = torch.einsum("... n d, ... m d -> ... n m", q, k)4 unmodified linesoutput = torch.einsum("... n m, ... m d -> ... n d", energy, v)eval_and_not_generate = eval(os.environ.get("eval_and_not_generate", default="False"))if eval_and_not_generate:kv = Noneelse:# b, h, n, e, dkv_outproduct = torch.einsum("... n e, ... n d -> ... n e d",k, v)# 1, 1, n, 1, 1index = torch.arange(n - 1, -1, -1).reshape(1, 1, -1, 1,1).to(x)# (h, 1, 1) -> (1, h, 1, 1, 1); (1, h, 1, 1, 1), (1, 1, n, 1, 1) -> (1, h, n, 1, 1)decay = ratio.unsqueeze(0).unsqueeze(-1)**indexkv_outproduct_with_decay = kv_outproduct * decaykv = torch.sum(kv_outproduct_with_decay, dim=-3)4 unmodified linesfor i in range(n):kv = ratio * kv + torch.einsum("... n d, ... n e -> ... d e",k[:, :, i:i + 1],v[:, :, i:i + 1],)qkv = torch.einsum("... n e, ... e d -> ... n d",q[:, :, i:i + 1], kv)output.append(qkv)output = torch.concat(output, dim=-2)12 unmodified linesclass TransnormerDecoderLayer(nn.Module):def __init__(self, config: TransnormerConfig):super().__init__()self.embed_dim = config.decoder_embed_dim32 unmodified linesreturn residual + xdef forward(self,x,attn_mask: Optional[torch.Tensor] = None,attn_padding_mask: Optional[torch.Tensor] = None,past_key_value: Optional[Tuple[torch.Tensor]] = None,output_attentions: Optional[bool] = False,use_cache: Optional[bool] = False,slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)):residual = xx = self.token_norm(x)13 unmodified linesx = self.channel_mixer(x)x = self.residual_connection(x, residual)outputs = (x, )if output_attentions:outputs += (self_attn_weights, )if use_cache:outputs += (present_key_value, )return outputs15 unmodified lines"""@add_start_docstrings(TRANSNORMER_START_DOCSTRING, )class TransnormerPreTrainedModel(PreTrainedModel):config_class = TransnormerConfigbase_model_prefix = "model"78 unmodified lines"""@add_start_docstrings(TRANSNORMER_START_DOCSTRING, )class TransnormerModel(TransnormerPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TransnormerDecoderLayer`]17 unmodified linesself.slopes = self._build_slope_tensor(config.decoder_attention_heads)# paramsself.embed_tokens = nn.Embedding(config.vocab_size,config.decoder_embed_dim,self.padding_idx)self.layers = nn.ModuleList([])for i in range(config.decoder_layers):if len(self.linear_use_lrpe_list) > 0:config.linear_use_lrpe = self.linear_use_lrpe_list[i]self.layers.append(TransnormerDecoderLayer(config))self.final_norm = get_norm_fn(config.norm_type)(config.decoder_embed_dim)self.embed_dim = config.decoder_embed_dimself.embed_scale = (1.0 if config.no_scale_embedding else math.sqrt(self.embed_dim))# Initialize weights and apply final processingself.post_init()@staticmethoddef _build_slope_tensor(n_attention_heads: int):def get_slopes(n):def get_slopes_power_of_2(n):start = 2**(-(2**-(math.log2(n) - 3)))ratio = startreturn [start * ratio**i for i in range(n)]2 unmodified linesn) # In the paper, we only train models that have 2^a heads for some a. This function haselse: # some good properties that only occur when the input is a power of 2. To maintain that evenclosest_power_of_2 = 2**math.floor(math.log2(n)) # when the number of heads is not a power of 2, we use this workaround.return (get_slopes_power_of_2(closest_power_of_2) + get_slopes(2 * closest_power_of_2)[0::2][:n - closest_power_of_2])# h, 1, 1slopes = torch.tensor(get_slopes(n_attention_heads)).reshape(n_attention_heads, 1, 1)return slopes6 unmodified linesdef set_input_embeddings(self, value):self.embed_tokens = valuedef _prepare_decoder_linear_attn_mask(self, input_shape, inputs_embeds,past_key_values_length):bsz, tgt_len = input_shapesrc_len = tgt_len + past_key_values_lengthdef power_log(x):return 2**(math.ceil(math.log(x, 2)))n = power_log(max(tgt_len, src_len))if self._linear_attn_mask.shape[-1] < n:def get_mask(n):mask = torch.triu(torch.zeros(n, n).float().fill_(float("-inf")), 1)# no slope version# -n, ..., -2, -1, 0for i in range(n):x = torch.arange(i + 1)y = xmask[i, :i + 1] = -torch.flip(y, [0])return mask5 unmodified lineslinear_attn_mask = self._linear_attn_mask[:, -tgt_len:, -src_len:]num_heads = linear_attn_mask.shape[0]return linear_attn_mask[None, :, :, :].expand(bsz, num_heads, tgt_len,src_len)@add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)def forward(7 unmodified linesoutput_hidden_states: Optional[bool] = None,return_dict: Optional[bool] = None,) -> Union[Tuple, BaseModelOutputWithPast]:output_attentions = (output_attentions if output_attentions is not Noneelse self.config.output_attentions)output_hidden_states = (output_hidden_statesif output_hidden_states is not None elseself.config.output_hidden_states)use_cache = use_cache if use_cache is not None else self.config.use_cachereturn_dict = (return_dict if return_dict is not None elseself.config.use_return_dict)# retrieve input_ids and inputs_embedsif input_ids is not None and inputs_embeds is not None:15 unmodified linesif past_key_values is not None:past_key_values_length = past_key_values[0][0].shape[-2]seq_length_with_past = seq_length_with_past + past_key_values_lengthif inputs_embeds is None:# !!! use embed_scaleinputs_embeds = self.embed_scale * self.embed_tokens(input_ids)15 unmodified lines##### norm linear layerslinear_attn_padding_mask = attn_padding_masklinear_attn_mask = self._prepare_decoder_linear_attn_mask((batch_size, seq_length), inputs_embeds, past_key_values_length)slope_rates = [self.slopes.to(input_ids.device) for _ in range(self.num_layers)]for idx, layer in enumerate(self.layers):if output_hidden_states:all_hidden_states += (hidden_states, )past_key_value = (past_key_values[idx]if past_key_values is not None else None)slope_rate = slope_rates[idx]slope_rate = slope_rate * (1 - idx / (self.num_layers - 1) + 1e-5)mask = linear_attn_maskif self.gradient_checkpointing and self.training:def create_custom_forward(module):def custom_forward(*inputs):# None for past_key_valuereturn module(*inputs, output_attentions, None)return custom_forwardlayer_outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(layer),hidden_states,mask,linear_attn_padding_mask,None,)else:layer_outputs = layer(hidden_states,attn_mask=mask,attn_padding_mask=linear_attn_padding_mask,past_key_value=past_key_value,output_attentions=output_attentions,use_cache=use_cache,slope_rate=slope_rate,)hidden_states = layer_outputs[0]if use_cache:next_decoder_cache += (layer_outputs[2 if output_attentions else 1], )if output_attentions:all_self_attns += (layer_outputs[1], )hidden_states = self.final_norm(hidden_states)# add hidden states from the last decoder layerif output_hidden_states:all_hidden_states += (hidden_states, )next_cache = next_decoder_cache if use_cache else Noneif not return_dict:return tuple(v for v in[hidden_states, next_cache, all_hidden_states, all_self_attns]if v is not None)return BaseModelOutputWithPast(last_hidden_state=hidden_states,past_key_values=next_cache,3 unmodified linesclass TransnormerForCausalLM(TransnormerPreTrainedModel):def __init__(self, config):super().__init__(config)self.model = TransnormerModel(config)1 unmodified linelogging_info(self.model)# the lm_head weight is automatically tied to the embed tokens weightself.lm_head = nn.Linear(config.decoder_embed_dim,config.vocab_size,bias=False)# Initialize weights and apply final processingself.post_init()17 unmodified linesreturn self.model@add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)@replace_return_docstrings(output_type=CausalLMOutputWithPast,config_class=_CONFIG_FOR_DOC)def forward(self,input_ids: torch.LongTensor = None,31 unmodified lines>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]"Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."```"""output_attentions = (output_attentions if output_attentions is not Noneelse self.config.output_attentions)output_hidden_states = (output_hidden_statesif output_hidden_states is not None elseself.config.output_hidden_states)return_dict = (return_dict if return_dict is not None elseself.config.use_return_dict)# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)outputs = self.model(24 unmodified linesloss = loss_fct(shift_logits, shift_labels)if not return_dict:output = (logits, ) + outputs[1:]return (loss, ) + output if loss is not None else outputreturn CausalLMOutputWithPast(loss=loss,20 unmodified lineselse:model_inputs = {"input_ids": input_ids}model_inputs.update({"past_key_values": past_key_values,"use_cache": kwargs.get("use_cache"),"attention_mask": attention_mask,})return model_inputs@staticmethoddef _reorder_cache(past_key_values, beam_idx):reordered_past = ()for layer_past in past_key_values:reordered_past += (tuple(past_state.index_select(0, beam_idx)for past_state in layer_past), )return reordered_past@add_start_docstrings("""The LLaMa Model transformer with a sequence classification head on top (linear layer).[`TransnormerForSequenceClassification`] uses the last token in order to do the classification, as other causal models(e.g. GPT-2) do.Since it does classification on the last token, it requires to know the position of the last token. If a`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. Ifno `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess thepadding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value ineach row of the batch).""",TRANSNORMER_START_DOCSTRING,)class TransnormerForSequenceClassification(TransnormerPreTrainedModel):_keys_to_ignore_on_load_missing = [r"lm_head.weight"]def __init__(self, config):super().__init__(config)self.num_labels = config.num_labelsself.model = TransnormerModel(config)self.score = nn.Linear(config.decoder_embed_dim,self.num_labels,bias=False)# Initialize weights and apply final processingself.post_init()def get_input_embeddings(self):return self.model.embed_tokensdef set_input_embeddings(self, value):self.model.embed_tokens = value@add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)def forward(self,input_ids: torch.LongTensor = None,attn_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,) -> Union[Tuple, SequenceClassifierOutputWithPast]:r"""labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If`config.num_labels > 1` a classification loss is computed (Cross-Entropy)."""return_dict = (return_dict if return_dict is not None elseself.config.use_return_dict)transformer_outputs = self.model(input_ids,attn_padding_mask=attn_mask,past_key_values=past_key_values,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]logits = self.score(hidden_states)if input_ids is not None:batch_size = input_ids.shape[0]else:batch_size = inputs_embeds.shape[0]if self.config.pad_token_id is None and batch_size != 1:raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")if self.config.pad_token_id is None:sequence_lengths = -1else:if input_ids is not None:sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) -1).to(logits.device)else:sequence_lengths = -1pooled_logits = logits[torch.arange(batch_size, device=logits.device),sequence_lengths]loss = Noneif labels is not None:labels = labels.to(logits.device)if self.config.problem_type is None:if self.num_labels == 1:self.config.problem_type = "regression"elif self.num_labels > 1 and (labels.dtype == torch.longor labels.dtype == torch.int):self.config.problem_type = "single_label_classification"else:self.config.problem_type = "multi_label_classification"if self.config.problem_type == "regression":loss_fct = MSELoss()if self.num_labels == 1:loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())else:loss = loss_fct(pooled_logits, labels)elif self.config.problem_type == "single_label_classification":loss_fct = CrossEntropyLoss()loss = loss_fct(pooled_logits.view(-1, self.num_labels),labels.view(-1))elif self.config.problem_type == "multi_label_classification":loss_fct = BCEWithLogitsLoss()loss = loss_fct(pooled_logits, labels)if not return_dict:output = (pooled_logits, ) + transformer_outputs[1:]return ((loss, ) + output) if loss is not None else outputreturn SequenceClassifierOutputWithPast(loss=loss,logits=pooled_logits,past_key_values=transformer_outputs.past_key_values,hidden_states=transformer_outputs.hidden_states,attentions=transformer_outputs.attentions,)10 unmodified lines1112131415161710 unmodified lines28293031323349 unmodified lines8384858687883 unmodified lines929394959697989910012 unmodified lines11311411511611711816 unmodified lines13513613713813914049 unmodified lines1901911921931941951961 unmodified line1981992002012022032042051 unmodified line20720820921021121221310 unmodified lines22422522622722822923023123223323423523623723823924012 unmodified lines2532542552562572582592602612622632642652661 unmodified line2682692702712722732742751 unmodified line27727827928028128228311 unmodified lines2952962972982993003014 unmodified lines3063073083093103113123133143153163173183193203213224 unmodified lines32732832933033133233333433533633733812 unmodified lines35135235335435535632 unmodified lines38939039139239339439539639739839940040140213 unmodified lines41641741841942042142242342442542642742815 unmodified lines44444544644744844945045145278 unmodified lines53153253353453553653753853917 unmodified lines5575585595605615625635645655665675685695705715725735745755765775785795805815825835845852 unmodified lines5885895905915925935945955965975985996006016026036046056 unmodified lines6126136146156166176186196206216226236246256266276286296306316326336346356366375 unmodified lines6436446456466476486497 unmodified lines65765865966066166266366466566666766866967067167267367467567667715 unmodified lines69369469569669769869915 unmodified lines7157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677683 unmodified lines7727737747757767771 unmodified line77978078178278378478578678717 unmodified lines80580680780880981081181281331 unmodified lines84584684784884985085185285385485585685785885986086186286324 unmodified lines88888989089189289389489520 unmodified lines91691791891992092192292392492592692792892993093193293393493593693793810 unmodified lines# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# coding=utf-8""" PyTorch Transnormer model."""import mathimport os10 unmodified linesfrom transformers.modeling_outputs import (BaseModelOutputWithPast,CausalLMOutputWithPast,)from transformers.modeling_utils import PreTrainedModelfrom transformers.utils import (49 unmodified lines########## start Transnormer##### Linearized Relative Positional Encoding: https://openreview.net/forum?id=xoLyps2qWc&referrer=%5BAuthor%20Console%5D(%2Fgroup%3Fid%3DTMLR%2FAuthors%23your-submissions)class Lrpe(nn.Module):def __init__(self,num_heads=8,3 unmodified linesd = num_heads * embed_dimself.index = torch.empty(0)self.theta = nn.Parameter(10000 ** (-2 / d * torch.arange(d)).reshape(num_heads, 1, -1))def extra_repr(self):return print_module(self)12 unmodified linesclass GLU(nn.Module):def __init__(self, d1, d2, bias=False):super().__init__()if debug:16 unmodified linesclass NormLinearAttention(nn.Module):def __init__(self,embed_dim,49 unmodified linesoutput_attentions,past_key_value,use_cache,slope_rate,)# x: b n dn = x.shape[-2]1 unmodified lineq, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)# reshapeq, k, v = map(lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads), [q, k, v])# actq = self.act(q)k = self.act(k)1 unmodified lineq_offset = 0# lrpe relys on position, get cache firstif past_key_value is not None:# reuse k, v, for evaluation onlyk = torch.cat([past_key_value[0], k], dim=-2)v = torch.cat([past_key_value[1], v], dim=-2)q_offset = past_key_value[0].shape[-2]10 unmodified linesif attn_padding_mask is not None:v = v.masked_fill((1 - attn_padding_mask).unsqueeze(1).unsqueeze(-1).to(torch.bool), 0)if not has_lightning_attention:if slope_rate != None:attn_mask = torch.exp(slope_rate * attn_mask)output = linear_attention(q, k, v, attn_mask)else:output = lightning_attention(q, k, v, True, slope_rate.squeeze(-1).squeeze(-1))# reshapeoutput = rearrange(output, "b h n d -> b n (h d)")12 unmodified linesreturn output, attn_weights, past_key_valuedef inference(self,x,attn_mask: Optional[torch.Tensor] = None, # (b, h, n, m)attn_padding_mask: Optional[torch.Tensor] = None, # (b, m)output_attentions: bool = False,past_key_value: Optional[Tuple[torch.Tensor]] = None,use_cache: bool = False,slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)):# x: b n dn = x.shape[-2]1 unmodified lineq, k, v, u = self.qkvu_proj(x).chunk(4, dim=-1)# reshapeq, k, v = map(lambda x: rearrange(x, "b n (h d) -> b h n d", h=self.num_heads), [q, k, v])# actq = self.act(q)k = self.act(k)1 unmodified line# rpeif self.linear_use_lrpe:q = self.lrpe(q, offset=self.offset)k = self.lrpe(k)if past_key_value == None:self.offset = q.shape[-2]11 unmodified linesif attn_padding_mask is not None:attn_mask = attn_mask.masked_fill((1 - attn_padding_mask).unsqueeze(1).unsqueeze(2).to(torch.bool),0,)energy = torch.einsum("... n d, ... m d -> ... n m", q, k)4 unmodified linesoutput = torch.einsum("... n m, ... m d -> ... n d", energy, v)eval_and_not_generate = eval(os.environ.get("eval_and_not_generate", default="False"))if eval_and_not_generate:kv = Noneelse:# b, h, n, e, dkv_outproduct = torch.einsum("... n e, ... n d -> ... n e d", k, v)# 1, 1, n, 1, 1index = torch.arange(n - 1, -1, -1).reshape(1, 1, -1, 1, 1).to(x)# (h, 1, 1) -> (1, h, 1, 1, 1); (1, h, 1, 1, 1), (1, 1, n, 1, 1) -> (1, h, n, 1, 1)decay = ratio.unsqueeze(0).unsqueeze(-1) ** indexkv_outproduct_with_decay = kv_outproduct * decaykv = torch.sum(kv_outproduct_with_decay, dim=-3)4 unmodified linesfor i in range(n):kv = ratio * kv + torch.einsum("... n d, ... n e -> ... d e",k[:, :, i : i + 1],v[:, :, i : i + 1],)qkv = torch.einsum("... n e, ... e d -> ... n d", q[:, :, i : i + 1], kv)output.append(qkv)output = torch.concat(output, dim=-2)12 unmodified linesclass TransnormerDecoderLayer(nn.Module):def __init__(self, config: TransnormerConfig):super().__init__()self.embed_dim = config.decoder_embed_dim32 unmodified linesreturn residual + xdef forward(self,x,attn_mask: Optional[torch.Tensor] = None,attn_padding_mask: Optional[torch.Tensor] = None,past_key_value: Optional[Tuple[torch.Tensor]] = None,output_attentions: Optional[bool] = False,use_cache: Optional[bool] = False,slope_rate: Optional[torch.Tensor] = None, # (h, 1, 1)):residual = xx = self.token_norm(x)13 unmodified linesx = self.channel_mixer(x)x = self.residual_connection(x, residual)outputs = (x,)if output_attentions:outputs += (self_attn_weights,)if use_cache:outputs += (present_key_value,)return outputs15 unmodified lines"""@add_start_docstrings(TRANSNORMER_START_DOCSTRING,)class TransnormerPreTrainedModel(PreTrainedModel):config_class = TransnormerConfigbase_model_prefix = "model"78 unmodified lines"""@add_start_docstrings(TRANSNORMER_START_DOCSTRING,)class TransnormerModel(TransnormerPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TransnormerDecoderLayer`]17 unmodified linesself.slopes = self._build_slope_tensor(config.decoder_attention_heads)# paramsself.embed_tokens = nn.Embedding(config.vocab_size, config.decoder_embed_dim, self.padding_idx)self.layers = nn.ModuleList([])for i in range(config.decoder_layers):if len(self.linear_use_lrpe_list) > 0:config.linear_use_lrpe = self.linear_use_lrpe_list[i]self.layers.append(TransnormerDecoderLayer(config))self.final_norm = get_norm_fn(config.norm_type)(config.decoder_embed_dim)self.embed_dim = config.decoder_embed_dimself.embed_scale = (1.0 if config.no_scale_embedding else math.sqrt(self.embed_dim))# Initialize weights and apply final processingself.post_init()@staticmethoddef _build_slope_tensor(n_attention_heads: int):def get_slopes(n):def get_slopes_power_of_2(n):start = 2 ** (-(2 ** -(math.log2(n) - 3)))ratio = startreturn [start * ratio**i for i in range(n)]2 unmodified linesn) # In the paper, we only train models that have 2^a heads for some a. This function haselse: # some good properties that only occur when the input is a power of 2. To maintain that evenclosest_power_of_2 = 2 ** math.floor(math.log2(n)) # when the number of heads is not a power of 2, we use this workaround.return (get_slopes_power_of_2(closest_power_of_2)+ get_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2])# h, 1, 1slopes = torch.tensor(get_slopes(n_attention_heads)).reshape(n_attention_heads, 1, 1)return slopes6 unmodified linesdef set_input_embeddings(self, value):self.embed_tokens = valuedef _prepare_decoder_linear_attn_mask(self, input_shape, inputs_embeds, past_key_values_length):bsz, tgt_len = input_shapesrc_len = tgt_len + past_key_values_lengthdef power_log(x):return 2 ** (math.ceil(math.log(x, 2)))n = power_log(max(tgt_len, src_len))if self._linear_attn_mask.shape[-1] < n:def get_mask(n):mask = torch.triu(torch.zeros(n, n).float().fill_(float("-inf")), 1)# no slope version# -n, ..., -2, -1, 0for i in range(n):x = torch.arange(i + 1)y = xmask[i, : i + 1] = -torch.flip(y, [0])return mask5 unmodified lineslinear_attn_mask = self._linear_attn_mask[:, -tgt_len:, -src_len:]num_heads = linear_attn_mask.shape[0]return linear_attn_mask[None, :, :, :].expand(bsz, num_heads, tgt_len, src_len)@add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)def forward(7 unmodified linesoutput_hidden_states: Optional[bool] = None,return_dict: Optional[bool] = None,) -> Union[Tuple, BaseModelOutputWithPast]:output_attentions = (output_attentionsif output_attentions is not Noneelse self.config.output_attentions)output_hidden_states = (output_hidden_statesif output_hidden_states is not Noneelse self.config.output_hidden_states)use_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_dict)# retrieve input_ids and inputs_embedsif input_ids is not None and inputs_embeds is not None:15 unmodified linesif past_key_values is not None:past_key_values_length = past_key_values[0][0].shape[-2]seq_length_with_past = seq_length_with_past + past_key_values_lengthif inputs_embeds is None:# !!! use embed_scaleinputs_embeds = self.embed_scale * self.embed_tokens(input_ids)15 unmodified lines##### norm linear layerslinear_attn_padding_mask = attn_padding_masklinear_attn_mask = self._prepare_decoder_linear_attn_mask((batch_size, seq_length), inputs_embeds, past_key_values_length)slope_rates = [self.slopes.to(input_ids.device) for _ in range(self.num_layers)]for idx, layer in enumerate(self.layers):if output_hidden_states:all_hidden_states += (hidden_states,)past_key_value = (past_key_values[idx] if past_key_values is not None else None)slope_rate = slope_rates[idx]slope_rate = slope_rate * (1 - idx / (self.num_layers - 1) + 1e-5)mask = linear_attn_masklayer_outputs = layer(hidden_states,attn_mask=mask,attn_padding_mask=linear_attn_padding_mask,past_key_value=past_key_value,output_attentions=output_attentions,use_cache=use_cache,slope_rate=slope_rate,)hidden_states = layer_outputs[0]if use_cache:next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)if output_attentions:all_self_attns += (layer_outputs[1],)hidden_states = self.final_norm(hidden_states)# add hidden states from the last decoder layerif output_hidden_states:all_hidden_states += (hidden_states,)next_cache = next_decoder_cache if use_cache else Noneif not return_dict:return tuple(vfor v in [hidden_states, next_cache, all_hidden_states, all_self_attns]if v is not None)return BaseModelOutputWithPast(last_hidden_state=hidden_states,past_key_values=next_cache,3 unmodified linesclass TransnormerForCausalLM(TransnormerPreTrainedModel):def __init__(self, config):super().__init__(config)self.model = TransnormerModel(config)1 unmodified linelogging_info(self.model)# the lm_head weight is automatically tied to the embed tokens weightself.lm_head = nn.Linear(config.decoder_embed_dim, config.vocab_size, bias=False)# Initialize weights and apply final processingself.post_init()17 unmodified linesreturn self.model@add_start_docstrings_to_model_forward(TRANSNORMER_INPUTS_DOCSTRING)@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)def forward(self,input_ids: torch.LongTensor = None,31 unmodified lines>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]"Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."```"""output_attentions = (output_attentionsif output_attentions is not Noneelse self.config.output_attentions)output_hidden_states = (output_hidden_statesif output_hidden_states is not Noneelse self.config.output_hidden_states)return_dict = (return_dict if return_dict is not None else self.config.use_return_dict)# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)outputs = self.model(24 unmodified linesloss = loss_fct(shift_logits, shift_labels)if not return_dict:output = (logits,) + outputs[1:]return (loss,) + output if loss is not None else outputreturn CausalLMOutputWithPast(loss=loss,20 unmodified lineselse:model_inputs = {"input_ids": input_ids}model_inputs.update({"past_key_values": past_key_values,"use_cache": kwargs.get("use_cache"),"attention_mask": attention_mask,})return model_inputs@staticmethoddef _reorder_cache(past_key_values, beam_idx):reordered_past = ()for layer_past in past_key_values:reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)return reordered_past
72 unmodified lines7374757677785 unmodified lines848586878889909192939472 unmodified linesif isinstance(unk_token, str) else unk_token)pad_token = (AddedToken(pad_token, lstrip=False, rstrip=False)if isinstance(pad_token, str) else pad_token)super().__init__(bos_token=bos_token,eos_token=eos_token,5 unmodified linesclean_up_tokenization_spaces=clean_up_tokenization_spaces,**kwargs,)self.vocab_file = vocab_fileself.add_bos_token = add_bos_tokenself.add_eos_token = add_eos_tokenself.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)self.sp_model.Load(vocab_file)def __getstate__(self):state = self.__dict__.copy()72 unmodified lines73747576777879808182835 unmodified lines89909192939472 unmodified linesif isinstance(unk_token, str) else unk_token)pad_token = (AddedToken(pad_token, lstrip=False, rstrip=False)if isinstance(pad_token, str) else pad_token)self.vocab_file = vocab_fileself.add_bos_token = add_bos_tokenself.add_eos_token = add_eos_tokenself.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)self.sp_model.Load(vocab_file)super().__init__(bos_token=bos_token,eos_token=eos_token,5 unmodified linesclean_up_tokenization_spaces=clean_up_tokenization_spaces,**kwargs,)def __getstate__(self):state = self.__dict__.copy()
generation_config.json+5-2
modeling_transnormer.py+145-279
tokenization_baichuan.py+5-5