Run this model with HF Jobs

Run gyung/LFM2-350M-ToolLLaMA on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/gyung/LFM2-350M-ToolLLaMA. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/gyung/LFM2-350M-ToolLLaMA on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/gyung/LFM2-350M-ToolLLaMA. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/gyung/LFM2-350M-ToolLLaMA. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
LFM2-350M-ToolLLaMA / README.md
gyung's picture
Update README.md
bb0917a verified
|
Raw History Blame Contribute Delete
32.6 kB
metadata
base_model: LiquidAI/LFM2-350M
library_name: transformers
model_name: LFM2-350M-ToolLLaMA
tags:
  - tool-calling
  - react-agent
  - sft
  - trl
  - toolbench
  - liquid-ai
  - lfm2
  - lnn
license: other
datasets:
  - gyung/toolbench-lfm-chatml
language:
  - en
  - ko
pipeline_tag: text-generation

πŸ”§ LFM2-350M-ToolLLaMA

πŸ‡ΊπŸ‡Έ English

πŸ‡°πŸ‡· ν•œκ΅­μ–΄

354M νŒŒλΌλ―Έν„° μ†Œν˜• λͺ¨λΈλ‘œ Tool Calling을 μˆ˜ν–‰ν•˜λŠ” ReAct μ—μ΄μ „νŠΈ

Base Model Dataset Paper

Liquid AI의 LFM2-350M을 ToolBench 데이터셋(187,494 μ˜ˆμ‹œ)으둜 Full SFTν•˜μ—¬, ReAct(Thought/Action/Action Input) ν˜•μ‹μ˜ Tool Calling을 μˆ˜ν–‰ν•˜λ„λ‘ ν•™μŠ΅ν•œ λͺ¨λΈμž…λ‹ˆλ‹€.

λ…Όλ¬Έ "Small Language Models for Efficient Agentic Tool Calling" (arXiv:2512.15943v1)의 μ‹€ν—˜μ„ LFM2 μ•„ν‚€ν…μ²˜(LNN 기반)둜 μž¬ν˜„ν•˜μ˜€μŠ΅λ‹ˆλ‹€.


Quick Start

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_id = "gyung/LFM2-350M-ToolLLaMA"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

system_prompt = """You are AutoGPT, you can use many tools(functions) to do the following task.
At each step, you need to give your thought to analyze the status now and what to do next, with a function call to actually execute your step.
Your output should follow this format:
Thought:
Action:
Action Input:"""

messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "What is the current weather in Seoul, South Korea?"},
]

inputs = tokenizer.apply_chat_template(
    messages, return_tensors="pt", add_generation_prompt=True
).to(model.device)

with torch.no_grad():
    outputs = model.generate(inputs, max_new_tokens=256, do_sample=True, temperature=0.1)

result = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
print(result)

μ‹€μ œ 좜λ ₯ μ˜ˆμ‹œ:

Thought: To find the current weather in Seoul, South Korea, I need to use the "weather" API.
I will call the "weather" function with the argument "location" set to "Seoul, South Korea"
to retrieve the weather information for that location.
Action: weather
Action Input: {"location": "Seoul, South Korea"}

λͺ¨λΈ 상세

ν•­λͺ© λ‚΄μš©
Base Model LiquidAI/LFM2-350M (LNN 기반)
νŒŒλΌλ―Έν„° 354M
ν•™μŠ΅ 데이터 gyung/toolbench-lfm-chatml (187,494 ν•™μŠ΅ μ˜ˆμ‹œ)
좜λ ₯ ν˜•μ‹ ReAct β€” Thought: / Action: / Action Input:
ν•™μŠ΅ 방식 Full SFT (TRL SFTTrainer)
정밀도 BF16
ν•™μŠ΅ ν™˜κ²½ NVIDIA H100 80GB Γ— 1 (VESSL AI)

ν•™μŠ΅ μ„€μ •

λ…Όλ¬Έ arXiv:2512.15943v1의 ν•˜μ΄νΌνŒŒλΌλ―Έν„°λ₯Ό μž¬ν˜„ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

