Fill-Mask
Transformers
PyTorch
Norwegian
Norwegian Bokmål
Norwegian Nynorsk
BERT
NorBERT
Norwegian
encoder
custom_code
Run this model with HF Jobs
Run ltg/norbert3-base 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/ltg/norbert3-base. 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/ltg/norbert3-base 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 ltg/norbert3-base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ltg/norbert3-base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="ltg/norbert3-base", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("ltg/norbert3-base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Fix compatibility with transformers v5
Browse files21 unmodified lines222324252627282930313286 unmodified lines11912012112212312412512612712812910 unmodified lines14014114214314414514614714814915015115269 unmodified lines2222232242252262272 unmodified lines2302312322332342352362372382392402412422432446 unmodified lines25125225325425525658 unmodified lines31531631731831932032132232332432532632732832933055 unmodified lines38638738838939039139239339439539639739852 unmodified lines45145245345445545645745845946046146246334 unmodified lines49849950050150250350450550650750850951054 unmodified lines56556656756856957057157257357457557657721 unmodified linesdef __init__(self, config, activation_checkpointing=False):super().__init__()self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])for i, layer in enumerate(self.layers):layer.mlp.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))layer.mlp.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))self.activation_checkpointing = activation_checkpointingdef forward(self, hidden_states, attention_mask, relative_embedding):86 unmodified linesself.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \- torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)position_indices = config.position_bucket_size - 1 + position_indicesself.register_buffer("position_indices", position_indices.contiguous(), persistent=False)self.dropout = nn.Dropout(config.attention_probs_dropout_prob)self.scale = 1.0 / math.sqrt(3 * self.head_size)10 unmodified linesbatch_size, key_len, _ = hidden_states.size()query_len = key_len# Recompute position_indices if sequence length exceeds the precomputed sizeif self.position_indices.size(0) < query_len:position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \- torch.arange(query_len, dtype=torch.long).unsqueeze(0)position_indices = self.make_log_bucket_position(position_indices, self.config.position_bucket_size, 512)position_indices = self.config.position_bucket_size - 1 + position_indicesself.position_indices = position_indices.to(hidden_states.device)# Pre-LN and project query/key/value.hidden_states = self.pre_layer_norm(hidden_states) # shape: [B, T, D]69 unmodified linesconfig_class = NorbertConfigbase_model_prefix = "norbert3"supports_gradient_checkpointing = Truedef _set_gradient_checkpointing(self, module, value=False):if isinstance(module, Encoder):2 unmodified linesdef _init_weights(self, module):std = math.sqrt(2.0 / (5.0 * self.hidden_size))if isinstance(module, nn.Linear):nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)if module.bias is not None:module.bias.data.zero_()elif isinstance(module, nn.Embedding):nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)elif isinstance(module, nn.LayerNorm):module.bias.data.zero_()module.weight.data.fill_(1.0)class NorbertModel(NorbertPreTrainedModel):6 unmodified linesself.transformer = Encoder(config, activation_checkpointing=gradient_checkpointing)self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else Nonedef get_input_embeddings(self):return self.embedding.word_embedding58 unmodified linesclass NorbertForMaskedLM(NorbertModel):_keys_to_ignore_on_load_unexpected = ["head"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=True, **kwargs)def get_output_embeddings(self):return self.classifier.nonlinearity[-1].weightdef set_output_embeddings(self, new_embeddings):self.classifier.nonlinearity[-1].weight = new_embeddingsdef forward(self,55 unmodified linesclass NorbertForSequenceClassification(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = config.num_labelsself.head = Classifier(config, self.num_labels)def forward(self,52 unmodified linesclass NorbertForTokenClassification(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = config.num_labelsself.head = Classifier(config, self.num_labels)def forward(self,34 unmodified linesclass NorbertForQuestionAnswering(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = config.num_labelsself.head = Classifier(config, self.num_labels)def forward(self,54 unmodified linesclass NorbertForMultipleChoice(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = getattr(config, "num_labels", 2)self.head = Classifier(config, self.num_labels)def forward(self,21 unmodified lines22232425262786 unmodified lines11411511611711811912010 unmodified lines13113213313413513613713813914014114214314469 unmodified lines2142152162172182192202212 unmodified lines2242252262272282292302312322332342356 unmodified lines24224324424524624724824958 unmodified lines30830931031131231331431531631731831932032132232332432555 unmodified lines38138238338438538638738838939039139239339452 unmodified lines44744844945045145245345445545645745845946034 unmodified lines49549649749849950050150250350450550650750854 unmodified lines56356456556656756856957057157257357457557621 unmodified linesdef __init__(self, config, activation_checkpointing=False):super().__init__()self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.num_hidden_layers)])self.activation_checkpointing = activation_checkpointingdef forward(self, hidden_states, attention_mask, relative_embedding):86 unmodified linesself.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)self.position_indices = Noneself.dropout = nn.Dropout(config.attention_probs_dropout_prob)self.scale = 1.0 / math.sqrt(3 * self.head_size)10 unmodified linesbatch_size, key_len, _ = hidden_states.size()query_len = key_len# Recompute position_indices at the beginning or if sequence length exceeds the precomputed sizeif self.position_indices is None or self.position_indices.size(0) < query_len:self.position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \- torch.arange(query_len, dtype=torch.long).unsqueeze(0)self.position_indices = self.make_log_bucket_position(self.position_indices, self.config.position_bucket_size, 512)self.position_indices = self.config.position_bucket_size - 1 + self.position_indicesif self.position_indices.device != hidden_states.device:self.position_indices = self.position_indices.to(hidden_states.device)# Pre-LN and project query/key/value.hidden_states = self.pre_layer_norm(hidden_states) # shape: [B, T, D]69 unmodified linesconfig_class = NorbertConfigbase_model_prefix = "norbert3"supports_gradient_checkpointing = True_tied_weights_keys = {}_keys_to_ignore_on_load_unexpected = [r".*position_indices.*"]def _set_gradient_checkpointing(self, module, value=False):if isinstance(module, Encoder):2 unmodified linesdef _init_weights(self, module):std = math.sqrt(2.0 / (5.0 * self.hidden_size))if isinstance(module, nn.Linear) or isinstance(module, nn.Embedding):nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-2*std, b=2*std)elif isinstance(module, nn.LayerNorm) and module.weight is not None:module.weight.fill_(1.0)if hasattr(module, "bias") and module.bias is not None:module.bias.zero_()class NorbertModel(NorbertPreTrainedModel):6 unmodified linesself.transformer = Encoder(config, activation_checkpointing=gradient_checkpointing)self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else Noneself.post_init()def get_input_embeddings(self):return self.embedding.word_embedding58 unmodified linesclass NorbertForMaskedLM(NorbertModel):_keys_to_ignore_on_load_unexpected = ["head", r".*position_indices.*"]_tied_weights_keys = {"classifier.nonlinearity.5.weight": "embedding.word_embedding.weight"}def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=True, **kwargs)self.post_init()def get_output_embeddings(self):return self.classifier.nonlinearity[-1]def set_output_embeddings(self, new_embeddings):self.classifier.nonlinearity[-1] = new_embeddingsdef forward(self,55 unmodified linesclass NorbertForSequenceClassification(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = config.num_labelsself.head = Classifier(config, self.num_labels)self.post_init()def forward(self,52 unmodified linesclass NorbertForTokenClassification(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = config.num_labelsself.head = Classifier(config, self.num_labels)self.post_init()def forward(self,34 unmodified linesclass NorbertForQuestionAnswering(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = config.num_labelsself.head = Classifier(config, self.num_labels)self.post_init()def forward(self,54 unmodified linesclass NorbertForMultipleChoice(NorbertModel):_keys_to_ignore_on_load_unexpected = ["classifier", r".*position_indices.*"]def __init__(self, config, **kwargs):super().__init__(config, add_mlm_layer=False, **kwargs)self.num_labels = getattr(config, "num_labels", 2)self.head = Classifier(config, self.num_labels)self.post_init()def forward(self,
modeling_norbert.py+31-32