Really-Amazing commited on
Commit
9f13c9d
·
verified ·
1 Parent(s): b6bf288

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -25
app.py CHANGED
@@ -9,23 +9,20 @@ MODEL_PATH = "model_000971.pt"
9
  print("Waking up the toddler (NanoChat-ClimbMix-D12)...")
10
  tokenizer = get_tokenizer()
11
 
12
- print("Creating GPT model skeleton with exact local config...")
13
- # EXACT values from your local scripts.chat_web output:
14
- # {'sequence_len': 2048, 'vocab_size': 32768, 'n_layer': 12, 'n_head': 6, 'n_kv_head': 6, 'n_embd': 768}
15
  config = GPTConfig(
16
  vocab_size=32768,
17
  n_layer=12,
18
- n_head=6, # Critical fix
19
- n_kv_head=6, # Critical fix
20
  n_embd=768,
21
- sequence_len=2048, # Updated from 1024
22
  )
23
 
24
  model = GPT(config)
25
 
26
  print("Loading weights...")
27
  state_dict = torch.load(MODEL_PATH, map_location="cpu", weights_only=False)
28
-
29
  unwanted_prefix = '_orig_mod.'
30
  for k in list(state_dict.keys()):
31
  if k.startswith(unwanted_prefix):
@@ -38,22 +35,26 @@ print("Model ready!")
38
 
39
  engine = Engine(model=model, tokenizer=tokenizer)
40
 
 
 
 
 
 
 
 
 
41
  def chat_fn(message, history):
42
  try:
43
- # 1. Build prompt and FORCE everything to be a flat list of integers
44
  prompt_tokens = []
45
 
46
  for user_msg, assistant_msg in history:
47
- # We wrap in list() to kill any generator objects returned by tokenizer
48
- prompt_tokens.extend(list(tokenizer.encode(f"<|user|>{user_msg}<|end|>")))
49
  if assistant_msg:
50
- prompt_tokens.extend(list(tokenizer.encode(f"<|assistant|>{assistant_msg}<|end|>")))
51
 
52
- # Current message
53
- prompt_tokens.extend(list(tokenizer.encode(f"<|user|>{message}<|end|><|assistant|>")))
54
 
55
- # 2. Generate (Blocking)
56
- # Note: We pass prompt_tokens which is now guaranteed to be a List[int]
57
  new_tokens = engine.generate(
58
  prompt_tokens,
59
  max_tokens=512,
@@ -61,13 +62,14 @@ def chat_fn(message, history):
61
  top_k=50,
62
  )
63
 
64
- # 3. Handle the output (ensure it's a list for decoding)
65
  if hasattr(new_tokens, 'tolist'):
66
  new_tokens = new_tokens.tolist()
67
-
 
 
68
  response = tokenizer.decode(list(new_tokens)).strip()
69
 
70
- # 4. Clean up the tags
71
  for stop_tag in ["<|end|>", "<|assistant_end|>", "<|EOS|>"]:
72
  if stop_tag in response:
73
  response = response.split(stop_tag)[0].strip()
@@ -75,18 +77,14 @@ def chat_fn(message, history):
75
  return response or "Toddler is thinking... 😅"
76
 
77
  except Exception as e:
78
- # If it still fails, this will tell us exactly which line crashed
79
- import traceback
80
- print(traceback.format_exc())
81
  return f"Toddler tantrum: {str(e)}"
82
 
83
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
84
- gr.Markdown("# 🧸 NanoChat-ClimbMix-D12 – Confident Toddler")
85
- gr.Markdown("Architecture: 12 Layers, 6 Heads (Verified). Fixed Sequence/Generator error.")
86
-
87
  gr.ChatInterface(
88
  fn=chat_fn,
89
- examples=["Tell me a joke", "What is UPI?", "Explain QA automation"],
90
  title="Chat with the Toddler"
91
  )
92
 
 
9
  print("Waking up the toddler (NanoChat-ClimbMix-D12)...")
10
  tokenizer = get_tokenizer()
11
 
12
+ # EXACT values from your local scripts.chat_web output
 
 
13
  config = GPTConfig(
14
  vocab_size=32768,
15
  n_layer=12,
16
+ n_head=6,
17
+ n_kv_head=6,
18
  n_embd=768,
19
+ sequence_len=2048,
20
  )
21
 
22
  model = GPT(config)
23
 
24
  print("Loading weights...")
25
  state_dict = torch.load(MODEL_PATH, map_location="cpu", weights_only=False)
 
26
  unwanted_prefix = '_orig_mod.'
27
  for k in list(state_dict.keys()):
28
  if k.startswith(unwanted_prefix):
 
35
 
36
  engine = Engine(model=model, tokenizer=tokenizer)
37
 
38
+ def safe_encode(text):
39
+ """Helper to ensure we only get the list of token IDs."""
40
+ encoded = tokenizer.encode(text)
41
+ # If it's a tuple (ids, mask), just take the ids
42
+ if isinstance(encoded, tuple):
43
+ return list(encoded[0])
44
+ return list(encoded)
45
+
46
  def chat_fn(message, history):
47
  try:
 
48
  prompt_tokens = []
49
 
50
  for user_msg, assistant_msg in history:
51
+ prompt_tokens.extend(safe_encode(f"<|user|>{user_msg}<|end|>"))
 
52
  if assistant_msg:
53
+ prompt_tokens.extend(safe_encode(f"<|assistant|>{assistant_msg}<|end|>"))
54
 
55
+ prompt_tokens.extend(safe_encode(f"<|user|>{message}<|end|><|assistant|>"))
 
56
 
57
+ # Blocking generation
 
58
  new_tokens = engine.generate(
59
  prompt_tokens,
60
  max_tokens=512,
 
62
  top_k=50,
63
  )
64
 
65
+ # Convert output to list if it's a tensor or tuple
66
  if hasattr(new_tokens, 'tolist'):
67
  new_tokens = new_tokens.tolist()
68
+ elif isinstance(new_tokens, tuple):
69
+ new_tokens = new_tokens[0]
70
+
71
  response = tokenizer.decode(list(new_tokens)).strip()
72
 
 
73
  for stop_tag in ["<|end|>", "<|assistant_end|>", "<|EOS|>"]:
74
  if stop_tag in response:
75
  response = response.split(stop_tag)[0].strip()
 
77
  return response or "Toddler is thinking... 😅"
78
 
79
  except Exception as e:
 
 
 
80
  return f"Toddler tantrum: {str(e)}"
81
 
82
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
83
+ gr.Markdown("# 🧸 NanoChat-ClimbMix-D12")
84
+ gr.Markdown("Architecture verified. Tuple/Generator issues handled.")
 
85
  gr.ChatInterface(
86
  fn=chat_fn,
87
+ examples=["Tell me a joke", "What is UPI?"],
88
  title="Chat with the Toddler"
89
  )
90