SFTConfig(
    output_dir="./sft-output",

    # === ν•™μŠ΅ νŒŒλΌλ―Έν„° (λ…Όλ¬Έ 기반) ===
    num_train_epochs=1,
    per_device_train_batch_size=8,       # H100 80GB: 350M BF16이면 16 μ—¬μœ 
    gradient_accumulation_steps=4,       # effective batch size = 8 Γ— 4 = 32
    gradient_checkpointing=True,

    # === μ΅œμ ν™” (λ…Όλ¬Έ μ„€μ •) ===
    learning_rate=5e-5,                  # λ…Όλ¬Έ: 5Γ—10⁻⁡
    lr_scheduler_type="cosine",
    warmup_steps=100,                    # λ…Όλ¬Έ: 100 warmup steps
    max_grad_norm=0.3,                   # λ…Όλ¬Έ: aggressive clipping
    weight_decay=0.01,                   # λ…Όλ¬Έ: AdamW 0.01
    optim="adamw_torch",

    # === 정밀도 (H100: BF16 λ„€μ΄ν‹°λΈŒ) ===
    bf16=True,
    fp16=False,

    # === μ‹œν€€μŠ€ μ„€μ • ===
    max_length=8192,                     # λ…Όλ¬Έ: 8192 tokens

    # === 체크포인트 + Hub μ—…λ‘œλ“œ ===
    # 총 ~5,800 steps β†’ 500 stepλ§ˆλ‹€ μ €μž₯ β†’ ~12회 체크포인트
    logging_steps=50,
    save_strategy="steps",
    save_steps=500,                      # 자주 μ €μž₯ (μž₯μ•  λŒ€λΉ„ + 쀑간 μ„±λŠ₯ 비ꡐ)
    save_total_limit=5,

    # === HuggingFace Hub μ—…λ‘œλ“œ ===
    push_to_hub=True,
    hub_model_id="gyung/LFM2-350M-ToolLLaMA",
    hub_strategy="every_save",           # λ§€ μ²΄ν¬ν¬μΈνŠΈλ§ˆλ‹€ HF μ—…λ‘œλ“œ

    # === 데이터셋 μ„€μ • ===
    dataset_text_field="messages",
    packing=False,
    report_to="none",
)
  • 총 ν•™μŠ΅ Step: 5,891 (187,494 / 32)
  • ν•™μŠ΅ μ‹œκ°„: 4μ‹œκ°„ 4λΆ„ 14초 (H100 80GB Γ— 1)
  • μ΅œμ’… Loss: 0.1668
  • 체크포인트: λ§€ 500 stepλ§ˆλ‹€ μžλ™ HuggingFace μ—…λ‘œλ“œ

Training Loss Curve

Step Loss Step Loss Step Loss
50 1.5385 500 0.3496 2000 0.1959
100 0.6595 1000 0.2441 3000 0.1717
200 0.4875 1500 0.2223 4000 0.1746
300 0.4343 1800 0.2081 5000 0.1743
5850 0.1668

ν•™μŠ΅ 초반 κΈ‰κ²©ν•œ loss κ°μ†Œ ν›„, ~1000 step 이후 μ•ˆμ •μ μœΌλ‘œ 수렴. μ΅œμ’… loss 0.1668.

ν•™μŠ΅ 톡계

ν•­λͺ© κ°’
μ΅œλŒ€ VRAM 53.73 GB / 80 GB
평균 ν•™μŠ΅ 속도 12.86 samples/s, 0.40 steps/s
평균 Train Loss 0.2236
Mean Token Accuracy 95.64%
총 ν•™μŠ΅ 토큰 ~500M tokens
Total FLOPs 1.42 Γ— 10¹⁸

Framework Versions

  • TRL: 0.20.0
  • Transformers: 4.54.0
  • PyTorch: 2.9.1+cu128
  • Datasets: 4.6.0
  • Tokenizers: 0.21.4

μ΅œμ’… λͺ¨λΈ ν…ŒμŠ€νŠΈ

1) 도ꡬ λͺ©λ‘ 없이 자유 생성

Query Thought Action Action Input 평가
"What is the current weather in Seoul?" βœ… 논리적 weather {"location": "Seoul, South Korea"} ⭐⭐⭐⭐⭐
"Search for the latest news about AI" βœ… 논리적 news_api μ μ ˆν•œ νŒŒλΌλ―Έν„° ⭐⭐⭐⭐
"Find info about movie 'Inception'" βœ… 논리적 search {"query": "Inception"} ⭐⭐⭐⭐

도ꡬ 이름이 genericν•œ 것은 system prompt에 도ꡬ λͺ©λ‘μ„ λͺ…μ‹œν•˜μ§€ μ•Šμ•˜κΈ° λ•Œλ¬Έ. ν˜•μ‹κ³Ό 좔둠은 μ™„λ²½.

2) 도ꡬ λͺ©λ‘ 포함 ν…ŒμŠ€νŠΈ β€” 4/4 (100%)

ToolBench ν˜•μ‹μœΌλ‘œ μ‚¬μš© κ°€λŠ₯ν•œ 도ꡬλ₯Ό system prompt에 λͺ…μ‹œν•œ 경우:

Query Expected Action Predicted Action Match
Current weather in Seoul get_current_weather_for_weatherapi get_current_weather_for_weatherapi βœ…
Latest news about AI search_news_for_newsapi search_news_for_newsapi βœ…
Movie info for 'Inception' search_movie_for_imdb search_movie_for_imdb βœ…
Ultimate Oscillator BTCUSDT ultimateoscillator_for_qvantana ultimateoscillator_for_qvantana βœ…
πŸ“ μ‹€μ œ 응닡 μ˜ˆμ‹œ (ν΄λ¦­ν•˜μ—¬ 펼치기)

Query: "Get the Ultimate Oscillator data for BTCUSDT on Binance with daily interval."

