Run this model with HF Jobs
Run tattabio/gLM2_650M_bgc_decoder 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/tattabio/gLM2_650M_bgc_decoder. 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/tattabio/gLM2_650M_bgc_decoder 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 tattabio/gLM2_650M_bgc_decoder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use tattabio/gLM2_650M_bgc_decoder with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="tattabio/gLM2_650M_bgc_decoder", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("tattabio/gLM2_650M_bgc_decoder", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload gLM2ForMaskedLM
Browse filesFiles changed (5)
- README.mdAdded+199
- config.jsonAdded+21
- configuration_glm2.pyAdded+38
- model.safetensorsAdded+3
- modeling_glm2.pyAdded+595
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199---library_name: transformerstags: []---
# Model Card for Model ID
<!-- Provide a quick summary of what the model is/does. -->
## Model Details
### Model Description
<!-- Provide a longer summary of what this model is. -->
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]
### Model Sources [optional]
<!-- Provide the basic links for the model. -->
- **Repository:** [More Information Needed]- **Paper [optional]:** [More Information Needed]- **Demo [optional]:** [More Information Needed]
## Uses
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
### Direct Use
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
[More Information Needed]
### Downstream Use [optional]
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
[More Information Needed]
### Out-of-Scope Use
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
[More Information Needed]
## Bias, Risks, and Limitations
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
[More Information Needed]
### Recommendations
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
## How to Get Started with the Model
Use the code below to get started with the model.
[More Information Needed]
## Training Details
### Training Data
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
[More Information Needed]
### Training Procedure
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
#### Preprocessing [optional]
[More Information Needed]
#### Training Hyperparameters
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
#### Speeds, Sizes, Times [optional]
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
[More Information Needed]
## Evaluation
<!-- This section describes the evaluation protocols and provides the results. -->
### Testing Data, Factors & Metrics
#### Testing Data
<!-- This should link to a Dataset Card if possible. -->
[More Information Needed]
#### Factors
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
[More Information Needed]
#### Metrics
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
[More Information Needed]
### Results
[More Information Needed]
#### Summary
## Model Examination [optional]
<!-- Relevant interpretability work for the model goes here -->
[More Information Needed]
## Environmental Impact
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
- **Hardware Type:** [More Information Needed]- **Hours used:** [More Information Needed]- **Cloud Provider:** [More Information Needed]- **Compute Region:** [More Information Needed]- **Carbon Emitted:** [More Information Needed]
## Technical Specifications [optional]
### Model Architecture and Objective
[More Information Needed]
### Compute Infrastructure
[More Information Needed]
#### Hardware
[More Information Needed]
#### Software
[More Information Needed]
## Citation [optional]
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
**BibTeX:**
[More Information Needed]
**APA:**
[More Information Needed]
## Glossary [optional]
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
[More Information Needed]
## More Information [optional]
[More Information Needed]
## Model Card Authors [optional]
[More Information Needed]
## Model Card Contact
[More Information Needed]123456789101112131415161718192021{ "architectures": [ "gLM2ForMaskedLM" ], "auto_map": { "AutoConfig": "configuration_glm2.gLM2Config", "AutoModel": "modeling_glm2.gLM2Model", "AutoModelForMaskedLM": "modeling_glm2.gLM2ForMaskedLM" }, "depth": 33, "dim": 1280, "ffn_dim_multiplier": null, "heads": 20, "model_type": "gLM2", "norm_eps": 1e-05, "swiglu_multiple_of": 256, "tie_word_embeddings": false, "torch_dtype": "float32", "transformers_version": "4.49.0", "vocab_size": 2036}1234567891011121314151617181920212223242526272829303132333435363738"""gLM2 model configuration"""
from typing import Optionalfrom transformers import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class gLM2Config(PretrainedConfig): model_type = "gLM2"
def __init__( self, dim: int = 640, depth: int = 30, heads: int = 10, vocab_size: int = 37, swiglu_multiple_of: int = 256, ffn_dim_multiplier: Optional[float] = None, norm_eps: float = 1e-5, tie_word_embeddings: bool = False, **kwargs ): super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs) self.dim = dim self.depth = depth self.heads = heads self.vocab_size = vocab_size self.swiglu_multiple_of = swiglu_multiple_of self.ffn_dim_multiplier = ffn_dim_multiplier self.norm_eps = norm_eps
self.auto_map = { "AutoConfig": "configuration_glm2.gLM2Config", "AutoModel": "modeling_glm2.gLM2Model", "AutoModelForMaskedLM": "modeling_glm2.gLM2ForMaskedLM" }123version https://git-lfs.github.com/spec/v1oid sha256:e86e2defac30f07cdb740bfeb03582baeadd23f91030cb5a5db012e9dcefbfd9size 2702952560123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595"""PyTorch gLM2 model.
Requires flash attention.Some modules adapted from:https://github.com/meta-llama/llama/blob/main/llama/model.py"""import mathimport torchfrom einops import rearrangefrom typing import Optional, Tuple, Unionfrom torch import nnfrom torch.nn import CrossEntropyLossfrom transformers.modeling_outputs import ( BaseModelOutput, MaskedLMOutput,)from transformers.modeling_utils import PreTrainedModelfrom transformers.utils import logging
try: from flash_attn.ops.activations import swiglu from flash_attn.layers.rotary import apply_rotary_emb_func from flash_attn import ( flash_attn_kvpacked_func, flash_attn_varlen_kvpacked_func, ) from flash_attn.bert_padding import pad_input, unpad_input from flash_attn.ops.triton.layer_norm import RMSNormexcept ImportError: raise ImportError( "gLM2 requires flash attention: `pip install flash-attn --no-build-isolation`")
from .configuration_glm2 import gLM2Config
logger = logging.get_logger(__name__)
class RotaryEmbedding(torch.nn.Module): """ Copied from https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/layers/rotary.py. Changed to only support passing in q or k individually, so that we can use varlen rotary. """
def __init__( self, dim: int, base=10000.0, interleaved=False, scale_base=None, pos_idx_in_fp32=True, device=None, ): super().__init__() self.dim = dim self.base = float(base) self.pos_idx_in_fp32 = pos_idx_in_fp32 # Generate and save the inverse frequency buffer (non trainable) inv_freq = self._compute_inv_freq(device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.interleaved = interleaved self.scale_base = scale_base scale = ( (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim) if scale_base is not None else None ) self.register_buffer("scale", scale, persistent=False)
self._seq_len_cached = 0 self._cos_cached = None self._sin_cached = None self._cos_k_cached = None self._sin_k_cached = None
def _compute_inv_freq(self, device=None): return 1.0 / ( self.base ** ( torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim ) )
def _update_cos_sin_cache(self, seqlen, device=None, dtype=None): # Reset the tables if the sequence length has changed, # if we're on a new device (possibly due to tracing for instance), # or if we're switching from inference mode to training if ( seqlen > self._seq_len_cached or self._cos_cached is None or self._cos_cached.device != device or self._cos_cached.dtype != dtype or (self.training and self._cos_cached.is_inference()) ): self._seq_len_cached = seqlen # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16 # And the output of arange can be quite large, so bf16 would lose a lot of precision. # However, for compatibility reason, we add an option to use the dtype of self.inv_freq. if self.pos_idx_in_fp32: t = torch.arange(seqlen, device=device, dtype=torch.float32) # We want fp32 here as well since inv_freq will be multiplied with t, and the output # will be large. Having it in bf16 will lose a lot of precision and cause the # cos & sin output to change significantly. # We want to recompute self.inv_freq if it was not loaded in fp32 if self.inv_freq.dtype != torch.float32: inv_freq = self._compute_inv_freq(device=device) else: inv_freq = self.inv_freq else: t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype) inv_freq = self.inv_freq # Don't do einsum, it converts fp32 to fp16 under AMP # freqs = torch.einsum("i,j->ij", t, self.inv_freq) freqs = torch.outer(t, inv_freq) if self.scale is None: self._cos_cached = torch.cos(freqs).to(dtype) self._sin_cached = torch.sin(freqs).to(dtype) else: power = ( torch.arange( seqlen, dtype=self.scale.dtype, device=self.scale.device ) - seqlen // 2 ) / self.scale_base scale = self.scale.to(device=power.device) ** rearrange( power, "s -> s 1" ) # We want the multiplication by scale to happen in fp32 self._cos_cached = (torch.cos(freqs) * scale).to(dtype) self._sin_cached = (torch.sin(freqs) * scale).to(dtype) self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype) self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
def forward( self, q: torch.Tensor, k: torch.Tensor, seqlen_offset: Union[int, torch.Tensor] = 0, cu_seqlens: Optional[torch.Tensor] = None, max_seqlen: Optional[int] = None, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ q: (batch, seqlen, nheads, headdim). If cu_seqlens is not None, shape (total_seqlen, nheads, headdim). k: (batch, seqlen, nheads, headdim). If cu_seqlens is not None, shape (total_seqlen, nheads, headdim). seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount. Most commonly used in inference when we have KV cache. If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one should pass in max_seqlen, which will update the cos / sin cache up to that length. Apply rotary embedding *inplace* to qkv and / or kv. """ if cu_seqlens is not None: assert max_seqlen is not None seqlen = q.shape[1] if max_seqlen is None else max_seqlen if max_seqlen is not None: self._update_cos_sin_cache( max_seqlen, device=q.device, dtype=q.dtype) elif isinstance(seqlen_offset, int): self._update_cos_sin_cache( seqlen + seqlen_offset, device=q.device, dtype=q.dtype ) q = apply_rotary_emb_func( q, self._cos_cached, self._sin_cached, interleaved=self.interleaved, inplace=True, seqlen_offsets=seqlen_offset, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, ) if self.scale is None: k = apply_rotary_emb_func( k, self._cos_cached, self._sin_cached, interleaved=self.interleaved, inplace=True, seqlen_offsets=seqlen_offset, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, ) else: k = apply_rotary_emb_func( k, self._cos_k_cached, self._sin_k_cached, interleaved=self.interleaved, inplace=True, seqlen_offsets=seqlen_offset, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, ) return q, k
# @torch.jit.script# def rmsnorm_func(hidden_states, weight, variance_epsilon):# """Apply the root mean square normalization."""# input_dtype = hidden_states.dtype# hidden_states = hidden_states.to(torch.float32)# variance = hidden_states.pow(2).mean(-1, keepdim=True)# hidden_states = hidden_states * torch.rsqrt(variance + variance_epsilon)# return (weight * hidden_states).to(input_dtype)
# class RMSNorm(nn.Module):# """Root mean square normalization."""
# def __init__(self, dim, eps=1e-6):# super().__init__()# self.weight = nn.Parameter(torch.ones(dim))# self.register_buffer(# "variance_epsilon",# torch.tensor(eps),# persistent=False,# )
# def forward(self, hidden_states):# return rmsnorm_func(hidden_states, self.weight, self.variance_epsilon)
class Attention(nn.Module): """Multi-head attention module."""
def __init__(self, config: gLM2Config): super().__init__() self.n_heads = config.heads self.head_dim = config.dim // config.heads
self.wqkv = nn.Linear(config.dim, self.n_heads * self.head_dim * 3, bias=False) self.wo = nn.Linear(config.heads * self.head_dim, config.dim, bias=False)
self.rotary_emb = RotaryEmbedding(self.head_dim)
def _forward_varlen( self, x: torch.Tensor, cu_seqlens: Optional[torch.Tensor] = None, max_seq_len: Optional[torch.Tensor] = None, ) -> torch.Tensor: total_seqlen, h_size = x.shape qkv = self.wqkv(x) q, k, v = torch.split(qkv, self.n_heads * self.head_dim, dim=-1)
q = q.view(total_seqlen, self.n_heads, self.head_dim) k = k.view(total_seqlen, self.n_heads, self.head_dim) v = v.view(total_seqlen, self.n_heads, self.head_dim)
q, k = self.rotary_emb( q, k, cu_seqlens=cu_seqlens, max_seqlen=max_seq_len)
# (seqlen, 2, n_heads, head_dim) kv = torch.stack([k, v], 1)
# (seqlen, n_heads, head_dim) output = flash_attn_varlen_kvpacked_func( q, kv, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, max_seqlen_q=max_seq_len, max_seqlen_k=max_seq_len, dropout_p=0.0, causal=False, ) output = output.view(total_seqlen, h_size) return self.wo(output)
def forward( self, x: torch.Tensor, cu_seqlens: Optional[torch.Tensor] = None, max_seq_len: Optional[torch.Tensor] = None, ) -> torch.Tensor: if cu_seqlens is not None: assert max_seq_len is not None return self._forward_varlen(x, cu_seqlens, max_seq_len)
bsz, seqlen, h_size = x.shape qkv = self.wqkv(x) q, k, v = torch.split(qkv, self.n_heads * self.head_dim, dim=-1) q = q.view(bsz, seqlen, self.n_heads, self.head_dim) k = k.view(bsz, seqlen, self.n_heads, self.head_dim) v = v.view(bsz, seqlen, self.n_heads, self.head_dim)
q, k = self.rotary_emb(q, k) # (bs, seqlen, 2, n_heads, head_dim) kv = torch.stack([k, v], 2)
output = flash_attn_kvpacked_func( q, kv, dropout_p=0.0, causal=False, ) output = output.view(bsz, seqlen, h_size) return self.wo(output)
class FeedForward(nn.Module): def __init__( self, dim: int, hidden_dim: int, multiple_of: int, ffn_dim_multiplier: Optional[float], ): """ SwiGLU FeedForward module.
Args: dim (int): Input dimension. hidden_dim (int): Hidden dimension of the feedforward layer. multiple_of (int): Value to ensure hidden dimension is a multiple of this value. ffn_dim_multiplier (float, optional): Custom multiplier for hidden dimension. Defaults to None. """ super().__init__() hidden_dim = int(2 * hidden_dim / 3) # custom dim factor multiplier if ffn_dim_multiplier is not None: hidden_dim = int(ffn_dim_multiplier * hidden_dim) hidden_dim = multiple_of * \ ((hidden_dim + multiple_of - 1) // multiple_of)
self.w1 = nn.Linear(dim, hidden_dim, bias=False) self.w2 = nn.Linear(hidden_dim, dim, bias=False) self.w3 = nn.Linear(dim, hidden_dim, bias=False)
def forward(self, x): return self.w2(swiglu(self.w1(x), self.w3(x)))
class TransformerBlock(nn.Module): def __init__(self, config: gLM2Config): super().__init__() self.n_heads = config.heads self.dim = config.dim self.head_dim = config.dim // config.heads self.attention = Attention(config) self.feed_forward = FeedForward( dim=config.dim, hidden_dim=4 * config.dim, multiple_of=config.swiglu_multiple_of, ffn_dim_multiplier=config.ffn_dim_multiplier, ) self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps) self.ffn_norm = RMSNorm(config.dim, eps=config.norm_eps)
def forward( self, x: torch.Tensor, cu_seqlens: Optional[torch.Tensor] = None, max_seq_len: Optional[torch.Tensor] = None, ) -> torch.Tensor: r = self.attention( self.attention_norm(x), cu_seqlens, max_seq_len ) h = x + r r = self.feed_forward(self.ffn_norm(h)) out = h + r return out
class TransformerLayers(nn.Module): def __init__(self, config: gLM2Config): super().__init__() self.config = config self.layers = torch.nn.ModuleList( [TransformerBlock(config=config) for _ in range(config.depth)] ) self.apply(self._init_weights) # Apply special scaled init to the residual projections, per GPT-2 paper. # Weight w2 is output of FeedForward. Weight wo is output of Attention. for pn, p in self.named_parameters(): if pn.endswith('w2.weight') or pn.endswith('wo.weight'): torch.nn.init.normal_( p, mean=0.0, std=0.02/math.sqrt(2 * self.config.depth))
def _init_weights(self, module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: torch.nn.init.zeros_(module.bias)
def forward( self, x: torch.FloatTensor, attention_mask: Optional[torch.BoolTensor] = None, return_all_hiddens: bool = False, ): if x.shape[-1] != self.config.dim: raise ValueError( f"Input feature dim should be {self.config.dim}, but input has shape {x.shape}" ) batch_size, seq_len = x.shape[:2] should_unpad = attention_mask is not None and not attention_mask.all() if should_unpad: x, indices, cu_seqlens, max_seq_len_in_batch = unpad_input( x, attention_mask ) else: indices, cu_seqlens, max_seq_len_in_batch = None, None, None hiddens = [] for layer in self.layers: x = layer(x, cu_seqlens, max_seq_len_in_batch) if return_all_hiddens: hiddens.append(x)
if should_unpad: x = pad_input(x, indices, batch_size, seq_len) if return_all_hiddens: hiddens = [pad_input(h, indices, batch_size, seq_len) for h in hiddens]
if return_all_hiddens: return x, hiddens return x
class gLM2PreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = gLM2Config base_model_prefix = "glm2" supports_gradient_checkpointing = False
# https://github.com/huggingface/transformers/blob/7032e0203262ebb2ebf55da8d2e01f873973e835/src/transformers/models/bert/modeling_bert.py#L748 def _init_weights(module, initializer_range=0.02): if isinstance(module, nn.Linear): nn.init.normal_(module.weight, std=initializer_range) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, std=initializer_range) if module.padding_idx is not None: nn.init.zeros_(module.weight[module.padding_idx])
class gLM2Model(gLM2PreTrainedModel): """gLM2 Model."""
def __init__(self, config: gLM2Config): super().__init__(config) self.config = config
self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim) self._init_weights(self.tok_embeddings) self.encoder = TransformerLayers(config)
def _init_weights(self, module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: torch.nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def get_input_embeddings(self): return self.tok_embeddings
def set_input_embeddings(self, value): self.tok_embeddings = value
def forward( self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple[torch.Tensor], BaseModelOutput]: output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
h = self.tok_embeddings(input_ids) if output_hidden_states: sequence_output, all_hidden_states = self.encoder( h, attention_mask, return_all_hiddens=True) else: sequence_output = self.encoder(h, attention_mask) all_hidden_states = None
if not return_dict: return (sequence_output, all_hidden_states)
return BaseModelOutput( last_hidden_state=sequence_output, hidden_states=all_hidden_states,
)
class gLM2ForMaskedLM(gLM2PreTrainedModel):
def __init__(self, config: gLM2Config): super().__init__(config)
self.glm2 = gLM2Model(config) self.lm_head = gLM2LMHead(config) self._init_weights(self.lm_head)
def _init_weights(self, module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: torch.nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def get_output_embeddings(self): return self.lm_head.proj_output
def set_output_embeddings(self, value): self.lm_head.proj_output = value
def forward( self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.LongTensor] = None, output_hidden_states: Optional[bool] = None, mask_prob: Optional[torch.Tensor] = None, reweight_loss: Optional[bool] = False, return_dict: Optional[bool] = None, ) -> Union[Tuple, MaskedLMOutput]: return_dict = return_dict if return_dict is not None else self.config.use_return_dict if attention_mask is not None: attention_mask = attention_mask.bool() outputs = self.glm2( input_ids, attention_mask=attention_mask, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] prediction_scores = self.lm_head(sequence_output)
masked_lm_loss = None
if labels is not None: if reweight_loss: assert mask_prob is not None loss_fct = CrossEntropyLoss(reduction='none') labels = labels.to(prediction_scores.device) masked_lm_loss = loss_fct( prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) mask_prob = mask_prob.to(masked_lm_loss.device) # Reshape loss to [batch, seq_len] to match mask_prob shape masked_lm_loss = masked_lm_loss.view(prediction_scores.size(0), -1) # Weight each example loss by 1-t masked_lm_loss = masked_lm_loss * (1.0 - mask_prob + 1e-3) masked_lm_loss = masked_lm_loss.sum() / (labels != -100).sum()
else: loss_fct = CrossEntropyLoss() labels = labels.to(prediction_scores.device) masked_lm_loss = loss_fct( prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict: output = (prediction_scores,) + outputs[2:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
class gLM2LMHead(nn.Module): """gLM2 head for masked language modeling."""
def __init__(self, config): super().__init__()
self.norm = RMSNorm(config.dim, eps=config.norm_eps) self.proj_output = nn.Linear( config.dim, config.vocab_size, bias=False)
def forward(self, features): return self.proj_output(self.norm(features))README.mdAdded+199
config.jsonAdded+21
configuration_glm2.pyAdded+38
model.safetensorsAdded+3
modeling_glm2.pyAdded+595