Views
No views yet
nvidia/megatron-bert-uncased-345m repository to make BioMegatron available in 🤗.convert_megatron_bert_checkpoint.py needed a modification. The reason is that the Megatron model shown in nvidia/megatron-bert-uncased-345m has included head layers, while the weights of the BioMegatron model that we upload to this repository do not contain a head.convert_megatron_bert_checkpoint.py.1import os
2import torch
3from convert_biomegatron_checkpoint import convert_megatron_checkpoint
4
5print_checkpoint_structure = True
6path_to_checkpoint = "/path/to/BioMegatron345mUncased/"
7
8# Extract the basename.
9basename = os.path.dirname(path_to_checkpoint).split('/')[-1]
10
11# Load the model.
12input_state_dict = torch.load(os.path.join(path_to_checkpoint, 'model_optim_rng.pt'), map_location="cpu")
13
14# Convert.
15print("Converting")
16output_state_dict, output_config = convert_megatron_checkpoint(input_state_dict, head_model=False)
17
18# Print the structure of converted state dict.
19if print_checkpoint_structure:
20 recursive_print(None, output_state_dict)
21
22# Store the config to file.
23output_config_file = os.path.join(path_to_checkpoint, "config.json")
24print(f'Saving config to "{output_config_file}"')
25with open(output_config_file, "w") as f:
26 json.dump(output_config, f)
27
28# Store the state_dict to file.
29output_checkpoint_file = os.path.join(path_to_checkpoint, "pytorch_model.bin")
30print(f'Saving checkpoint to "{output_checkpoint_file}"')
31torch.save(output_state_dict, output_checkpoint_file)
32nvidia/megatron-bert-uncased-345m.1import os
2import torch
3
4from transformers import BertTokenizer, MegatronBertForMaskedLM, AutoModelForMaskedLM
5checkpoint = "EMBO/BioMegatron345mUncased"
6
7# The tokenizer. Megatron was trained with standard tokenizer(s).
8tokenizer = BertTokenizer.from_pretrained(checkpoint)
9# Load the model from $MYDIR/nvidia/megatron-bert-uncased-345m.
10model = AutoModelForMaskedLM.from_pretrained(checkpoint)
11device = torch.device("cpu")
12# Create inputs (from the BERT example page).
13input = tokenizer("The capital of France is [MASK]", return_tensors="pt").to(device)
14label = tokenizer("The capital of France is Paris", return_tensors="pt")["input_ids"].to(device)
15
16# Run the model.
17with torch.no_grad():
18 output = model(**input, labels=label)
19 print(output)