Thought: I need to call the 'ultimateoscillator_for_qvantana' function to get the
Ultimate Oscillator data for BTCUSDT on Binance with a daily interval. The current
arguments for the function call are: exchange - "Binance", market - "BTCUSDT",
and interval - "1d". This will allow me to retrieve the necessary data for analysis.
Action: ultimateoscillator_for_qvantana
Action Input: {
  "exchange": "Binance",
  "market": "BTCUSDT",
  "interval": "1d"
}

πŸ’‘ 도ꡬ λͺ©λ‘μ΄ 2~3개둜 λͺ…ν™•ν•œ μ‹œλ‚˜λ¦¬μ˜€μ—μ„œλŠ” 100% 정확도. λ³΅μž‘ν•œ μ‹œλ‚˜λ¦¬μ˜€(도ꡬ 10개+)μ—μ„œλŠ” ToolBench eval κΈ°μ€€ ~55%.


평가 κ²°κ³Ό

평가 ν™˜κ²½

  • Hardware: NVIDIA A100-SXM4-80GB
  • 평가 데이터: gyung/toolbench-lfm-chatml (eval split, 762 samples)
  • 생성 μ„€μ •: max_new_tokens=512, temperature=0.1

평가 μ§€ν‘œ

μ§€ν‘œ μ„€λͺ…
Completion Rate 의미 μžˆλŠ” 응닡(10자 이상)을 μƒμ„±ν•œ λΉ„μœ¨
Format Accuracy ReAct ν˜•μ‹(Thought: + Action:) 포함 λΉ„μœ¨
Action Match Rate μ •λ‹΅ Action 이름과 μ •ν™•νžˆ μΌμΉ˜ν•˜λŠ” λΉ„μœ¨

κ²°κ³Ό 비ꡐ

λͺ¨λΈ Params Completion Format Acc. Action Match
LFM2-350M (Base) 354M 100% 62.7% 0.0%
LFM2-350M-ToolLLaMA (1K step) 354M 100% 100.0% 55.1%
LFM2-350M-ToolLLaMA (2.5K step) 354M 100% 100.0% 54.1%
LFM2-350M-ToolLLaMA (5.9K step, μ΅œμ’…) 354M 100% 99.9% 56.3%
LFM2-1.2B-Tool (Liquid AI 곡식) 1.2B 100% 97.9% 0.0%
GPT-5-Nano (OpenAI, ν•™μŠ΅ μ—†μŒ) β€” 100%* 78.6%* 8.5%*
ToolLLaMA-2-7b-v2 (λ…Όλ¬Έ 원본) 6.7B 100% 99.7% 75.3%

핡심 μΈμ‚¬μ΄νŠΈ

  1. SFT 효과: ν•™μŠ΅ μ „ 0.0% β†’ μ΅œμ’… 56.3% Action Match Rate, Format Accuracy 99.9% 달성
  2. 졜적 체크포인트: 1K step(55.1%) β†’ 2.5K(54.1%) β†’ 5.9K(56.3%) β€” μ΅œμ’… λͺ¨λΈμ΄ κ°€μž₯ 높은 μ„±λŠ₯
  3. LFM2-1.2B-Tool 비ꡐ: 3.5λ°° 큰 곡식 λͺ¨λΈ(0.0%)을 압도 β€” ν•™μŠ΅ 데이터 ν˜•μ‹ μ •λ ¬μ˜ μ€‘μš”μ„±
  4. ToolLLaMA-7B λŒ€λΉ„: 20λ°° μž‘μ€ λͺ¨λΈλ‘œ 75.3% λŒ€λΉ„ 56.3% 달성 (74.8% μˆ˜μ€€)

λ…Όλ¬Έ 평가 λ°©μ‹κ³Όμ˜ 차이

λ…Όλ¬Έμ—μ„œ 보고된 OPT-350M의 Pass Rate 77.55% 와 λ³Έ λͺ¨λΈμ˜ Action Match RateλŠ” 직접 비ꡐ가 λΆˆκ°€λŠ₯ν•©λ‹ˆλ‹€.

ν•­λͺ© λ…Όλ¬Έ (ToolEval) λ³Έ ν”„λ‘œμ νŠΈ
평가 방법 ChatGPT-based judge (4회 νŒμ • + λ‹€μˆ˜κ²°) λ¬Έμžμ—΄ μ •ν™• 일치
평가 κΈ°μ€€ ν•΄κ²° 경둜의 μ μ ˆμ„± (Pass/Fail) Action 이름 μ •ν™• 일치
ν…ŒμŠ€νŠΈμ…‹ 1,100 queries (G1~G3, 6개 μΉ΄ν…Œκ³ λ¦¬) 762 samples (eval split)
μ‹€ν–‰ 방식 닀단계 μΆ”λ‘  (μ΅œλŒ€ 10회 반볡) 단일 ν„΄ 생성

πŸ’‘ λ…Όλ¬Έμ˜ ToolEval은 λͺ¨λΈμ΄ μ‹€μ œλ‘œ μ—¬λŸ¬ 턴에 걸쳐 tool을 ν˜ΈμΆœν•˜λ©° 문제λ₯Ό ν•΄κ²°ν•˜λŠ” 전체 과정을 ChatGPTκ°€ ν‰κ°€ν•˜λŠ” λ°©μ‹μž…λ‹ˆλ‹€. λ³Έ ν”„λ‘œμ νŠΈμ˜ Action Match RateλŠ” 첫 번째 tool 호좜의 μ •ν™•ν•œ 이름 일치만 μΈ‘μ •ν•˜λ―€λ‘œ, 더 보수적인(μ—„κ²©ν•œ) μ§€ν‘œμž…λ‹ˆλ‹€.

LLM-as-Judge 평가 (ToolEval μŠ€νƒ€μΌ)

λ…Όλ¬Έμ˜ ToolEval에 κ°€κΉŒμš΄ 평가λ₯Ό μœ„ν•΄, eval_judge.pyμ—μ„œ GPT 기반 judgeλ₯Ό κ΅¬ν˜„ν•˜μ˜€μŠ΅λ‹ˆλ‹€:

# 단일 λΌμš΄λ“œ 평가 (λΉ λ₯Έ ν…ŒμŠ€νŠΈ)
python eval_judge.py --input results/eval_results.json --rounds 1

# λ…Όλ¬Έ μž¬ν˜„ (4λΌμš΄λ“œ λ‹€μˆ˜κ²° νˆ¬ν‘œ)
python eval_judge.py --input results/eval_results.json --rounds 4

이 judgeλŠ” Action μ΄λ¦„μ˜ μ •ν™•ν•œ μΌμΉ˜κ°€ μ•„λ‹Œ, 도ꡬ μ„ νƒμ˜ 논리적 μ μ ˆμ„±μ„ κΈ°μ€€μœΌλ‘œ νŒμ •ν•©λ‹ˆλ‹€.


데이터 ν˜•μ‹

λ³Έ λͺ¨λΈμ€ ChatML ν˜•μ‹μ˜ λŒ€ν™” λ°μ΄ν„°λ‘œ ν•™μŠ΅λ˜μ—ˆμŠ΅λ‹ˆλ‹€.

{
  "messages": [
    {"role": "system", "content": "You are AutoGPT, you can use many tools(functions) to do the following task..."},
    {"role": "user", "content": "μ‚¬μš©μž 쿼리..."},
    {"role": "assistant", "content": "Thought: ...\nAction: tool_name\nAction Input: {\"param\": \"value\"}"},
    {"role": "tool", "content": "{\"response\": ...}"}
  ]
}

원본 ToolBench의 "function" 역할은 LFM2 ChatML ν˜Έν™˜μ„ μœ„ν•΄ "tool"둜 λ³€ν™˜ν•˜μ˜€μŠ΅λ‹ˆλ‹€.


μ‹€μ „ 배포 μ „λž΅

354M λͺ¨λΈμ˜ 강점(λΉ λ₯Έ μΆ”λ‘ , μ €λΉ„μš©, μ—£μ§€ 배포)을 살리렀면, λΌμš°ν„° + 도ꡬ 선별 μ£Όμž… νŒŒμ΄ν”„λΌμΈμ΄ κ°€μž₯ νš¨κ³Όμ μž…λ‹ˆλ‹€.

μ‚¬μš©μž 쿼리 β†’ [λΌμš°ν„°: μΈν…νŠΈ λΆ„λ₯˜] β†’ ν•΄λ‹Ή 도ꡬ 2~3개만 ν”„λ‘¬ν”„νŠΈμ— μ£Όμž… β†’ LFM2-350M β†’ ~100% 정확도
비ꡐ 도ꡬ 전체 μ£Όμž… (ToolBench식) λΌμš°ν„° + 선별 μ£Όμž…
ν”„λ‘¬ν”„νŠΈ 도ꡬ 수 10~50개 2~3개
Action Match ~56% ~100%
ν”„λ‘¬ν”„νŠΈ 길이 수천 토큰 수백 토큰
μΆ”λ‘  속도 느림 빠름
# Stage 1: λΌμš°ν„° (인코더 λͺ¨λΈ / μž„λ² λ”© μœ μ‚¬λ„ 기반)
TOOL_CATEGORIES = {
    "weather": ["get_current_weather_for_weatherapi", "get_forecast_for_weatherapi"],
    "finance": ["ultimateoscillator_for_qvantana", "typicalprice_for_qvantana"],
    "news":    ["search_news_for_newsapi", "get_top_headlines_for_newsapi"],
}

# Stage 2: ν•΄λ‹Ή λ„κ΅¬λ§Œ ν”„λ‘¬ν”„νŠΈμ— μ£Όμž… β†’ LFM2-350M β†’ ~100%
category = classify_query(user_query)   # BERT, 코사인 μœ μ‚¬λ„ λ“±
tools = TOOL_CATEGORIES[category]       # 2~3개만 선택
prompt = build_prompt(tools, user_query)
response = model.generate(prompt)       # β†’ 거의 100%

