Forge
Skip to main content

Tutorial: Evaluating Moonshot AI Kimi K2 Instruct Using W&B Inference and Weave

Running and evaluating Moonshot AI Kimi K2 Instruct with W&B Inference and Weave.
Last updated: April 6, 2026
In this tutorial, we'll walk through how to run and evaluate the Moonshot AI Kimi K2 Instruct model using Weights & Biases Inference, a quick and easy way to host and serve some of the latest Large language models. We'll show how to deploy Kimi K2 on W&B Inference and use W&B Weave to trace requests, inspect model outputs, and systematically evaluate performance.
Whether you're testing Kimi K2 for agentic AI applications, validating its exceptional coding capabilities, or comparing its reasoning performance against other frontier models, this guide will help you build a clear, observable evaluation workflow you can trust.

Table of contents



What is Moonshot AI's Kimi K2 Instruct?

Moonshot AI's Kimi K2 Instruct is a state-of-the-art Mixture of Experts (MoE) language model developed by Moonshot AI, featuring 1 trillion total parameters with 32 billion activated parameters per forward pass.
Built on a Transformer architecture with MLA attention mechanism, Kimi K2 was trained on 15.5 trillion tokens using the innovative MuonClip optimizer, achieving zero training instability at unprecedented scale.
Kimi K2 is specifically designed for agentic intelligence, excelling at tool use, reasoning, and autonomous problem solving. It achieves state-of-the-art performance across multiple coding benchmarks.
Some of its key features include:
  • 256K context window (0905 version) for long horizon tasks
  • Native tool calling capabilities for building autonomous agents
  • Strong frontend coding with React, Vue, and Angular support
  • Multilingual proficiency across diverse languages
Among today's most capable open-weight language models, Moonshot AI Kimi K2 Instruct firmly earns its place as a top choice for agentic AI applications.

W&B Inference

W&B Inference is a managed inference service that lets you run, test, and deploy large language models without hosting the infrastructure yourself. It provides an OpenAI-compatible API, so you can call models using familiar SDKs while W&B handles scaling, routing, and performance behind the scenes.

W&B Inference provides access to a wide range of popular language models, including Meta’s Llama, OpenAI’s GPT OSS models, DeepSeek, Moonshot (Kimi), and many others. You can explore the full list of available models and their configurations directly through the W&B Inference model catalog using the provided link.
In short, W&B Inference removes the operational overhead of serving LLMs while giving you deep visibility into how they behave, making it ideal for benchmarking, evaluation, and real-world LLM applications.

W&B Weave


W&B Weave is a powerful LLM observability and debugging platform by Weights & Biases that helps developers track, evaluate, and improve AI applications built with large language models. It enables end-to-end visibility into prompts, model outputs, traces, and evaluations, making it easier to understand how LLMs behave in real-world workflows.
With Weave, teams can debug failures, compare model versions, monitor performance, and iterate faster, all through an intuitive interface. It's especially useful for building reliable, production-ready AI systems, turning experimentation into confidence and insight.

Tutorial: Running inference with Kimi K2 Instruct using W&B Inference

For the practical section, we’ll run Moonshot AI Kimi K2 Instruct in a Kaggle notebook.
The same code works seamlessly in other Python environments, such as Jupyter notebooks or any standard local or cloud based Python setup.
💡
Prerequisites
Some required and optional requirements for this tutorial include:

Account requirements

Technical requirements

  • Python 3.9 or higher
  • Basic familiarity with Python
  • Kaggle/Jupyter Notebook or any Python environment

Helpful background (optional)

  • Familiarity with the OpenAI SDK (W&B Inference uses an OpenAI-compatible API)
  • Basic understanding of LLM concepts (prompts, tokens, temperature)
  • Experience with chat completions APIs

Step 1: Install dependencies & imports

Install and import the required libraries. We use OpenAI for the API client (W&B Inference uses OpenAI compatible endpoints), Weave for tracing and evaluation, and wandb for experiment tracking.
! pip install openai weave requests wandb

import os
import json
import time
import re
import openai
import weave
import wandb

Step 2: Configuration

Set up your W&B API key, project name, and model ID. The project follows the format team-name/project-name, and the model ID references Kimi K2 from the W&B Inference model registry.
WANDB_API_KEY = os.getenv("WANDB_API_KEY", "your-api-key-here")
TEAM_PROJECT = "your-team/your-project"
MODEL_ID = "moonshotai/Kimi-K2-Instruct"

wandb.login(key=WANDB_API_KEY, relogin=True)

Step 3: Initialize weave & client

We will rely heavily on Weave for automatic tracing and on creating an OpenAI-compatible client that points to the W&B Inference endpoint. All API calls will be logged to your Weave dashboard.
weave.init(TEAM_PROJECT)
print(f"✓ Weave initialized for project: {TEAM_PROJECT}")

client = openai.OpenAI(
base_url="https://api.inference.wandb.ai/v1",
api_key=WANDB_API_KEY,
project=TEAM_PROJECT,
)
print(f"✓ Client ready for model: {MODEL_ID}")

Step 4: Define benchmark datasets

For a comprehensive evaluation, we will be defining 43 benchmark questions across 7 categories: math reasoning, logic reasoning, code generation, instruction following, multilingual, debugging, and data extraction. Each question includes difficulty level, expected answer, and validation criteria.

4.1 Math reasoning

