Views
No views yet

pip install transformers1from transformers import AutoModelForCausalLM, AutoTokenizer
2checkpoint = "HuggingFaceTB/SmolLM2-1.7B-Instruct"
3
4device = "cuda" # for GPU usage or "cpu" for CPU usage
5tokenizer = AutoTokenizer.from_pretrained(checkpoint)
6# for multiple GPUs install accelerate and do `model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto")`
7model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
8
9messages = [{"role": "user", "content": "What is the capital of France."}]
10input_text=tokenizer.apply_chat_template(messages, tokenize=False)
11inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
12outputs = model.generate(inputs, max_new_tokens=50, temperature=0.2, top_p=0.9, do_sample=True)
13print(tokenizer.decode(outputs[0]))1pip install trl
2trl chat --model_name_or_path HuggingFaceTB/SmolLM2-1.7B-Instruct --device cpunpm i @huggingface/transformers1import { pipeline } from "@huggingface/transformers";
2
3// Create a text generation pipeline
4const generator = await pipeline(
5 "text-generation",
6 "HuggingFaceTB/SmolLM2-1.7B-Instruct",
7);
8
9// Define the list of messages
10const messages = [
11 { role: "system", content: "You are a helpful assistant." },
12 { role: "user", content: "Tell me a joke." },
13];
14
15// Generate a response
16const output = await generator(messages, { max_new_tokens: 128 });
17console.log(output[0].generated_text.at(-1).content);
18// "Why don't scientists trust atoms?\n\nBecause they make up everything!"| Metric | SmolLM2-1.7B | Llama-1B | Qwen2.5-1.5B | SmolLM1-1.7B |
|---|---|---|---|---|
| HellaSwag | 68.7 | 61.2 | 66.4 | 62.9 |
| ARC (Average) | 60.5 | 49.2 | 58.5 | 59.9 |
| PIQA | 77.6 | 74.8 | 76.1 | 76.0 |
| MMLU-Pro (MCF) | 19.4 | 11.7 | 13.7 | 10.8 |
| CommonsenseQA | 43.6 | 41.2 | 34.1 | 38.0 |
| TriviaQA | 36.7 | 28.1 | 20.9 | 22.5 |
| Winogrande | 59.4 | 57.8 | 59.3 | 54.7 |
| OpenBookQA | 42.2 | 38.4 | 40.0 | 42.4 |
| GSM8K (5-shot) | 31.0 | 7.2 | 61.3 | 5.5 |
| Metric | SmolLM2-1.7B-Instruct | Llama-1B-Instruct | Qwen2.5-1.5B-Instruct | SmolLM1-1.7B-Instruct |
|---|---|---|---|---|
| IFEval (Average prompt/inst) | 56.7 | 53.5 | 47.4 | 23.1 |
| MT-Bench | 6.13 | 5.48 | 6.52 | 4.33 |
| OpenRewrite-Eval (micro_avg RougeL) | 44.9 | 39.2 | 46.9 | NaN |
| HellaSwag | 66.1 | 56.1 | 60.9 | 55.5 |
| ARC (Average) | 51.7 | 41.6 | 46.2 | 43.7 |
| PIQA | 74.4 | 72.3 | 73.2 | 71.6 |
| MMLU-Pro (MCF) | 19.3 | 12.7 | 24.2 | 11.7 |
| BBH (3-shot) | 32.2 | 27.6 | 35.3 | 25.7 |
| GSM8K (5-shot) | 48.2 | 26.8 | 42.8 | 4.62 |
1system_prompt_rewrite = "You are an AI writing assistant. Your task is to rewrite the user's email to make it more professional and approachable while maintaining its main points and key message. Do not return any text other than the rewritten message."
2user_prompt_rewrite = "Rewrite the message below to make it more friendly and approachable while maintaining its main points and key message. Do not add any new information or return any text other than the rewritten message\nThe message:"
3messages = [{"role": "system", "content": system_prompt_rewrite}, {"role": "user", "content":f"{user_prompt_rewrite} The CI is failing after your last commit!"}]
4input_text=tokenizer.apply_chat_template(messages, tokenize=False)
5inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
6outputs = model.generate(inputs, max_new_tokens=50, temperature=0.2, top_p=0.9, do_sample=True)
7print(tokenizer.decode(outputs[0]))Hey there! I noticed that the CI isn't passing after your latest commit. Could you take a look and let me know what's going on? Thanks so much for your help!1system_prompt_summarize = "Provide a concise, objective summary of the input text in up to three sentences, focusing on key actions and intentions without using second or third person pronouns."
2messages = [{"role": "system", "content": system_prompt_summarize}, {"role": "user", "content": INSERT_LONG_EMAIL}]
3input_text=tokenizer.apply_chat_template(messages, tokenize=False)
4inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
5outputs = model.generate(inputs, max_new_tokens=50, temperature=0.2, top_p=0.9, do_sample=True)
6print(tokenizer.decode(outputs[0]))1import json
2import re
3from typing import Optional
4
5from jinja2 import Template
6import torch
7from transformers import AutoModelForCausalLM, AutoTokenizer
8from transformers.utils import get_json_schema
9
10
11system_prompt = Template("""You are an expert in composing functions. You are given a question and a set of possible functions.
12Based on the question, you will need to make one or more function/tool calls to achieve the purpose.
13If none of the functions can be used, point it out and refuse to answer.
14If the given question lacks the parameters required by the function, also point it out.
15
16You have access to the following tools:
17<tools>{{ tools }}</tools>
18
19The output MUST strictly adhere to the following format, and NO other text MUST be included.
20The example format is as follows. Please make sure the parameter type is correct. If no function call is needed, please make the tool calls an empty list '[]'.
21<tool_call>[
22{"name": "func_name1", "arguments": {"argument1": "value1", "argument2": "value2"}},
23... (more tool calls as required)
24]</tool_call>""")
25
26
27def prepare_messages(
28 query: str,
29 tools: Optional[dict[str, any]] = None,
30 history: Optional[list[dict[str, str]]] = None
31) -> list[dict[str, str]]:
32 """Prepare the system and user messages for the given query and tools.
33
34 Args:
35 query: The query to be answered.
36 tools: The tools available to the user. Defaults to None, in which case if a
37 list without content will be passed to the model.
38 history: Exchange of messages, including the system_prompt from
39 the first query. Defaults to None, the first message in a conversation.
40 """
41 if tools is None:
42 tools = []
43 if history:
44 messages = history.copy()
45 messages.append({"role": "user", "content": query})
46 else:
47 messages = [
48 {"role": "system", "content": system_prompt.render(tools=json.dumps(tools))},
49 {"role": "user", "content": query}
50 ]
51 return messages
52
53
54def parse_response(text: str) -> str | dict[str, any]:
55 """Parses a response from the model, returning either the
56 parsed list with the tool calls parsed, or the
57 model thought or response if couldn't generate one.
58
59 Args:
60 text: Response from the model.
61 """
62 pattern = r"<tool_call>(.*?)</tool_call>"
63 matches = re.findall(pattern, text, re.DOTALL)
64 if matches:
65 return json.loads(matches[0])
66 return text
67
68
69model_name_smollm = "HuggingFaceTB/SmolLM2-1.7B-Instruct"
70model = AutoModelForCausalLM.from_pretrained(model_name_smollm, device_map="auto", torch_dtype="auto", trust_remote_code=True)
71tokenizer = AutoTokenizer.from_pretrained(model_name_smollm)
72
73from datetime import datetime
74import random
75
76def get_current_time() -> str:
77 """Returns the current time in 24-hour format.
78
79 Returns:
80 str: Current time in HH:MM:SS format.
81 """
82 return datetime.now().strftime("%H:%M:%S")
83
84
85def get_random_number_between(min: int, max: int) -> int:
86 """
87 Gets a random number between min and max.
88
89 Args:
90 min: The minimum number.
91 max: The maximum number.
92
93 Returns:
94 A random number between min and max.
95 """
96 return random.randint(min, max)
97
98
99tools = [get_json_schema(get_random_number_between), get_json_schema(get_current_time)]
100
101toolbox = {"get_random_number_between": get_random_number_between, "get_current_time": get_current_time}
102
103query = "Give me a number between 1 and 300"
104
105messages = prepare_messages(query, tools=tools)
106
107inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
108outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
109result = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
110
111tool_calls = parse_response(result)
112# [{'name': 'get_random_number_between', 'arguments': {'min': 1, 'max': 300}}
113
114# Get tool responses
115tool_responses = [toolbox.get(tc["name"])(*tc["arguments"].values()) for tc in tool_calls]
116# [63]
117
118# For the second turn, rebuild the history of messages:
119history = messages.copy()
120# Add the "parsed response"
121history.append({"role": "assistant", "content": result})
122query = "Can you give me the hour?"
123history.append({"role": "user", "content": query})
124
125inputs = tokenizer.apply_chat_template(history, add_generation_prompt=True, return_tensors="pt").to(model.device)
126outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
127result = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
128
129tool_calls = parse_response(result)
130tool_responses = [toolbox.get(tc["name"])(*tc["arguments"].values()) for tc in tool_calls]
131# ['07:57:25']1@misc{allal2025smollm2smolgoesbig,
2 title={SmolLM2: When Smol Goes Big -- Data-Centric Training of a Small Language Model},
3 author={Loubna Ben Allal and Anton Lozhkov and Elie Bakouch and Gabriel Martín Blázquez and Guilherme Penedo and Lewis Tunstall and Andrés Marafioti and Hynek Kydlíček and Agustín Piqueres Lajarín and Vaibhav Srivastav and Joshua Lochner and Caleb Fahlgren and Xuan-Son Nguyen and Clémentine Fourrier and Ben Burtenshaw and Hugo Larcher and Haojun Zhao and Cyril Zakka and Mathieu Morlon and Colin Raffel and Leandro von Werra and Thomas Wolf},
4 year={2025},
5 eprint={2502.02737},
6 archivePrefix={arXiv},
7 primaryClass={cs.CL},
8 url={https://arxiv.org/abs/2502.02737},
9}