Create handler.py
Browse files- handler.py +91 -0
handler.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from typing import Dict, List, Any
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from transformers import GPT2LMHeadModel, GPT2Config, GPT2Tokenizer, PreTrainedModel
|
| 5 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
# # get dtype
|
| 10 |
+
# dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] == 8 else torch.float16
|
| 11 |
+
|
| 12 |
+
class CustomGPT2Model(PreTrainedModel):
|
| 13 |
+
def __init__(self, config):
|
| 14 |
+
super(CustomGPT2Model, self).__init__(config)
|
| 15 |
+
|
| 16 |
+
self.gpt2 = GPT2LMHeadModel.from_pretrained('gpt2-medium')
|
| 17 |
+
# Create an MLP layer to transform the ada-002 embedding to the GPT-2 hidden size
|
| 18 |
+
self.mlp = nn.Sequential(
|
| 19 |
+
nn.Linear(1536, 768), # Adjust the hidden layer size as necessary
|
| 20 |
+
nn.ReLU(),
|
| 21 |
+
nn.Linear(768, config.n_embd) # Adjust the output size to match GPT-2 embedding size
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def forward(self, inputs=None, ada_embedding=None, decoded_tkns=None, labels=None):
|
| 27 |
+
emb = self.mlp(ada_embedding)
|
| 28 |
+
emb = emb.unsqueeze(1)
|
| 29 |
+
|
| 30 |
+
if decoded_tkns is not None:
|
| 31 |
+
# Add the "encoded:" prefix, ada-002 embedding, "decoded:" prefix, and the decoded token
|
| 32 |
+
decoded_tkns = torch.cat([emb, self.gpt2.transformer.wte(decoded_tkns)], dim=1)
|
| 33 |
+
else:
|
| 34 |
+
decoded_tkns = emb
|
| 35 |
+
|
| 36 |
+
# Create the position ids
|
| 37 |
+
position_ids = torch.arange(0, decoded_tkns.size(1), dtype=torch.long).unsqueeze(0).to(emb.device)
|
| 38 |
+
# Forward the embeddings through the GPT-2 model with the correct position ids
|
| 39 |
+
outputs = self.gpt2(inputs_embeds=decoded_tkns, position_ids=position_ids)
|
| 40 |
+
logits = outputs.logits
|
| 41 |
+
|
| 42 |
+
loss = None
|
| 43 |
+
if labels is not None:
|
| 44 |
+
loss_fct = CrossEntropyLoss()
|
| 45 |
+
loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
|
| 46 |
+
|
| 47 |
+
return CausalLMOutput(loss, logits, outputs.hidden_states)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class EndpointHandler:
|
| 51 |
+
def __init__(self, path=""):
|
| 52 |
+
# load the model
|
| 53 |
+
# Load the GPT-2 configuration
|
| 54 |
+
self.config = GPT2Config.from_pretrained('gpt2-medium')
|
| 55 |
+
|
| 56 |
+
# Create the custom GPT-2 model and load the trained weights
|
| 57 |
+
self.model = CustomGPT2Model.from_pretrained(path, config=self.config)
|
| 58 |
+
|
| 59 |
+
# Load the tokenizer
|
| 60 |
+
self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2-medium')
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
|
| 64 |
+
embedding = data.pop("embedding", None)
|
| 65 |
+
max_length=200
|
| 66 |
+
with torch.no_grad():
|
| 67 |
+
outputs = self.model(ada_embedding=embedding, decoded_tkns=None)
|
| 68 |
+
decoded_tkns = outputs.logits.argmax(dim=-1)
|
| 69 |
+
|
| 70 |
+
for _ in range(max_length):
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
outputs = self.model(ada_embedding=embedding, decoded_tkns=decoded_tkns)
|
| 73 |
+
|
| 74 |
+
# Get the most likely next token, sampled from top k
|
| 75 |
+
logits = outputs.logits[:, -1]
|
| 76 |
+
top_k_logits, top_k_indices = torch.topk(logits, k = 5)
|
| 77 |
+
next_token = torch.multinomial(F.softmax(top_k_logits, dim=-1), num_samples=1)
|
| 78 |
+
next_token = top_k_indices.gather(dim=1, index=next_token)
|
| 79 |
+
|
| 80 |
+
if next_token[0].item() == self.tokenizer.eos_token_id:
|
| 81 |
+
break
|
| 82 |
+
|
| 83 |
+
decoded_tkns = torch.cat((decoded_tkns, next_token), dim=1)
|
| 84 |
+
|
| 85 |
+
# Convert the tensor of token IDs to a list of token IDs
|
| 86 |
+
token_ids = decoded_tkns[0].cpu().numpy().tolist()
|
| 87 |
+
|
| 88 |
+
# Decode the token IDs back to a string
|
| 89 |
+
output_text = self.tokenizer.decode(token_ids, skip_special_tokens=True)
|
| 90 |
+
|
| 91 |
+
return output_text
|