MATH_REASONING_DATASET = [
{"id": "math_01_medium", "level": "medium", "question": "A store sells apples at $3 per kg. If you buy more than 5 kg, you get 10% off the entire purchase. How much do you pay for 8 kg? Answer with just the number (no $ sign).", "expected": "21.6", "category": "math_reasoning"},
{"id": "math_02_hard", "level": "hard", "question": "A car travels from A to B at 60 km/h and returns at 40 km/h. What is the average speed for the entire round trip in km/h? Answer with just the number.", "expected": "48", "category": "math_reasoning"},
{"id": "math_03_very_hard", "level": "very_hard", "question": "In a class, 60% of students passed math, 70% passed English, and 40% passed both. What percentage of students failed both subjects? Answer with just the number.", "expected": "10", "category": "math_reasoning"},
{"id": "math_04_expert", "level": "expert", "question": "A merchant marks up goods by 50% above cost, then offers two successive discounts of 20% and 10%. What is the final profit or loss percentage? Answer as a positive number for profit or negative for loss.", "expected": "8", "category": "math_reasoning"},
{"id": "math_05_expert", "level": "expert", "question": "A can complete a job in 12 days. B can complete it in 18 days. They work together for 4 days, then A leaves. How many more days does B need to finish alone? Answer with just the number.", "expected": "8", "category": "math_reasoning"},
{"id": "math_06_extreme", "level": "extreme", "question": "A sum doubles in 5 years at compound interest. In how many years will it become 8 times itself? Answer with just the number.", "expected": "15", "category": "math_reasoning"},
{"id": "math_07_extreme", "level": "extreme", "question": "A bag has 5 red and 3 blue balls. You draw 3 balls without replacement. What is the probability of getting exactly 2 red balls? Express as a simplified fraction in format 'a/b'.", "expected": "15/28", "category": "math_reasoning"},
{"id": "math_08_extreme", "level": "extreme", "question": "What is the remainder when 2^100 is divided by 7? Answer with just the number.", "expected": "2", "category": "math_reasoning"},
]

4.2 Logic reasoning

LOGIC_REASONING_DATASET = [
{"id": "logic_01_medium", "level": "medium", "question": "If all birds can fly, and penguins are birds, then penguins can fly. Is this argument logically VALID (ignoring real-world facts)? Answer only 'valid' or 'invalid'.", "expected": "valid", "category": "logic_reasoning"},
{"id": "logic_02_hard", "level": "hard", "question": "Statement: 'If it's a dog, it's a mammal.' We observe: 'It's a mammal.' Can we conclude: 'It's a dog'? Answer 'yes' or 'no'.", "expected": "no", "category": "logic_reasoning"},
{"id": "logic_03_very_hard", "level": "very_hard", "question": "Given: 'All successful people work hard.' Which statement MUST be true?\nA) All hard workers are successful\nB) Some non-hard-workers are not successful\nC) No unsuccessful person works hard\nD) Some unsuccessful people don't work hard\nAnswer with just the letter.", "expected": "B", "category": "logic_reasoning"},
{"id": "logic_04_expert", "level": "expert", "question": "On an island, Knights always tell truth, Knaves always lie. A says: 'B is a Knight.' B says: 'A and I are different types.' What is A? Answer 'knight' or 'knave'.", "expected": "knave", "category": "logic_reasoning"},
{"id": "logic_05_expert", "level": "expert", "question": "Five people (A,B,C,D,E) sit in a row. B is not at either end. C is immediately right of A. E is not adjacent to B. D is at the left end. Who sits at the right end? Answer with one letter.", "expected": "E", "category": "logic_reasoning"},
{"id": "logic_06_extreme", "level": "extreme", "question": "In a village, the barber shaves all and only those who do not shave themselves. Does the barber shave himself? Answer 'yes', 'no', or 'paradox'.", "expected": "paradox", "category": "logic_reasoning"},
{"id": "logic_07_extreme", "level": "extreme", "question": "Given these rules for a game:\n1. If you have a RED card, you must have a BLUE card.\n2. If you have a GREEN card, you cannot have a RED card.\n3. Everyone has at least one of: RED, GREEN.\nCan someone have only a GREEN card? Answer 'yes' or 'no'.", "expected": "yes", "category": "logic_reasoning"},
{"id": "logic_08_extreme", "level": "extreme", "question": "Three suspects: A, B, C. Facts:\n- The crime happened at 3 PM\n- A was with B from 2-4 PM\n- C was alone from 1-5 PM\n- The criminal acted alone\n- At least one of them is guilty\nWho committed the crime? Answer with one letter, or 'impossible' if contradictory.", "expected": "C", "category": "logic_reasoning"},
]

4.3 Code generation

CODE_GENERATION_DATASET = [
{"id": "code_01_hard", "level": "hard", "question": """Write a Python function `merge_intervals(intervals)` that:
- Takes a list of intervals as [start, end] pairs
- Returns merged overlapping intervals, sorted by start time
- Example: merge_intervals([[1,3],[2,6],[8,10],[15,18]]) → [[1,6],[8,10],[15,18]]

Provide only the function code, no explanations.""", "expected": "def merge_intervals", "test_cases": [("merge_intervals([[1,3],[2,6],[8,10],[15,18]])", [[1,6],[8,10],[15,18]]), ("merge_intervals([[1,4],[4,5]])", [[1,5]]), ("merge_intervals([[1,4],[0,4]])", [[0,4]]), ("merge_intervals([[1,4],[2,3]])", [[1,4]]), ("merge_intervals([])", [])], "category": "code_generation"},
{"id": "code_02_hard", "level": "hard", "question": """Write a Python function `find_anagrams(s, p)` that:
- Finds all start indices of p's anagrams in s
- Returns a list of starting indices
- Example: find_anagrams("cbaebabacd", "abc") → [0, 6]

Use O(n) time complexity. Provide only the function code.""", "expected": "def find_anagrams", "test_cases": [('find_anagrams("cbaebabacd", "abc")', [0, 6]), ('find_anagrams("abab", "ab")', [0, 1, 2]), ('find_anagrams("hello", "xyz")', [])], "category": "code_generation"},
{"id": "code_03_extreme", "level": "extreme", "question": """Write a Python class LRUCache(capacity) with methods:
- get(key): returns the value if key exists, otherwise returns -1
- put(key, value): inserts or updates the key-value pair

Requirements:
- Both operations must be O(1) time complexity
- When capacity is exceeded, evict the least recently used item

Provide only the complete Python code, no explanations.""", "expected": "class LRUCache", "test_cases": [("cache = LRUCache(2)", None), ("cache.put(1, 1)", None), ("cache.put(2, 2)", None), ("cache.get(1)", 1), ("cache.put(3, 3)", None), ("cache.get(2)", -1), ("cache.get(3)", 3)], "category": "code_generation"},
{"id": "code_04_extreme", "level": "extreme", "question": """Write a Python function `min_window(s, t)` that:
- Finds the minimum window substring of s that contains all characters in t
- Returns "" if no such window exists
- Example: min_window("ADOBECODEBANC", "ABC") → "BANC"

Must be O(n) time complexity. Provide only the function code.""", "expected": "def min_window", "test_cases": [('min_window("ADOBECODEBANC", "ABC")', "BANC"), ('min_window("a", "a")', "a"), ('min_window("a", "aa")', "")], "category": "code_generation"},
{"id": "code_05_extreme", "level": "extreme", "question": """Write a Python function `calculate(s)` that:
- Evaluates a basic calculator expression string
- Supports +, -, *, / and parentheses ()
- Follows standard operator precedence
- Example: calculate("3+2*2") → 7

Handle spaces in input. Provide only the function code.""", "expected": "def calculate", "test_cases": [('calculate("3+2*2")', 7), ('calculate("1+1")', 2), ('calculate(" 2-1 + 2 ")', 3)], "category": "code_generation"},
]

