Repository navigation
Expand file tree
/
Copy pathdownloadweights.py
More file actions
49 lines (38 loc) · 1.67 KB
/
Copy pathdownloadweights.py
File metadata and controls
49 lines (38 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import shutil
print("importing pytorch...")
import torch
print("importing huggingface modules...")
from huggingface_hub import hf_hub_download, snapshot_download
from safetensors.torch import save_file
from transformers import T5EncoderModel
class XTR(torch.nn.Module):
def __init__(self):
super().__init__()
encoder_model = T5EncoderModel.from_pretrained(
"google/xtr-base-en",
use_safetensors=True,
)
self.encoder = encoder_model.encoder
self.linear = torch.nn.Linear(768, 128, bias=False)
to_dense_path = hf_hub_download(
repo_id="google/xtr-base-en",
filename="2_Dense/pytorch_model.bin",
)
state = torch.load(to_dense_path, map_location="cpu", weights_only=True)
self.linear.load_state_dict({"weight": state["linear.weight"]})
def forward(self, input_ids):
encoder_output = self.encoder(input_ids)
hidden_states = encoder_output.last_hidden_state if hasattr(encoder_output, 'last_hidden_state') else encoder_output[0]
return self.linear(hidden_states)
print("downloading pretrained XTR model...")
snapshot_download(repo_id="google/xtr-base-en", local_dir="xtr-base-en",
local_dir_use_symlinks=False, revision="main")
print("loading model...")
xtr = XTR()
fp16_state_dict = {k: v.half().cpu() for k, v in xtr.state_dict().items()}
print("writing as .safetensors...")
save_file(fp16_state_dict, "xtr.safetensors")
print(f"Saved xtr.safetensors with {len(fp16_state_dict)} tensors")
shutil.copy("xtr-base-en/config.json", "assets/xtr-config.json")
shutil.copy("xtr-base-en/tokenizer.json", "assets/xtr-tokenizer.json")