이것이 λ…Όλ¬Έμ—μ„œ λ§ν•˜λŠ” **"Small Language Models for Efficient Agentic Tool Calling"**의 싀전적 μ˜λ―Έμž…λ‹ˆλ‹€: μž‘μ€ λͺ¨λΈ + 슀마트 λΌμš°νŒ… = 큰 λͺ¨λΈλ³΄λ‹€ λΉ λ₯΄κ³  μ €λ ΄ν•˜κ³  μ •ν™•ν•œ μ‹œμŠ€ν…œ.


μ œν•œ 사항

  • πŸ“Š 평가 μ§€ν‘œ ν•œκ³„ β€” Action Match RateλŠ” μ—„κ²©ν•œ λ¬Έμžμ—΄ 맀칭으둜, 의미적으둜 λ™μΌν•œ 도ꡬλ₯Ό λ‹€λ₯Έ μ΄λ¦„μœΌλ‘œ μ˜ˆμΈ‘ν•œ 경우 μ‹€νŒ¨λ‘œ 처리
  • 🧠 단일 ν„΄ 평가 β€” λ©€ν‹° ν„΄ μ—μ΄μ „νŠΈ μ‹œλ‚˜λ¦¬μ˜€(도ꡬ κ²°κ³Όλ₯Ό λ°›κ³  λ‹€μ‹œ μΆ”λ‘ )에 λŒ€ν•œ 평가 λ―Έμ‹€μ‹œ
  • πŸ—οΈ μ•„ν‚€ν…μ²˜ 차이 β€” 논문은 OPT-350M(Transformer), λ³Έ λͺ¨λΈμ€ LFM2-350M(LNN 기반)으둜 직접적인 μ•„ν‚€ν…μ²˜ λΉ„κ΅λŠ” λΆˆκ°€

ν–₯ν›„ κ°œμ„  λ°©ν–₯: 길이별 λΆ„ν•  ν•™μŠ΅

ν˜„μž¬ ν•™μŠ΅μ€ λͺ¨λ“  μƒ˜ν”Œμ„ max_length=8192둜 ν†΅μΌν•˜μ—¬ μ²˜λ¦¬ν•©λ‹ˆλ‹€. ν•˜μ§€λ§Œ ToolBench λ°μ΄ν„°μ˜ λŒ€λΆ€λΆ„μ€ 1K~4K 토큰 λ²”μœ„μ΄λ―€λ‘œ, κΈΈμ΄λ³„λ‘œ 버킷을 λ‚˜λˆ  배치 μ‚¬μ΄μ¦ˆλ₯Ό λ‹€λ₯΄κ²Œ μ„€μ •ν•˜λ©΄ ν•™μŠ΅ 속도λ₯Ό 크게 κ°œμ„ ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

버킷 context length batch size 효과
짧은 데이터 ~1024 64~128 νŒ¨λ”© λ‚­λΉ„ μ΅œμ†Œν™”
쀑간 데이터 ~2048–4096 16~32 λŒ€λΆ€λΆ„μ˜ 데이터 ν•΄λ‹Ή
κΈ΄ 데이터 ~8192 8 ν˜„μž¬μ™€ 동일
  • 속도: 전체 ν•™μŠ΅ μ‹œκ°„ 5060% 단좕 κ°€λŠ₯ (4μ‹œκ°„ β†’ ~1.52μ‹œκ°„)
  • μ„±λŠ₯: νŒ¨λ”© κ°μ†Œλ‘œ gradient 좔정이 μ•ˆμ •μ μ΄ λ˜μ–΄, λ™μΌν•˜κ±°λ‚˜ μ•½κ°„ λ‚˜μ€ μ„±λŠ₯ κΈ°λŒ€
  • κ°„νŽΈν•œ λŒ€μ•ˆ: TRL의 packing=True μ˜΅μ…˜ β€” 짧은 μ‹œν€€μŠ€ μ—¬λŸ¬ 개λ₯Ό ν•˜λ‚˜μ— 이어뢙여 νŒ¨λ”© λ‚­λΉ„λ₯Ό 없앨 수 있음

ν•™μŠ΅ μž¬ν˜„

사전 μ€€λΉ„

  1. HuggingFace 토큰 (Write κΆŒν•œ) β€” λ°œκΈ‰ 링크
  2. GPU ν™˜κ²½ β€” NVIDIA H100/A100 80GB ꢌμž₯

ν•™μŠ΅ μ‹€ν–‰

# VESSL AIμ—μ„œ μ‹€ν–‰
vessl run create -f vessl_notebook.yaml
# β†’ Jupyterμ—μ„œ notebooks/01_train_trl.ipynb μ—…λ‘œλ“œ ν›„ μˆœμ„œλŒ€λ‘œ μ‹€ν–‰

평가 μ‹€ν–‰

# VESSL AI 같은 μΈμŠ€ν„΄μŠ€μ—μ„œ
# β†’ notebooks/03_evaluate.ipynb μ—…λ‘œλ“œ ν›„ μˆœμ„œλŒ€λ‘œ μ‹€ν–‰

참고 자료


Citation

@misc{vonwerra2022trl,
    title        = {{TRL: Transformer Reinforcement Learning}},
    author       = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallou{\'e}dec},
    year         = 2020,
    journal      = {GitHub repository},
    publisher    = {GitHub},
    howpublished = {\url{https://github.com/huggingface/trl}}
}
@article{qin2023toolllm,
    title   = {ToolLLM: Facilitating Large Language Models to Master 16000+ Real-world APIs},
    author  = {Qin, Yujia and others},
    journal = {arXiv preprint arXiv:2307.16789},
    year    = {2023}
}
@article{liquidai2025lfm2,
 title={LFM2 Technical Report},
 author={Liquid AI},
 journal={arXiv preprint arXiv:2511.23404},
 year={2025}
}


πŸ‡ΊπŸ‡Έ English

A 354M parameter ReAct agent for Tool Calling, fine-tuned on ToolBench

Base Model Dataset Paper

This model is a full SFT of Liquid AI's LFM2-350M on the ToolBench dataset (187,494 training examples), trained to perform Tool Calling in the ReAct (Thought/Action/Action Input) format.

It reproduces the experiment from "Small Language Models for Efficient Agentic Tool Calling" (arXiv:2512.15943v1) using the LFM2 architecture (LNN-based).


Quick Start

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_id = "gyung/LFM2-350M-ToolLLaMA"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

system_prompt = """You are AutoGPT, you can use many tools(functions) to do the following task.
At each step, you need to give your thought to analyze the status now and what to do next, with a function call to actually execute your step.
Your output should follow this format:
Thought:
Action:
Action Input:"""

messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "What is the current weather in Seoul, South Korea?"},
]

inputs = tokenizer.apply_chat_template(
    messages, return_tensors="pt", add_generation_prompt=True
).to(model.device)

with torch.no_grad():
    outputs = model.generate(inputs, max_new_tokens=256, do_sample=True, temperature=0.1)

result = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
print(result)

Actual Output Example:

Thought: To find the current weather in Seoul, South Korea, I need to use the "weather" API.
I will call the "weather" function with the argument "location" set to "Seoul, South Korea"
to retrieve the weather information for that location.
Action: weather
Action Input: {"location": "Seoul, South Korea"}

Model Details

Item Details
Base Model LiquidAI/LFM2-350M (LNN-based)
Parameters 354M
Training Data gyung/toolbench-lfm-chatml (187,494 examples)
Output Format ReAct β€” Thought: / Action: / Action Input:
Training Method Full SFT (TRL SFTTrainer)
Precision BF16
Training Hardware NVIDIA H100 80GB Γ— 1 (VESSL AI)

Training Configuration

Hyperparameters reproduced from arXiv:2512.15943v1.

SFTConfig(
    output_dir="./sft-output",

    # === Training Parameters (Paper-based) ===
    num_train_epochs=1,
    per_device_train_batch_size=8,       # H100 80GB: 350M BF16 fits 16 easily
    gradient_accumulation_steps=4,       # effective batch size = 8 Γ— 4 = 32
    gradient_checkpointing=True,

    # === Optimization (Paper Settings) ===
    learning_rate=5e-5,                  # Paper: 5Γ—10⁻⁡
    lr_scheduler_type="cosine",
    warmup_steps=100,                    # Paper: 100 warmup steps
    max_grad_norm=0.3,                   # Paper: aggressive clipping
    weight_decay=0.01,                   # Paper: AdamW 0.01
    optim="adamw_torch",

    # === Precision (H100: native BF16) ===
    bf16=True,
    fp16=False,

    # === Sequence Settings ===
    max_length=8192,                     # Paper: 8192 tokens

    # === Checkpointing + Hub Upload ===
    # Total ~5,800 steps β†’ save every 500 β†’ ~12 checkpoints
    logging_steps=50,
    save_strategy="steps",
    save_steps=500,                      # Frequent saves (fault tolerance + perf comparison)
    save_total_limit=5,

    # === HuggingFace Hub Upload ===
    push_to_hub=True,
    hub_model_id="gyung/LFM2-350M-ToolLLaMA",
    hub_strategy="every_save",           # Upload to HF at every checkpoint

    # === Dataset Settings ===
    dataset_text_field="messages",
    packing=False,
    report_to="none",
)
  • Total Training Steps: 5,891 (187,494 / 32)
  • Training Time: 4h 4m 14s (H100 80GB Γ— 1)
  • Final Loss: 0.1668
  • Checkpoints: Auto-uploaded to HuggingFace every 500 steps

Training Loss Curve

Step Loss Step Loss Step Loss
50 1.5385 500 0.3496 2000 0.1959
100 0.6595 1000 0.2441 3000 0.1717
200 0.4875 1500 0.2223 4000 0.1746
300 0.4343 1800 0.2081 5000 0.1743
5850 0.1668

Rapid loss drop in early training, stabilizing after ~1000 steps. Final loss: 0.1668.

Training Statistics

Item Value
Peak VRAM 53.73 GB / 80 GB
Avg. Throughput 12.86 samples/s, 0.40 steps/s
Avg. Train Loss 0.2236
Mean Token Accuracy 95.64%
Total Tokens Trained ~500M tokens
Total FLOPs 1.42 Γ— 10¹⁸

Framework Versions

  • TRL: 0.20.0
  • Transformers: 4.54.0
  • PyTorch: 2.9.1+cu128
  • Datasets: 4.6.0
  • Tokenizers: 0.21.4

Final Model Test

1) Free generation (no tool list)