4.4 Instruction following

INSTRUCTION_FOLLOWING_DATASET = [
{"id": "instruction_01_medium", "level": "medium", "question": """Write a haiku about programming. Requirements:
- Line 1: exactly 5 syllables
- Line 2: exactly 7 syllables
- Line 3: exactly 5 syllables
- Must mention "code" or "bug" somewhere
- NO title, just the three lines""", "expected": None, "constraints": {"line_count": 3, "must_contain_any": ["code", "bug"], "no_title": True}, "category": "instruction_following"},
{"id": "instruction_02_hard", "level": "hard", "question": """Generate a JSON object with EXACTLY this structure:
{
"users": [exactly 3 users],
each user has: "id" (number 1-100), "name" (string, 4-8 chars), "active" (boolean)
}
Rules:
- At least one user must have active=false
- All names must start with uppercase letter
- IDs must be unique and in ascending order
- Output ONLY valid JSON, no explanation""", "expected": None, "constraints": {"valid_json": True, "has_users_array": True, "user_count": 3}, "category": "instruction_following"},
{"id": "instruction_03_hard", "level": "hard", "question": """Write exactly 5 sentences about climate change following ALL these rules:
1. Sentence 1 must be a question
2. Sentence 2 must contain exactly 2 numbers
3. Sentence 3 must start with "However"
4. Sentence 4 must be under 10 words
5. Sentence 5 must end with an exclamation mark
6. Total response must be 50-80 words
7. Do NOT use the words: "global", "warming", "crisis"

Output only the 5 sentences.""", "expected": None, "constraints": {"sentence_count": 5, "s1_is_question": True, "s3_starts_with_however": True, "s5_ends_exclamation": True, "word_count_min": 50, "word_count_max": 80, "forbidden_words": ["global", "warming", "crisis"]}, "category": "instruction_following"},
{"id": "instruction_04_extreme", "level": "extreme", "question": """Create a 4x4 grid representing a maze:
- Use # for walls, . for paths, S for start, E for end
- S must be in top-left corner
- E must be in bottom-right corner
- There must be exactly ONE valid path from S to E
- Surround the entire maze with # walls (making it 6x6 total)

Output ONLY the maze, nothing else.""", "expected": None, "constraints": {"has_S": True, "has_E": True, "has_walls": True, "has_path": True}, "category": "instruction_following"},
{"id": "instruction_05_extreme", "level": "extreme", "question": """Write a Python function with these EXACT constraints:
1. Function name must be "process_data"
2. Must have exactly 3 parameters: lst, threshold, flag
3. Must contain exactly 2 for loops (not while, not comprehensions)
4. Must contain exactly 1 if statement and 1 else clause
5. Must have exactly 3 comments (lines starting with #)
6. Must return a list
7. Do not include any code outside the function

Output ONLY the function.""", "expected": None, "constraints": {"function_name": "process_data", "has_if": True, "has_else": True, "has_comments": True, "returns_list": True}, "category": "instruction_following"},
{"id": "instruction_06_extreme", "level": "extreme", "question": """Generate a fictional person profile following ALL rules:

FORMAT (use exactly this structure):
NAME: [first] [last]
AGE: [number]
JOB: [occupation]
HOBBIES: [hobby1], [hobby2], [hobby3]
BIO: [one sentence bio]

RULES:
- First name: exactly 4 letters, starts with J
- Last name: exactly 6 letters, ends with "son"
- Age: prime number between 20-40
- Job: compound word (two words joined, like "firefighter")
- Hobbies: all must start with different letters
- Bio: exactly 12 words, must mention their job

Output ONLY the profile in the exact format above.""", "expected": None, "constraints": {"has_name_line": True, "has_age_line": True, "has_job_line": True, "has_hobbies_line": True, "has_bio_line": True}, "category": "instruction_following"},
]

4.5 Long context

