Alterlab Transformers 标志

Alterlab Transformers

社区
AlterLab-IEU
alterlab-transformers

Loads, runs, and fine-tunes pretrained models with Hugging Face Transformers v5 (PyTorch-only) — pipeline() inference for chat-model text generation, text classification, NER, zero-shot, speech recognition, image classification, object detection, and image-text-to-text VLMs; AutoModel/AutoTokenizer loading with dtype, device_map and bitsandbytes quantization; generate() decoding control; and Trainer fine-tuning with optional PEFT/LoRA. Use when running inference with a Hugging Face Hub checkpoint, fine-tuning BERT/ModernBERT/Qwen-style models on a custom labelled dataset, controlling generation (sampling, beam search, streaming, chat templates), or porting v4 code (torch_dtype, removed summarization/translation/QA pipelines, TF/Flax) to v5. Part of the AlterLab Academic Skills suite.

概览

发布者AlterLab-IEU
代码仓库AlterLab-Academic-Skills
技能名称alterlab-transformers
星标数
84
复刻数
16
附带文件
6
许可协议Apache-2.0
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 6 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 AlterLab-IEU 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Alterlab Transformers AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/AlterLab-IEU/AlterLab-Academic-Skills/tree/main/skills/data-science/alterlab-transformers
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/AlterLab-IEU/AlterLab-Academic-Skills.git /tmp/AlterLab-Academic-Skills
mkdir -p .claude/skills
cp -r /tmp/AlterLab-Academic-Skills/skills/data-science/alterlab-transformers .claude/skills/alterlab-transformers
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Alterlab Transformers,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Alterlab Transformers。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Alterlab Transformers 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Transformers

Overview

Hugging Face Transformers loads pretrained checkpoints from the Hub for NLP, vision, audio, and multimodal tasks, runs inference through pipeline() or the Auto* classes, and fine-tunes them with Trainer. This skill targets transformers v5 (≥ 5.0; current 5.17.0 as of 2026-09). v5 is PyTorch-only and changes several v4 idioms, so check "v5 changes that break v4 code" below before reusing older snippets from papers, blogs, or model cards.

When to Use This Skill

Use this skill when the user wants to:

  • Run quick inference with a Hub checkpoint via pipeline() — text classification, NER, zero-shot classification, text generation with a chat model, speech recognition, image classification/detection, or image-text-to-text with a VLM.
  • Load a model plus tokenizer/processor with explicit dtype, device_map, attention backend, or 4/8-bit quantization.
  • Control decoding in model.generate() (greedy, sampling, beam search, streaming, chat templates).
  • Fine-tune an encoder or decoder on a custom labelled dataset with Trainer, optionally with LoRA via peft.
  • Port v4-era code (torch_dtype=, load_in_8bit=, removed pipelines, TF/Flax models) to v5.

Does NOT Trigger

ScenarioUse Instead
Classical ML on tabular features (random forests, preprocessing pipelines, CV grid search)alterlab-scikit-learn
Structuring a custom PyTorch architecture's training loop, multi-GPU strategy, and checkpointing with a LightningModulealterlab-pytorch-lightning
Topic models, embeddings, or text classifiers as a social-science measurement design (validity, BERTopic, dictionaries)alterlab-text-as-data
Protein language models (ESM3 / ESM C embeddings, protein design)alterlab-esm
Zero-shot time-series forecasting with a pretrained foundation modelalterlab-timesfm

Installation

bash
uv pip install "transformers>=5" torch accelerate datasets
  • Vision: add pillow and torchvision (the default image-processor backend; timm only for timm-backed models).
  • Audio: add librosa soundfile.
  • LoRA / quantization: peft, bitsandbytes (CUDA). Metrics: evaluate or plain scikit-learn metrics.

Authentication

Gated or private models need a Hub token. Either log in once:

python
from huggingface_hub import login
login()  # or run `hf auth login` in a shell (huggingface-cli is deprecated)

or export the variable the Hub client reads:

