DataChem commited on
Commit
5102dda
·
verified ·
1 Parent(s): 6ebc598

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -16
app.py CHANGED
@@ -1,7 +1,8 @@
1
  from fastapi import FastAPI, Request
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
  from fastapi.responses import StreamingResponse
 
4
  import torch
 
5
 
6
  app = FastAPI()
7
 
@@ -9,6 +10,8 @@ app = FastAPI()
9
  model_name = "EleutherAI/gpt-neo-1.3B" # Replace with your desired model
10
  tokenizer = AutoTokenizer.from_pretrained(model_name)
11
  model = AutoModelForCausalLM.from_pretrained(model_name)
 
 
12
 
13
  @app.get("/")
14
  def read_root():
@@ -22,22 +25,49 @@ async def predict(request: Request):
22
  return {"error": "Prompt is required"}
23
 
24
  # Tokenize the input
25
- inputs = tokenizer(prompt, return_tensors="pt").to("cpu") # Use "cuda" if GPU is enabled
 
 
26
 
27
  # Generator function to stream tokens
28
  def token_generator():
29
- outputs = model.generate(
30
- inputs.input_ids,
31
- max_length=100,
32
- do_sample=True,
33
- num_return_sequences=1,
34
- temperature=0.7,
35
- top_p=0.9,
36
- repetition_penalty=1.2,
37
- )
38
- for token_id in outputs[0]:
39
- token = tokenizer.decode(token_id, skip_special_tokens=True)
40
- yield f"{token} "
41
-
42
- # Return StreamingResponse
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  return StreamingResponse(token_generator(), media_type="text/plain")
 
1
  from fastapi import FastAPI, Request
 
2
  from fastapi.responses import StreamingResponse
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import torch
5
+ import torch.nn.functional as F
6
 
7
  app = FastAPI()
8
 
 
10
  model_name = "EleutherAI/gpt-neo-1.3B" # Replace with your desired model
11
  tokenizer = AutoTokenizer.from_pretrained(model_name)
12
  model = AutoModelForCausalLM.from_pretrained(model_name)
13
+ device = "cuda" if torch.cuda.is_available() else "cpu"
14
+ model.to(device)
15
 
16
  @app.get("/")
17
  def read_root():
 
25
  return {"error": "Prompt is required"}
26
 
27
  # Tokenize the input
28
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
29
+ input_ids = inputs.input_ids
30
+ attention_mask = inputs.attention_mask
31
 
32
  # Generator function to stream tokens
33
  def token_generator():
34
+ temperature = 0.7
35
+ top_p = 0.9
36
+
37
+ for _ in range(100): # Limit the number of generated tokens
38
+ # Get the model outputs
39
+ outputs = model(input_ids=input_ids, attention_mask=attention_mask)
40
+ next_token_logits = outputs.logits[:, -1, :] # Logits for the last token
41
+
42
+ # Apply temperature scaling
43
+ next_token_logits = next_token_logits / temperature
44
+
45
+ # Convert logits to probabilities
46
+ next_token_probs = F.softmax(next_token_logits, dim=-1)
47
+
48
+ # Apply top-p nucleus sampling
49
+ sorted_probs, sorted_indices = torch.sort(next_token_probs, descending=True)
50
+ cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
51
+ sorted_probs = sorted_probs[cumulative_probs <= top_p]
52
+ sorted_indices = sorted_indices[:len(sorted_probs)]
53
+
54
+ # Sample from the filtered distribution
55
+ if len(sorted_probs) > 0:
56
+ next_token_id = sorted_indices[torch.multinomial(sorted_probs, 1)]
57
+ else:
58
+ # Fallback to greedy selection if no tokens meet top-p
59
+ next_token_id = torch.argmax(next_token_probs)
60
+
61
+ # Append the generated token to the input
62
+ input_ids = torch.cat([input_ids, next_token_id.unsqueeze(-1)], dim=-1)
63
+
64
+ # Decode the token and yield it
65
+ token = tokenizer.decode(next_token_id.squeeze(), skip_special_tokens=True)
66
+ yield token + " "
67
+
68
+ # Stop if the model generates the end-of-sequence token
69
+ if next_token_id.squeeze().item() == tokenizer.eos_token_id:
70
+ break
71
+
72
+ # Return the generator as a streaming response
73
  return StreamingResponse(token_generator(), media_type="text/plain")