Run this model with HF Jobs
Run jinaai/xlm-roberta-flash-implementation 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 to fine-tune https://huggingface.co/jinaai/xlm-roberta-flash-implementation. 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/jinaai/xlm-roberta-flash-implementation 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.
Instructions to use jinaai/xlm-roberta-flash-implementation with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use jinaai/xlm-roberta-flash-implementation with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("jinaai/xlm-roberta-flash-implementation", device_map="auto") - Notebooks
- Google Colab
- Kaggle
make-lora-stateless (#25)
Browse files- draft (6cc0f517fef666dc2c5c0f0fe7c92935f7b7d7bb)
- poc (eefe43c08d4952b1e2a3c17d6e20090a72a52474)
- refactor: finalize impl (509511d7e5d7b46de5b143e5fc908784eada3f07)
- refactor: modify encode (3eb20d0a7451e244a9c2ee80e7bb762d17a9f9d1)
- fix: 0 is not none (ae40cb93420908fdd3f370e6af3cb0cbe9cbf90d)
- fix: remove prints (acffa62b444442f4933a3023f19d09148de9e2fb)
- refactor: kwargs comprehension (4e13c908bafe0f54becc8c278b3752a37c207c50)
- fix: residual is kept in kwargs (d9d83063f0fcb5bfa22cd4946f23baa1421b9930)
- feat: merge with recent changes (493416fa0cabc0de4deba3c317c58043f9998d49)
Files changed (6)
- block.py+1-1
- embedding.py+4-3
- mha.py+11-3
- mlp.py+4-3
- modeling_lora.py+51-91
- modeling_xlm_roberta.py+15-11
232 unmodified lines233234235236237238239232 unmodified linesis_rms_norm=isinstance(self.norm1, RMSNorm),)if not isinstance(self.mlp, nn.Identity):mlp_out = self.mlp(hidden_states)if self.return_residual: # mlp out is actually a pair heremlp_out, hidden_states = mlp_outif not self.fused_dropout_add_ln:232 unmodified lines233234235236237238239232 unmodified linesis_rms_norm=isinstance(self.norm1, RMSNorm),)if not isinstance(self.mlp, nn.Identity):mlp_out = self.mlp(hidden_states, task_type=mixer_kwargs.get('task_type'))if self.return_residual: # mlp out is actually a pair heremlp_out, hidden_states = mlp_outif not self.fused_dropout_add_ln:
39 unmodified lines40414243444546474849505152533 unmodified lines57585960616239 unmodified linesif self.type_vocab_size > 0:self.token_type_embeddings = nn.Embedding(type_vocab_size, embed_dim, **factory_kwargs)def forward(self, input_ids, position_ids=None, token_type_ids=None):"""input_ids: (batch, seqlen)position_ids: (batch, seqlen)token_type_ids: (batch, seqlen)"""batch_size, seqlen = input_ids.shapeembeddings = self.word_embeddings(input_ids)if self.max_position_embeddings > 0:if position_ids is None:position_ids = create_position_ids_from_input_ids(input_ids, padding_idx=self.word_embeddings.padding_idx).to(input_ids.device)3 unmodified linesif self.type_vocab_size > 0:if token_type_ids is None:token_type_ids = torch.zeros(seqlen, dtype=torch.long, device=input_ids.device)token_type_embeddings = self.token_type_embeddings(token_type_ids)embeddings = embeddings + token_type_embeddingsreturn embeddings39 unmodified lines4041424344454647484950515253543 unmodified lines58596061626339 unmodified linesif self.type_vocab_size > 0:self.token_type_embeddings = nn.Embedding(type_vocab_size, embed_dim, **factory_kwargs)def forward(self, input_ids, position_ids=None, token_type_ids=None, task_type=None):"""input_ids: (batch, seqlen)position_ids: (batch, seqlen)token_type_ids: (batch, seqlen)"""batch_size, seqlen = input_ids.shapelora_kwargs = {'task_type': task_type} if task_type is not None else {}embeddings = self.word_embeddings(input_ids, **lora_kwargs)if self.max_position_embeddings > 0:if position_ids is None:position_ids = create_position_ids_from_input_ids(input_ids, padding_idx=self.word_embeddings.padding_idx).to(input_ids.device)3 unmodified linesif self.type_vocab_size > 0:if token_type_ids is None:token_type_ids = torch.zeros(seqlen, dtype=torch.long, device=input_ids.device)token_type_embeddings = self.token_type_embeddings(token_type_ids, **lora_kwargs)embeddings = embeddings + token_type_embeddingsreturn embeddings
449 unmodified lines450451452453454455133 unmodified lines58959059159259359448 unmodified lines64364464564664764864965065165278 unmodified lines731732733734735449 unmodified linesif fused_bias_fc and FusedDense is None:raise ImportError("fused_dense is not installed")linear_cls = nn.Linear if not fused_bias_fc else FusedDenselinear_resid_cls = (LinearResidual if not fused_bias_fc else partial(FusedDense, return_residual=True)133 unmodified linesmax_seqlen=None,mixer_subset=None,inference_params=None,**kwargs,):"""48 unmodified linesbatch, seqlen = x.shape[:2]if not self.cross_attn and self.num_heads_kv == self.num_heads:assert x_kv is None and mixer_subset is Noneif not self.return_residual:qkv = self.Wqkv(x)else:qkv, x = self.Wqkv(x)if self.dwconv:qkv = rearrange(self.dwconv_qkv(rearrange(qkv, "b s d -> b d s"))[..., :-2], "b d s -> b s d"78 unmodified linescontext = self._update_kvcache_attention(q, kv, inference_params)else:context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params)out = self.out_proj(rearrange(context, "... h d -> ... (h d)"))return out if not self.return_residual else (out, x)449 unmodified lines450451452453454455456133 unmodified lines59059159259359459559648 unmodified lines64564664764864965065165265365465565665765878 unmodified lines737738739740741742743449 unmodified linesif fused_bias_fc and FusedDense is None:raise ImportError("fused_dense is not installed")linear_cls = nn.Linear if not fused_bias_fc else FusedDenselinear_resid_cls = (LinearResidual if not fused_bias_fc else partial(FusedDense, return_residual=True)133 unmodified linesmax_seqlen=None,mixer_subset=None,inference_params=None,task_type=None,**kwargs,):"""48 unmodified linesbatch, seqlen = x.shape[:2]if not self.cross_attn and self.num_heads_kv == self.num_heads:assert x_kv is None and mixer_subset is Nonelora_kwargs = {'task_type': task_type} if task_type is not None else {}if not self.return_residual:qkv = self.Wqkv(x, **lora_kwargs)else:if lora_kwargs:lora_kwargs['residual'] = Trueqkv, x = self.Wqkv(x, **lora_kwargs)if self.dwconv:qkv = rearrange(self.dwconv_qkv(rearrange(qkv, "b s d -> b d s"))[..., :-2], "b d s -> b s d"78 unmodified linescontext = self._update_kvcache_attention(q, kv, inference_params)else:context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params)lora_kwargs.pop('residual', None)out = self.out_proj(rearrange(context, "... h d -> ... (h d)"), **lora_kwargs)return out if not self.return_residual else (out, x)
46 unmodified lines4748495051525354555646 unmodified linesself.activation = activationself.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs)def forward(self, x):y = self.fc1(x)y = self.activation(y)y = self.fc2(y)return y if not self.return_residual else (y, x)46 unmodified lines474849505152535455565746 unmodified linesself.activation = activationself.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs)def forward(self, x, task_type=None):lora_kwargs = {'task_type': task_type} if task_type is not None else {}y = self.fc1(x, **lora_kwargs)y = self.activation(y)y = self.fc2(y, **lora_kwargs)return y if not self.return_residual else (y, x)
8 unmodified lines9101112131473 unmodified lines8889909192939495969798991001011021031041051061071081091 unmodified line11111211311411511611711811912012112212312412512612712812945 unmodified lines1751761771781791807 unmodified lines1881891901911921937 unmodified lines20120220320420520620720820921040 unmodified lines25125225325425525625725825947 unmodified lines30730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635713 unmodified lines3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024038 unmodified linesimport torch.nn.utils.parametrize as parametrizefrom torch import nnfrom torch.nn import Parameterfrom transformers import PretrainedConfigfrom .modeling_xlm_roberta import XLMRobertaFlashConfig, XLMRobertaModel, XLMRobertaPreTrainedModel73 unmodified linestorch.ones(self.swap((1, fan_in)), dtype=self.lora_A.dtype),persistent=False,)self.forward_fn = lambda x: xself.current_task = Nonedef _dropout(self, A):# to mimic the original implementation: A @ dropout(x), we do (A * dropout(ones)) @ xreturn A * self.lora_dropout(self.lora_dropout_mask)def lora_forward(self, X):assert self.current_task is not Nonereturn (X+ torch.matmul(*self.swap((self.lora_B[self.current_task],self.dropout_fn(self.lora_A[self.current_task]),))).view(X.shape)1 unmodified line)def forward(self, X):return self.forward_fn(X)@propertydef current_task(self):return self._current_task@current_task.setterdef current_task(self, task: Union[None, int]):self._current_task = taskif task is None:self.forward_fn = lambda x: xelse:self.forward_fn = self.lora_forward@classmethoddef from_linear(45 unmodified linesrank: int,dropout_p: float,alpha: float,):if isinstance(layer, nn.Linear):parametrize.register_parametrization(7 unmodified linesalpha=alpha,),)elif isinstance(layer, nn.Embedding):parametrize.register_parametrization(layer,7 unmodified lines),)@staticmethoddef select_task_for_layer(layer: nn.Module, task_idx: Optional[int] = None):if isinstance(layer, LoRAParametrization):layer.current_task = task_idxclass XLMRobertaLoRA(XLMRobertaPreTrainedModel):40 unmodified linesalpha=self._alpha,)self.main_params_trainable = config.lora_main_params_trainableself._task_idx = None# By default, disable LoRA until it's specified which adapter/task to useself.current_task = None@propertydef main_params_trainable(self):47 unmodified linesrank=rank,dropout_p=dropout_p,alpha=alpha,))@propertydef current_task(self):"""Which LoRA is currently selected:return: Integer or None (when LoRA is disabled)"""return self._task_idx@current_task.setterdef current_task(self, task_name: Union[None, str]):"""Set the LoRA that is to be used.The LoRA is specified by `task_idx`, which may be an integer >= 0,indexing the available LoRAs. If it is None, no LoRA is used.:param task_name: Which LoRA to use:return:"""if task_name and task_name not in self._lora_adaptations:raise ValueError(f"Unsupported task '{task_name}'. "f"Supported tasks are: {', '.join(self.config.lora_adaptations)}."f"Alternatively, set `task` to `None` if you want to disable LoRA.")task_idx = self._adaptation_map[task_name] if task_name else Noneif self._task_idx != task_idx:# In this case, we need to update the LoRAs everywhereself._task_idx = task_idxself.apply(partial(LoRAParametrization.select_task_for_layer, task_idx=task_idx))def forward(self, *args, task_type: Union[str, None] = None, **kwargs):if task_type:self.current_task = task_typeelse:input_ids = kwargs["input_ids"]input_text = self.roberta.tokenizer.decode(input_ids[0], skip_special_tokens=True)for task_name, prompt in self._lora_prompts.items():if input_text.startswith(prompt):self.current_task = task_namebreakelse:self.current_task = None # No task-specific adapter is found, just use the general-purpose weightsreturn self.roberta(*args, **kwargs)def parameters(self, recurse: bool = True) -> Iterator[Parameter]:13 unmodified linesdef encode(self,*args,task_type: Union[str, None] = None,**kwargs,) -> Union[List[torch.Tensor], np.ndarray, torch.Tensor]:"""Computes sentence embeddingstask(`str`, *optional*, defaults to `LORA_NO_UPDATE`):Specifies the task for which the encoding is intended. This parameter controls theuse of specialized LoRA adapters that are tuned for specific tasks. If `task` is setto `None`, all LoRA adapters are disabled, and the model reverts to its original,general-purpose weights. If `task` is set to a specific LoRA adaptation, that adaptationis activated."""if task_type:self.current_task = task_typeelse: # infer the task from the input textinput_text = args[0][0] if isinstance(args[0], list) else args[0] # take only the first sentencefor task_name, prompt in self._lora_prompts.items():if input_text.startswith(prompt):self.current_task = task_namebreakelse:warnings.warn(f"Task-specific embeddings are disabled. To enable, specify the `task` "f"argument with one of the supported tasks: {', '.join(self.config.lora_adaptations)}",category=UserWarning,)self.current_task = None # No task-specific adapter is found, just use the general-purpose weightsreturn self.roberta.encode(*args, **kwargs)8 unmodified lines910111213141573 unmodified lines89909192939495969798991001011021031041051061071 unmodified line10911011111211311411545 unmodified lines1611621631641651661677 unmodified lines1751761771781791801811821831841851861871881891901911921931941951967 unmodified lines20420520620720820921021121221321421521621721821922022122222340 unmodified lines26426526626726826927047 unmodified lines31831932032132232332432532632732813 unmodified lines3423433443453463473483493503513523533543553563573583593603613623638 unmodified linesimport torch.nn.utils.parametrize as parametrizefrom torch import nnfrom torch.nn import Parameterfrom torch.nn import functional as Ffrom transformers import PretrainedConfigfrom .modeling_xlm_roberta import XLMRobertaFlashConfig, XLMRobertaModel, XLMRobertaPreTrainedModel73 unmodified linestorch.ones(self.swap((1, fan_in)), dtype=self.lora_A.dtype),persistent=False,)def _dropout(self, A):# to mimic the original implementation: A @ dropout(x), we do (A * dropout(ones)) @ xreturn A * self.lora_dropout(self.lora_dropout_mask)def lora_forward(self, X, current_task):return (X+ torch.matmul(*self.swap((self.lora_B[current_task],self.dropout_fn(self.lora_A[current_task]),))).view(X.shape)1 unmodified line)def forward(self, X):return X@classmethoddef from_linear(45 unmodified linesrank: int,dropout_p: float,alpha: float,adaptation_map: dict,):if isinstance(layer, nn.Linear):parametrize.register_parametrization(7 unmodified linesalpha=alpha,),)def new_forward(self, input, task_type, residual=False):task_idx = adaptation_map[task_type] if task_type else Noneif task_idx is not None:weights = self.parametrizations.weight[0].lora_forward(self.weight, current_task=task_idx)else:weights = self.weightout = F.linear(input, weights, self.bias)if residual:return out, inputreturn outlayer.forward = new_forward.__get__(layer, layer.__class__)elif isinstance(layer, nn.Embedding):parametrize.register_parametrization(layer,7 unmodified lines),)def new_forward(self, input, task_type):task_idx = adaptation_map[task_type] if task_type else Noneif task_idx is not None:weights = self.parametrizations.weight[0].lora_forward(self.weight, current_task=task_idx)else:weights = self.weightout = F.embedding(input, weights, self.padding_idx, self.max_norm,self.norm_type, self.scale_grad_by_freq, self.sparse)return outlayer.forward = new_forward.__get__(layer, layer.__class__)class XLMRobertaLoRA(XLMRobertaPreTrainedModel):40 unmodified linesalpha=self._alpha,)self.main_params_trainable = config.lora_main_params_trainable@propertydef main_params_trainable(self):47 unmodified linesrank=rank,dropout_p=dropout_p,alpha=alpha,adaptation_map=self._adaptation_map,))def forward(self, *args, **kwargs):return self.roberta(*args, **kwargs)def parameters(self, recurse: bool = True) -> Iterator[Parameter]:13 unmodified linesdef encode(self,*args,task_type: Optional[str] = None,**kwargs,) -> Union[List[torch.Tensor], np.ndarray, torch.Tensor]:"""Computes sentence embeddingstask_type(`str`, *optional*, defaults to `None`):Specifies the task for which the encoding is intended. If `task_type` is not provide,all LoRA adapters are disabled, and the model reverts to its original,general-purpose weights."""if task_type and task_type not in self._lora_adaptations:raise ValueError(f"Unsupported task '{task_type}'. "f"Supported tasks are: {', '.join(self.config.lora_adaptations)}."f"Alternatively, don't pass the `task_type` argument to disable LoRA.")return self.roberta.encode(*args, task_type=task_type, **kwargs)
203 unmodified lines2042052062072082092104 unmodified lines21521621721821922011 unmodified lines23223323423523623723870 unmodified lines309310311312313314315316317318319134 unmodified lines45445545645745845978 unmodified lines53853954054154254354454554654754854955055181 unmodified lines6336346356366376386397 unmodified lines64764864965065165265317 unmodified lines6716726736746756766776786796806816827 unmodified lines690691692693694695696203 unmodified linesdef gradient_checkpointing(self, value):self._grad_checkpointing = valuedef forward(self, hidden_states, key_padding_mask=None, subset_mask=None):"""If subset_mask is not None, we only want output for the subset of the sequence.This means that we only compute the last layer output for these tokens.subset_mask: (batch, seqlen), dtype=torch.bool4 unmodified linesif key_padding_mask is not Noneelse None)for layer in self.layers:if self._grad_checkpointing:hidden_states = torch.utils.checkpoint.checkpoint(11 unmodified lineshidden_states, indices, cu_seqlens, max_seqlen_in_batch = unpad_input(hidden_states, key_padding_mask)mixer_kwargs = {"cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen_in_batch}if subset_mask is None:for layer in self.layers:if self._grad_checkpointing:70 unmodified linesself.dense = linear_cls(config.hidden_size, config.hidden_size)self.activation = nn.Tanh()def forward(self, hidden_states, pool=True):# We "pool" the model by simply taking the hidden state corresponding# to the first token.first_token_tensor = hidden_states[:, 0] if pool else hidden_statespooled_output = self.dense(first_token_tensor)pooled_output = self.activation(pooled_output)return pooled_output134 unmodified linesdevice: Optional[torch.device] = None,normalize_embeddings: bool = False,truncate_dim: Optional[int] = None,**tokenizer_kwargs,) -> Union[List[torch.Tensor], np.ndarray, torch.Tensor]:"""78 unmodified lines)else:range_iter = range(0, len(sentences), batch_size)for i in range_iter:encoded_input = self.tokenizer(sentences[i : i + batch_size],return_tensors='pt',**tokenizer_kwargs,).to(self.device)token_embs = self.forward(**encoded_input)[0]# Accumulate in fp32 to avoid overflowtoken_embs = token_embs.float()81 unmodified lineslayer output for these tokens.masked_tokens_mask: (batch, seqlen), dtype=torch.bool"""if kwargs:for key, value in kwargs.items():if value is not None:7 unmodified lines)hidden_states = self.embeddings(input_ids, position_ids=position_ids, token_type_ids=token_type_ids)# TD [2022-12:18]: Don't need to force residual in fp32# BERT puts embedding LayerNorm before embedding dropout.17 unmodified linessubset_mask = Nonesequence_output = self.encoder(hidden_states, key_padding_mask=attention_mask, subset_mask=subset_mask)if masked_tokens_mask is None:pooled_output = (self.pooler(sequence_output) if self.pooler is not None else None)else:# TD [2022-03-01]: the indexing here is very tricky.7 unmodified linespool_input = sequence_output[first_col_mask[subset_mask]]sequence_output = sequence_output[masked_tokens_mask[subset_mask]]pooled_output = (self.pooler(pool_input, pool=False) if self.pooler is not None else None)if not return_dict:203 unmodified lines2042052062072082092104 unmodified lines21521621721821922022111 unmodified lines23323423523623723823970 unmodified lines310311312313314315316317318319320321322134 unmodified lines45745845946046146246378 unmodified lines54254354454554654754854955055155255355455581 unmodified lines6376386396406416426437 unmodified lines65165265365465565665717 unmodified lines6756766776786796806816826836846856867 unmodified lines694695696697698699700203 unmodified linesdef gradient_checkpointing(self, value):self._grad_checkpointing = valuedef forward(self, hidden_states, key_padding_mask=None, subset_mask=None, task_type=None):"""If subset_mask is not None, we only want output for the subset of the sequence.This means that we only compute the last layer output for these tokens.subset_mask: (batch, seqlen), dtype=torch.bool4 unmodified linesif key_padding_mask is not Noneelse None)mixer_kwargs['task_type'] = task_typefor layer in self.layers:if self._grad_checkpointing:hidden_states = torch.utils.checkpoint.checkpoint(11 unmodified lineshidden_states, indices, cu_seqlens, max_seqlen_in_batch = unpad_input(hidden_states, key_padding_mask)mixer_kwargs = {"cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen_in_batch, "task_type": task_type}if subset_mask is None:for layer in self.layers:if self._grad_checkpointing:70 unmodified linesself.dense = linear_cls(config.hidden_size, config.hidden_size)self.activation = nn.Tanh()def forward(self, hidden_states, pool=True, task_type=None):# We "pool" the model by simply taking the hidden state corresponding# to the first token.lora_kwargs = {'task_type': task_type} if task_type is not None else {}first_token_tensor = hidden_states[:, 0] if pool else hidden_statespooled_output = self.dense(first_token_tensor, **lora_kwargs)pooled_output = self.activation(pooled_output)return pooled_output134 unmodified linesdevice: Optional[torch.device] = None,normalize_embeddings: bool = False,truncate_dim: Optional[int] = None,task_type: Optional[str] = None,**tokenizer_kwargs,) -> Union[List[torch.Tensor], np.ndarray, torch.Tensor]:"""78 unmodified lines)else:range_iter = range(0, len(sentences), batch_size)lora_kwargs = {'task_type': task_type} if task_type is not None else {}for i in range_iter:encoded_input = self.tokenizer(sentences[i : i + batch_size],return_tensors='pt',**tokenizer_kwargs,).to(self.device)token_embs = self.forward(**encoded_input, **lora_kwargs)[0]# Accumulate in fp32 to avoid overflowtoken_embs = token_embs.float()81 unmodified lineslayer output for these tokens.masked_tokens_mask: (batch, seqlen), dtype=torch.bool"""task_type = kwargs.pop('task_type', None)if kwargs:for key, value in kwargs.items():if value is not None:7 unmodified lines)hidden_states = self.embeddings(input_ids, position_ids=position_ids, token_type_ids=token_type_ids, task_type=task_type)# TD [2022-12:18]: Don't need to force residual in fp32# BERT puts embedding LayerNorm before embedding dropout.17 unmodified linessubset_mask = Nonesequence_output = self.encoder(hidden_states, key_padding_mask=attention_mask, subset_mask=subset_mask, task_type=task_type)if masked_tokens_mask is None:pooled_output = (self.pooler(sequence_output, task_type=task_type) if self.pooler is not None else None)else:# TD [2022-03-01]: the indexing here is very tricky.7 unmodified linespool_input = sequence_output[first_col_mask[subset_mask]]sequence_output = sequence_output[masked_tokens_mask[subset_mask]]pooled_output = (self.pooler(pool_input, pool=False, task_type=task_type) if self.pooler is not None else None)if not return_dict: