File size: 5,505 Bytes
5477c5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<!DOCTYPE html>
<html>
<head>
  <title>ONNX WebGPU Test</title>
  <script type="module">
    import { pipeline, TextStreamer } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.0.0-next.8/dist/transformers.min.js';

    const log = (msg) => {
      console.log(msg);
      document.getElementById('log').textContent += msg + '\n';
    };

    const MODELS = {
      reference: 'onnx-community/NVIDIA-Nemotron-3-Nano-4B-BF16-ONNX',
      finetuned: 'bobber/lex-interviewer-nemotron-4b-grpo-v12',
    };

    window.runTest = async (modelKey) => {
      const modelId = MODELS[modelKey];
      document.getElementById('log').textContent = '';
      log(`Testing: ${modelId}`);
      log(`Device: webgpu`);

      // Check WebGPU
      if (!navigator.gpu) { log('❌ No WebGPU!'); return; }
      const adapter = await navigator.gpu.requestAdapter();
      log(`GPU: ${adapter ? (adapter.info?.description || adapter.name || 'adapter found') : 'no adapter'}`);

      log('Loading pipeline (this downloads ~2.5GB)...');
      const statusEl = document.getElementById('status');
      statusEl.textContent = 'Downloading model...';

      let gen;
      try {
        gen = await pipeline('text-generation', modelId, {
          dtype: 'q4',
          device: 'webgpu',
          progress_callback: (p) => {
            if (p.status === 'progress') {
              const pct = Math.round((p.loaded / p.total) * 100);
              statusEl.textContent = `Downloading: ${pct}%`;
            }
          }
        });
      } catch(e) {
        log(`❌ Pipeline error: ${e.message}`);
        return;
      }
      statusEl.textContent = 'Model loaded!';
      log('Model loaded ✓');

      // Test with thinking enabled
      for (const enableThinking of [true, false]) {
        log(`\n=== enable_thinking: ${enableThinking} ===`);

        const allChunks = [];
        const streamer = new TextStreamer(gen.tokenizer, {
          skip_prompt: true,
          skip_special_tokens: false,
          callback_function: (output) => {
            allChunks.push(output);
          },
        });

        const messages = [
          { role: 'system', content: 'You are an AI interviewer. Ask one question at a time.' },
          { role: 'user', content: "I think neural networks are simple." },
        ];

        log('Generating...');
        await gen(messages, {
          max_new_tokens: 512,
          do_sample: false,
          eos_token_id: [2, 11],
          streamer,
          tokenizer_encode_kwargs: { enable_thinking: enableThinking },
        });

        const fullText = allChunks.join('');
        log(`Total chunks: ${allChunks.length}`);
        log(`Total chars: ${fullText.length}`);
        log(`Contains </think>: ${fullText.includes('</think>')}`);
        log(`Contains <|im_end|>: ${fullText.includes('<|im_end|>')}`);

        log(`First 3 chunks: ${allChunks.slice(0, 3).map(c => JSON.stringify(c)).join(', ')}`);
        log(`Last 3 chunks: ${allChunks.slice(-3).map(c => JSON.stringify(c)).join(', ')}`);

        if (fullText.includes('</think>')) {
          const afterThink = fullText.slice(fullText.indexOf('</think>') + 8)
            .replace(/<\|im_end\|>/g, '').trim();
          log(`Content after </think>: ${JSON.stringify(afterThink.slice(0, 200))}`);
        } else {
          log(`❌ No </think> found!`);
          log(`Full output (last 300): ${JSON.stringify(fullText.slice(-300))}`);
        }

        // Simulate the parser
        let isFirst = true;
        let inThink = false;
        let reasoning = '';
        let content = '';
        let buf = '';
        for (const chunk of allChunks) {
          if (!chunk || chunk === '<|im_end|>') continue;
          let text = chunk;
          if (isFirst && enableThinking) { text = '<think>' + text; isFirst = false; }
          else if (isFirst) { isFirst = false; }
          buf += text;
          while (buf.length > 0) {
            if (inThink) {
              const ci = buf.indexOf('</think>');
              if (ci !== -1) {
                reasoning += buf.slice(0, ci);
                buf = buf.slice(ci + 8);
                inThink = false;
                continue;
              }
              reasoning += buf;
              buf = '';
              break;
            }
            const oi = buf.indexOf('<think>');
            if (oi !== -1) {
              content += buf.slice(0, oi);
              buf = buf.slice(oi + 7);
              inThink = true;
              continue;
            }
            content += buf;
            buf = '';
            break;
          }
        }
        log(`Parser result: content=${JSON.stringify(content.trim().slice(0, 200))}`);
        log(`Parser result: reasoning_length=${reasoning.length}`);
        log(`Parser result: still_in_think=${inThink}`);
        log(`Would show "No response": ${!content.trim()}`);
      }

      log('\n✅ Test complete!');
      statusEl.textContent = 'Test complete!';
    };
  </script>
</head>
<body style="font-family: monospace; padding: 20px; background: #1a1a1a; color: #eee;">
  <h2>ONNX WebGPU Think-Tag Test</h2>
  <p id="status">Ready</p>
  <button onclick="runTest('reference')" style="padding: 10px 20px; margin: 5px;">Test Reference Model</button>
  <button onclick="runTest('finetuned')" style="padding: 10px 20px; margin: 5px;">Test Fine-tuned Model</button>
  <hr>
  <pre id="log" style="white-space: pre-wrap; max-height: 80vh; overflow-y: auto;"></pre>
</body>
</html>