def generate_long_context_dataset(difficulty: str = "expert") -> dict:
filler_topics = ["artificial intelligence", "quantum computing", "blockchain", "cybersecurity", "cloud architecture", "machine learning", "data engineering", "DevOps practices", "microservices", "API design", "database optimization", "network protocols"]
filler_template = """
The field of {topic} continues to evolve rapidly. Industry experts have noted significant
advancements in recent years, with major technology companies investing heavily in research
and development. Best practices in {topic} emphasize scalability, maintainability, and
security. Teams working in this area often collaborate across multiple time zones, using
modern tools for version control and continuous integration. Documentation remains crucial
for knowledge transfer, and regular code reviews help maintain quality standards."""
distractors = [
"CRITICAL: The primary encryption key is ALPHA-7749-BETA (24 chars)",
"AUTH_TOKEN: GAMMA-8832-DELTA - master token for system access",
"IMPORTANT: Secret passphrase is 'BlueHorse42Running'",
"System password: EPSILON-9921-ZETA - required for admin access",
"API_KEY: THETA-1156-IOTA - for external integrations",
"Recovery code: KAPPA-2267-LAMBDA - store securely",
"Master credential: SIGMA-4478-OMEGA - highest priority",
]
needles = {
"expert": [("The actual database password is: NEPTUNE-3847-MARS", "NEPTUNE-3847-MARS", "35%")],
"extreme": [("First fragment of the launch code: APOLLO", "APOLLO", "25%"), ("Second fragment of the launch code: ELEVEN", "ELEVEN", "55%"), ("Third fragment of the launch code: LUNAR", "LUNAR", "85%")],
"nightmare": [("Agent codename for Operation Sunrise: FALCON", "FALCON", "15%"), ("The meeting point coordinates encoded as: 47N-122W", "47N-122W", "40%"), ("Extraction time in military format: 0347", "0347", "65%"), ("The safe combination sequence is: 27-14-33", "27-14-33", "90%")],
}
target_words = {"expert": 15000, "extreme": 30000, "nightmare": 50000}[difficulty]
paragraphs_needed = target_words // 100
document_parts = []
needle_list = needles[difficulty]
distractor_positions = [int(paragraphs_needed * p) for p in [0.1, 0.2, 0.3, 0.45, 0.5, 0.6, 0.75]]
needle_positions = [int(paragraphs_needed * float(n[2].strip('%'))/100) for n in needle_list]
for i in range(paragraphs_needed):
document_parts.append(filler_template.format(topic=filler_topics[i % len(filler_topics)]))
if i in distractor_positions:
document_parts.append(f"\n[SYSTEM NOTICE: {distractors[distractor_positions.index(i) % len(distractors)]}]\n")
for j, (needle_text, _, _) in enumerate(needle_list):
if i == needle_positions[j]:
document_parts.append(f"\n[CONFIDENTIAL: {needle_text}]\n")
full_document = "\n\n".join(document_parts)
questions = {
"expert": ("What is the actual database password mentioned in the document? Provide ONLY the password, nothing else.", ["NEPTUNE-3847-MARS"]),
"extreme": ("Find all three fragments of the launch code in the document. List them in order separated by hyphens. Format: WORD-WORD-WORD", ["APOLLO-ELEVEN-LUNAR"]),
"nightmare": ("Find ALL four pieces of intelligence: 1) Agent codename 2) Coordinates 3) Extraction time 4) Safe combination. Format: CODENAME / COORDINATES / TIME / COMBINATION", ["FALCON / 47N-122W / 0347 / 27-14-33", "FALCON/47N-122W/0347/27-14-33"]),
}
return {
"id": f"long_context_{difficulty}", "level": difficulty, "document": full_document,
"question": questions[difficulty][0], "expected": questions[difficulty][1],
"needle_count": len(needle_list), "distractor_count": len(distractors),
"word_count": len(full_document.split()), "category": "long_context"
}

LONG_CONTEXT_DATASET = [generate_long_context_dataset("expert"), generate_long_context_dataset("extreme"), generate_long_context_dataset("nightmare")]

4.6 Multilingual

MULTILINGUAL_DATASET = [
{"id": "multilingual_01_spanish", "level": "hard", "question": """Explica en español cómo funciona el algoritmo de búsqueda binaria. Incluye: 1. Complejidad temporal (Big O notation) 2. Requisito principal de los datos 3. Un caso donde NO funcionaría. Responde completamente en español.""", "requirements": {"language": "Spanish", "must_mention": ["O(log n)", "ordenado"], "min_sentences": 5}, "category": "multilingual"},
{"id": "multilingual_02_french", "level": "hard", "question": """En français, résolvez ce problème: Un train part de Paris à 9h00 à 120 km/h. Un autre train part de Lyon (465 km de Paris) à 10h00 à 150 km/h vers Paris. À quelle heure se croiseront-ils? Montrez les calculs, réponse en format HH:MM.""", "requirements": {"language": "French", "must_show_calculation": True, "expected_answer": "12:30"}, "category": "multilingual"},
{"id": "multilingual_03_german", "level": "extreme", "question": """Auf Deutsch, erkläre den Unterschied zwischen: 1. Stack und Heap Speicher 2. Pass by Value und Pass by Reference 3. Kompilierte und interpretierte Sprachen. Gib für jeden Punkt ein Beispiel. Antworte vollständig auf Deutsch.""", "requirements": {"language": "German", "sections": 3, "must_have_examples": True}, "category": "multilingual"},
{"id": "multilingual_04_thai", "level": "extreme", "question": """อธิบายความแตกต่างระหว่าง LSTM และ GRU ในบริบทของ recurrent neural networks โดยครอบคลุม: 1) สมการทางคณิตศาสตร์ของแต่ละ gate 2) ความซับซ้อนในการคำนวณ 3) กรณีการใช้งานที่เหมาะสม ตอบเป็นภาษาไทย""", "requirements": {"language": "Thai", "must_mention": ["LSTM", "GRU", "gate"], "min_sentences": 5}, "category": "multilingual"},
{"id": "multilingual_05_mixed", "level": "extreme", "question": """Translate into THREE languages (Spanish, French, German). Preserve technical terms in English.

"The API uses REST architecture with JSON payloads. Authentication is handled via OAuth 2.0 tokens with a 3600-second expiry."

Format:
[ES]: (Spanish)
[FR]: (French)
[DE]: (German)""", "requirements": {"has_spanish": True, "has_french": True, "has_german": True}, "category": "multilingual"},
]

4.7 Debugging