bash
export HF_TOKEN="your_token_here"

Tokens: https://huggingface.co/settings/tokens. Pass token= (not the removed use_auth_token=) when you need it explicitly.

Quick Start

python
from transformers import pipeline

# Text generation with a small open chat model (CPU-friendly; add device_map="auto" on GPU)
generator = pipeline("text-generation", model="Qwen/Qwen3-0.6B")
messages = [{"role": "user", "content": "Explain p-hacking in two sentences."}]
out = generator(
    messages,
    max_new_tokens=128,
    tokenizer_encode_kwargs={"enable_thinking": False},  # Qwen3 chat-template switch; omit for other models
)
print(out[0]["generated_text"][-1]["content"])

# Text classification — pin the checkpoint; task defaults change between releases
classifier = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
classifier(["This movie was excellent!", "Terrible pacing."])

# Zero-shot classification
zero_shot = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
zero_shot("The grant covers two postdoc salaries.", candidate_labels=["funding", "teaching", "ethics"])

Use max_new_tokens (tokens to generate) rather than max_length (prompt + output, and in the text-generation pipeline it also feeds tokenizer truncation). Summarization, translation, and question answering no longer have dedicated pipelines in v5 — prompt a chat model as above.

v5 Changes That Break v4 Code

v4 idiomv5 replacement
torch_dtype=torch.float16dtype=torch.float16 (torch_dtype only warns). Default is now dtype="auto" — the checkpoint's dtype, often bf16 — not float32
TFAutoModel… / FlaxAutoModel…, framework="tf", return_tensors="tf"Removed; PyTorch only (return_tensors accepts "pt", "np", "mlx")
load_in_8bit=True / load_in_4bit=Truequantization_config=BitsAndBytesConfig(...)
pipeline("summarization" / "translation_xx_to_yy" / "text2text-generation" / "question-answering")Removed — pipeline("text-generation") with a chat model and an instruction prompt
pipeline("image-to-text" / "visual-question-answering")pipeline("image-text-to-text") with a VLM, e.g. Qwen/Qwen3-VL-2B-Instruct
AutoModelForVision2Seq, AutoModelWithLMHeadAutoModelForImageTextToText; AutoModelForCausalLM / AutoModelForMaskedLM / AutoModelForSeq2SeqLM
apply_chat_template(..., tokenize=True) returned a tensor of idsReturns a BatchEncoding (input_ids, attention_mask) → model.generate(**inputs)
Slow vs fast tokenizers, use_fast=One tokenizer per model on the 🤗 tokenizers backend; AutoTokenizer ignores use_fast
batch_decode, encode_plus, additional_special_tokensdecode handles batches, tokenizer(...), extra_special_tokens (old names kept for backward compatibility)
penalty_alpha (contrastive search), force_words_ids / constraints, group beam search, DoLaMoved to Hub custom_generate repos — e.g. custom_generate="transformers-community/contrastive-search", trust_remote_code=True
TrainingArguments(logging_dir=..., warmup_ratio=...)Both removed: set the TENSORBOARD_LOGGING_DIR env var; warmup_steps=0.1 (a float < 1 is a ratio)
Trainer(tokenizer=...)Trainer(processing_class=...); report_to now defaults to "none"
save_pretrained(safe_serialization=False), use_auth_token=Always safetensors; token=
TRANSFORMERS_CACHE, low_cpu_mem_usage=TrueHF_HOME / HF_HUB_CACHE; low-memory loading is always on (flag ignored)

Source: the official v5 migration guide, cross-checked against the 5.17.0 release.

Core Capabilities

1. Pipelines for Quick Inference

One call covers tokenization, the forward pass, and post-processing for text classification, NER, zero-shot, fill-mask, text generation, ASR, audio classification, image classification/segmentation, object detection, depth estimation, and image-text-to-text. Use for prototyping and batch inference without custom preprocessing. See references/pipelines.md.

2. Model Loading and Management

