#!/usr/bin/env python3 """NeuroFlow 完整推理 — 加载 NF + LM Head + Tokenizer""" import struct, json, numpy as np, time, sys, math # ═══════════════════════════════════════════════════════════ # 模型加载 # ═══════════════════════════════════════════════════════════ def load_nfv1(path): """加载 NFv1 格式权重 (NeuroFlowModel)""" weights = {} with open(path, 'rb') as f: assert f.read(4) == b'NFv1', f"Bad magic in {path}" while True: nl = struct.unpack(' 1 and candidate not in prefix_set: continue if best_token is not None: ids.append(vocab[best_token]) i = best_end else: ch = text[i] byte_len = 1 if ord(ch) >= 0x80: if ord(ch) < 0xE0: byte_len = 2 elif ord(ch) < 0xF0: byte_len = 3 else: byte_len = 4 byte_seq = text[i:i + byte_len] bpe_result = apply_bpe(byte_seq, merge_ranks) if bpe_result in vocab: ids.append(vocab[bpe_result]) else: for c in bpe_result: ids.append(vocab.get(c, 1)) i += byte_len ids.append(3) return ids def decode(ids, id2token): parts = [] for tid in ids: if tid in (0, 1, 2, 3): continue if tid in id2token: t = id2token[tid] if not t.startswith(' 0.01: logits = logits / temp # Top-K filter if 0 < top_k < len(logits): topk_indices = np.argpartition(logits, -top_k)[-top_k:] mask = np.full(len(logits), -np.inf, dtype=np.float32) mask[topk_indices] = logits[topk_indices] logits = mask probs = softmax(logits) next_id = int(rng.choice(len(probs), p=probs)) if next_id == 3: break # eos generated.append(next_id) ids.append(next_id) if step < 5: tok = id2token.get(next_id, f'<{next_id}>') print(f" [{step}] id={next_id} '{tok}' p={probs[next_id]:.4f}") return decode(generated, id2token) # ═══════════════════════════════════════════════════════════ # Main # ═══════════════════════════════════════════════════════════ if __name__ == '__main__': CKPT_DIR = '/home/administrator/output_final2/checkpoint_step5000' NF_MODEL = f'{CKPT_DIR}/checkpoint_step5000/model.nfv1' LM_MODEL = f'{CKPT_DIR}/lm_head.nfv1' TOKENIZER = '/mnt/d/neuroflow-C++/configs/tokenizer_128k.json' print("⏳ 加载模型...") t0 = time.time() nf_w = load_nfv1(NF_MODEL) lm_w = load_lmh1(LM_MODEL) print(f"✅ NF: {len(nf_w)}层 | LM: {len(lm_w)}层 ({time.time()-t0:.1f}s)") vocab, id2token, merge_ranks = load_tokenizer(TOKENIZER) print(f"✅ 词表: {len(vocab)} tokens") d_model = nf_w['input_proj.weight'].shape[1] # in_features hidden_dim = nf_w['input_proj.weight'].shape[0] # out_features print(f" d_model={d_model} hidden_dim={hidden_dim}") print("\n" + "=" * 60) print("🧪 NeuroFlow 推理测试 (Step 5000)") print("=" * 60) # 测试1 print("\n📝 贪心解码") for prompt in ["人工智能", "中国", "数学"]: r = generate(prompt, nf_w, lm_w, vocab, id2token, merge_ranks, max_tokens=15, temp=0.01, top_k=1, seed=42) print(f" '{prompt}' → '{r}'") # 测试2 print("\n📝 温度采样 (temp=0.8, top_k=40)") for prompt in ["哲学", "科学", "文化"]: r = generate(prompt, nf_w, lm_w, vocab, id2token, merge_ranks, max_tokens=20, temp=0.8, top_k=40, seed=123) print(f" '{prompt}' → '{r}'") # 测试3: 完整生成 print("\n📝 长文本生成") r = generate("人工智能是", nf_w, lm_w, vocab, id2token, merge_ranks, max_tokens=50, temp=0.7, top_k=50, seed=42) print(f" 结果: '{r}'") # 测试4: Logits 分析 print("\n📊 Logits 分析") ids = encode("中", vocab, merge_ranks) logits = neuroflow_full_forward(ids[-d_model:], nf_w, lm_w) probs = softmax(logits / 0.8) top10 = np.argsort(probs)[-10:][::-1] print(" Top-10 预测:") for idx in top10: tok = id2token.get(int(idx), f'') print(f" id={idx:6d} {repr(tok):15s} p={probs[idx]:.4f}") print(f"\n✅ 测试完成")