DEBUGGING_DATASET = [
{"id": "debug_01_python", "level": "hard", "question": """Find ALL bugs in this Python code. There are exactly 4 bugs.

```python
def find_duplicates(lst):
seen = set()
duplicates = []
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return sorted(duplicates, reverse=true)

result = find_duplicates([1, 2, 2, 3, 3, 3])
print(f"Found: {results}")
```

Format: Line X: problem → fix""", "expected_bugs": [{"line": 5, "issue": "duplicates.add on list"}, {"line": 8, "issue": "true not True"}, {"line": 11, "issue": "results undefined"}], "bug_count": 4, "category": "debugging"},
{"id": "debug_02_javascript", "level": "hard", "question": """Find ALL bugs in this JavaScript code. There are exactly 5 bugs.

```javascript
const fetchUserData = async (userId) => {
const response = await fetch(`/api/users/${userId}`)
const data = response.json()
if (response.status = 200) {
return { success: true, user: data }
} else {
return { success: false, error: response.statusText }
}
}
```

Format: Line X: problem → fix""", "expected_bugs": [{"line": 3, "issue": "missing await"}, {"line": 5, "issue": "assignment not comparison"}, {"line": 2, "issue": "missing error handling"}], "bug_count": 5, "category": "debugging"},
{"id": "debug_03_race_condition", "level": "extreme", "question": """This Python code has a race condition. Find ALL issues.

```python
import threading
counter = 0
lock = threading.Lock()

def increment():
global counter
for _ in range(100000):
temp = counter
counter = temp + 1

threads = []
for i in range(4):
t = threading.Thread(target=increment())
threads.append(t)
t.start()
```

Format: Line X: problem → fix""", "expected_bugs": [{"line": 9, "issue": "no lock used"}, {"line": 13, "issue": "increment() called immediately"}], "bug_count": 3, "category": "debugging"},
{"id": "debug_04_sql_injection", "level": "extreme", "question": """This code has security vulnerabilities. Find ALL issues.

```python
import sqlite3

def get_user(username, password):
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
cursor.execute(query)
user = cursor.fetchone()
return user
```

Format: Line X: problem → fix""", "expected_bugs": [{"line": 7, "issue": "SQL injection"}, {"line": 7, "issue": "password plain text"}, {"line": 10, "issue": "connection not closed"}], "bug_count": 6, "category": "debugging"},
{"id": "debug_05_memory_leak", "level": "extreme", "question": """This JavaScript has memory leaks. Find ALL bugs.

```javascript
class DataProcessor {
constructor() {
this.data = []
this.listeners = []
window.addEventListener('resize', this.handleResize)
}
handleResize() {
console.log('Resizing, data:', this.data.length)
}
addListener(callback) {
this.listeners.push(callback)
setInterval(() => callback(this.data), 1000)
}
destroy() {
this.data = []
this.listeners = []
}
}
```

Format: Description → fix""", "expected_bugs": [{"line": 5, "issue": "event listener not removed"}, {"line": 5, "issue": "handleResize this binding"}, {"line": 13, "issue": "intervals never cleared"}], "bug_count": 4, "category": "debugging"},
{"id": "debug_06_async", "level": "extreme", "question": """This async Python code has multiple bugs. Find ALL of them.

```python
import asyncio

async def fetch_data(url):
await asyncio.sleep(1)
return f"Data from {url}"

async def process_urls(urls):
results = []
for url in urls:
result = fetch_data(url)
results.append(result)
return results

async def main():
urls = ["http://api.com/1", "http://api.com/2"]
results = process_urls(urls)
for r in results:
print(r)

asyncio.run(main())
```

Format: Line X: problem → fix""", "expected_bugs": [{"line": 10, "issue": "missing await on fetch_data"}, {"line": 16, "issue": "missing await on process_urls"}], "bug_count": 4, "category": "debugging"},
]

4.8 Data extraction

DATA_EXTRACTION_DATASET = [
{"id": "extraction_01_nested_json", "level": "hard", "question": """Extract all email addresses from this nested JSON. Return as a flat JSON array of unique emails, sorted alphabetically.

```json
{
"company": {
"departments": [
{"name": "Engineering", "lead": {"email": "[email protected]"}, "members": [{"email": "[email protected]"}, {"email": "[email protected]"}]},
{"name": "Sales", "lead": {"email": "[email protected]"}, "members": [{"email": "[email protected]"}, {"email": "[email protected]"}]}
],
"contact": "[email protected]"
}
}
```

Output ONLY the JSON array.""", "expected": '["alice@company.com", "bob@company.com", "charlie@company.com", "diana@company.com", "eve@company.com", "info@company.com"]', "expected_count": 6, "category": "data_extraction"},
{"id": "extraction_02_log_parsing", "level": "hard", "question": """Parse these logs and output JSON with error counts by type.

```
2024-01-15 10:23:45 ERROR DatabaseError: Connection timeout
2024-01-15 10:24:12 WARN MemoryWarning: High usage
2024-01-15 10:25:33 ERROR ValidationError: Invalid input
2024-01-15 10:26:01 ERROR DatabaseError: Query failed
2024-01-15 10:28:44 ERROR NetworkError: Host unreachable
2024-01-15 10:29:02 ERROR ValidationError: Missing field
```

Output: {"ErrorType": count, ...} for ERROR entries only. Output ONLY the JSON.""", "expected": '{"DatabaseError": 2, "ValidationError": 2, "NetworkError": 1}', "category": "data_extraction"},
{"id": "extraction_03_xml_to_json", "level": "extreme", "question": """Convert this XML to JSON with proper types.

```xml
<library>
<book id="1" available="true">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
<price currency="USD">12.99</price>
</book>
<book id="2" available="false">
<title>1984</title>
<author>George Orwell</author>
<year>1949</year>
<price currency="GBP">9.99</price>
</book>
</library>
```

Requirements: id/year as integers, available as boolean, price as {amount, currency}. Output ONLY valid JSON.""", "expected_structure": {"library": [{"id": 1, "available": True, "title": "The Great Gatsby"}]}, "category": "data_extraction"},
{"id": "extraction_04_markdown_table", "level": "extreme", "question": """Parse this markdown table and output as JSON with calculated fields.

| Product | Q1 Sales | Q2 Sales | Q3 Sales | Q4 Sales |
|---------|----------|----------|----------|----------|
| Widget A | $1,234 | $2,345 | $1,890 | $3,210 |
| Widget B | $890 | $1,200 | $1,500 | $2,100 |

Output JSON with each product as object, sales as numbers (no $ or ,), calculated "total" and "average" fields. Output ONLY JSON array.""", "expected_structure": [{"product": "Widget A", "total": 8679}], "category": "data_extraction"},
{"id": "extraction_05_regex_transform", "level": "extreme", "question": """Extract function signatures from this code into JSON.

```python
def calculate_total(items: list[dict], tax_rate: float = 0.08) -> float:
pass

async def fetch_user(user_id: int, include_profile: bool = True) -> dict[str, any]:
pass
```

Output JSON array with: name, async (boolean), parameters (array of {name, type, default}), return_type. Output ONLY JSON.""", "expected_structure": [{"name": "calculate_total", "async": False}], "category": "data_extraction"},
]

Step 5: Generate a long context dataset

Dynamically generate 3 "needle in haystack" tests with documents ranging from 15K to 50K words. Hidden facts (needles) and misleading distractors test the model's ability to retrieve specific information from long contexts.
def generate_long_context_dataset(difficulty: str = "expert") -> dict:
# Generate filler content (15K-50K words)
# Insert "needle" facts at specific positions
# Insert distractor facts to test precision
return {
"id": f"long_context_{difficulty}",
"document": full_document,
"question": question,
"expected": expected_answers,
...
}