from_pretrained with dtype, device_map, attn_implementation (SDPA by default), and quantization_config; saving, Hub upload, and ONNX export options. See references/models.md.

3. Text Generation

generate() with greedy, sampling (temperature/top-k/top-p), and beam search; chat templates, streaming, and static caches. See references/generation.md.

4. Training and Fine-Tuning

Trainer + TrainingArguments with mixed precision, gradient accumulation/checkpointing, callbacks, hyperparameter search, and LoRA via peft. See references/training.md.

5. Tokenization

Padding, truncation, special tokens, offsets, and chat templates. See references/tokenizers.md.

Common Patterns

Pattern 1: Simple Inference

python
pipe = pipeline("task-name", model="org/model-id")
output = pipe(input_data)

Pattern 2: Explicit Model + Tokenizer (chat model)

python
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto", device_map="auto")

messages = [{"role": "user", "content": "State the central limit theorem in one sentence."}]
inputs = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt=True,
    return_tensors="pt",
    enable_thinking=False,  # Qwen3-specific template variable
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=128)
new_tokens = outputs[0, inputs["input_ids"].shape[1]:]
print(tokenizer.decode(new_tokens, skip_special_tokens=True))

Pattern 3: Fine-Tuning a Classifier

python
from datasets import load_dataset
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
                          DataCollatorWithPadding, Trainer, TrainingArguments)

model_id = "google-bert/bert-base-uncased"  # or answerdotai/ModernBERT-base
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(model_id, num_labels=5)

ds = load_dataset("Yelp/yelp_review_full")
ds = ds.map(lambda b: tokenizer(b["text"], truncation=True), batched=True)

args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    eval_strategy="epoch",
    warmup_steps=0.1,          # ratio of total steps
    report_to="tensorboard",   # default is "none" in v5
)
trainer = Trainer(
    model=model,
    args=args,
    train_dataset=ds["train"],
    eval_dataset=ds["test"],
    processing_class=tokenizer,
    data_collator=DataCollatorWithPadding(tokenizer),
)
trainer.train()

Practical Notes

  • Pin model IDs (and ideally revision=) in research code: pipeline defaults and Hub repos change, which silently changes results.
  • Report the exact checkpoint, transformers version, decoding parameters, and seed (transformers.set_seed) when generated text or fine-tuned metrics appear in a paper.
  • Check the model card's license and gating terms before redistributing weights or outputs.

Reference Documentation

  • references/pipelines.md — supported v5 tasks, parameters, batching, and removed pipelines
  • references/models.md — loading, dtype/device/attention/quantization, saving, export
  • references/generation.md — decoding strategies, chat templates, streaming, caches
  • references/training.md — Trainer workflow, TrainingArguments, PEFT, tuning
  • references/tokenizers.md — tokenization, special tokens, chat templates

Part of the AlterLab Academic Skills suite.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Alterlab Transformers AI 技能有什么作用?

Loads, runs, and fine-tunes pretrained models with Hugging Face Transformers v5 (PyTorch-only) — pipeline() inference for chat-model text generation, text classification, NER, zero-shot, speech recognition, image classification, object detection, and image-text-to-text VLMs; AutoModel/AutoTokenizer loading with dtype, device_map and bitsandbytes quantization; generate() decoding control; and Trainer fine-tuning with optional PEFT/LoRA. Use when running inference with a Hugging Face Hub checkpoint, fine-tuning BERT/ModernBERT/Qwen-style models on a custom labelled dataset, controlling genera...

为什么在 TypingMind 中使用 Alterlab Transformers?

因为您只需安装一次,就能搭配任何模型使用。Alterlab Transformers 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Alterlab Transformers?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/AlterLab-IEU/AlterLab-Academic-Skills/tree/main/skills/data-science/alterlab-transformers。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Alterlab Transformers?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Alterlab Transformers 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Alterlab Transformers 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Alterlab Transformers AI 技能免费吗?

是的。AlterLab-IEU 已在 GitHub 上根据 Apache-2.0 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