用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/majiayu000/claude-skill-registry --skill transformers命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
LLM token logprobs and calibration. Per-decision confidence, ECE, Brier, reliability diagrams, low-confidence triage.
Analyze LLM token logprobs and calibration. Use for per-decision confidence, ECE, Brier scores, reliability diagrams, and low-confidence triage.
回顾最近 N 天的 Claude Code 使用记录——扫描原始会话数据,按主题分组汇总"我都做了什么",并从个人操作系统视角输出模式、风险与增删建议。当用户说 /recap、"看看我这几天做了什么"、"回顾一下我最近的会话"、"这两天我用 claude 干了啥"、"活动回顾" 时使用。
基于 SOC 职业分类
正在显示 SKILL.md
| name | transformers |
| description | python library |
| version | 5.2.0 |
| ecosystem | python |
| license | Apache 2.0 License" |
| generated_with | claude-sonnet-4-5-20250929 |
import transformers
from transformers import AutoTokenizer, pipeline
from transformers.utils.metrics import attach_tracer, traced
from transformers import pipeline
def main() -> None:
text_gen = pipeline(task="text-generation", model="openai-community/gpt2")
out = text_gen("The secret to baking a really good cake is ", max_new_tokens=40)
print(out[0]["generated_text"])
img_cls = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
preds = img_cls("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
print(preds[:2])
if __name__ == "__main__":
main()
transformers.pipeline(task=..., model=...) for quick inference; it handles preprocessing/postprocessing and downloads/caches weights.text-generation pipeline ✅ Currentimport torch
from transformers import pipeline
def main() -> None:
chat = [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Give me 3 ideas for a weekend trip from Paris."},
]
pipe = pipeline(
task="text-generation",
model="meta-llama/Meta-Llama-3-8B-Instruct",
dtype=torch.bfloat16,
device_map="auto",
)
response = pipe(chat, max_new_tokens=200)
# Many chat-capable pipelines return a list of messages in generated_text
print(response[0]["generated_text"][-1]["content"])
if __name__ == "__main__":
main()
{role, content} messages (not just a single string).dtype= and device_map="auto" to control memory/placement for larger models.import tempfile
import shutil
from transformers import AutoTokenizer
def main() -> None:
tmp_dir = tempfile.mkdtemp()
try:
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
# Add a special token and ensure it tokenizes as a single token
special = "[SPECIAL_TOKEN_1]"
tokenizer.add_tokens([special], special_tokens=True)
assert tokenizer.tokenize(special) == [special]
# Add extra special tokens without replacing existing ones
extra = "[SPECIAL_TOKEN_2]"
tokenizer.add_special_tokens({"extra_special_tokens": [extra]}, replace_extra_special_tokens=False)
assert tokenizer.tokenize(extra) == [extra]
# Save and reload round-trip
tokenizer.save_pretrained(tmp_dir)
reloaded = tokenizer.__class__.from_pretrained(tmp_dir)
text = "He is very happy, UNwanté,dunning"
assert tokenizer.encode(text, add_special_tokens=False) == reloaded.encode(text, add_special_tokens=False)
assert tokenizer.get_vocab() == reloaded.get_vocab()
# Common conventions
assert reloaded.model_input_names[0] in ["input_ids", "input_values"]
print("Tokenizer round-trip OK:", tmp_dir)
finally:
shutil.rmtree(tmp_dir)
if __name__ == "__main__":
main()
AutoTokenizer.from_pretrained() loads a tokenizer from a model id or local directory.save_pretrained() + from_pretrained() should preserve vocab and tokenization behavior.__call__ and BatchEncoding ✅ Currentfrom transformers import AutoTokenizer
def main() -> None:
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
sequences = ["Hello world!", "Transformers tokenizers batch encode."]
encoding = tokenizer(sequences, padding=True)
# BatchEncoding behaves like a dict; `.data` exposes the underlying mapping
data = encoding.data
input_ids = data["input_ids"]
decoded = [tokenizer.decode(ids, skip_special_tokens=True) for ids in input_ids]
for src, dst in zip(sequences, decoded):
print("SRC:", src)
print("DEC:", dst)
print("---")
if __name__ == "__main__":
main()
tokenizer(texts, padding=True, truncation=True, return_tensors=...) for batch preprocessing.skip_special_tokens=True for human-readable text.attach_tracer and traced ✅ Currentfrom __future__ import annotations
from transformers.utils.metrics import attach_tracer, traced
@attach_tracer()
class ExampleClass:
def __init__(self, name: str) -> None:
self.name = name
@traced
def process_data(self, data: str) -> str:
return f"Processed {data} with {self.name}"
@traced(span_name="custom_operation")
def special_operation(self, value: int) -> int:
return value * 2
@traced(
additional_attributes=[
("name", "object.name", lambda x: x.upper()),
("name", "object.fixed_value", "static_value"),
]
)
def operation_with_attributes(self) -> str:
return "Operation completed"
@traced
def () -> :
arg1 + arg2
() -> :
ex = ExampleClass()
(ex.process_data())
(ex.special_operation())
(ex.operation_with_attributes())
(standalone_function(, ))
__name__ == :
main()
@attach_tracer() is a class decorator that ensures instances have self.tracer.@traced works on methods and standalone functions; supports span_name= and additional_attributes=.from typing import Any
import torch
from transformers import AutoModelForCausalLM
from transformers.quantizers import HfQuantizer, register_quantization_config, register_quantizer
from transformers.utils.quantization_config import QuantizationConfigMixin
@register_quantization_config("custom")
class CustomConfig(QuantizationConfigMixin):
def __init__(self) -> None:
self.quant_method = "custom"
self.bits = 8
def to_dict(self) -> dict[str, Any]:
return {"num_bits": self.bits}
@register_quantizer("custom")
class CustomQuantizer(HfQuantizer):
def __init__(self, quantization_config, **kwargs) -> None:
super().__init__(quantization_config, **kwargs)
self.quantization_config = quantization_config
def _process_model_before_weight_loading() -> :
() -> :
() -> :
() -> :
() -> :
model_8bit = AutoModelForCausalLM.from_pretrained(
,
quantization_config=CustomConfig(),
dtype=
)
()
__name__ == :
main()
@register_quantization_config to register a custom quantization configuration class.@register_quantizer to register the corresponding quantizer implementation.QuantizationConfigMixin and HfQuantizer for full integration with the transformers quantization system.pip install "transformers[torch]" (PyTorch required per README: Python 3.10+, PyTorch 2.4+).pip install "transformers[jax]"pip install "transformers[tf]"pipeline() / from_pretrained() are cached and reused across runs (location depends on Hugging Face cache configuration).dtype=torch.bfloat16 (or torch.float16) and device_map="auto".from_pretrained()):
do_lower_case=True (model-dependent), plus tokenizer-specific kwargs; they are persisted in tokenizer.init_kwargs.tokenizer.add_tokens([...], special_tokens=True)tokenizer.add_special_tokens({"extra_special_tokens": [...]}, replace_extra_special_tokens=False)additional_special_tokens is deprecated in v5 and converted to extra_special_tokens (prefer extra_special_tokens for new code).pipeline factory with a Pipeline instancefrom transformers import pipeline
pipeline = pipeline(task="text-generation", model="openai-community/gpt2")
# Now `pipeline(...)` is no longer the factory function; it's a Pipeline object.
pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
from transformers import pipeline
text_gen = pipeline(task="text-generation", model="openai-community/gpt2")
img_cls = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
from transformers import pipeline
pipe = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct")
out = pipe("Hey, can you tell me any fun things to do in New York?")
print(out)
{role, content} messagesimport torch
from transformers import pipeline
chat = [
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"},
]
pipe = pipeline(
task="text-generation",
model="meta-llama/Meta-Llama-3-8B-Instruct",
dtype=torch.bfloat16,
device_map="auto",
)
response = pipe(chat, max_new_tokens=256)
print(response[0]["generated_text"][-1]["content"])
from transformers import pipeline
vqa = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
# Missing `image=`; this cannot build inputs for VQA.
print(vqa("What is in the image?"))
from transformers import pipeline
vqa = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
image_url = "https://huggingface.co/datasets/huggingface/documentation-images/"
image_url += "resolve/main/transformers/tasks/idefics-few-shot.jpg"
print(
vqa(
image=image_url,
question="What is in the image?",
)
)
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tokenizer.add_tokens(["[SPECIAL_TOKEN_1]"]) # not marked special
print(tokenizer.tokenize("[SPECIAL_TOKEN_1]"))
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tokenizer.add_tokens(["[SPECIAL_TOKEN_1]"], special_tokens=True)
assert tokenizer.tokenize("[SPECIAL_TOKEN_1]") == ["[SPECIAL_TOKEN_1]"]
PretrainedConfig (lowercase)from transformers import PretrainedConfig # Deprecated naming
config = PretrainedConfig()
PreTrainedConfig (PascalCase)from transformers import PreTrainedConfig
config = PreTrainedConfig()
# Python 3.9 or PyTorch 2.3
# Transformers 5.2.0 will not work properly
# Python 3.10+ and PyTorch 2.4+
# Verify before installing:
# python --version # Should be 3.10 or higher
# pip install "transformers[torch]>=5.2.0"
Minimum Python version: Python 3.10+ is now required (previously 3.9+).
Minimum PyTorch version: PyTorch 2.4+ is now required (previously 2.3+).
pip install "torch>=2.4"Special tokens parameter naming: additional_special_tokens is deprecated in favor of extra_special_tokens.
{"additional_special_tokens": [...]} with {"extra_special_tokens": [...]} when calling tokenizer.add_special_tokens(...).Update environment:
# Ensure Python 3.10+
python --version
# Upgrade PyTorch
pip install "torch>=2.4"
# Upgrade transformers
pip install "transformers[torch]>=5.2.0"
Update tokenizer special tokens:
# Old (deprecated in v5)
tokenizer.add_special_tokens({"additional_special_tokens": ["[SPECIAL]"]})
# New (v5+)
tokenizer.add_special_tokens({"extra_special_tokens": ["[SPECIAL]"]})
Update config class naming:
# Old (deprecated)
from transformers import PretrainedConfig
# New
from transformers import PreTrainedConfig
Pipeline; key kwargs include dtype=, device_map=, revision=, torch_dtype=, trust_remote_code=.BatchEncoding.special_tokens=True for special tokens.extra_special_tokens.input_ids or input_values)..data attribute.input_ids, attention_mask).config=, cache_dir=, quantization_config=, device_map=, dtype=.PreTrainedConfig; use PreTrainedConfig instead.self.tracer).