LONG_CONTEXT_DATASET = [
generate_long_context_dataset("expert"), # 15K words, 1 needle
generate_long_context_dataset("extreme"), # 30K words, 3 needles
generate_long_context_dataset("nightmare"), # 50K words, 4 needles
]

Step 6: Create weave model class

Wrap the model in a Weave Model class with @weave.op() decorated methods. This automatically traces all predictions, logging inputs, outputs, and latency to your Weave project.
class KimiK2Model(weave.Model):
"""Weave Model wrapper for Kimi K2 Instruct."""
model_name: str = MODEL_ID
system_prompt: str = "You are Kimi, an AI assistant created by Moonshot AI. Be precise and concise."
temperature: float = 0.3
@weave.op()
def predict(self, question: str, max_tokens: int = 2000) -> str:
response = client.chat.completions.create(
model=self.model_name,
messages=[
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": question}
],
temperature=self.temperature,
max_tokens=max_tokens,
)
return response.choices[0].message.content
@weave.op()
def predict_long_context(self, document: str, question: str) -> str:
prompt = f"""Read the following document carefully and answer the question.

DOCUMENT:
{document}

QUESTION: {question}

Answer precisely based only on information found in the document."""
response = client.chat.completions.create(
model=self.model_name,
messages=[
{"role": "system", "content": "You are a careful document analyst. Find and report specific information accurately."},
{"role": "user", "content": prompt}
],
temperature=0.1,
max_tokens=500,
)
return response.choices[0].message.content


Step 7: Define scorers

We will then create 8 category-specific scoring functions that extract answers from model outputs and compare against expected values. Each scorer handles different validation logic (exact match, code execution, constraint checking, etc.).
@weave.op()
def math_scorer(output: str, expected: str) -> dict:
output_clean = output.strip().lower().replace("$", "").replace(",", "").replace(" ", "")
expected_clean = expected.strip().lower()
numbers = re.findall(r'-?[\d.]+(?:/\d+)?', output_clean)
if "/" in expected_clean:
exact_match = expected_clean in output_clean
if not exact_match:
try:
num, den = map(int, expected_clean.split("/"))
expected_decimal = num / den
for n in numbers:
if "/" in n:
n_num, n_den = map(int, n.split("/"))
if abs(n_num/n_den - expected_decimal) < 0.001:
exact_match = True
break
except:
pass
else:
try:
expected_val = float(expected_clean)
exact_match = any(abs(float(n) - expected_val) < 0.01 for n in numbers if n.replace('.','').replace('-','').isdigit())
except:
exact_match = expected_clean in output_clean
return {"exact_match": exact_match, "expected": expected, "score": 1.0 if exact_match else 0.0}


@weave.op()
def logic_scorer(output: str, expected: str) -> dict:
output_clean = output.strip().lower()
expected_clean = expected.strip().lower()
first_line = output_clean.split('\n')[0].strip()
first_words = first_line.split()[:5]
if expected_clean in ["yes", "no", "valid", "invalid", "paradox"]:
if expected_clean == "yes":
match = "yes" in first_words and "no" not in first_words[:3]
elif expected_clean == "no":
match = "no" in first_words or "cannot" in first_words
elif expected_clean == "valid":
match = "valid" in output_clean and "invalid" not in output_clean
elif expected_clean == "invalid":
match = "invalid" in output_clean
elif expected_clean == "paradox":
match = "paradox" in output_clean
else:
match = expected_clean in output_clean
elif len(expected_clean) == 1:
patterns = [rf'^{expected_clean}[^a-z]', rf'answer[:\s]+{expected_clean}', rf'\({expected_clean}\)']
match = any(re.search(p, output_clean) for p in patterns) or output_clean.strip().startswith(expected_clean)
else:
match = expected_clean in output_clean
return {"match": match, "expected": expected_clean, "score": 1.0 if match else 0.0}


@weave.op()
def code_scorer(output: str, test_cases: list) -> dict:
results = {"syntax_valid": False, "tests_passed": 0, "total_tests": len([t for t in test_cases if t[1] is not None]) if test_cases else 0}
code_block = output
if "```python" in output:
match = re.search(r'```python\s*(.*?)\s*```', output, re.DOTALL)
if match:
code_block = match.group(1)
elif "```" in output:
match = re.search(r'```\s*(.*?)\s*```', output, re.DOTALL)
if match:
code_block = match.group(1)
try:
compile(code_block, '<string>', 'exec')
results["syntax_valid"] = True
except SyntaxError as e:
results["syntax_error"] = str(e)
results["score"] = 0.0
return results
if results["syntax_valid"] and test_cases:
try:
exec_globals = {}
exec(code_block, exec_globals)
for test_expr, expected in test_cases:
if expected is None:
exec(test_expr, exec_globals)
continue
try:
actual = eval(test_expr, exec_globals)
if actual == expected:
results["tests_passed"] += 1
except:
pass
except:
pass
results["score"] = results["tests_passed"] / results["total_tests"] if results["total_tests"] > 0 else (0.5 if results["syntax_valid"] else 0.0)
return results


@weave.op()
def instruction_scorer(output: str, constraints: dict) -> dict:
results = {"checks": [], "passed": 0, "total": 0}
output_stripped = output.strip()
for key, val in constraints.items():
passed = False
if key == "line_count":
lines = [l for l in output_stripped.split('\n') if l.strip()]
passed = len(lines) == val
elif key == "must_contain_any":
passed = any(w.lower() in output_stripped.lower() for w in val)
elif key == "valid_json":
try:
json.loads(output_stripped)
passed = True
except:
try:
match = re.search(r'```(?:json)?\s*([\s\S]*?)\s*```', output_stripped)
if match:
json.loads(match.group(1))
passed = True
except:
pass
elif key == "forbidden_words":
passed = not any(w.lower() in output_stripped.lower() for w in val)
elif key == "word_count_min":
passed = len(output_stripped.split()) >= val
elif key == "word_count_max":
passed = len(output_stripped.split()) <= val
elif key.startswith("has_"):
check = key.replace("has_", "").replace("_line", "").replace("_", " ").upper()
if check in ["S", "E"]:
passed = check in output_stripped
elif "LINE" in key.upper():
passed = check.split()[0] in output_stripped.upper()
elif key == "has_walls":
passed = "#" in output_stripped
elif key == "has_path":
passed = "." in output_stripped
elif key == "has_if":
passed = " if " in output_stripped
elif key == "has_else":
passed = "else" in output_stripped
elif key == "has_comments":
passed = "#" in output_stripped
else:
passed = True
elif key == "function_name":
passed = val in output_stripped
elif key == "returns_list":
passed = "return" in output_stripped and "[" in output_stripped
else:
continue
results["checks"].append({"constraint": key, "passed": passed})
results["total"] += 1
if passed:
results["passed"] += 1
results["score"] = results["passed"] / results["total"] if results["total"] > 0 else 0.0
return results