Query Thought Action Action Input Rating
"What is the current weather in Seoul?" βœ… Logical weather {"location": "Seoul, South Korea"} ⭐⭐⭐⭐⭐
"Search for the latest news about AI" βœ… Logical news_api Appropriate params ⭐⭐⭐⭐
"Find info about movie 'Inception'" βœ… Logical search {"query": "Inception"} ⭐⭐⭐⭐

Generic tool names are expected since no tool list was given. Format and reasoning are perfect.

2) With tool list in prompt β€” 4/4 (100%)

When available tools are specified in the system prompt (ToolBench style):

Query Expected Action Predicted Action Match
Current weather in Seoul get_current_weather_for_weatherapi get_current_weather_for_weatherapi βœ…
Latest news about AI search_news_for_newsapi search_news_for_newsapi βœ…
Movie info for 'Inception' search_movie_for_imdb search_movie_for_imdb βœ…
Ultimate Oscillator BTCUSDT ultimateoscillator_for_qvantana ultimateoscillator_for_qvantana βœ…
πŸ“ Actual response example (click to expand)

Query: "Get the Ultimate Oscillator data for BTCUSDT on Binance with daily interval."

Thought: I need to call the 'ultimateoscillator_for_qvantana' function to get the
Ultimate Oscillator data for BTCUSDT on Binance with a daily interval. The current
arguments for the function call are: exchange - "Binance", market - "BTCUSDT",
and interval - "1d". This will allow me to retrieve the necessary data for analysis.
Action: ultimateoscillator_for_qvantana
Action Input: {
  "exchange": "Binance",
  "market": "BTCUSDT",
  "interval": "1d"
}

πŸ’‘ 100% accuracy with 2–3 clear tool choices. For complex scenarios (10+ tools), ToolBench eval shows ~55% Action Match Rate.


Evaluation Results

Evaluation Setup

  • Hardware: NVIDIA A100-SXM4-80GB
  • Eval Data: gyung/toolbench-lfm-chatml (eval split, 762 samples)
  • Generation Settings: max_new_tokens=512, temperature=0.1

Metrics

Metric Description
Completion Rate Ratio of non-empty responses (β‰₯10 chars)
Format Accuracy Ratio containing ReAct format (Thought: + Action:)
Action Match Rate Exact string match with ground truth Action name

Results Comparison

Model Params Completion Format Acc. Action Match
LFM2-350M (Base) 354M 100% 62.7% 0.0%
LFM2-350M-ToolLLaMA (1K step) 354M 100% 100.0% 55.1%
LFM2-350M-ToolLLaMA (2.5K step) 354M 100% 100.0% 54.1%
LFM2-350M-ToolLLaMA (5.9K step, Final) 354M 100% 99.9% 56.3%
LFM2-1.2B-Tool (Liquid AI Official) 1.2B 100% 97.9% 0.0%
GPT-5-Nano (OpenAI, no ToolBench training) β€” 100%* 78.6%* 8.5%*
ToolLLaMA-2-7b-v2 (Paper Original) 6.7B 100% 99.7% 75.3%

Key Insights

  1. SFT Effect: Base 0.0% β†’ Final 56.3% Action Match Rate, Format Accuracy 99.9%
  2. Best checkpoint: 1K(55.1%) β†’ 2.5K(54.1%) β†’ 5.9K(56.3%) β€” final model achieves the highest score
  3. vs LFM2-1.2B-Tool: Outperforms 3.5Γ— larger official model (0.0%) β€” importance of training data format alignment
  4. vs ToolLLaMA-7B: 56.3% vs 75.3% with a 20Γ— smaller model (74.8% of 7B performance)

Difference from Paper's Evaluation

The paper's reported OPT-350M Pass Rate of 77.55% and this model's Action Match Rate are not directly comparable.

Aspect Paper (ToolEval) This Project
Method ChatGPT-based judge (4 rounds + majority vote) Exact string match
Criteria Solution path adequacy (Pass/Fail) Exact Action name match
Test Set 1,100 queries (G1~G3, 6 categories) 762 samples (eval split)
Execution Multi-step reasoning (up to 10 iterations) Single-turn generation

