"""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)