File size: 2,659 Bytes
dd38d87 | 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 50 51 52 53 54 55 56 57 58 59 60 | """Load EdgeCoder GGUF weights with the Transformers DeBERTa-v2 encoder."""
import gzip
import json
from pathlib import Path
import shutil
from tempfile import TemporaryDirectory
import gguf
import numpy as np
import torch
from transformers import AutoTokenizer, DebertaV2Config, DebertaV2Model
TOKENIZER_FILES = ('config.json', 'tokenizer_config.json', 'spm.model',
'special_tokens_map.json', 'added_tokens.json')
class EdgeCoderWeights:
def __init__(self, path):
reader = gguf.GGUFReader(path)
self.reader = reader
if reader.fields['general.architecture'].contents() != 'deberta-v2':
raise ValueError('Expected an EdgeCoder DeBERTa-v2 GGUF')
self.config = json.loads(reader.fields['edgecoder.config.json'].contents())
self.shapes = json.loads(reader.fields['edgecoder.tensor_shapes'].contents())
prefix = reader.fields.get('edgecoder.encoder_prefix')
self.prefix = prefix.contents() if prefix else ''
self.tensors = {tensor.name: tensor for tensor in reader.tensors}
if len(self.tensors) != len(reader.tensors) or self.tensors.keys() != self.shapes.keys():
raise ValueError('Unexpected GGUF tensor inventory')
def tensor(self, name, dtype=torch.bfloat16):
tensor = self.tensors[name]
if tensor.tensor_type == gguf.GGMLQuantizationType.BF16:
value = torch.from_numpy(np.array(tensor.data).view(np.int16)).view(torch.bfloat16)
else:
value = torch.from_numpy(gguf.quants.dequantize(tensor.data, tensor.tensor_type))
return value.reshape(self.shapes[name]).to(dtype=dtype)
def load_encoder(path, device='cpu', dtype=torch.float32):
"""Restore the encoder from a GGUF file and return it in evaluation mode."""
weights = EdgeCoderWeights(path)
model = DebertaV2Model(DebertaV2Config.from_dict(weights.config))
state = {name: weights.tensor(weights.prefix + name, dtype) for name in model.state_dict()}
model.load_state_dict(state, strict=True, assign=True)
return model.to(device=device, dtype=dtype).eval()
def load_tokenizer(directory):
"""Load the source tokenizer packaged beside the GGUF model files."""
directory = Path(directory)
with TemporaryDirectory() as temp:
temp = Path(temp)
for name in TOKENIZER_FILES:
shutil.copyfile(directory / name, temp / name)
with gzip.open(directory / 'tokenizer.json.gz', 'rb') as compressed, (temp / 'tokenizer.json').open('wb') as raw:
shutil.copyfileobj(compressed, raw)
return AutoTokenizer.from_pretrained(temp, local_files_only=True)
|