SmolLM是什么?
SmolLM是由 Huggingface 最新发布的一系列最先进的小型语言模型,有三种规格:1.35亿、3.6亿和17亿个参数。这些模型建立在 Cosmo-Corpus 上,Cosmo-Corpus 是一个精心策划的高质量训练数据集。Cosmo-Corpus 包括 Cosmopedia v2(由 Mixtral 生成的 280 亿个合成教科书和故事词块)、Python-Edu(由 The Stack 提供的 40 亿个 Python 教育样本词块)和 FineWeb-Edu(由 FineWeb 提供的 2200 亿个重复教育网络样本词块)。
SmolLM模型适合需要在本地设备上运行语言模型的开发者和研究人员。它们特别适合那些需要在资源受限的环境中进行高效推理的应用场景,如智能手机、笔记本电脑等。
SmolLM的测试结果
Hugging Face 团队将开发出的 SmolLM 模型与相同参数量的其他模型进行了基准测试,其中 SmolLM-135M 在多项测试中超越了小于 2 亿参数的其他模型;而 SmolLM-360M 的测试成绩优于所有小于 5 亿参数以下的模型,不过某些项目逊于 Meta 刚刚公布的 MobileLLM-350M;SmolLM-1.7B 模型则超越了所有参数量小于 20 亿参数的模型,包括微软 Phi-1.5、MobileLLM-1.5B 及 Qwen2。
代码
# pip install transformers
from transformers import AutoModelForCausalLM, AutoTokenizer
checkpoint = "HuggingFaceTB/SmolLM-1.7B"
device = "cuda" # for GPU usage or "cpu" for CPU usage
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
# for multiple GPUs install accelerate and do `model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto")`
model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to(device)
outputs = model.generate(inputs)
print(tokenizer.decode(outputs[0]))
用 torch.bfloat16
# pip install accelerate
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
checkpoint = "HuggingFaceTB/SmolLM-1.7B"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
# for fp16 use `torch_dtype=torch.float16` instead
model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", torch_dtype=torch.bfloat16)
inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to("cuda")
outputs = model.generate(inputs)
print(tokenizer.decode(outputs[0]))
>>> print(f"Memory footprint: {model.get_memory_footprint() / 1e6:.2f} MB")
Memory footprint: 3422.76 MB
通过 bitsandbytes 量化
- int8
# pip install bitsandbytes accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
# to use 4bit use `load_in_4bit=True` instead
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
checkpoint = "HuggingFaceTB/SmolLM-1.7B"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint, quantization_config=quantization_config)
inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to("cuda")
outputs = model.generate(inputs)
print(tokenizer.decode(outputs[0]))
>>> print(f"Memory footprint: {model.get_memory_footprint() / 1e6:.2f} MB")
# load_in_8bit
Memory footprint: 1812.14 MB
# load_in_4bit
>>> print(f"Memory footprint: {model.get_memory_footprint() / 1e6:.2f} MB")
Memory footprint: 1006.84 MB