pip install "transformers[torch]"★v5 is PyTorch-only. Addacceleratefor multi-GPU/device_map,datasetsfor data,bitsandbytesfor 4/8-bit.import transformers; transformers.__version__Requires Python 3.10+, PyTorch 2.4+. Python 3.9 is rejected.export HF_HOME=/data/hfCache location for models/datasets (default~/.cache/huggingface).HF_TOKENsupplies auth non-interactively.transformers envCLI (replacestransformers-cli) — prints versions/CUDA for bug reports;transformers chat/servealso exist.
from transformers import pipeline pipe = pipeline("text-generation", model="Qwen/Qwen3-8B")★Handles tokenize → forward → decode. Task string picks the head; omitmodelfor a task default.pipe("Hello, ", max_new_tokens=50)Call with text (or a list to batch). Kwargs pass through togenerate()/ the model.pipeline(task, model=m, device_map="auto", dtype="auto")★Spread across GPUs and load in the checkpoint's native precision.pipeline("automatic-speech-recognition") # asr, image-classification, # zero-shot-classification, feature-extraction, image-text-to-text ...Same API across modalities.image-text-to-textis the modern vision-LLM task.
from transformers import AutoModelForCausalLM, AutoTokenizer★Auto classes pick the right architecture from the checkpoint config. AlsoAutoModelForSequenceClassification,...ForTokenClassification,...ForImageTextToText,AutoProcessor.model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B")★Downloads + caches weights (safetensors) and builds the model. Pair withAutoTokenizer.from_pretrained(same_id).from_pretrained(id, dtype="auto", device_map="auto")★dtype="auto"uses the saved precision (the v5 default). Passrevision="..."to pin a commit,token=...for gated repos.model.save_pretrained("out/") # writes model.safetensors + config.json tok.save_pretrained("out/")Reload withfrom_pretrained("out/"). Serialization is safetensors-only in v5.model.config · model.generation_configconfigis architecture;generation_configholds default decoding params shipped with the model.
dtype=torch.bfloat16 # or "auto" (default), torch.float16, torch.float32★v5: the oldtorch_dtype=name is superseded bydtype=. Default changed from fp32 to"auto"— pintorch.float32for the old behavior.device_map="auto" # or "cuda", {"": 0}, a custom dict★Needsaccelerate. Shards a big model across GPUs/CPU/disk. For a single device just.to("cuda").attn_implementation="flash_attention_2" # or "sdpa" (default), "eager"sdpa(PyTorch scaled-dot-product) is the default;flash_attention_2needs theflash-attnpackage + supported GPU.model.eval() · with torch.inference_mode(): ...★Disable dropout and autograd for inference — faster and less memory.