πŸ’‘ The paper's ToolEval evaluates the entire multi-turn tool-calling process via ChatGPT judge. This project's Action Match Rate only measures exact first-turn tool name match, making it a more conservative (stricter) metric.

LLM-as-Judge Evaluation (ToolEval Style)

For evaluation closer to the paper's ToolEval, a GPT-based judge is implemented in eval_judge.py:

# Single round (quick test)
python eval_judge.py --input results/eval_results.json --rounds 1

# Paper reproduction (4-round majority voting)
python eval_judge.py --input results/eval_results.json --rounds 4

This judge evaluates logical appropriateness of tool selection rather than exact string matching.


Data Format

The model was trained on ChatML-formatted conversation data.

{
  "messages": [
    {"role": "system", "content": "You are AutoGPT, you can use many tools(functions) to do the following task..."},
    {"role": "user", "content": "User query..."},
    {"role": "assistant", "content": "Thought: ...\nAction: tool_name\nAction Input: {\"param\": \"value\"}"},
    {"role": "tool", "content": "{\"response\": ...}"}
  ]
}

The original ToolBench "function" role was converted to "tool" for LFM2 ChatML compatibility.


Practical Deployment Strategy

To maximize the 354M model's strengths (fast inference, low cost, edge deployment), a router + selective tool injection pipeline is most effective.

User Query β†’ [Router: Intent Classification] β†’ Inject 2-3 relevant tools β†’ LFM2-350M β†’ ~100% accuracy
Comparison All tools injected (ToolBench style) Router + Selective injection
Tools in prompt 10–50 2–3
Action Match ~56% ~100%
Prompt length Thousands of tokens Hundreds of tokens
Inference speed Slow Fast
# Stage 1: Router (encoder model / embedding similarity)
TOOL_CATEGORIES = {
    "weather": ["get_current_weather_for_weatherapi", "get_forecast_for_weatherapi"],
    "finance": ["ultimateoscillator_for_qvantana", "typicalprice_for_qvantana"],
    "news":    ["search_news_for_newsapi", "get_top_headlines_for_newsapi"],
}

# Stage 2: Inject only relevant tools β†’ LFM2-350M β†’ ~100%
category = classify_query(user_query)   # BERT, cosine similarity, etc.
tools = TOOL_CATEGORIES[category]       # Select only 2-3
prompt = build_prompt(tools, user_query)
response = model.generate(prompt)       # β†’ Near 100%

This is the practical meaning of "Small Language Models for Efficient Agentic Tool Calling": small model + smart routing = faster, cheaper, and more accurate than a single large model.


Limitations

  • πŸ“Š Evaluation metric limitation β€” Action Match Rate uses strict string matching; semantically equivalent tools predicted under different names count as failures
  • 🧠 Single-turn evaluation β€” Multi-turn agent scenarios (receiving tool results and reasoning again) not yet evaluated
  • πŸ—οΈ Architecture difference β€” Paper uses OPT-350M (Transformer), this model uses LFM2-350M (LNN-based); direct architecture comparison not possible

Potential Improvements: Length-Bucketed Training

The current training uses a uniform max_length=8192 for all samples. However, most ToolBench data falls in the 1K–4K token range, meaning significant compute is wasted on padding. Bucketing by sequence length with different batch sizes could substantially improve training speed.

Bucket Context Length Batch Size Effect
Short data ~1024 64–128 Minimal padding waste
Medium data ~2048–4096 16–32 Covers majority of data
Long data ~8192 8 Same as current
  • Speed: Could reduce total training time by 50–60% (4h β†’ ~1.5–2h)
  • Performance: Reduced padding leads to more stable gradient estimation β€” expect equal or slightly better performance
  • Simple alternative: TRL's packing=True β€” concatenates multiple short sequences into one, eliminating padding waste

Reproduction

Prerequisites

  1. HuggingFace Token (Write permission) β€” Get token
  2. GPU Environment β€” NVIDIA H100/A100 80GB recommended

Training

# Run on VESSL AI
vessl run create -f vessl_notebook.yaml
# β†’ Upload notebooks/01_train_trl.ipynb in Jupyter and run cells sequentially

Evaluation

# On the same VESSL AI instance
# β†’ Upload notebooks/03_evaluate.ipynb and run cells sequentially

References


Citation

@misc{vonwerra2022trl,
    title        = {{TRL: Transformer Reinforcement Learning}},
    author       = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallou{\'e}dec},
    year         = 2020,
    journal      = {GitHub repository},
    publisher    = {GitHub},
    howpublished = {\url{https://github.com/huggingface/trl}}
}
@article{qin2023toolllm,
    title   = {ToolLLM: Facilitating Large Language Models to Master 16000+ Real-world APIs},
    author  = {Qin, Yujia and others},
    journal = {arXiv preprint arXiv:2307.16789},
    year    = {2023}
}
@article{liquidai2025lfm2,
 title={LFM2 Technical Report},
 author={Liquid AI},
 journal={arXiv preprint arXiv:2511.23404},
 year={2025}
}