@weave.op()
def long_context_scorer(output: str, expected: list, needle_count: int) -> dict:
output_upper = output.upper()
distractor_patterns = ["ALPHA-7749", "GAMMA-8832", "EPSILON-9921", "THETA-1156", "KAPPA-2267", "SIGMA-4478"]
results = {"found_correct": False, "distractors_found": [d for d in distractor_patterns if d in output_upper]}
for exp in expected:
if exp.upper() in output_upper or exp.upper().replace(" ", "") in output_upper.replace(" ", ""):
results["found_correct"] = True
break
if results["distractors_found"] and not results["found_correct"]:
results["score"] = 0.0
elif results["found_correct"] and not results["distractors_found"]:
results["score"] = 1.0
elif results["found_correct"]:
results["score"] = 0.5
else:
results["score"] = 0.0
return results


@weave.op()
def multilingual_scorer(output: str, requirements: dict) -> dict:
results = {"checks": []}
language_patterns = {"Spanish": r'[áéíóúñ¿¡]', "French": r'[àâçéèêëîïôùûü]', "German": r'[äöüß]', "Thai": r'[\u0E00-\u0E7F]'}
lang = requirements.get("language", "")
if lang in language_patterns:
results["checks"].append({"constraint": f"has_{lang}", "passed": bool(re.search(language_patterns[lang], output))})
for key in ["must_mention", "has_spanish", "has_french", "has_german"]:
if key in requirements:
if key == "must_mention":
for term in requirements[key]:
results["checks"].append({"constraint": f"mentions_{term}", "passed": term.lower() in output.lower()})
else:
tag = {"has_spanish": "[ES]", "has_french": "[FR]", "has_german": "[DE]"}[key]
results["checks"].append({"constraint": key, "passed": tag in output})
results["score"] = sum(1 for c in results["checks"] if c["passed"]) / len(results["checks"]) if results["checks"] else 0.5
return results


@weave.op()
def debugging_scorer(output: str, expected_bugs: list, bug_count: int) -> dict:
output_lower = output.lower()
results = {"bugs_found": 0, "bugs_expected": bug_count}
for bug in expected_bugs:
line = bug.get("line", 0)
issue = bug.get("issue", "").lower()
line_mentioned = f"line {line}" in output_lower if line > 0 else True
issue_words = [w for w in issue.split() if len(w) > 3]
keywords_found = sum(1 for w in issue_words if w in output_lower)
if (line_mentioned and keywords_found >= 1) or keywords_found >= 2:
results["bugs_found"] += 1
results["score"] = results["bugs_found"] / bug_count if bug_count > 0 else 0.0
return results


@weave.op()
def data_extraction_scorer(output: str, expected) -> dict:
results = {"valid_json": False, "score": 0.0}
output_clean = output.strip()
if "```" in output_clean:
match = re.search(r'```(?:json)?\s*([\s\S]*?)\s*```', output_clean)
if match:
output_clean = match.group(1)
array_match = re.search(r'(\[[\s\S]*\])', output_clean)
object_match = re.search(r'(\{[\s\S]*\})', output_clean)
if array_match:
output_clean = array_match.group(1)
elif object_match:
output_clean = object_match.group(1)
try:
parsed = json.loads(output_clean)
results["valid_json"] = True
if isinstance(expected, str):
try:
expected_parsed = json.loads(expected)
results["score"] = 1.0 if parsed == expected_parsed else 0.5
except:
results["score"] = 0.5
else:
results["score"] = 0.5
except:
results["score"] = 0.0
return results

Step 8: Evaluation runner

