SeaWolf-AI commited on
Commit
7421815
·
verified ·
1 Parent(s): 6ea129e

fix: unwrap BatchEncoding from apply_chat_template before generate()

Browse files
Files changed (1) hide show
  1. app.py +15 -3
app.py CHANGED
@@ -98,11 +98,23 @@ class GenReq(BaseModel):
98
  def _prep(req: "GenReq"):
99
  tok, model, dev = _state["tok"], _state["model"], _state["device"]
100
  prompt = (req.prompt or "").strip()[:4000]
 
101
  try: # use the instruct chat template when available
102
- ids = tok.apply_chat_template([{"role": "user", "content": prompt}],
103
- add_generation_prompt=True, return_tensors="pt").to(dev)
 
 
 
 
 
 
 
 
104
  except Exception:
105
- ids = tok(prompt, return_tensors="pt").input_ids.to(dev) # batch_size = 1 ONLY
 
 
 
106
  temp = float(req.temperature if req.temperature is not None else 0.7)
107
  gen = dict(
108
  max_new_tokens=min(int(req.max_new_tokens or MAX_NEW), MAX_NEW),
 
98
  def _prep(req: "GenReq"):
99
  tok, model, dev = _state["tok"], _state["model"], _state["device"]
100
  prompt = (req.prompt or "").strip()[:4000]
101
+ ids = None
102
  try: # use the instruct chat template when available
103
+ enc = tok.apply_chat_template([{"role": "user", "content": prompt}],
104
+ add_generation_prompt=True, return_tensors="pt")
105
+ # Transformers 5.x may hand back a BatchEncoding rather than a bare tensor. Passing that
106
+ # into generate() dies on `inputs_tensor.shape[0]`, so always unwrap to the tensor.
107
+ if hasattr(enc, "input_ids"):
108
+ ids = enc.input_ids
109
+ elif isinstance(enc, dict):
110
+ ids = enc["input_ids"]
111
+ else:
112
+ ids = enc
113
  except Exception:
114
+ ids = None
115
+ if ids is None or not hasattr(ids, "shape"):
116
+ ids = tok(prompt, return_tensors="pt").input_ids
117
+ ids = ids.to(dev) # batch_size = 1 ONLY
118
  temp = float(req.temperature if req.temperature is not None else 0.7)
119
  gen = dict(
120
  max_new_tokens=min(int(req.max_new_tokens or MAX_NEW), MAX_NEW),