The main evaluation loop that iterates through all categories and questions, calls the model, scores responses, aggregates results, and prints a visual summary with progress bars.
@weave.op()
def run_comprehensive_evaluation(skip_long_context: bool = False) -> dict:
model = KimiK2Model(temperature=0.3)
all_results = {}
categories = [
("math_reasoning", "📊 MATH REASONING", MATH_REASONING_DATASET, lambda i, o: math_scorer(o, i["expected"])),
("logic_reasoning", "🧠 LOGIC REASONING", LOGIC_REASONING_DATASET, lambda i, o: logic_scorer(o, i["expected"])),
("code_generation", "💻 CODE GENERATION", CODE_GENERATION_DATASET, lambda i, o: code_scorer(o, i.get("test_cases", []))),
("instruction_following", "📝 INSTRUCTION FOLLOWING", INSTRUCTION_FOLLOWING_DATASET, lambda i, o: instruction_scorer(o, i["constraints"])),
("multilingual", "🌍 MULTILINGUAL", MULTILINGUAL_DATASET, lambda i, o: multilingual_scorer(o, i["requirements"])),
("debugging", "🐛 DEBUGGING", DEBUGGING_DATASET, lambda i, o: debugging_scorer(o, i["expected_bugs"], i["bug_count"])),
("data_extraction", "📋 DATA EXTRACTION", DATA_EXTRACTION_DATASET, lambda i, o: data_extraction_scorer(o, i.get("expected") or i.get("expected_structure"))),
]
for cat_id, cat_name, dataset, scorer_fn in categories:
print(f"\n{'='*70}\n{cat_name} ({len(dataset)} questions)\n{'='*70}")
results = []
for item in dataset:
print(f" [{item['level']:10}] {item['id']}...", end=" ", flush=True)
max_tokens = 3000 if cat_id == "code_generation" else 2500 if cat_id == "multilingual" else 2000
output = model.predict(item["question"], max_tokens=max_tokens)
scores = scorer_fn(item, output)
results.append({"id": item["id"], "level": item["level"], "score": scores["score"]})
status = "✅" if scores["score"] >= 0.5 else "❌"
extra = f"({scores.get('tests_passed', '')}/{scores.get('total_tests', '')})" if 'tests_passed' in scores else ""
extra = extra or (f"({scores.get('bugs_found', '')}/{scores.get('bugs_expected', '')})" if 'bugs_found' in scores else "")
print(f"{status} {scores['score']:.0%} {extra}")
all_results[cat_id] = {"results": results, "avg_score": sum(r["score"] for r in results) / len(results), "total": len(results)}
# Long context
if not skip_long_context:
print(f"\n{'='*70}\n📚 LONG CONTEXT ({len(LONG_CONTEXT_DATASET)} questions)\n{'='*70}")
lc_results = []
for item in LONG_CONTEXT_DATASET:
print(f" [{item['level']:10}] {item['id']} (~{item['word_count']} words)...", end=" ", flush=True)
output = model.predict_long_context(item["document"], item["question"])
scores = long_context_scorer(output, item["expected"], item["needle_count"])
lc_results.append({"id": item["id"], "level": item["level"], "score": scores["score"]})
print(f"{'✅' if scores['score'] >= 0.5 else '❌'} {scores['score']:.0%}")
all_results["long_context"] = {"results": lc_results, "avg_score": sum(r["score"] for r in lc_results) / len(lc_results), "total": len(lc_results)}
else:
all_results["long_context"] = {"results": [], "avg_score": 0, "total": 0, "skipped": True}
# Summary
print(f"\n{'='*70}\n📈 EVALUATION SUMMARY\n{'='*70}")
total_score, total_q = 0, 0
for cat, data in all_results.items():
if data.get("skipped"):
print(f"⏭️ {cat.upper():25} SKIPPED")
continue
avg, count = data.get("avg_score", 0), data.get("total", 0)
if count == 0:
continue
total_score += avg * count
total_q += count
emoji = "✅" if avg >= 0.7 else "⚠️" if avg >= 0.4 else "❌"
bar = "█" * int(avg * 20) + "░" * (20 - int(avg * 20))
print(f"{emoji} {cat.upper():25} {bar} {avg:6.1%} ({count} q)")
print("-" * 70)
overall = total_score / total_q if total_q > 0 else 0
bar = "█" * int(overall * 20) + "░" * (20 - int(overall * 20))
print(f"{'🏆' if overall >= 0.7 else '🎯'} {'OVERALL':25} {bar} {overall:6.1%} ({total_q} total)")
print("=" * 70)
all_results["summary"] = {"overall_score": overall, "total_questions": total_q}
return all_results

Step 9: Save results & run

Save results to JSON for later analysis and execute the evaluation. The output includes a Weave dashboard link for exploring all traced predictions.
def save_results(results: dict, filename: str = "kimi_k2_hard_benchmark_results.json"):
with open(filename, "w", encoding="utf-8") as f:
json.dump({"model": MODEL_ID, "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "results": results}, f, indent=2, default=str)
print(f"\n📁 Results saved to {filename}")


def main():
print(f"\n{'='*70}\n🚀 W&B Inference + Weave + Kimi K2 - HARD Benchmark\n 46 Questions Across 8 Categories\n{'='*70}")
print(f"Model: {MODEL_ID}\nProject: {TEAM_PROJECT}\n{'='*70}")
results = run_comprehensive_evaluation(skip_long_context=False)
save_results(results)
print(f"\n🔗 View traces: https://wandb.ai/{TEAM_PROJECT}/weave\n{'='*70}")
return results


if __name__ == "__main__":
results = main()
Below is our summary table showing how our model performed across the various ranges of prompts we threw its way.

As shown above, Moonshot AI Kimi K2 Instruct achieves an overall score of 84.6%, compared to the Microsoft Phi4 3.8B model, which achieves an overall score of 66.0%. The model demonstrates strong performance across several categories, including logical reasoning, code generation, instruction following, multilingual text understanding, and long-context tasks. The model performs particularly well on reasoning-heavy and structured generation tasks. Its weakest area is debugging, where it scores 51.7%, indicating room for improvement in error analysis and code correction.

Inspecting the "Thinking" process in Weave

In order to open the Weights and Biases dashboard, click on the view traces link provided at the end of the run. By using W&B Weave, we can save all the prompts we have passed to our model, using them alongside the model's given response. This allows us to compare our model's performance against other models, such as fine-tuning some of its parameters, integrating an RAG system, etc.


Weave also allows us to log each prompt's usage token, which correlates with the cost of using a given model, based on the model's token/money ratio. The token utilization is divided into completion and prompt tokens.

Lastly, we can log the model's latency for a given prompt, i.e., the time it takes to respond. The latency for a given model is extremely important, especially when integrating an LLM as a third party, for instance, into a given application.


⭐ Best practices

📈 Track quality, latency, and cost together

Running evaluations without operational metrics is like grading exams without timing them. A model that scores 95% but takes 15 seconds per query might be worse than one scoring 85% in 500ms.

🎯 Match temperature to task type

Don't use one temperature for everything. Kimi K2's recommended default is 0.6, but optimal settings vary by category:
  • Code generation: 0.2–0.4 (deterministic, correct syntax)
  • Math/Logic: 0.3 (consistent reasoning chains)
  • Creative writing: 0.7–0.9 (varied, interesting outputs)
  • Instruction following: 0.5–0.6 (balance between creativity and compliance)
  • Data extraction: 0.1–0.3 (precise, no hallucinated fields)

🧪 Re-evaluate After Every Change

Prompt tweaks, temperature adjustments, and model updates can all shift performance. Treat your benchmark like a test suite, run it after every change.

📊 Log everything to weave

Every prediction should be traceable. When something breaks in production, you need to know exactly what prompt caused it.

🚀 What to do next?

Now that you have a solid understanding of W&B Inference and Weave, and how to evaluate large language models across a variety of tasks, a natural next step is to experiment with additional models. Try comparing multiple models to identify the one that best fits your specific requirements, whether that’s extracting information from long documents, strong logical reasoning, code generation, or multilingual support.
From there, consider iterating on model performance by adjusting prompts, fine-tuning model parameters, or introducing a Retrieval Augmented Generation (RAG) pipeline. Evaluating the same tasks before and after these changes will help you clearly measure improvements in quality, latency, and cost. By continuously tracking these experiments in Weave, you can make data-driven decisions and confidently refine your LLM-powered applications.